mains-frequency-counter-stm32/cube/User/Src/networkAbstractionLayer.c

71 lines
2.1 KiB
C
Raw Normal View History

2021-02-16 10:37:09 +01:00
#include <networkAbstractionLayer.h>
2021-02-16 11:01:01 +01:00
#include <PontCoopScheduler.h>
#include <iwdg.h>
#include <logger.h>
2021-02-16 11:18:41 +01:00
#include <sinkStruct.h>
#include <config.h>
2021-02-16 10:37:09 +01:00
2021-02-16 11:44:51 +01:00
#include <networkAbstractionLayer_impl.h>
2021-02-16 11:26:49 +01:00
2021-02-16 10:37:09 +01:00
2021-02-16 11:26:49 +01:00
const uint16_t SINK_PORT = 20169;
2021-02-16 10:37:09 +01:00
2021-02-16 11:04:45 +01:00
static t_seconds seconds = { .seconds = 0, .missedUpdates = 0, .valid = false };
2021-02-16 11:18:41 +01:00
static t_configBlock *config;
2021-02-16 11:01:01 +01:00
static void networkSecondsHandler(void *handle) {
static bool tryAgain = false;
seconds.seconds += 1;
if (! seconds.valid) {
coloredMsg(LOG_YELLOW, "nsh, initially querying time");
2021-02-16 11:26:49 +01:00
uint64_t tmpSeconds = networkSntpQuery();
2021-02-16 11:01:01 +01:00
if (tmpSeconds != 0) {
coloredMsg(LOG_YELLOW, "nsh, success, time is %lu", tmpSeconds);
seconds.seconds = tmpSeconds;
2021-02-16 11:04:45 +01:00
seconds.missedUpdates = 0;
2021-02-16 11:01:01 +01:00
seconds.valid = true;
} else {
coloredMsg(LOG_YELLOW, "nsh, failed");
2021-02-16 11:04:45 +01:00
seconds.missedUpdates += 1;
2021-02-16 11:01:01 +01:00
}
} else if (tryAgain || ((seconds.seconds % 3600) == 0)) {
coloredMsg(LOG_YELLOW, "nsh, periodically querying time");
2021-02-16 11:26:49 +01:00
uint64_t tmpSeconds = networkSntpQuery();
2021-02-16 11:01:01 +01:00
if (tmpSeconds != 0) {
coloredMsg(LOG_YELLOW, "nsh, success, network time is %lu", tmpSeconds);
2021-02-16 11:04:45 +01:00
seconds.missedUpdates = 0;
2021-02-16 11:01:01 +01:00
tryAgain = false;
if (seconds.seconds != tmpSeconds) {
coloredMsg(LOG_YELLOW, "nsh, local time updated");
seconds.seconds = tmpSeconds;
} else {
coloredMsg(LOG_YELLOW, "nsh, local time still in sync");
}
} else {
coloredMsg(LOG_YELLOW, "nsh, failed, trying again ...");
2021-02-16 11:04:45 +01:00
seconds.missedUpdates += 1;
2021-02-16 11:01:01 +01:00
tryAgain = true;
}
}
HAL_IWDG_Refresh(&hiwdg);
}
t_seconds* networkGetSeconds() {
return &seconds;
}
2021-02-16 11:18:41 +01:00
int8_t networkSendMinuteBuffer(t_minuteBuffer *minuteBuffer) {
return networkUdpSend(config->sinkServer, SINK_PORT, minuteBuffer->b, sizeof(minuteBuffer->b));
}
2021-02-16 10:37:09 +01:00
void networkInit() {
2021-02-16 11:44:51 +01:00
networkImplInit();
2021-02-16 11:20:37 +01:00
config = getConfig();
2021-02-16 11:01:01 +01:00
schAdd(networkSecondsHandler, NULL, 0, 1000);
}