polytreewm/services/datetime.c

82 lines
1.3 KiB
C
Raw Normal View History

#include "datetime.h"
2021-11-12 16:48:06 -05:00
#include "../atoms.h"
2021-11-12 06:11:59 -05:00
#include "status.h"
2021-11-12 04:05:43 -05:00
#include <pthread.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
2021-11-12 06:11:59 -05:00
static void datetime_lock();
static void datetime_unlock();
static void *run(void *vargp);
static const char *const default_text = "date & time";
2021-11-12 04:09:03 -05:00
static pthread_mutex_t mutex;
static bool running = false;
static pthread_t thread;
2021-11-12 04:09:03 -05:00
static bool thread_created = false;
static char buffer[DATETIME_BUFFER_SIZE];
2021-11-12 04:09:03 -05:00
void datetime_lock()
{
pthread_mutex_lock(&mutex);
}
void datetime_unlock()
{
pthread_mutex_unlock(&mutex);
}
2021-11-12 04:05:43 -05:00
bool datetime_start()
{
2021-11-12 04:09:03 -05:00
datetime_lock();
if (running) return false;
running = true;
strcpy(buffer, default_text);
2021-11-12 04:05:43 -05:00
2021-11-12 04:09:03 -05:00
thread_created = pthread_create(&thread, NULL, run, NULL) == 0;
2021-11-12 04:05:43 -05:00
2021-11-12 04:09:03 -05:00
datetime_unlock();
2021-11-12 04:05:43 -05:00
2021-11-12 04:09:03 -05:00
return thread_created;
}
void datetime_stop()
{
2021-11-12 04:09:03 -05:00
datetime_lock();
if (!running) return;
running = false;
2021-11-12 04:09:03 -05:00
if (thread_created) pthread_join(thread, NULL);
datetime_unlock();
}
void *run(void *vargp)
{
while (running) {
time_t raw_time;
time(&raw_time);
const struct tm *const time_info = localtime(&raw_time);
datetime_lock();
strftime(buffer, sizeof(buffer), "%a, %e %b %Y, %H:%M:%S", time_info);
datetime_unlock();
2021-11-12 06:11:59 -05:00
status_set_datetime(buffer);
2021-11-12 04:05:43 -05:00
sleep(1);
}
return NULL;
}