• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

traintastic / traintastic / 23121060083

15 Mar 2026 10:43PM UTC coverage: 26.616% (-0.005%) from 26.621%
23121060083

push

github

reinder
[cbus] fixed endless loop of RESTP/ESTOP (could potentially also occur with track on/off)

0 of 9 new or added lines in 2 files covered. (0.0%)

1 existing line in 1 file now uncovered.

8246 of 30981 relevant lines covered (26.62%)

185.52 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/server/src/hardware/interface/cbusinterface.cpp
1
/**
2
 * This file is part of Traintastic,
3
 * see <https://github.com/traintastic/traintastic>.
4
 *
5
 * Copyright (C) 2026 Reinder Feenstra
6
 *
7
 * This program is free software; you can redistribute it and/or
8
 * modify it under the terms of the GNU General Public License
9
 * as published by the Free Software Foundation; either version 2
10
 * of the License, or (at your option) any later version.
11
 *
12
 * This program is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU General Public License
18
 * along with this program; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20
 */
21

22
#include "cbusinterface.hpp"
23
#include "cbus/cbussettings.hpp"
24
#include "../decoder/decoderchangeflags.hpp"
25
#include "../decoder/list/decoderlist.hpp"
26
#include "../decoder/list/decoderlisttablemodel.hpp"
27
#include "../input/list/inputlist.hpp"
28
#include "../output/list/outputlist.hpp"
29
#include "../protocol/cbus/cbusconst.hpp"
30
#include "../protocol/cbus/cbuskernel.hpp"
31
#include "../protocol/cbus/iohandler/cbuscanusbiohandler.hpp"
32
#include "../protocol/cbus/iohandler/cbuscanetheriohandler.hpp"
33
#include "../protocol/cbus/iohandler/cbussimulationiohandler.hpp"
34
#include "../protocol/cbus/simulator/cbussimulator.hpp"
35
#include "../protocol/cbus/simulator/module/cbuscancmd.hpp"
36
#include "../../core/attributes.hpp"
37
#include "../../core/eventloop.hpp"
38
#include "../../core/method.tpp"
39
#include "../../core/objectproperty.tpp"
40
#include "../../log/log.hpp"
41
#include "../../log/logmessageexception.hpp"
42
#include "../../utils/displayname.hpp"
43
#include "../../utils/inrange.hpp"
44
#include "../../world/world.hpp"
45

46
constexpr auto decoderListColumns = DecoderListColumn::Id | DecoderListColumn::Name | DecoderListColumn::Address;
47
constexpr auto inputListColumns = InputListColumn::Channel | InputListColumn::Node | InputListColumn::Address;
48
constexpr auto outputListColumns = OutputListColumn::Channel | OutputListColumn::Node | OutputListColumn::Address;
49

50
constexpr auto nodeNumberRange = std::make_pair(std::numeric_limits<uint16_t>::min(), std::numeric_limits<uint16_t>::max());
51
constexpr auto eventNumberRange = std::make_pair(std::numeric_limits<uint16_t>::min(), std::numeric_limits<uint16_t>::max());
52

53
CREATE_IMPL(CBUSInterface)
×
54

55
CBUSInterface::CBUSInterface(World& world, std::string_view _id)
×
56
  : Interface(world, _id)
57
  , DecoderController(*this, decoderListColumns)
58
  , InputController(static_cast<IdObject&>(*this))
59
  , OutputController(static_cast<IdObject&>(*this))
60
  , type{this, "type", CBUSInterfaceType::CANUSB, PropertyFlags::ReadWrite | PropertyFlags::Store,
×
61
      [this](CBUSInterfaceType /*value*/)
×
62
      {
63
        updateVisible();
×
64
      }}
×
65
  , device{this, "device", "", PropertyFlags::ReadWrite | PropertyFlags::Store}
×
66
  , hostname{this, "hostname", "", PropertyFlags::ReadWrite | PropertyFlags::Store}
×
67
  , port{this, "port", 0, PropertyFlags::ReadWrite | PropertyFlags::Store}
×
68
  , cbus{this, "cbus", nullptr, PropertyFlags::ReadOnly | PropertyFlags::Store | PropertyFlags::SubObject}
×
69
{
70
  name = "CBUS/VLCB";
×
71
  cbus.setValueInternal(std::make_shared<CBUSSettings>(*this, cbus.name()));
×
72

73
  Attributes::addDisplayName(type, DisplayName::Interface::type);
×
74
  Attributes::addEnabled(type, !online);
×
75
  Attributes::addValues(type, CBUSInterfaceTypeValues);
×
76
  m_interfaceItems.insertBefore(type, notes);
×
77

78
  Attributes::addEnabled(device, !online);
×
79
  Attributes::addVisible(device, false);
×
80
  m_interfaceItems.insertBefore(device, notes);
×
81

82
  Attributes::addDisplayName(hostname, DisplayName::IP::hostname);
×
83
  Attributes::addEnabled(hostname, !online);
×
84
  Attributes::addVisible(hostname, false);
×
85
  m_interfaceItems.insertBefore(hostname, notes);
×
86

87
  Attributes::addDisplayName(port, DisplayName::IP::port);
×
88
  Attributes::addEnabled(port, !online);
×
89
  Attributes::addVisible(port, false);
×
90
  m_interfaceItems.insertBefore(port, notes);
×
91

92
  m_interfaceItems.insertBefore(cbus, notes);
×
93

94
  m_interfaceItems.insertBefore(decoders, notes);
×
95

96
  m_interfaceItems.insertBefore(inputs, notes);
×
97

98
  m_interfaceItems.insertBefore(outputs, notes);
×
99

100
  m_cbusPropertyChanged = cbus->propertyChanged.connect(
×
101
    [this](BaseProperty& /*property*/)
×
102
    {
103
      if(m_kernel)
×
104
      {
105
        m_kernel->setConfig(cbus->config());
×
106
      }
107
    });
×
108

109
  updateVisible();
×
110
}
×
111

112
CBUSInterface::~CBUSInterface() = default;
×
113

114
bool CBUSInterface::send(std::vector<uint8_t> message)
×
115
{
116
  if(m_kernel)
×
117
  {
118
    return m_kernel->send(std::move(message));
×
119
  }
120
  return false;
×
121
}
122

123
bool CBUSInterface::sendDCC(std::vector<uint8_t> dccPacket, uint8_t repeat)
×
124
{
125
  if(m_kernel)
×
126
  {
127
    return m_kernel->sendDCC(std::move(dccPacket), repeat);
×
128
  }
129
  return false;
×
130
}
131

132
std::span<const DecoderProtocol> CBUSInterface::decoderProtocols() const
×
133
{
134
  static constexpr std::array<DecoderProtocol, 2> protocols{DecoderProtocol::DCCShort, DecoderProtocol::DCCLong};
135
  return std::span<const DecoderProtocol>{protocols.data(), protocols.size()};
×
136
}
137

138
void CBUSInterface::decoderChanged(const Decoder& decoder, DecoderChangeFlags changes, uint32_t functionNumber)
×
139
{
140
  if(m_kernel)
×
141
  {
142
    const bool longAddress = (decoder.protocol == DecoderProtocol::DCCLong);
×
143

144
    if(has(changes, DecoderChangeFlags::FunctionValue) && functionNumber <= CBUS::engineFunctionMax)
×
145
    {
146
      m_kernel->setEngineFunction(
×
147
        decoder.address,
148
        longAddress,
149
        static_cast<uint8_t>(functionNumber),
150
        decoder.getFunctionValue(functionNumber));
×
151
    }
152
    else
153
    {
154
      m_kernel->setEngineSpeedDirection(
×
155
        decoder.address,
156
        longAddress,
157
        Decoder::throttleToSpeedStep<uint8_t>(decoder.throttle, decoder.speedSteps),
×
158
        decoder.speedSteps,
159
        decoder.emergencyStop,
160
        decoder.direction == Direction::Forward);
×
161
    }
162
  }
163
}
×
164

165
std::span<const InputChannel> CBUSInterface::inputChannels() const
×
166
{
167
  static const std::array<InputChannel, 2> channels{
168
    InputChannel::ShortEvent,
169
    InputChannel::LongEvent,
170
  };
171
  return channels;
×
172
}
173

174
bool CBUSInterface::isInputLocation(InputChannel channel, const InputLocation& location) const
×
175
{
176
  if(hasNodeAddressLocation(channel))
×
177
  {
178
    return
179
      inRange<uint32_t>(std::get<InputNodeAddress>(location).node, nodeNumberRange) &&
×
180
      inRange<uint32_t>(std::get<InputNodeAddress>(location).address, inputAddressMinMax(channel));
×
181
  }
182
  return InputController::isInputLocation(channel, location);
×
183
}
184

185
std::pair<uint32_t, uint32_t> CBUSInterface::inputAddressMinMax(InputChannel /*channel*/) const
×
186
{
187
  return eventNumberRange;
×
188
}
189

190
void CBUSInterface::inputSimulateChange(InputChannel channel, const InputLocation& location, SimulateInputAction action)
×
191
{
192
  if(m_simulator)
×
193
  {
194
    m_kernel->ioContext().post(
×
195
      [this, channel, location, action]
×
196
      {
197
        switch(channel)
×
198
        {
199
          case InputChannel::ShortEvent:
×
200
            m_simulator->shortEvent(std::get<InputAddress>(location).address, action);
×
201
            break;
×
202

203
          case InputChannel::LongEvent:
×
204
            m_simulator->longEvent(std::get<InputNodeAddress>(location).node, std::get<InputNodeAddress>(location).address, action);
×
205
            break;
×
206

207
          default: [[unlikely]]
×
208
            assert(false);
×
209
            break;
210
        }
211
      });
×
212
  }
213
}
×
214

215
std::span<const OutputChannel> CBUSInterface::outputChannels() const
×
216
{
217
  static const std::array<OutputChannel, 2> channels{
218
    OutputChannel::ShortEvent,
219
    OutputChannel::LongEvent,
220
    //OutputChannel::AccessoryDCC,
221
    //OutputChannel::DCCext,
222
  };
223
  return channels;
×
224
}
225

226
std::pair<uint32_t, uint32_t> CBUSInterface::outputNodeMinMax(OutputChannel /*channel*/) const
×
227
{
228
  return eventNumberRange;
×
229
}
230

231
std::pair<uint32_t, uint32_t> CBUSInterface::outputAddressMinMax(OutputChannel channel) const
×
232
{
233
  switch(channel)
×
234
  {
235
    case OutputChannel::LongEvent:
×
236
    case OutputChannel::ShortEvent:
237
      return {std::numeric_limits<uint16_t>::min(), std::numeric_limits<uint16_t>::max()};
×
238

239
    default:
×
240
      return OutputController::outputAddressMinMax(channel);
×
241
  }
242
}
243

244
bool CBUSInterface::setOutputValue(OutputChannel channel, const OutputLocation& location, OutputValue value)
×
245
{
246
  if(m_kernel)
×
247
  {
248
    switch(channel)
×
249
    {
250
      case OutputChannel::ShortEvent:
×
251
        if(auto v = std::get<TriState>(value); v != TriState::Undefined)
×
252
        {
253
          const auto address = static_cast<uint16_t>(std::get<OutputAddress>(location).address);
×
254
          m_kernel->setAccessoryShort(address, v == TriState::True);
×
255
          return true;
×
256
        }
257
        break;
×
258

259
      case OutputChannel::LongEvent:
×
260
        if(auto v = std::get<TriState>(value); v != TriState::Undefined)
×
261
        {
262
          const auto node = static_cast<uint16_t>(std::get<OutputNodeAddress>(location).node);
×
263
          const auto address = static_cast<uint16_t>(std::get<OutputNodeAddress>(location).address);
×
264
          m_kernel->setAccessory(node, address, v == TriState::True);
×
265
          return true;
×
266
        }
267
        break;
×
268

269
      default: [[unlikely]]
×
270
        assert(false);
×
271
        break;
272
    }
273
  }
274
  return false;
×
275
}
276

277
void CBUSInterface::addToWorld()
×
278
{
279
  Interface::addToWorld();
×
280
  DecoderController::addToWorld();
×
281
  InputController::addToWorld(inputListColumns);
×
282
  OutputController::addToWorld(outputListColumns);
×
283
}
×
284

285
void CBUSInterface::loaded()
×
286
{
287
  Interface::loaded();
×
288

289
  updateVisible();
×
290
}
×
291

292
void CBUSInterface::destroying()
×
293
{
294
  m_cbusPropertyChanged.disconnect();
×
295
  OutputController::destroying();
×
296
  InputController::destroying();
×
297
  DecoderController::destroying();
×
298
  Interface::destroying();
×
299
}
×
300

301
void CBUSInterface::worldEvent(WorldState state, WorldEvent event)
×
302
{
303
  Interface::worldEvent(state, event);
×
304

305
  switch(event)
×
306
  {
307
    case WorldEvent::PowerOff:
×
308
      if(m_kernel)
×
309
      {
310
        m_kernel->trackOff();
×
311
      }
312
      break;
×
313

314
    case WorldEvent::PowerOn:
×
315
      if(m_kernel)
×
316
      {
317
        m_kernel->trackOn();
×
318
      }
319
      break;
×
320

321
    case WorldEvent::Stop:
×
322
      if(m_kernel)
×
323
      {
324
        m_kernel->requestEmergencyStop();
×
325
      }
326
      break;
×
327

328
    case WorldEvent::Run:
×
329
      if(m_kernel)
×
330
      {
331
        // TODO: send all known speed values
332
      }
333
      break;
×
334

335
    default:
×
336
      break;
×
337
  }
338
}
×
339

340
bool CBUSInterface::setOnline(bool& value, bool simulation)
×
341
{
342
  if(!m_kernel && value)
×
343
  {
344
    try
345
    {
346
      if(simulation)
×
347
      {
348
        m_simulator = std::make_unique<CBUS::Simulator>();
×
349
        m_simulator->addModule(std::make_unique<CBUS::Module::CANCMD>(*m_simulator));
×
350
        m_kernel = CBUS::Kernel::create<CBUS::SimulationIOHandler>(id.value(), cbus->config(), std::ref(*m_simulator));
×
351
      }
352
      else
353
      {
354
        switch(type)
×
355
        {
356
          case CBUSInterfaceType::CANUSB:
×
357
            m_kernel = CBUS::Kernel::create<CBUS::CANUSBIOHandler>(id.value(), cbus->config(), device.value());
×
358
            break;
×
359

360
          case CBUSInterfaceType::CANEther:
×
361
            m_kernel = CBUS::Kernel::create<CBUS::CANEtherIOHandler>(id.value(), cbus->config(), hostname.value(), port.value());
×
362
            break;
×
363
        }
364
      }
365

366
      setState(InterfaceState::Initializing);
×
367

368
      m_kernel->setOnStarted(
×
369
        [this]()
×
370
        {
371
          setState(InterfaceState::Online);
×
372
        });
×
373
      m_kernel->setOnError(
×
374
        [this]()
×
375
        {
376
          setState(InterfaceState::Error);
×
377
          online = false; // communication no longer possible
×
378
        });
×
379
      m_kernel->onTrackOff =
×
380
        [this]()
×
381
        {
NEW
382
          if(contains(m_world.state, WorldState::PowerOn))
×
383
          {
NEW
384
            m_world.powerOff();
×
385
          }
386
        };
×
387
      m_kernel->onTrackOn =
×
388
        [this]()
×
389
        {
NEW
390
          if(!contains(m_world.state, WorldState::PowerOn))
×
391
          {
NEW
392
            m_world.powerOn();
×
393
          }
394
        };
×
395
      m_kernel->onEmergencyStop =
×
396
        [this]()
×
397
        {
NEW
398
          if(contains(m_world.state, WorldState::Run))
×
399
          {
NEW
400
            m_world.stop();
×
401
          }
402
        };
×
403
      m_kernel->onShortEvent =
×
404
        [this](uint16_t eventNumber, bool on)
×
405
        {
406
          updateInputValue(InputChannel::ShortEvent, InputAddress(eventNumber), toTriState(on));
×
407
          updateOutputValue(OutputChannel::ShortEvent, OutputAddress(eventNumber), toTriState(on));
×
408
        };
×
409
      m_kernel->onLongEvent =
×
410
        [this](uint16_t nodeNumber, uint16_t eventNumber, bool on)
×
411
        {
412
          updateInputValue(InputChannel::LongEvent, InputNodeAddress(nodeNumber, eventNumber), toTriState(on));
×
413
          updateOutputValue(OutputChannel::LongEvent, OutputNodeAddress(nodeNumber, eventNumber), toTriState(on));
×
414
        };
×
415

416
      m_kernel->start();
×
417
    }
418
    catch(const LogMessageException& e)
×
419
    {
420
      setState(InterfaceState::Offline);
×
421
      Log::log(*this, e.message(), e.args());
×
422
      return false;
×
423
    }
×
424
  }
425
  else if(m_kernel && !value)
×
426
  {
427
    m_kernel->stop();
×
428
    EventLoop::deleteLater(m_kernel.release());
×
429
    EventLoop::deleteLater(m_simulator.release());
×
430

431
    if(status->state != InterfaceState::Error)
×
432
    {
433
      setState(InterfaceState::Offline);
×
434
    }
435
  }
436
  return true;
×
437
}
438

439
void CBUSInterface::updateVisible()
×
440
{
441
  const bool isSerial = (type == CBUSInterfaceType::CANUSB);
×
442
  Attributes::setVisible(device, isSerial);
×
443

444
  const bool isNetwork = (type == CBUSInterfaceType::CANEther);
×
445
  Attributes::setVisible(hostname, isNetwork);
×
446
  Attributes::setVisible(port, isNetwork);
×
447
}
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc