ArduinoYunSecure.ino 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // This example uses an Arduino Yun or a Yun-Shield
  2. // and the MQTTClient to connect to shiftr.io.
  3. //
  4. // You can check on your device after a successful
  5. // connection here: https://shiftr.io/try.
  6. //
  7. // by Joël Gähwiler
  8. // https://github.com/256dpi/arduino-mqtt
  9. #include <Bridge.h>
  10. #include <BridgeSSLClient.h>
  11. #include <MQTT.h>
  12. BridgeSSLClient net;
  13. MQTTClient client;
  14. unsigned long lastMillis = 0;
  15. void connect() {
  16. Serial.print("connecting...");
  17. while (!client.connect("arduino", "try", "try")) {
  18. Serial.print(".");
  19. delay(1000);
  20. }
  21. Serial.println("\nconnected!");
  22. client.subscribe("/hello");
  23. // client.unsubscribe("/hello");
  24. }
  25. void messageReceived(String &topic, String &payload) {
  26. Serial.println("incoming: " + topic + " - " + payload);
  27. }
  28. void setup() {
  29. Bridge.begin();
  30. Serial.begin(115200);
  31. // Note: Local domain names (e.g. "Computer.local" on OSX) are not supported by Arduino.
  32. // You need to set the IP address directly.
  33. //
  34. // MQTT brokers usually use port 8883 for secure connections.
  35. client.begin("broker.shiftr.io", 8883, net);
  36. client.onMessage(messageReceived);
  37. connect();
  38. }
  39. void loop() {
  40. client.loop();
  41. if (!client.connected()) {
  42. connect();
  43. }
  44. // publish a message roughly every second.
  45. if (millis() - lastMillis > 1000) {
  46. lastMillis = millis();
  47. client.publish("/hello", "world");
  48. }
  49. }