Debian Codegraph @

Hardware/Protocols/EsuCAN.cpp

raw symbols SCIP
1 /*
2 RailControl - Model Railway Control Software
3
4 Copyright (c) 2017-2025 by Teddy / Dominik Mahrer - www.railcontrol.org
5
6 RailControl is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 3, or (at your option) any
9 later version.
10
11 RailControl is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
14 See the GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with RailControl; see the file LICENCE. If not see
18 <http://www.gnu.org/licenses/>.
19 */
20
21 #include <deque>
22 #include <cstring>
23
24 #include "DataModel/AccessoryBase.h"
25 #include "Hardware/HardwareInterface.h"
26 #include "Hardware/HardwareParams.h"
27 #include "Hardware/Protocols/EsuCAN.h"
28 #include "Utils/Integer.h"
29
30 using std::deque;
31 using std::string;
32 using std::strlen;
33 using std::to_string;
34
35 namespace Hardware
36 {
37 namespace Protocols
38 {
39 const char* const EsuCAN::CommandActivateBoosterUpdates = "request(1,view)\n";
40 const char* const EsuCAN::CommandQueryLocos = "queryObjects(10,name)\n";
41 const char* const EsuCAN::CommandQueryAccessories = "queryObjects(11,name1,name2,name3)\n";
42 const char* const EsuCAN::CommandQueryFeedbacks = "queryObjects(26,ports)\n";
43
44 EsuCAN::EsuCAN(const HardwareParams* params, const std::string& controlName)
45 : HardwareInterface(params->GetManager(),
46 params->GetControlID(),
47 controlName + " / " + params->GetName() + " at IP " + params->GetArg1(),
48 params->GetName()),
49 run(false),
50 tcp(Network::TcpClient::GetTcpClientConnection(logger, params->GetArg1(), EsuCANPort)),
51 readBufferLength(0),
52 readBufferPosition(0),
53 locoCache(params->GetControlID(), params->GetManager()),
54 accessoryCache(params->GetControlID(), params->GetManager()),
55 feedbackCache(params->GetControlID(), params->GetManager())
56 {
57 logger->Info(Languages::TextStarting, GetFullName());
58 std::memset(feedbackMemory, 0, MaxFeedbackModules);
59 receiverThread = std::thread(&Hardware::Protocols::EsuCAN::Receiver, this);
60 if (!tcp.IsConnected())
61 {
62 return;
63 }
64 SendActivateBoosterUpdates();
65 SendQueryLocos();
66 SendQueryAccessories();
67 SendQueryFeedbacks();
68 }
69
70 EsuCAN::~EsuCAN()
71 {
72 run = false;
73 receiverThread.join();
74 logger->Info(Languages::TextTerminatingSenderSocket);
75 }
76
77 void EsuCAN::LocoSpeed(__attribute__((unused)) const Protocol protocol,
78 const Address address,
79 const Speed speed)
80 {
81 const unsigned int locoId = address + OffsetLocoAddress;
82 SendGetHandle(locoId);
83 const string command = "set(" + to_string(locoId) + ",speed[" + to_string(speed >> 3) + "])\n";
84 Send(command.c_str());
85 }
86
87 void EsuCAN::LocoOrientation(__attribute__((unused)) const Protocol protocol,
88 const Address address,
89 const Orientation orientation)
90 {
91 const unsigned int locoId = address + OffsetLocoAddress;
92 SendGetHandle(locoId);
93 const string command = "set(" + to_string(locoId) + ",dir[" + (orientation == OrientationRight ? "0" : "1") + "])\n";
94 Send(command.c_str());
95 }
96
97 void EsuCAN::LocoFunction(__attribute__((unused)) const Protocol protocol,
98 const Address address,
99 const DataModel::LocoFunctionNr function,
100 const DataModel::LocoFunctionState on)
101 {
102 const unsigned int locoId = address + OffsetLocoAddress;
103 SendGetHandle(locoId);
104 const string command = "set(" + to_string(locoId) + ",func[" + to_string(function) + "," + (on == DataModel::LocoFunctionStateOn ? "1" : "0") + "])\n";
105 Send(command.c_str());
106 }
107
108 void EsuCAN::Accessory(__attribute__((unused)) const Protocol protocol,
109 const Address address,
110 const DataModel::AccessoryState state,
111 const bool on,
112 __attribute__((unused)) const DataModel::AccessoryPulseDuration duration)
113 {
114 if (!on)
115 {
116 return;
117 }
118 const unsigned int accessoryId = address + OffsetAccessoryAddress;
119 SendGetHandle(accessoryId);
120 const string command = "set(" + to_string(accessoryId) + ",state[" + (state ? "0" : "1") + "])\n";
121 Send(command.c_str());
122 }
123
124 void EsuCAN::Send(const char* data)
125 {
126 int ret = tcp.Send(data);
127 if (ret < 0)
128 {
129 logger->Error(Languages::TextUnableToSendDataToControl);
130 }
131 }
132
133 void EsuCAN::Receiver()
134 {
135 Utils::Utils::SetThreadName("EsuCAN");
136 if (!tcp.IsConnected())
137 {
138 return;
139 }
140 logger->Info(Languages::TextReceiverThreadStarted);
141
142 run = true;
143 while (run)
144 {
145 ReadLine();
146
147 if (run == false)
148 {
149 break;
150 }
151
152 if (readBufferLength == 0)
153 {
154 if (errno == ETIMEDOUT)
155 {
156 continue;
157 }
158
159 logger->Error(Languages::TextUnableToReceiveData);
160 break;
161 }
162
163 Parser();
164 }
165 tcp.Terminate();
166 logger->Info(Languages::TextTerminatingReceiverThread);
167 }
168
169 void EsuCAN::ReadLine()
170 {
171 readBufferPosition = 0;
172 readBufferLength = -1;
173 while (true)
174 {
175 int dataLength = tcp.Receive(readBuffer + readBufferPosition, 1);
176 if (dataLength != 1)
177 {
178 readBufferLength = 0;
179 break;
180 }
181 if (readBuffer[readBufferPosition] == '\r')
182 {
183 continue;
184 }
185 if (readBuffer[readBufferPosition] == '\n')
186 {
187 readBufferLength = readBufferPosition;
188 break;
189 }
190 ++readBufferPosition;
191 if (readBufferPosition >= MaxMessageSize)
192 {
193 break;
194 }
195 }
196 readBufferPosition = 0;
197 if (readBufferLength == 0)
198 {
199 return;
200 }
201 logger->HexIn(reinterpret_cast<unsigned char*>(readBuffer), readBufferLength);
202 }
203
204 void EsuCAN::Parser()
205 {
206 if (!CheckAndConsumeChar('<'))
207 {
208 logger->Error(Languages::TextInvalidDataReceived);
209 return;
210 }
211 char type = ReadAndConsumeChar();
212 switch (type)
213 {
214 case 'R':
215 ParseReply();
216 return;
217
218 case 'E':
219 ParseEvent();
220 return;
221
222 default:
223 logger->Error(Languages::TextInvalidDataReceived);
224 return;
225 }
226 }
227
228 void EsuCAN::ParseReply()
229 {
230 if (CompareAndConsume("EPLY", 4) == false)
231 {
232 logger->Error(Languages::TextInvalidDataReceived);
233 return;
234 }
235 SkipWhiteSpace();
236
237 if (Compare(CommandQueryLocos, strlen(CommandQueryLocos) - 1))
238 {
239 ParseQueryLocos();
240 return;
241 }
242
243 if (Compare(CommandQueryAccessories, strlen(CommandQueryAccessories) - 1))
244 {
245 ParseQueryAccessories();
246 return;
247 }
248
249 if (Compare(CommandQueryFeedbacks, strlen(CommandQueryFeedbacks) - 1))
250 {
251 ParseQueryFeedbacks();
252 return;
253 }
254
255 ReadLine();
256 while (GetChar() != '<')
257 {
258 // ParseLine()
259 ReadLine();
260 }
261 ParseEndLine();
262 }
263
264 void EsuCAN::ParseQueryLocos()
265 {
266 ReadLine();
267 while (GetChar() != '<')
268 {
269 ParseLocoData();
270 ReadLine();
271 }
272 ParseEndLine();
273 }
274
275 void EsuCAN::ParseQueryAccessories()
276 {
277 ReadLine();
278 while (GetChar() != '<')
279 {
280 ParseAccessoryData();
281 ReadLine();
282 }
283 ParseEndLine();
284 }
285
286 void EsuCAN::ParseQueryFeedbacks()
287 {
288 ReadLine();
289 while (GetChar() != '<')
290 {
291 ParseFeedbackData();
292 ReadLine();
293 }
294 ParseEndLine();
295 }
296
297 void EsuCAN::ParseLocoData()
298 {
299 const unsigned int locoId = ParseInt();
300 const Address address = locoId - OffsetLocoAddress;
301 SendActivateUpdates(locoId);
302
303 string name;
304 while (true)
305 {
306 string option;
307 string value;
308 ParseOption(option, value);
309 if (option.size() == 0)
310 {
311 break;
312 }
313
314 if (option.compare("name") == 0)
315 {
316 name = value;
317 }
318 }
319
320 LocoCacheEntry cacheEntry(locoCache.GetControlId());
321 cacheEntry.SetMatchKey(locoId);
322 cacheEntry.SetProtocol(ProtocolServer);
323 cacheEntry.SetAddress(address);
324 cacheEntry.SetName(name);
325 locoCache.Save(cacheEntry);
326
327 logger->Info(Languages::TextFoundLocoInEcosDatabase, address, name);
328 }
329
330 void EsuCAN::ParseAccessoryData()
331 {
332 const unsigned int accessoryId = ParseInt();
333 const Address address = accessoryId - OffsetAccessoryAddress;
334 SendActivateUpdates(accessoryId);
335
336 string name;
337 string name2;
338 string name3;
339 while (true)
340 {
341 string option;
342 string value;
343 ParseOption(option, value);
344 if (option.size() == 0)
345 {
346 break;
347 }
348
349 if (option.compare("name1") == 0)
350 {
351 name = value;
352 }
353 else if (option.compare("name2") == 0)
354 {
355 name2 = value;
356 }
357 else if (option.compare("name3") == 0)
358 {
359 name3 = value;
360 }
361 }
362
363 AccessoryCacheEntry cacheEntry(accessoryCache.GetControlId());
364 cacheEntry.SetMatchKey(accessoryId);
365 cacheEntry.SetProtocol(ProtocolServer);
366 cacheEntry.SetAddress(address);
367
368 if (name2.size())
369 {
370 name += " " + name2;
371 }
372 if (name3.size())
373 {
374 name += " " + name3;
375 }
376 cacheEntry.SetName(name);
377 accessoryCache.Save(cacheEntry);
378
379 logger->Info(Languages::TextFoundAccessoryInEcosDatabase, address, name, name2, name3);
380 }
381
382 void EsuCAN::ParseFeedbackData()
383 {
384 const int moduleId = ParseInt();
385 const int moduleIdHuman = moduleId - OffsetFeedbackModuleAddress;
386 const int moduleIdMachine = moduleId - OffsetFeedbackModuleAddress - 1;
387 SendActivateUpdates(moduleId);
388
389 int ports = 0;
390 string name;
391 while (true)
392 {
393 string option;
394 string value;
395 ParseOption(option, value);
396 if (option.size() == 0)
397 {
398 break;
399 }
400
401 if (option.compare("ports") == 0)
402 {
403 ports = Utils::Integer::StringToInteger(value, 16);
404 name = "Module " + Utils::Utils::ToStringWithLeadingZeros(moduleIdHuman, 3) + " Pin ";
405 }
406 }
407
408 FeedbackCacheEntry cacheEntry(feedbackCache.GetControlId());
409 for (int pinOfModule = 1; pinOfModule <= ports; ++pinOfModule)
410 {
411 int pin = (moduleIdMachine * 16) + pinOfModule;
412 const string pinAsText = Utils::Utils::ToStringWithLeadingZeros(pinOfModule, 2);
413 cacheEntry.SetMatchKey(to_string(moduleId) + "/" + pinAsText);
414 cacheEntry.SetFeedbackID(FeedbackNone);
415 cacheEntry.SetPin(pin);
416 cacheEntry.SetName(name + pinAsText);
417 feedbackCache.Save(cacheEntry);
418 }
419
420 logger->Info(Languages::TextFoundFeedbackModuleInEcosDatabase, moduleIdHuman);
421 }
422
423 void EsuCAN::ParseOption(string& option, string& value)
424 {
425 SkipWhiteSpace();
426 option = ReadUntilChar('[');
427 if (!CheckAndConsumeChar('['))
428 {
429 return;
430 }
431 if (GetChar() == '"')
432 {
433 CheckAndConsumeChar('"');
434 value = ReadUntilChar('"');
435 CheckAndConsumeChar('"');
436 }
437 else
438 {
439 value = ReadUntilChar(']');
440 }
441 CheckAndConsumeChar(']');
442 }
443
444 void EsuCAN::ParseOptionInt(string& option, int& value)
445 {
446 string stringValue;
447 ParseOption(option, stringValue);
448 value = Utils::Integer::StringToInteger(stringValue, 0);
449 }
450
451 void EsuCAN::ParseOptionHex(string& option, int& value)
452 {
453 string stringValue;
454 ParseOption(option, stringValue);
455 value = Utils::Integer::HexToInteger(stringValue, 0);
456 }
457
458 void EsuCAN::ParseEvent()
459 {
460 if (CompareAndConsume("VENT", 4) == false)
461 {
462 logger->Error(Languages::TextInvalidDataReceived);
463 return;
464 }
465 ParseInt();
466 if (CheckGraterThenAtLineEnd() == false)
467 {
468 logger->Error(Languages::TextInvalidDataReceived);
469 return;
470 }
471 while (true)
472 {
473 ReadLine();
474 if (GetChar() == '<')
475 {
476 ParseEndLine();
477 return;
478 }
479 ParseEventLine();
480 }
481 }
482
483 void EsuCAN::ParseEventLine()
484 {
485 int object = ParseInt();
486 SkipWhiteSpace();
487
488 if (object >= MinAccessoryId)
489 {
490 ParseAccessoryEvent(object);
491 return;
492 }
493
494 if (object >= MinLocoId)
495 {
496 ParseLocoEvent(object);
497 return;
498 }
499
500 if (object >= MinFeedbackModuleId)
501 {
502 ParseFeedbackEvent(object);
503 return;
504 }
505
506 if (object == 1)
507 {
508 ParseBoosterEvent();
509 return;
510 }
511
512 string event = ReadUntilLineEnd();
513 logger->HexIn(event);
514 }
515
516 void EsuCAN::ParseBoosterEvent()
517 {
518 if (Compare("status[GO]", 10))
519 {
520 manager->Booster(ControlTypeHardware, BoosterStateGo);
521 }
522 else if (Compare("status[STOP]", 12))
523 {
524 manager->Booster(ControlTypeHardware, BoosterStateStop);
525 }
526 }
527
528 void EsuCAN::ParseLocoEvent(int loco)
529 {
530 const Address address = loco - OffsetLocoAddress;
531 string option;
532 string value;
533 ParseOption(option, value);
534
535 if (option.compare("speed") == 0)
536 {
537 Speed speed = Utils::Integer::StringToInteger(value) << 3;
538 manager->LocoSpeed(ControlTypeHardware, controlID, ProtocolServer, address, speed);
539 return;
540 }
541
542 if (option.compare("dir") == 0)
543 {
544 Orientation orientation = (Utils::Integer::StringToInteger(value) == 1 ? OrientationLeft : OrientationRight);
545 manager->LocoOrientation(ControlTypeHardware, controlID, ProtocolServer, address, orientation);
546 return;
547 }
548
549 if (option.compare("func") == 0)
550 {
551 deque < string > valueList;
552 Utils::Utils::SplitString(value, ",", valueList);
553 if (valueList.size() < 2)
554 {
555 logger->Error(Languages::TextInvalidDataReceived);
556 return;
557 }
558 DataModel::LocoFunctionNr function = Utils::Integer::StringToInteger(valueList[0], 0);
559 DataModel::LocoFunctionState on = Utils::Utils::StringToBool(valueList[1])
560 ? DataModel::LocoFunctionStateOn : DataModel::LocoFunctionStateOff;
561 manager->LocoFunctionState(ControlTypeHardware, controlID, ProtocolServer, address, function, on);
562 return;
563 }
564 }
565
566 void EsuCAN::ParseAccessoryEvent(int accessory)
567 {
568 const Address address = accessory - OffsetAccessoryAddress;
569 string option;
570 int value;
571 ParseOptionInt(option, value);
572
573 if (option.compare("state") == 0)
574 {
575 DataModel::AccessoryState state = (
576 value == 0 ? DataModel::AccessoryStateOn : DataModel::AccessoryStateOff);
577 manager->AccessoryBaseState(ControlTypeHardware, controlID, ProtocolServer, address, state);
578 return;
579 }
580 }
581
582 void EsuCAN::ParseFeedbackEvent(int feedback)
583 {
584 string option;
585 int value;
586 ParseOptionHex(option, value);
587
588 if (option.compare("state") == 0)
589 {
590 unsigned int module1 = (feedback - MinFeedbackModuleId) << 1;
591 unsigned int module2 = module1 + 1;
592 uint8_t moduleData1 = value & 0xFF;
593 uint8_t moduleData2 = (value >> 8) & 0xFF;
594 CheckFeedbackDiff(module1, moduleData1);
595 CheckFeedbackDiff(module2, moduleData2);
596 return;
597 }
598 }
599
600 void EsuCAN::CheckFeedbackDiff(unsigned int module, uint8_t data)
601 {
602 uint8_t oldData = feedbackMemory[module];
603 if (oldData == data)
604 {
605 return;
606 }
607
608 for (unsigned int pin = 0; pin < 8; ++pin)
609 {
610 uint8_t oldPinData = (oldData >> pin) & 0x01;
611 uint8_t pinData = (data >> pin) & 0x01;
612 if (oldPinData == pinData)
613 {
614 continue;
615 }
616 const unsigned int address = (module << 3) + pin + 1;
617 const DataModel::Feedback::FeedbackState state =
618 pinData == 1 ? DataModel::Feedback::FeedbackStateOccupied : DataModel::Feedback::FeedbackStateFree;
619 manager->FeedbackState(controlID, address, state);
620 logger->Info(Languages::TextFeedbackChange, address & 0x000F, address >> 4, state);
621 }
622 feedbackMemory[module] = data;
623 }
624
625 void EsuCAN::ParseEndLine()
626 {
627 if (CompareAndConsume("<END", 4) == false)
628 {
629 logger->Error(Languages::TextInvalidDataReceived);
630 return;
631 }
632 int i = ParseInt();
633 if (i == 0)
634 {
635 return;
636 }
637 SkipWhiteSpace();
638 string error = ReadUntilChar('>');
639 logger->Error(Languages::TextControlReturnedError, error);
640 }
641
642 string EsuCAN::ReadUntilChar(const char c)
643 {
644 string out;
645 while (true)
646 {
647 const char readChar = GetChar();
648 if (readChar == c || readChar == 0)
649 {
650 return out;
651 }
652 out.append(1, ReadAndConsumeChar());
653 }
654 }
655
656 string EsuCAN::ReadUntilLineEnd()
657 {
658 string out = ReadUntilChar('\n');
659 return out;
660 }
661
662 bool EsuCAN::Compare(const char* reference, const size_t size) const
663 {
664 for (size_t index = 0; index < size; ++index)
665 {
666 if (GetChar(index) != reference[index])
667 {
668 return false;
669 }
670 }
671 return true;
672 }
673
674 bool EsuCAN::CompareAndConsume(const char* reference, const size_t size)
675 {
676 for (size_t index = 0; index < size; ++index)
677 {
678 if (ReadAndConsumeChar() != reference[index])
679 {
680 return false;
681 }
682 }
683 return true;
684 }
685
686 bool EsuCAN::SkipOptionalChar(const char charToSkip)
687 {
688 if (charToSkip == GetChar())
689 {
690 ++readBufferPosition;
691 return true;
692 }
693 return false;
694 }
695
696 bool EsuCAN::IsNumber() const
697 {
698 const char c = GetChar();
699 return (c >= '0' && c <= '9');
700 }
701
702 int EsuCAN::ParseInt()
703 {
704 SkipWhiteSpace();
705 int out = 0;
706 while (IsNumber())
707 {
708 out *= 10;
709 out += ReadAndConsumeChar() - '0';
710 }
711 return out;
712 }
713 } // namespace
714 } // namespace