能源管控程序
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

68 lines
1.7 KiB

  1. // This example uses an Arduino Uno together with
  2. // an Ethernet Shield 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 Joël Gähwiler
  8. // https://github.com/256dpi/arduino-mqtt
  9. #include <Ethernet.h>
  10. #include <MQTT.h>
  11. byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
  12. byte ip[] = {192, 168, 1, 177}; // <- change to match your network
  13. EthernetClient net;
  14. MQTTClient client;
  15. unsigned long lastMillis = 0;
  16. void connect() {
  17. Serial.print("connecting...");
  18. while (!client.connect("arduino", "public", "public")) {
  19. Serial.print(".");
  20. delay(1000);
  21. }
  22. Serial.println("\nconnected!");
  23. client.subscribe("/hello");
  24. // client.unsubscribe("/hello");
  25. }
  26. void messageReceived(String &topic, String &payload) {
  27. Serial.println("incoming: " + topic + " - " + payload);
  28. // Note: Do not use the client in the callback to publish, subscribe or
  29. // unsubscribe as it may cause deadlocks when other things arrive while
  30. // sending and receiving acknowledgments. Instead, change a global variable,
  31. // or push to a queue and handle it in the loop after calling `client.loop()`.
  32. }
  33. void setup() {
  34. Serial.begin(115200);
  35. Ethernet.begin(mac, ip);
  36. // Note: Local domain names (e.g. "Computer.local" on OSX) are not supported
  37. // by Arduino. You need to set the IP address directly.
  38. client.begin("public.cloud.shiftr.io", net);
  39. client.onMessage(messageReceived);
  40. connect();
  41. }
  42. void loop() {
  43. client.loop();
  44. if (!client.connected()) {
  45. connect();
  46. }
  47. // publish a message roughly every second.
  48. if (millis() - lastMillis > 1000) {
  49. lastMillis = millis();
  50. client.publish("/hello", "world");
  51. }
  52. }