diff --git a/readme.md b/readme.md new file mode 100644 index 0000000..e38f349 --- /dev/null +++ b/readme.md @@ -0,0 +1,25 @@ +System of monitoring and controlling heating. + +Modules (called units) send their data via UDP. +Each datagram contains JSON object of following form: +{ + "id": "", + "ip": "", + "v1": "123", + ... +} + +Where ID is unit's identifier (MAC address usually), +IP is unit's current IP address (for server to be able +to contact it). +Other values in object are names and values of sensors +available on the unit. + +Server could send datagram with some commands to unit. +For simplicity datagram is simple string with command and +optional arguments, everything separated with character 0x01. + +Possible commands are: + +1. ping - no arguments. Informs unit that server is still alive +and able to communicate \ No newline at end of file diff --git a/thermo_sensor/thermo_sensor.ino b/thermo_sensor/thermo_sensor.ino index aefa276..b7044aa 100644 --- a/thermo_sensor/thermo_sensor.ino +++ b/thermo_sensor/thermo_sensor.ino @@ -6,12 +6,15 @@ #define DHTPIN 5 #define DHTTYPE DHT22 #define READ_INTERVAL 1000 - +#define UDP_PORT 7000 +#define PING_INTERVAL 60000 // one minute seems to be ok for us WiFiUDP udp; DHT dht(DHTPIN, DHTTYPE); char id[64]; +long last_ping; + void setup() { Serial.begin(115200); @@ -34,6 +37,9 @@ void setup() WiFi.macAddress(macAddr); sprintf(id, "%02x:%02x:%02x:%02x:%02x:%02x", macAddr[0], macAddr[1], macAddr[2], macAddr[3], macAddr[4], macAddr[5]); Serial.printf("Connected, mac address: %s\n", id); + udp.begin(UDP_PORT); + + last_ping = millis(); } char payload[1024]; @@ -73,6 +79,28 @@ void ReadAndSend() udp.endPacket(); } + + +char incoming_packet[4096]; + +void ParseIncomingPacket() +{ + int len = udp.read(incoming_packet, sizeof(incoming_packet)); + if (len == 0) return; + // find command + int pos = 0; + while (pos < len && incoming_packet[pos] != 0x01) pos++; + if (strncmp(incoming_packet, "ping", pos) == 0) + { + Serial.println("Ping command received"); + } + else + { + // unknown command + Serial.println("Unknown command received"); + } +} + unsigned long last_read = 0; void loop() @@ -83,4 +111,15 @@ void loop() ReadAndSend(); last_read = current; } + int packetSize = udp.parsePacket(); + if (packetSize) + { + ParseIncomingPacket(); + } + if (current < last_ping || current - last_ping >= PING_INTERVAL) + { + // no pings for long time, reboot + Serial.println("No pings for long time, reboot"); + ESP.restart(); + } }