ArduinoWiFi101Secure.ino 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // This example uses an Arduino/Genuino Zero together with
  2. // a WiFi101 Shield or a MKR1000 to connect to shiftr.io.
  3. //
  4. // IMPORTANT: This example uses the new WiFi101 library.
  5. //
  6. // IMPORTANT: You need to install/update the SSL certificates first:
  7. // https://github.com/arduino-libraries/WiFi101-FirmwareUpdater#to-update-ssl-certificates
  8. //
  9. // You can check on your device after a successful
  10. // connection here: https://shiftr.io/try.
  11. //
  12. // by Gilberto Conti
  13. // https://github.com/256dpi/arduino-mqtt
  14. #include <WiFi101.h>
  15. #include <MQTT.h>
  16. const char ssid[] = "ssid";
  17. const char pass[] = "pass";
  18. WiFiSSLClient net;
  19. MQTTClient client;
  20. unsigned long lastMillis = 0;
  21. void connect() {
  22. Serial.print("checking wifi...");
  23. while (WiFi.status() != WL_CONNECTED) {
  24. Serial.print(".");
  25. delay(1000);
  26. }
  27. Serial.print("\nconnecting...");
  28. while (!client.connect("arduino", "try", "try")) {
  29. Serial.print(".");
  30. delay(1000);
  31. }
  32. Serial.println("\nconnected!");
  33. client.subscribe("/hello");
  34. // client.unsubscribe("/hello");
  35. }
  36. void messageReceived(String &topic, String &payload) {
  37. Serial.println("incoming: " + topic + " - " + payload);
  38. }
  39. void setup() {
  40. Serial.begin(115200);
  41. WiFi.begin(ssid, pass);
  42. // Note: Local domain names (e.g. "Computer.local" on OSX) are not supported by Arduino.
  43. // You need to set the IP address directly.
  44. //
  45. // MQTT brokers usually use port 8883 for secure connections.
  46. client.begin("broker.shiftr.io", 8883, net);
  47. client.onMessage(messageReceived);
  48. connect();
  49. }
  50. void loop() {
  51. client.loop();
  52. if (!client.connected()) {
  53. connect();
  54. }
  55. // publish a message roughly every second.
  56. if (millis() - lastMillis > 1000) {
  57. lastMillis = millis();
  58. client.publish("/hello", "world");
  59. }
  60. }