AdafruitHuzzahESP8266Secure.ino 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // This example uses an Adafruit Huzzah ESP8266
  2. // 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 <ESP8266WiFi.h>
  10. #include <MQTT.h>
  11. const char ssid[] = "ssid";
  12. const char pass[] = "pass";
  13. WiFiClientSecure net;
  14. MQTTClient client;
  15. unsigned long lastMillis = 0;
  16. void connect() {
  17. Serial.print("checking wifi...");
  18. while (WiFi.status() != WL_CONNECTED) {
  19. Serial.print(".");
  20. delay(1000);
  21. }
  22. Serial.print("\nconnecting...");
  23. while (!client.connect("arduino", "try", "try")) {
  24. Serial.print(".");
  25. delay(1000);
  26. }
  27. Serial.println("\nconnected!");
  28. client.subscribe("/hello");
  29. // client.unsubscribe("/hello");
  30. }
  31. void messageReceived(String &topic, String &payload) {
  32. Serial.println("incoming: " + topic + " - " + payload);
  33. }
  34. void setup() {
  35. Serial.begin(115200);
  36. WiFi.begin(ssid, pass);
  37. // Note: Local domain names (e.g. "Computer.local" on OSX) are not supported by Arduino.
  38. // You need to set the IP address directly.
  39. //
  40. // MQTT brokers usually use port 8883 for secure connections.
  41. client.begin("broker.shiftr.io", 8883, net);
  42. client.onMessage(messageReceived);
  43. connect();
  44. }
  45. void loop() {
  46. client.loop();
  47. delay(10); // <- fixes some issues with WiFi stability
  48. if (!client.connected()) {
  49. connect();
  50. }
  51. // publish a message roughly every second.
  52. if (millis() - lastMillis > 1000) {
  53. lastMillis = millis();
  54. client.publish("/hello", "world");
  55. }
  56. }