Skip to content

Commit

Permalink
Added communication timout reset
Browse files Browse the repository at this point in the history
If no valid message is received for 2sec then Traintastic will reset and power off.
(Release builds only)
  • Loading branch information
reinder committed Sep 8, 2024
1 parent 47148f1 commit b9def86
Showing 1 changed file with 34 additions and 2 deletions.
36 changes: 34 additions & 2 deletions src/traintasticcs/traintasticcs.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,22 @@
#include "messages.hpp"
#include "../s88/s88.hpp"
#include "../xpressnet/xpressnet.hpp"
#include "../utils/time.hpp"

#ifndef NDEBUG
#define DISABLE_COMMUNICATION_TIMEOUT
#endif

static constexpr uint32_t baudrate = 115'200;
#ifndef DISABLE_COMMUNICATION_TIMEOUT
static constexpr uint32_t communicationTimeout = 2'000; // 2 sec
#endif

static uint8_t g_rxBuffer[2 + 255 + 1];
static uint8_t g_rxCount = 0;
#ifndef DISABLE_COMMUNICATION_TIMEOUT
static absolute_time_t g_communicationTimeout = at_the_end_of_time;
#endif

namespace TraintasticCS
{
Expand All @@ -48,6 +60,15 @@ void init()
uart_getc(TRAINTASTIC_CS_UART); // FIXME: why do we receive 0xFF at startup ??
}

static void reset()
{
S88::disable();
XpressNet::disable();
#ifndef DISABLE_COMMUNICATION_TIMEOUT
g_communicationTimeout = at_the_end_of_time;
#endif
}

void process()
{
while(uart_is_readable(TRAINTASTIC_CS_UART))
Expand All @@ -70,6 +91,14 @@ void process()
}
}
}

#ifndef DISABLE_COMMUNICATION_TIMEOUT
if(get_absolute_time() >= g_communicationTimeout)
{
// No communication from the host -> reset
reset();
}
#endif
}

void send(const Message& message)
Expand All @@ -86,15 +115,18 @@ static void received()
{
const auto& message = *reinterpret_cast<const Message*>(g_rxBuffer);

#ifndef DISABLE_COMMUNICATION_TIMEOUT
g_communicationTimeout = make_timeout_time_ms(communicationTimeout);
#endif

switch(message.command)
{
case Command::Reset:
if(message.length != 0)
{
return send(Error(message.command, ErrorCode::InvalidCommandPayload));
}
S88::disable();
XpressNet::disable();
reset();
return send(ResetOk());

case Command::Ping:
Expand Down

0 comments on commit b9def86

Please sign in to comment.