Browse code

Init commit

Richard Cornwell (K9RCP) authored on 03/08/2022 10:13:11
Showing 1 changed files
1 1
new file mode 100644
... ...
@@ -0,0 +1,53 @@
1
+
2
+#include <SPI.h>
3
+#include <EthernetENC.h>
4
+#include <PubSubClient.h>
5
+
6
+// Update these with values suitable for your network.
7
+byte mac[]    = {  0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
8
+IPAddress ip(10, 13, 37, 165); 
9
+byte server[] = {10, 13, 37, 101};
10
+
11
+void callback(char* topic, byte* payload, unsigned int length) {
12
+  // handle message arrived
13
+}
14
+
15
+EthernetClient ethClient;
16
+PubSubClient client(server, 1883, callback, ethClient);
17
+
18
+void setup()
19
+{
20
+  Serial.begin(9600);
21
+  Ethernet.begin(mac, ip);
22
+  client.setBufferSize(255);
23
+ 
24
+}
25
+
26
+void reconnect() {
27
+  // Loop until we're reconnected
28
+  while (!client.connected()) {
29
+    Serial.print("Attempting MQTT connection...");
30
+    // Attempt to connect
31
+    if (client.connect("connectionName", "[[USER]]", "[[PASS]]")) {
32
+      Serial.println("connected");
33
+      // Once connected, publish an announcement...
34
+      client.publish("outTopic","hello world");
35
+      // ... and resubscribe
36
+      client.subscribe("inTopic");
37
+    } else {
38
+      Serial.print("failed, rc=");
39
+      Serial.print(client.state());
40
+      Serial.println(" try again in 5 seconds");
41
+      // Wait 5 seconds before retrying
42
+      delay(5000);
43
+    }
44
+  }
45
+}
46
+
47
+void loop()
48
+{
49
+  if (!client.connected()) {
50
+    reconnect();
51
+  }
52
+  client.loop();
53
+}