/* To compile : gcc -o TnHserver TnHserver.c */ #include #include #include #include #include #include // The ESP12 is going to send Temperature and Humidity as two strings // into the UDP packet payload on the port 7777 // The maximum payload would be something like this: // |-12.4\0100.0\0| // A smaller packet could look like this: // |15.7\0\056.7\0\0| // The \0 is a byte with all zeros and in the C-language \0 is the string termination. #define BUFLEN 12 #define PORT 7777 int main(void) { struct sockaddr_in si_me, si_client; int udp_sock, nb, slen=sizeof(si_client); char buf[BUFLEN]; char oke[4] = "OK!"; char command[80]; bzero((char *) &si_me, sizeof(si_me)); si_me.sin_family = AF_INET; si_me.sin_port = htons(PORT); si_me.sin_addr.s_addr = htonl(INADDR_ANY); // Create a UDP socket if ((udp_sock=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))<0) { printf("Error opening UDP socket.\n"); exit(1); } // Bind the socket to our IP address and our port if (bind(udp_sock, &si_me, sizeof(si_me))<0) { printf("Error binding UDP socket.\n"); exit(1); } printf("We are listening on: %s:%d\n\n\n",inet_ntoa(si_me.sin_addr), ntohs(si_me.sin_port)); // we enter an endless loop, waiting for UDP packets with the readings... while (1) { // recvfrom is going to wait till our socket has received a packet nb = recvfrom(udp_sock, buf, BUFLEN, 0, &si_client, &slen); if (nb<0) { // if you get a negative number of byte, chances are that the server/socket has a problem. // I send an alert to my gmail account. system("echo \"TnHserver died!\" | mail -s \"RPI TnHserver has crashed!\" user@gmail.com"); close(udp_sock); return 0; } // We're still here so we got a packet, I am not going to do any checks, just send "OK!" back to sender. sendto(udp_sock, oke, 3, 0, &si_client, slen); printf("Received packet from %s:%d\n",inet_ntoa(si_client.sin_addr), ntohs(si_client.sin_port)); printf("Byte: %d\t\tData:>%s:%s<\n", nb, buf, &buf[6]); // Now we create the command line to update the RRD sprintf(command,"/usr/bin/rrdtool update /home/user/data/TnHdatabase.rrd N:%s:%s\n",buf,&buf[6]); // ... and we execute the command! Easy peasy! system(command); // Good practice to clear the buffer once we have registered the values... bzero(buf,BUFLEN); } // If we get here, something must have gone wrong... sending an e-mail alert. system("echo \"TnHserver died!\" | mail -s \"RPI TnHserver has crashed!\" user@gmail.com"); close(udp_sock); return 0; }