126 lines
2.4 KiB
Arduino
126 lines
2.4 KiB
Arduino
#include "DHT.h"
|
|
#include <ESP8266WiFi.h>
|
|
#include <WiFiUdp.h>
|
|
#include "config.h"
|
|
|
|
#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);
|
|
Serial.println("Initialised...");
|
|
|
|
dht.begin();
|
|
|
|
WiFi.begin(WIFI_NAME, WIFI_PASS);
|
|
Serial.print("Connecting");
|
|
while (WiFi.status() != WL_CONNECTED)
|
|
{
|
|
delay(500);
|
|
Serial.print(".");
|
|
}
|
|
Serial.println();
|
|
|
|
Serial.print("Connected, IP address: ");
|
|
Serial.println(WiFi.localIP());
|
|
uint8_t macAddr[6];
|
|
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];
|
|
|
|
void Convert(float v, char* s)
|
|
{
|
|
if (isnan(v))
|
|
{
|
|
strcpy(s, "null");
|
|
}
|
|
else
|
|
{
|
|
sprintf(s, "%.3f", v);
|
|
}
|
|
}
|
|
|
|
void ReadAndSend()
|
|
{
|
|
float h = dht.readHumidity();
|
|
float t = dht.readTemperature();
|
|
|
|
char h_str[15];
|
|
char t_str[15];
|
|
Convert(h, h_str);
|
|
Convert(t, t_str);
|
|
|
|
int len = snprintf(payload, sizeof(payload), "{\"t\":%s,\"h\":%s,\"id\":\"%s\",\"ip\":\"%s\"}", t_str, h_str, id, WiFi.localIP().toString().c_str());
|
|
Serial.print("Sending payload:\n");
|
|
Serial.println(payload);
|
|
|
|
if (!udp.beginPacket(REMOTE_IP, REMOTE_PORT))
|
|
{
|
|
Serial.println("Error with destination ip or port");
|
|
return;
|
|
}
|
|
udp.write(payload, len);
|
|
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()
|
|
{
|
|
unsigned long current = millis();
|
|
if (current < last_read || current - last_read >= READ_INTERVAL)
|
|
{
|
|
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();
|
|
}
|
|
}
|