Skip to content

Instantly share code, notes, and snippets.

@tpoechtrager
Last active May 22, 2019 11:16
Show Gist options
  • Save tpoechtrager/fbe44b0d998c1868860e46f9f43ce8f2 to your computer and use it in GitHub Desktop.
Save tpoechtrager/fbe44b0d998c1868860e46f9f43ce8f2 to your computer and use it in GitHub Desktop.
#include <time.h>
#include <errno.h>
#include <sys/sysctl.h>
#include <stdio.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <string.h>
#include <stdlib.h>
int udp; /* udp fd */
double uptime;
void set_up_udp_sock()
{
struct sockaddr_in sockaddr;
memset(&sockaddr, 0, sizeof(sockaddr));
udp = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (udp < 0) exit(1);
sockaddr.sin_family = AF_INET;
sockaddr.sin_port = htons(4444);
sockaddr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(udp, (struct sockaddr*)&sockaddr, sizeof(sockaddr)) == -1)
exit(1);
}
void process_udp_message(int fd)
{
char msg[1024];
struct sockaddr_in sockaddr;
memset(&sockaddr, 0, sizeof(sockaddr));
socklen_t sockaddr_len = sizeof(struct sockaddr_in);
struct sockaddr *saddr = (struct sockaddr *)&sockaddr;
ssize_t length;
length = recvfrom(fd, msg, sizeof(msg) - 1, 0, saddr, &sockaddr_len);
if (length <= 0) return;
msg[length] = '\0';
int request = atoi(msg);
switch (request)
{
case 0:
{
snprintf(msg, sizeof(msg), "uptime=%lf\n", uptime);
break;
}
}
char msg2[sizeof(msg)];
strcpy(msg2, msg);
length = snprintf(msg, sizeof(msg), "%d\n%s", request, msg2);
if (length <= 0) return;
sendto(fd, msg, length, 0, saddr, sockaddr_len);
}
int process_udp(int wait)
{
fd_set fds;
FD_ZERO(&fds);
FD_SET(udp, &fds);
struct timeval tv;
tv.tv_sec = wait / 1000;
tv.tv_usec = (wait % 1000) * 1000;
int ret = select(udp + 1, &fds, NULL, NULL, &tv);
if (ret > 0)
{
if (FD_ISSET(udp, &fds))
process_udp_message(udp);
}
else if (ret < 0)
{
return -1;
}
return 0;
}
void update()
{
struct timeval boot_time;
struct timeval current_time;
size_t len = sizeof(boot_time);
int mib[2] = { CTL_KERN, KERN_BOOTTIME };
if (sysctl(mib, 2, &boot_time, &len, NULL, 0) >= 0)
{
long long usec;
long long current_usec;
usec = boot_time.tv_sec * 1000000LL;
usec += boot_time.tv_usec;
if (gettimeofday(&current_time, NULL) < 0)
{
uptime = 0.0;
}
else
{
current_usec = current_time.tv_sec * 1000000LL;
current_usec += current_time.tv_usec;
uptime = (current_usec - usec) / 1000000.0;
}
}
else uptime = 0.0;
}
extern float battery_level;
void enable_battery_monitoring();
int main()
{
//enable_battery_monitoring();
if (daemon(0, 0) < 0)
return 1;
set_up_udp_sock();
while (1)
{
if (process_udp(250) < 0)
break;
update();
}
if (udp >= 0)
close(udp);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment