ArduinoMKRGSM1400Secure.ino 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // This example uses an Arduino MKR GSM 1400 board
  2. // to securely connect to shiftr.io.
  3. //
  4. // IMPORTANT: This example uses the new MKRGSM library.
  5. //
  6. // You can check on your device after a successful
  7. // connection here: https://shiftr.io/try.
  8. //
  9. // by Sandeep Mistry
  10. // https://github.com/256dpi/arduino-mqtt
  11. #include <MKRGSM.h>
  12. #include <MQTT.h>
  13. const char pin[] = "";
  14. const char apn[] = "apn";
  15. const char login[] = "login";
  16. const char password[] = "password";
  17. GSMSSLClient net;
  18. GPRS gprs;
  19. GSM gsmAccess;
  20. MQTTClient client;
  21. unsigned long lastMillis = 0;
  22. void connect() {
  23. // connection state
  24. bool connected = false;
  25. Serial.print("connecting to cellular network ...");
  26. // After starting the modem with gsmAccess.begin()
  27. // attach to the GPRS network with the APN, login and password
  28. while (!connected) {
  29. if ((gsmAccess.begin(pin) == GSM_READY) &&
  30. (gprs.attachGPRS(apn, login, password) == GPRS_READY)) {
  31. connected = true;
  32. } else {
  33. Serial.print(".");
  34. delay(1000);
  35. }
  36. }
  37. Serial.print("\nconnecting...");
  38. while (!client.connect("arduino", "try", "try")) {
  39. Serial.print(".");
  40. delay(1000);
  41. }
  42. Serial.println("\nconnected!");
  43. client.subscribe("/hello");
  44. // client.unsubscribe("/hello");
  45. }
  46. void messageReceived(String &topic, String &payload) {
  47. Serial.println("incoming: " + topic + " - " + payload);
  48. }
  49. void setup() {
  50. Serial.begin(115200);
  51. // Note: Local domain names (e.g. "Computer.local" on OSX) are not supported by Arduino.
  52. // You need to set the IP address directly.
  53. //
  54. // MQTT brokers usually use port 8883 for secure connections.
  55. client.begin("broker.shiftr.io", 8883, net);
  56. client.onMessage(messageReceived);
  57. connect();
  58. }
  59. void loop() {
  60. client.loop();
  61. if (!client.connected()) {
  62. connect();
  63. }
  64. // publish a message roughly every second.
  65. if (millis() - lastMillis > 1000) {
  66. lastMillis = millis();
  67. client.publish("/hello", "world");
  68. }
  69. }