#include #include #include #include #include #include #include #include #include #include #include #include #define SOCKETNAME "/tmp/monitord.socket" #define BACKLOG 4 static int socketfd; void runcommand(int command, int clientfd) { char buf[32]; int total; float rx, tx; float temp; switch(command) { case 0: total = traffic_gettotal(); memcpy(buf, &total, sizeof(int)); send(clientfd, buf, sizeof(int), 0); break; case 1: traffic_getspeeds(&rx, &tx); memcpy(buf, &rx, sizeof(float)); memcpy(buf + sizeof(float), &tx, sizeof(float)); send(clientfd, buf, sizeof(float) * 2, 0); break; case 2: traffic_writetotal(); break; case 3: temp = get_temperature_vesi(); memcpy(buf, &temp, sizeof(float)); send(clientfd, buf, sizeof(float), 0); break; case 4: temp = get_temperature_ulkoilma(); memcpy(buf, &temp, sizeof(float)); send(clientfd, buf, sizeof(float), 0); break; } } void server_handle(int clientfd) { int command; if (recv(clientfd, &command, sizeof(command), MSG_WAITALL) != sizeof(command)) return; runcommand(command, clientfd); } /* Public functions */ void server_initialize() { unlink(SOCKETNAME); struct sockaddr_un servaddr; socketfd = socket(AF_UNIX, SOCK_STREAM, 0); memset(&servaddr, 0, sizeof(servaddr)); servaddr.sun_family = AF_UNIX; strncpy(servaddr.sun_path, SOCKETNAME, 108); if (bind(socketfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) != 0) { perror(SOCKETNAME); exit(1); } listen(socketfd, 4); fcntl(socketfd, F_SETFL, O_NONBLOCK); } void server_do() { int clientfd; while (1) { clientfd = accept(socketfd, NULL, NULL); if (clientfd == -1 && errno == EAGAIN) { // No connections waiting return; } else if (clientfd == -1) { perror("socket_receive"); return; } server_handle(clientfd); close(clientfd); } } void server_dolong(int timeout) { int endtime = time(NULL) + timeout; struct pollfd sfd_poll; sfd_poll.fd = socketfd; sfd_poll.events = POLLIN; while (time(NULL) < endtime) { if (poll(&sfd_poll, 1, endtime - time(NULL))) server_do(); } }