From 042e59d1c63249a7ec40ce9e33bfd20a6d3417cd Mon Sep 17 00:00:00 2001 From: mreenen Date: Mon, 27 Mar 2023 20:05:59 +0200 Subject: [PATCH] add back the clock --- src/modules/clock.c | 102 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100644 src/modules/clock.c diff --git a/src/modules/clock.c b/src/modules/clock.c new file mode 100644 index 0000000..67931de --- /dev/null +++ b/src/modules/clock.c @@ -0,0 +1,102 @@ +#include +#include +#include +#include + +#include "conf.h" +#include "module.h" +#include "mqtt.h" + +int lastSec = 0; +int lastMin = 0; +int lastHour = 0; + +pthread_t *Thread = NULL; + +void *Worker(void *args); + +void Stop() +{ + printf("DEBUG: clock.Stop()\n"); + if (Thread != NULL) + { + pthread_cancel(*Thread); + free(Thread); + Thread = NULL; + } +} + +void Start() +{ + printf("DEBUG: clock.Start()\n"); + if (Thread != NULL) + { + Stop(); + } + printf("DEBUG: clock.Start(): create thread\n"); + int rc = pthread_create(Thread, NULL, Worker, Thread); + printf("DEBUG: clock.Start(): done %d\n", rc); +} + +Module_t Module_Clock() +{ + Module_t module; + module.Name = "clock"; + module.Start = &Start; + module.Stop = &Stop; + return module; +} + +void sendTick(char* name, struct tm* t) +{ + char topic[100] = BASE_TOPIC "clock/"; + strcat(&topic[0], name); + + char payload[50]; + sprintf(&payload[0], "%04d-%02d-%02dT%02d:%02d:%02d", + t->tm_year, + t->tm_mon + 1, + t->tm_mday, + t->tm_hour, + t->tm_min, + t->tm_sec + ); + printf("topic = %s\n", &topic[0]); + + MQTT_publish(topic, &payload[0], 1); +} + +void *Worker(void *args) +{ + printf("DEBUG: clock.Worker()\n"); + int returnCode = 1; + time_t rowNow; + while (returnCode = 1) + { + time(&rowNow); + struct tm *now = gmtime(&rowNow); + + if (now->tm_sec != lastSec) + { + sendTick("second", now); + lastSec = now->tm_sec; + + if (now->tm_min != lastMin) + { + sendTick("minute", now); + lastMin = now->tm_min; + + if (now->tm_hour != lastHour) + { + sendTick("hour", now); + lastHour = now->tm_hour; + } + } + } + + usleep(500e3); + } + + pthread_exit(0); + return NULL; +}