|
| 1 | +// This example uses an Arduino MKR NB 1500 board |
| 2 | +// to connect to shiftr.io. |
| 3 | +// |
| 4 | +// You can check on your device after a successful |
| 5 | +// connection here: https://www.shiftr.io/try. |
| 6 | +// |
| 7 | +// by Max Kriegleder |
| 8 | +// https://github.com/256dpi/arduino-mqtt |
| 9 | + |
| 10 | +#include <MKRNB.h> |
| 11 | +#include <MQTT.h> |
| 12 | + |
| 13 | +const char pin[] = ""; |
| 14 | +const char apn[] = "apn"; |
| 15 | +const char login[] = "login"; |
| 16 | +const char password[] = "password"; |
| 17 | + |
| 18 | +NBClient net; |
| 19 | +NB nbAccess; |
| 20 | +MQTTClient client; |
| 21 | + |
| 22 | +unsigned long lastMillis = 0; |
| 23 | + |
| 24 | +void connect() { |
| 25 | + // connection state |
| 26 | + bool connected = false; |
| 27 | + |
| 28 | + Serial.print("connecting to cellular network ..."); |
| 29 | + |
| 30 | + while (!connected) { |
| 31 | + if ((nbAccess.begin(pin, apn, login, password) == NB_READY)) { |
| 32 | + connected = true; |
| 33 | + } else { |
| 34 | + Serial.print("."); |
| 35 | + delay(1000); |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + Serial.print("\nconnecting..."); |
| 40 | + while (!client.connect("arduino", "public", "public")) { |
| 41 | + Serial.print("."); |
| 42 | + delay(1000); |
| 43 | + } |
| 44 | + |
| 45 | + Serial.println("\nconnected!"); |
| 46 | + |
| 47 | + client.subscribe("/hello"); |
| 48 | + // client.unsubscribe("/hello"); |
| 49 | +} |
| 50 | + |
| 51 | +void messageReceived(String &topic, String &payload) { |
| 52 | + Serial.println("incoming: " + topic + " - " + payload); |
| 53 | + |
| 54 | + // Note: Do not use the client in the callback to publish, subscribe or |
| 55 | + // unsubscribe as it may cause deadlocks when other things arrive while |
| 56 | + // sending and receiving acknowledgments. Instead, change a global variable, |
| 57 | + // or push to a queue and handle it in the loop after calling `client.loop()`. |
| 58 | +} |
| 59 | + |
| 60 | +void setup() { |
| 61 | + Serial.begin(115200); |
| 62 | + |
| 63 | + // Note: Local domain names (e.g. "Computer.local" on OSX) are not supported |
| 64 | + // by Arduino. You need to set the IP address directly. |
| 65 | + client.begin("public.cloud.shiftr.io", net); |
| 66 | + client.onMessage(messageReceived); |
| 67 | + |
| 68 | + connect(); |
| 69 | +} |
| 70 | + |
| 71 | +void loop() { |
| 72 | + client.loop(); |
| 73 | + |
| 74 | + if (!client.connected()) { |
| 75 | + connect(); |
| 76 | + } |
| 77 | + |
| 78 | + // publish a message roughly every second. |
| 79 | + if (millis() - lastMillis > 1000) { |
| 80 | + lastMillis = millis(); |
| 81 | + client.publish("/hello", "world"); |
| 82 | + } |
| 83 | +} |
0 commit comments