100 lines
2.9 KiB
C
100 lines
2.9 KiB
C
#include <networkAbstractionLayer.h>
|
|
#include <PontCoopScheduler.h>
|
|
#include <iwdg.h>
|
|
#include <logger.h>
|
|
#include <sinkStruct.h>
|
|
#include <config.h>
|
|
|
|
#include <wizHelper.h>
|
|
#include <wizchip_conf.h>
|
|
|
|
|
|
static t_seconds seconds = { .seconds = 0, .missedUpdates = 0, .valid = false };
|
|
static t_configBlock *config;
|
|
|
|
|
|
static void networkSecondsHandler(void *handle) {
|
|
static bool tryAgain = false;
|
|
|
|
seconds.seconds += 1;
|
|
|
|
if (! seconds.valid) {
|
|
coloredMsg(LOG_YELLOW, "nsh, initially querying time");
|
|
uint64_t tmpSeconds = wizSntpQuery();
|
|
if (tmpSeconds != 0) {
|
|
coloredMsg(LOG_YELLOW, "nsh, success, time is %lu", tmpSeconds);
|
|
seconds.seconds = tmpSeconds;
|
|
seconds.missedUpdates = 0;
|
|
seconds.valid = true;
|
|
} else {
|
|
coloredMsg(LOG_YELLOW, "nsh, failed");
|
|
seconds.missedUpdates += 1;
|
|
}
|
|
} else if (tryAgain || ((seconds.seconds % 3600) == 0)) {
|
|
coloredMsg(LOG_YELLOW, "nsh, periodically querying time");
|
|
uint64_t tmpSeconds = wizSntpQuery();
|
|
if (tmpSeconds != 0) {
|
|
coloredMsg(LOG_YELLOW, "nsh, success, network time is %lu", tmpSeconds);
|
|
seconds.missedUpdates = 0;
|
|
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 ...");
|
|
seconds.missedUpdates += 1;
|
|
tryAgain = true;
|
|
}
|
|
}
|
|
|
|
HAL_IWDG_Refresh(&hiwdg);
|
|
}
|
|
|
|
t_seconds* networkGetSeconds() {
|
|
return &seconds;
|
|
}
|
|
|
|
|
|
extern uint8_t SINK_SOCK;
|
|
const uint16_t SINK_PORT = 20169;
|
|
|
|
int8_t networkUdpSend(char *hostname, uint16_t port, uint8_t *buf, uint16_t bufLen) {
|
|
uint8_t sinkAddr[4];
|
|
if (! wizDnsQuery(hostname, sinkAddr)) {
|
|
coloredMsg(LOG_BLUE, "nus, failed to resolve sink server name");
|
|
return -1;
|
|
} else {
|
|
coloredMsg(LOG_BLUE, "nus, sink server at %d.%d.%d.%d", sinkAddr[0], sinkAddr[1], sinkAddr[2], sinkAddr[3]);
|
|
}
|
|
|
|
socket(SINK_SOCK, Sn_MR_UDP, SINK_PORT, 0);
|
|
uint8_t sockState = getSn_SR(SINK_SOCK);
|
|
if (sockState == SOCK_UDP) {
|
|
sendto(SINK_SOCK, buf, bufLen, sinkAddr, SINK_PORT);
|
|
coloredMsg(LOG_BLUE, "nus, sent");
|
|
} else {
|
|
coloredMsg(LOG_BLUE, "nus, socket in unexpected state: %d", sockState);
|
|
return -2;
|
|
}
|
|
|
|
close(SINK_SOCK);
|
|
|
|
return 1;
|
|
}
|
|
|
|
|
|
int8_t networkSendMinuteBuffer(t_minuteBuffer *minuteBuffer) {
|
|
return networkUdpSend(config->sinkServer, SINK_PORT, minuteBuffer->b, sizeof(minuteBuffer->b));
|
|
}
|
|
|
|
void networkInit() {
|
|
static t_configBlock *config;
|
|
|
|
wizInit();
|
|
|
|
schAdd(networkSecondsHandler, NULL, 0, 1000);
|
|
}
|