Debian Codegraph @

Hardware/Protocols/Z21.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 <cstdint> //int64_t;
22 #include <cstdio> //printf
23 #include <cstdlib> //exit(0);
24 #include <cstring> //memset
25 #include <iostream>
26 #include <sstream>
27 #include <string>
28 #include <thread>
29 #include "Hardware/Protocols/Z21.h"
30 #include "Utils/Integer.h"
31 #include "Utils/Utils.h"
32
33 namespace Hardware
34 {
35 namespace Protocols
36 {
37 Z21::Z21(const HardwareParams* params, const std::string& controlName)
38 : HardwareInterface(params->GetManager(),
39 params->GetControlID(),
40 controlName + " / " + params->GetName() + " at IP " + params->GetArg1(),
41 params->GetName()),
42 run(true),
43 connection(logger, params->GetArg1(), Z21Port),
44 lastProgramMode(ProgramModeMm),
45 connected(false)
46 {
47 logger->Info(Languages::TextStarting, GetFullName());
48
49 if (connection.IsConnected())
50 {
51 logger->Info(Languages::TextSenderSocketCreated);
52 }
53 else
54 {
55 logger->Error(Languages::TextUnableToCreateUdpSocket, params->GetArg1(), Z21Port);
56 }
57 receiverThread = std::thread(&Hardware::Protocols::Z21::Receiver, this);
58 heartBeatThread = std::thread(&Hardware::Protocols::Z21::HeartBeatSender, this);
59 accessorySenderThread = std::thread(&Hardware::Protocols::Z21::AccessorySender, this);
60 }
61
62 Z21::~Z21()
63 {
64 run = false;
65 SendLogOff();
66 accessoryQueue.Terminate();
67 connection.Terminate();
68 accessorySenderThread.join();
69 heartBeatThread.join();
70 receiverThread.join();
71 logger->Info(Languages::TextTerminatingSenderSocket);
72 }
73
74 void Z21::Booster(const BoosterState status)
75 {
76 logger->Info(status ? Languages::TextTurningBoosterOn : Languages::TextTurningBoosterOff);
77 unsigned char buffer[7] = { 0x07, 0x00, 0x40, 0x00, 0x21, 0x80, 0xA1 };
78 buffer[5] |= status;
79 Send(buffer, sizeof(buffer));
80 }
81
82 unsigned char Z21::EncodeSpeed14(const Speed speed)
83 {
84 Speed speedInternal = speed >> 6;
85 switch (speedInternal)
86 {
87 case MinSpeed:
88 return 0x00;
89
90 case 0x0F:
91 return 0x0F;
92
93 default:
94 return speedInternal + 1;
95 }
96 }
97
98 Speed Z21::DecodeSpeed14(unsigned char data)
99 {
100 switch (data)
101 {
102 case 0x00:
103 return MinSpeed;
104
105 case 0x0F:
106 return MaxSpeed;
107
108 default:
109 return (data - 1) << 6;
110 }
111 }
112
113 unsigned char Z21::EncodeSpeed28(const Speed speed)
114 {
115 Speed speedInternal = speed >> 5;
116 switch (speedInternal)
117 {
118 case MinSpeed:
119 return 0x00;
120
121 case 0x1F:
122 return 0x1F;
123
124 default:
125 ++speedInternal;
126 return (speedInternal >> 1 | (speedInternal & 0x01) << 4);
127 }
128 }
129
130 Speed Z21::DecodeSpeed28(unsigned char data)
131 {
132 switch (data)
133 {
134 case 0x00:
135 return MinSpeed;
136
137 case 0x1F:
138 return MaxSpeed;
139
140 default:
141 unsigned char internalData = ((data >> 4) & 0x01) | ((data & 0x0F) << 1);
142 --internalData;
143 return internalData << 5;
144 }
145 }
146
147 unsigned char Z21::EncodeSpeed128(const Speed speed)
148 {
149 Speed speedInternal = speed >> 3;
150 switch (speedInternal)
151 {
152 case MinSpeed:
153 return 0x00;
154
155 case 0x7F:
156 return 0x7F;
157
158 default:
159 return speedInternal + 1;
160 }
161 }
162
163 Speed Z21::DecodeSpeed128(unsigned char data)
164 {
165 switch (data)
166 {
167 case 0x00:
168 return MinSpeed;
169
170 case 0x7F:
171 return MaxSpeed;
172
173 default:
174 return (data - 1) << 3;
175 }
176 }
177
178 void Z21::LocoSpeed(const Protocol protocol, const Address address, const Speed speed)
179 {
180 if (!LocoProtocolSupported(protocol))
181 {
182 return;
183 }
184 Orientation orientation = locoCache.GetOrientation(address);
185 locoCache.SetSpeed(address, speed);
186 LocoSpeedOrientation(protocol, address, speed, orientation);
187 }
188
189 void Z21::LocoOrientation(const Protocol protocol, const Address address, const Orientation orientation)
190 {
191 if (!LocoProtocolSupported(protocol))
192 {
193 return;
194 }
195 Speed speed = locoCache.GetSpeed(address);
196 locoCache.SetOrientation(address, orientation);
197 LocoSpeedOrientation(protocol, address, speed, orientation);
198 }
199
200 void Z21::LocoSpeedOrientation(const Protocol protocol, const Address address, const Speed speed,
201 const Orientation orientation)
202 {
203 if (!LocoProtocolSupported(protocol))
204 {
205 return;
206 }
207 unsigned char buffer[10] = { 0x0A, 0x00, 0x40, 0x00, 0xE4 };
208 switch (protocol)
209 {
210 case ProtocolMM1:
211 case ProtocolDCC14:
212 buffer[5] = 0x10;
213 buffer[8] = EncodeSpeed14(speed);
214 break;
215
216 case ProtocolMM15:
217 case ProtocolDCC28:
218 buffer[5] = 0x12;
219 buffer[8] = EncodeSpeed28(speed);
220 break;
221
222 case ProtocolMM2:
223 case ProtocolDCC128:
224 buffer[5] = 0x13;
225 buffer[8] = EncodeSpeed128(speed);
226 break;
227
228 default:
229 return;
230 }
231 SendSetLocoMode(address, protocol);
232 Utils::Integer::ShortToDataBigEndian(address | 0xC000, buffer + 6);
233 buffer[8] |= static_cast<unsigned char>(orientation) << 7;
234 buffer[9] = buffer[4] ^ buffer[5] ^ buffer[6] ^ buffer[7] ^ buffer[8];
235 Send(buffer, sizeof(buffer));
236 }
237
238 void Z21::LocoFunction(__attribute__ ((unused)) const Protocol protocol,
239 const Address address,
240 const DataModel::LocoFunctionNr function,
241 const DataModel::LocoFunctionState on)
242 {
243 if (!LocoProtocolSupported(protocol))
244 {
245 return;
246 }
247 locoCache.SetFunction(address, function, on);
248 unsigned char buffer[10] = { 0x0A, 0x00, 0x40, 0x00, 0xE4, 0xF8 };
249 Utils::Integer::ShortToDataBigEndian(address | 0xC000, buffer + 6);
250 buffer[8] = (static_cast<unsigned char>(on == DataModel::LocoFunctionStateOn) << 6) | (function & 0x3F);
251 buffer[9] = buffer[4] ^ buffer[5] ^ buffer[6] ^ buffer[7] ^ buffer[8];
252 Send(buffer, sizeof(buffer));
253 }
254
255 void Z21::LocoSpeedOrientationFunctions(const Protocol protocol,
256 const Address address,
257 const Speed speed,
258 const Orientation orientation,
259 std::vector<DataModel::LocoFunctionEntry>& functions)
260 {
261 if (!LocoProtocolSupported(protocol))
262 {
263 return;
264 }
265 locoCache.SetSpeedOrientationProtocol(address, speed, orientation, protocol);
266 LocoSpeedOrientation(protocol, address, speed, orientation);
267 for (const DataModel::LocoFunctionEntry& function : functions)
268 {
269 LocoFunction(protocol, address, function.nr, function.state);
270 }
271 }
272
273 void Z21::Accessory(const Protocol protocol,
274 const Address address,
275 const DataModel::AccessoryState state,
276 __attribute__((unused)) const bool on,
277 const DataModel::AccessoryPulseDuration duration)
278 {
279 AccessoryQueueEntry entry(protocol, address, state, duration);
280 accessoryQueue.EnqueueBack(entry);
281 }
282
283 void Z21::AccessoryOnOrOff(const Address address,
284 const DataModel::AccessoryState state,
285 const bool on)
286 {
287 const Address zeroBasedAddress = address - 1;
288 unsigned char buffer[9] = { 0x09, 0x00, 0x40, 0x00, 0x53 };
289 Utils::Integer::ShortToDataBigEndian(zeroBasedAddress, buffer + 5);
290 buffer[7] = 0x80 | (static_cast<unsigned char>(on) << 3) | static_cast<unsigned char>(state);
291 buffer[8] = buffer[4] ^ buffer[5] ^ buffer[6] ^ buffer[7];
292 Send(buffer, sizeof(buffer));
293 }
294
295 void Z21::AccessorySender()
296 {
297 Utils::Utils::SetThreadName("Z21 Accessory Sender");
298 logger->Info(Languages::TextAccessorySenderThreadStarted);
299 while (run)
300 {
301 AccessoryQueueEntry entry = accessoryQueue.Dequeue();
302 if (entry.protocol == ProtocolNone)
303 {
304 // ProtocolNone is in queue when we should quit
305 continue;
306 }
307 SendSetTurnoutMode(entry.address, entry.protocol);
308 AccessoryOnOrOff(entry.address, entry.state, true);
309 Utils::Utils::SleepForMilliseconds(entry.duration);
310 AccessoryOnOrOff(entry.address, entry.state, false);
311 }
312 logger->Info(Languages::TextTerminatingAccessorySenderThread);
313 }
314
315 void Z21::ProgramRead(const ProgramMode mode, const Address address, const CvNumber cv)
316 {
317 switch (mode)
318 {
319 case ProgramModeDccDirect:
320 logger->Info(Languages::TextProgramDccDirectRead, cv);
321 ProgramDccRead(cv);
322 break;
323
324 case ProgramModeDccPomLoco:
325 logger->Info(Languages::TextProgramDccPomLocoRead, address, cv);
326 ProgramDccPom(Z21Enums::PomLoco, Z21Enums::PomReadByte, address, cv);
327 break;
328
329 case ProgramModeDccPomAccessory:
330 logger->Info(Languages::TextProgramDccPomAccessoryRead, address, cv);
331 ProgramDccPom(Z21Enums::PomAccessory, Z21Enums::PomReadByte, address, cv);
332 break;
333
334 default:
335 return;
336 }
337 lastProgramMode = mode;
338 }
339
340 void Z21::ProgramWrite(const ProgramMode mode, const Address address, const CvNumber cv, const CvValue value)
341 {
342 switch (mode)
343 {
344 case ProgramModeMm:
345 logger->Info(Languages::TextProgramMm, cv, static_cast<int>(value));
346 ProgramMm(cv, value);
347 break;
348
349 case ProgramModeDccDirect:
350 logger->Info(Languages::TextProgramDccDirectWrite, cv, static_cast<int>(value));
351 ProgramDccWrite(cv, value);
352 break;
353
354 case ProgramModeDccPomLoco:
355 logger->Info(Languages::TextProgramDccPomLocoWrite, address, cv, value);
356 ProgramDccPom(Z21Enums::PomLoco, Z21Enums::PomWriteByte, address, cv, value);
357 break;
358
359 case ProgramModeDccPomAccessory:
360 logger->Info(Languages::TextProgramDccPomAccessoryWrite, address, cv, value);
361 ProgramDccPom(Z21Enums::PomAccessory, Z21Enums::PomWriteByte, address, cv, value);
362 break;
363
364 default:
365 return;
366 }
367 lastProgramMode = mode;
368 }
369
370 void Z21::ProgramMm(const CvNumber cv, const CvValue value)
371 {
372 const unsigned char zeroBasedCv = static_cast<unsigned char>((cv - 1) & 0xFF);
373 unsigned char buffer[10] = { 0x0A, 0x00, 0x40, 0x00, 0x24, 0xFF, 0x00, zeroBasedCv, value };
374 buffer[9] = buffer[4] ^ buffer[5] ^ buffer[6] ^ buffer[7] ^ buffer[8];
375 Send(buffer, sizeof(buffer));
376 }
377
378 void Z21::ProgramDccRead(const CvNumber cv)
379 {
380 const CvNumber zeroBasedCv = cv - 1;
381 unsigned char buffer[9] = { 0x09, 0x00, 0x40, 0x00, 0x23, 0x11 };
382 Utils::Integer::ShortToDataBigEndian(zeroBasedCv, buffer + 6);
383 buffer[8] = buffer[4] ^ buffer[5] ^ buffer[6] ^ buffer[7];
384 Send(buffer, sizeof(buffer));
385 }
386
387 void Z21::ProgramDccWrite(const CvNumber cv, const CvValue value)
388 {
389 const CvNumber zeroBasedCv = cv - 1;
390 unsigned char buffer[10] = { 0x0A, 0x00, 0x40, 0x00, 0x24, 0x12 };
391 Utils::Integer::ShortToDataBigEndian(zeroBasedCv, buffer + 6);
392 buffer[8] = value;
393 buffer[9] = buffer[4] ^ buffer[5] ^ buffer[6] ^ buffer[7] ^ buffer[8];
394 Send(buffer, sizeof(buffer));
395 }
396
397 void Z21::ProgramDccPom(const Z21Enums::PomDB0 db0,
398 const Z21Enums::PomOption option,
399 const Address address,
400 const CvNumber cv,
401 const CvValue value)
402 {
403 Address internalAddress = address;
404 if (db0 == Z21Enums::PomAccessory)
405 {
406 internalAddress <<= 4;
407 }
408 const CvNumber OptionAndZeroBasedCv = option | ((cv - 1) & 0x03FF);
409 unsigned char buffer[12] = { 0x0C, 0x00, 0x40, 0x00, 0xE6, db0 };
410 Utils::Integer::ShortToDataBigEndian(internalAddress, buffer + 6);
411 Utils::Integer::ShortToDataBigEndian(OptionAndZeroBasedCv, buffer + 8);
412 buffer[10] = value;
413 buffer[11] = buffer[4] ^ buffer[5] ^ buffer[6] ^ buffer[7] ^ buffer[8] ^ buffer[9] ^ buffer[10];
414 Send(buffer, sizeof(buffer));
415 }
416
417 void Z21::StartUpConnection()
418 {
419 SendGetSerialNumber();
420 SendGetHardwareInfo();
421 SendGetCode();
422 SendBroadcastFlags(static_cast<Z21Enums::BroadCastFlags>(Z21Enums::BroadCastFlagBasic
423 | Z21Enums::BroadCastFlagRBus
424 | Z21Enums::BroadCastFlagAllLoco
425 | Z21Enums::BroadCastFlagCanDetector));
426 SendGetDetectorState();
427 }
428
429 void Z21::HeartBeatSender()
430 {
431 Utils::Utils::SetMinThreadPriority();
432 Utils::Utils::SetThreadName("Z21 Heartbeat Sender");
433 logger->Info(Languages::TextHeartBeatThreadStarted);
434 const unsigned int counterMask = 0x07;
435 unsigned int counter = counterMask;
436 while (run)
437 {
438 Utils::Utils::SleepForSeconds(1);
439 ++counter;
440 counter &= counterMask;
441 if (counter > 0)
442 {
443 continue;
444 }
445 if (connected)
446 {
447 connected = false;
448 }
449 else
450 {
451 StartUpConnection();
452 }
453 SendGetStatus();
454 }
455 logger->Info(Languages::TextTerminatingHeartBeatThread);
456 }
457
458 void Z21::Receiver()
459 {
460 Utils::Utils::SetThreadName("Z21 Receiver");
461 logger->Info(Languages::TextReceiverThreadStarted);
462
463 unsigned char buffer[Z21CommandBufferLength];
464 while (run)
465 {
466 ssize_t dataLength = connection.Receive(buffer, sizeof(buffer));
467
468 if (run == false)
469 {
470 break;
471 }
472
473 if (dataLength < 0)
474 {
475 logger->Error(Languages::TextUnableToReceiveData);
476 break;
477 }
478
479 if (dataLength == 0)
480 {
481 continue;
482 }
483
484 logger->HexIn(buffer, dataLength);
485
486 ssize_t dataRead = 0;
487 while (dataRead < dataLength)
488 {
489 ssize_t ret = ParseData(buffer + dataRead, dataLength - dataRead);
490 if (ret == -1)
491 {
492 break;
493 }
494 dataRead += ret;
495 }
496 }
497 logger->Info(Languages::TextTerminatingReceiverThread);
498 }
499
500 ssize_t Z21::ParseData(const unsigned char* buffer, size_t bufferLength)
501 {
502 unsigned short dataLength = Utils::Integer::DataLittleEndianToShort(buffer);
503 if (dataLength < 4 || dataLength > bufferLength)
504 {
505 return -1;
506 }
507
508 Z21Enums::Header header = static_cast<Z21Enums::Header>(Utils::Integer::DataLittleEndianToShort(buffer + 2));
509 switch (header)
510 {
511 case Z21Enums::HeaderSerialNumber:
512 {
513 unsigned int serialNumber = Utils::Integer::DataLittleEndianToInt(buffer + 4);
514 logger->Info(Languages::TextSerialNumberIs, serialNumber);
515 break;
516 }
517
518 case Z21Enums::HeaderGetCode:
519 switch (buffer[4])
520 {
521 case Z21Enums::FeaturesNotRestricted:
522 logger->Debug(Languages::TextZ21NotRestricted);
523 break;
524
525 case Z21Enums::FeaturesStartLocked:
526 logger->Error(Languages::TextZ21StartLocked);
527 break;
528
529 case Z21Enums::FeaturesStartUnlocked:
530 logger->Debug(Languages::TextZ21StartUnlocked);
531 break;
532
533 default:
534 logger->Debug(Languages::TextZ21RestrictionsUnknown);
535 }
536 break;
537
538 case Z21Enums::HeaderGetHardwareInfo:
539 {
540 unsigned int hardwareType = Utils::Integer::DataLittleEndianToInt(buffer + 4);
541 std::string hardwareTypeText;
542 switch (hardwareType)
543 {
544 case 0x00000200:
545 hardwareTypeText = Languages::GetText(Languages::TextZ21Black2012);
546 break;
547
548 case 0x00000201:
549 hardwareTypeText = Languages::GetText(Languages::TextZ21Black2013);
550 break;
551
552 case 0x00000202:
553 hardwareTypeText = Languages::GetText(Languages::TextZ21SmartRail2012);
554 break;
555
556 case 0x00000203:
557 hardwareTypeText = Languages::GetText(Languages::TextZ21White2013);
558 break;
559
560 case 0x00000204:
561 hardwareTypeText = Languages::GetText(Languages::TextZ21Start2016);
562 break;
563
564 default:
565 hardwareTypeText = Languages::GetText(Languages::TextZ21Unknown);
566 break;
567 }
568
569 unsigned char firmwareVersionMajor = buffer[9];
570 unsigned char firmwareVersionMinor = buffer[8];
571 std::string firmwareVersionText = Utils::Integer::IntegerToBCD(firmwareVersionMajor) + "."
572 + Utils::Integer::IntegerToBCD(firmwareVersionMinor);
573 logger->Info(Languages::TextZ21Type, hardwareTypeText, firmwareVersionText);
574 break;
575 }
576
577 case Z21Enums::HeaderSeeXHeader:
578 ParseXHeader(buffer);
579 break;
580
581 case Z21Enums::HeaderGetBroadcastFlags:
582 logger->Warning(Languages::TextNotImplemented, __FILE__, __LINE__);
583 break;
584
585 case Z21Enums::HeaderGetLocoMode:
586 logger->Warning(Languages::TextNotImplemented, __FILE__, __LINE__);
587 break;
588
589 case Z21Enums::HeaderGetTurnoutMode:
590 logger->Warning(Languages::TextNotImplemented, __FILE__, __LINE__);
591 break;
592
593 case Z21Enums::HeaderRmBusData:
594 ParseRmBusData(buffer);
595 break;
596
597 case Z21Enums::HeaderSystemData:
598 logger->Warning(Languages::TextNotImplemented, __FILE__, __LINE__);
599 break;
600
601 case Z21Enums::HeaderRailComtData:
602 logger->Warning(Languages::TextNotImplemented, __FILE__, __LINE__);
603 break;
604
605 case Z21Enums::HeaderLocoNetRx:
606 case Z21Enums::HeaderLocoNetTx:
607 case Z21Enums::HeaderLocoNetLan:
608 case Z21Enums::HeaderLocoNetDispatch:
609 // we do not parse LocoNet data
610 break;
611
612 case Z21Enums::HeaderLocoNetDetector:
613 ParseLocoNetDetector(buffer);
614 break;
615
616 case Z21Enums::HeaderDetector:
617 ParseDetectorData(buffer);
618 break;
619
620 default:
621 logger->Warning(Languages::TextZ21DoesNotUnderstand);
622 return -1;
623 }
624 return dataLength;
625 }
626
627 void Z21::ParseXHeader(const unsigned char* buffer)
628 {
629 Z21Enums::XHeader xHeader = static_cast<Z21Enums::XHeader>(buffer[4]);
630 switch (xHeader)
631 {
632 case Z21Enums::XHeaderTurnoutInfo:
633 ParseTurnoutData(buffer);
634 break;
635
636 case Z21Enums::XHeaderSeeDB0_2:
637 ParseDB0(buffer);
638 break;
639
640 case Z21Enums::XHeaderStatusChanged:
641 connected = true;
642 break;
643
644 case Z21Enums::XHeaderVersion:
645 logger->Warning(Languages::TextNotImplemented, __FILE__, __LINE__);
646 break;
647
648 case Z21Enums::XHeaderCvResult:
649 ParseCvData(buffer);
650 break;
651
652 case Z21Enums::XHeaderBcStopped:
653 logger->Warning(Languages::TextNotImplemented, __FILE__, __LINE__);
654 break;
655
656 case Z21Enums::XHeaderLocoInfo:
657 ParseLocoData(buffer);
658 break;
659
660 case Z21Enums::XHeaderFirmwareVersion:
661 logger->Warning(Languages::TextNotImplemented, __FILE__, __LINE__);
662 break;
663
664 default:
665 break;
666 }
667 }
668
669 void Z21::ParseDB0(const unsigned char* buffer)
670 {
671 switch (buffer[5])
672 {
673 case Z21Enums::DB0PowerOff:
674 if (buffer[6] != 0x61)
675 {
676 logger->Error(Languages::TextCheckSumError);
677 }
678 logger->Debug(Languages::TextBoosterIsTurnedOff);
679 manager->Booster(ControlTypeHardware, BoosterStateStop);
680 break;
681
682 case Z21Enums::DB0PowerOn:
683 if (buffer[6] != 0x60)
684 {
685 logger->Error(Languages::TextCheckSumError);
686 }
687 logger->Debug(Languages::TextBoosterIsTurnedOn);
688 manager->Booster(ControlTypeHardware, BoosterStateGo);
689 break;
690
691 case Z21Enums::DB0ProgrammingMode:
692 if (buffer[6] != 0x63)
693 {
694 logger->Error(Languages::TextCheckSumError);
695 }
696 logger->Debug(Languages::TextProgrammingMode);
697 manager->Booster(ControlTypeHardware, BoosterStateStop);
698 break;
699
700 case Z21Enums::DB0ShortCircuit:
701 if (buffer[6] != 0x69)
702 {
703 logger->Error(Languages::TextCheckSumError);
704 }
705 logger->Debug(Languages::TextShortCircuit);
706 manager->Booster(ControlTypeInternal, BoosterStateStop);
707 break;
708
709 case Z21Enums::DB0CvShortCircuit:
710 if (buffer[6] != 0x73)
711 {
712 logger->Error(Languages::TextCheckSumError);
713 }
714 logger->Debug(Languages::TextShortCircuit);
715 manager->Booster(ControlTypeInternal, BoosterStateStop);
716 break;
717
718 case Z21Enums::DB0CvNack:
719 if (buffer[6] != 0x72)
720 {
721 logger->Error(Languages::TextCheckSumError);
722 }
723 logger->Debug(Languages::TextNoAnswerFromDecoder);
724 break;
725
726 case Z21Enums::DB0UnknownCommand:
727 logger->Warning(Languages::TextZ21DoesNotUnderstand);
728 break;
729 }
730 }
731
732 void Z21::ParseTurnoutData(const unsigned char* buffer)
733 {
734 DataModel::AccessoryState state;
735 switch (buffer[7])
736 {
737 case 0x01:
738 state = DataModel::AccessoryStateOff;
739 break;
740
741 case 0x02:
742 state = DataModel::AccessoryStateOn;
743 break;
744
745 default:
746 return;
747 }
748 const Address zeroBasedAddress = Utils::Integer::DataBigEndianToShort(buffer + 5);
749 const Address address = zeroBasedAddress + 1;
750 const Protocol protocol = turnoutCache.GetProtocol(address);
751 manager->AccessoryBaseState(ControlTypeHardware, controlID, protocol, address, state);
752 }
753
754 void Z21::ParseLocoData(const unsigned char* buffer)
755 {
756 const Address address = Utils::Integer::DataBigEndianToShort(buffer + 5) & 0x3FFF;
757 const unsigned char protocolType = buffer[7] & 0x07;
758 Protocol protocol;
759 const unsigned char speedData = buffer[8] & 0x7F;
760 Speed newSpeed;
761 Protocol storedProtocol = locoCache.GetProtocol(address);
762 switch (protocolType)
763 {
764 case 0:
765 switch (storedProtocol)
766 {
767 case ProtocolDCC14:
768 protocol = ProtocolDCC14;
769 break;
770
771 case ProtocolMM1:
772 protocol = ProtocolMM1;
773 break;
774
775 default:
776 locoCache.SetProtocol(address, ProtocolDCC14);
777 protocol = ProtocolDCC14;
778 logger->Warning(Languages::TextActualAndStoredProtocolsDiffer, ProtocolSymbols[ProtocolDCC14], ProtocolSymbols[storedProtocol]);
779 break;
780 }
781 newSpeed = DecodeSpeed14(speedData);
782 break;
783
784 case 2:
785 switch (storedProtocol)
786 {
787 case ProtocolDCC28:
788 protocol = ProtocolDCC28;
789 break;
790
791 case ProtocolMM15:
792 protocol = ProtocolMM15;
793 break;
794
795 default:
796 locoCache.SetProtocol(address, ProtocolDCC28);
797 protocol = ProtocolDCC28;
798 logger->Warning(Languages::TextActualAndStoredProtocolsDiffer, ProtocolSymbols[ProtocolDCC28], ProtocolSymbols[storedProtocol]);
799 break;
800 }
801 newSpeed = DecodeSpeed28(speedData);
802 break;
803
804 case 4:
805 switch (storedProtocol)
806 {
807 case ProtocolDCC128:
808 protocol = ProtocolDCC128;
809 break;
810
811 case ProtocolMM2:
812 protocol = ProtocolMM2;
813 break;
814
815 default:
816 locoCache.SetProtocol(address, ProtocolDCC128);
817 protocol = ProtocolDCC128;
818 logger->Warning(Languages::TextActualAndStoredProtocolsDiffer, ProtocolSymbols[ProtocolDCC128], ProtocolSymbols[storedProtocol]);
819 break;
820 }
821 newSpeed = DecodeSpeed128(speedData);
822 break;
823
824 default:
825 return;
826 }
827 const Speed oldSpeed = locoCache.GetSpeed(address);
828 if (newSpeed != oldSpeed)
829 {
830 locoCache.SetSpeed(address, newSpeed);
831 manager->LocoSpeed(ControlTypeHardware, controlID, protocol, address, newSpeed);
832 }
833 const Orientation newOrientation = (buffer[8] >> 7) ? OrientationRight : OrientationLeft;
834 const Orientation oldOrientation = locoCache.GetOrientation(address);
835 if (newOrientation != oldOrientation)
836 {
837 locoCache.SetOrientation(address, newOrientation);
838 manager->LocoOrientation(ControlTypeHardware, controlID, protocol, address, newOrientation);
839 }
840 const uint32_t oldFunctions = locoCache.GetFunctions(address);
841 const uint32_t f0 = (static_cast<uint32_t>(buffer[9]) >> 4) & 0x01;
842 const uint32_t f1_4 = (static_cast<uint32_t>(buffer[9]) << 1) & 0x1E;
843 const uint32_t f5_12 = static_cast<uint32_t>(buffer[10]) << 5;
844 const uint32_t f13_20 = static_cast<uint32_t>(buffer[11]) << 13;
845 const uint32_t f21_28 = static_cast<uint32_t>(buffer[12]) << 21;
846 const uint32_t newFunctions = f0 | f1_4 | f5_12 | f13_20 | f21_28;
847 if (newFunctions == oldFunctions)
848 {
849 return;
850 }
851 const uint32_t functionsDiff = newFunctions ^ oldFunctions;
852 for (DataModel::LocoFunctionNr function = 0; function <= 28; ++function)
853 {
854 const bool stateChange = (functionsDiff >> function) & 0x01;
855 if (stateChange == false)
856 {
857 continue;
858 }
859 const DataModel::LocoFunctionState newState =
860 ((newFunctions >> function) & 0x01 ? DataModel::LocoFunctionStateOn :
861 DataModel::LocoFunctionStateOff);
862 locoCache.SetFunction(address, function, newState);
863 manager->LocoFunctionState(ControlTypeHardware, controlID, protocol, address, function, newState);
864 }
865 }
866
867 void Z21::ParseCvData(const unsigned char* buffer)
868 {
869 if (buffer[5] != 0x14)
870 {
871 logger->Error(Languages::TextCheckSumError);
872 return;
873 }
874 if (lastProgramMode == ProgramModeMm)
875 {
876 return;
877 }
878 const CvNumber cv = Utils::Integer::DataBigEndianToShort(buffer + 6) + 1;
879 const CvValue value = buffer[8];
880 logger->Debug(Languages::TextProgramReadValue, cv, value);
881 manager->ProgramValue(cv, value);
882 }
883
884 void Z21::ParseRmBusData(const unsigned char* buffer)
885 {
886 if (buffer[4] > 1)
887 {
888 return;
889 }
890 unsigned char moduleShift = buffer[4] * 10;
891 for (unsigned char index = 0; index < 10; ++index)
892 {
893 const unsigned char module = index + moduleShift;
894 const unsigned char newData = buffer[5 + index];
895 const unsigned char oldData = feedbackCache.Get(module);
896 if (newData == oldData)
897 {
898 continue;
899 }
900 const unsigned char diff = newData ^ oldData;
901 for (unsigned char pinOnModule = 0; pinOnModule < 8; ++pinOnModule)
902 {
903 const unsigned char pinDiff = (diff >> pinOnModule) & 0x01;
904 if (pinDiff == 0)
905 {
906 continue;
907 }
908 const unsigned char pinData = newData >> pinOnModule;
909 const unsigned char pin = module * 8 + pinOnModule + 1;
910 logger->Info(Languages::TextFeedbackChange, pin, module,
911 Languages::GetOnOff(static_cast<DataModel::Feedback::FeedbackState>(pinData)));
912 manager->FeedbackState(controlID, pin, static_cast<DataModel::Feedback::FeedbackState>(pinData));
913 }
914 feedbackCache.Set(module, newData);
915 }
916 }
917
918 void Z21::ParseLocoNetDetector(const unsigned char* buffer)
919 {
920 if (buffer[4] != 0x01)
921 {
922 // we only parse simple detectors
923 return;
924 }
925 FeedbackPin pin = Utils::Integer::DataLittleEndianToShort(buffer + 5);
926 ++pin;
927 DataModel::Feedback::FeedbackState state = buffer[7] > 0 ? DataModel::Feedback::FeedbackStateOccupied : DataModel::Feedback::FeedbackStateFree;
928 manager->FeedbackState(controlID, pin, state);
929 }
930
931 void Z21::ParseDetectorData(const unsigned char* buffer)
932 {
933 FeedbackPin pin = Utils::Integer::DataLittleEndianToShort(buffer + 6);
934 uint8_t port = buffer[8];
935 --pin;
936 pin <<= 3;
937 pin += port;
938 ++pin;
939 uint8_t type = buffer[9];
940 uint16_t value1 = Utils::Integer::DataLittleEndianToShort(buffer + 10);
941 DataModel::Feedback::FeedbackState state;
942 switch (type)
943 {
944 case 0x01:
945 {
946 value1 >>= 12;
947 value1 &= 0x0001;
948 state = static_cast<DataModel::Feedback::FeedbackState>(value1);
949 break;
950 }
951
952 default:
953 {
954 state =
955 (value1 > 0 ? DataModel::Feedback::FeedbackStateOccupied :
956 DataModel::Feedback::FeedbackStateFree);
957 break;
958 }
959 }
960 manager->FeedbackState(controlID, pin, state);
961 }
962
963 void Z21::SendGetSerialNumber()
964 {
965 char buffer[4] = { 0x04, 0x00, 0x10, 0x00 };
966 Send(buffer, sizeof(buffer));
967 }
968
969 void Z21::SendGetHardwareInfo()
970 {
971 char buffer[4] = { 0x04, 0x00, 0x1A, 0x00 };
972 Send(buffer, sizeof(buffer));
973 }
974
975 void Z21::SendGetStatus()
976 {
977 char buffer[7] = { 0x07, 0x00, 0x40, 0x00, 0x21, 0x24, 0x05 };
978 Send(buffer, sizeof(buffer));
979 }
980
981 void Z21::SendGetCode()
982 {
983 char buffer[4] = { 0x04, 0x00, 0x18, 0x00 };
984 Send(buffer, sizeof(buffer));
985 }
986
987 void Z21::SendGetDetectorState()
988 {
989 unsigned char buffer[7] = { 0x07, 0x00, 0xC4, 0x00, 0x00, 0x00, 0xD0 };
990 Send(buffer, sizeof(buffer));
991 }
992
993 void Z21::SendLogOff()
994 {
995 char buffer[4] = { 0x04, 0x00, 0x30, 0x00 };
996 Send(buffer, sizeof(buffer));
997 }
998
999 void Z21::SendBroadcastFlags()
1000 {
1001 SendBroadcastFlags(static_cast<Z21Enums::BroadCastFlags>(Z21Enums::BroadCastFlagBasic
1002 | Z21Enums::BroadCastFlagRBus
1003 | Z21Enums::BroadCastFlagAllLoco
1004 | Z21Enums::BroadCastFlagCanDetector));
1005 }
1006
1007 void Z21::SendBroadcastFlags(const Z21Enums::BroadCastFlags flags)
1008 {
1009 unsigned char buffer[8] = { 0x08, 0x00, 0x50, 0x00 };
1010 Utils::Integer::IntToDataLittleEndian(flags, buffer + 4);
1011 Send(buffer, sizeof(buffer));
1012 }
1013
1014 void Z21::SendSetMode(const Address address, const Z21Enums::Command command, const Z21Enums::ProtocolMode mode)
1015 {
1016 switch (command)
1017 {
1018 case Z21Enums::CommandSetLocoMode:
1019 case Z21Enums::CommandSetTurnoutMode:
1020 break;
1021
1022 default:
1023 return;
1024 }
1025
1026 switch (mode)
1027 {
1028 case Z21Enums::ProtocolModeMM:
1029 if (address > MaxMMAddress)
1030 {
1031 return;
1032 }
1033 break;
1034
1035 case Z21Enums::ProtocolModeDCC:
1036 break;
1037
1038 default:
1039 return;
1040 }
1041
1042 unsigned char buffer[7] = { 0x07, 0x00, command, 0x00, 0x00, 0x00, mode };
1043 Utils::Integer::ShortToDataBigEndian(address, buffer + 4);
1044 Send(buffer, sizeof(buffer));
1045 }
1046
1047 void Z21::SendSetLocoMode(const Address address, const Protocol protocol)
1048 {
1049 const Protocol storedProtocol = locoCache.GetProtocol(address);
1050 if (storedProtocol == protocol)
1051 {
1052 return;
1053 }
1054 switch (protocol)
1055 {
1056 case ProtocolMM1:
1057 case ProtocolMM15:
1058 case ProtocolMM2:
1059 SendSetLocoModeMM(address);
1060 break;
1061
1062 case ProtocolDCC14:
1063 case ProtocolDCC28:
1064 case ProtocolDCC128:
1065 SendSetLocoModeDCC(address);
1066 break;
1067
1068 default:
1069 return;
1070 }
1071 locoCache.SetProtocol(address, protocol);
1072 }
1073
1074 void Z21::SendSetLocoModeMM(const Address address)
1075 {
1076 SendSetMode(address, Z21Enums::CommandSetLocoMode, Z21Enums::ProtocolModeMM);
1077 }
1078
1079 void Z21::SendSetLocoModeDCC(const Address address)
1080 {
1081 SendSetMode(address, Z21Enums::CommandSetLocoMode, Z21Enums::ProtocolModeDCC);
1082 }
1083
1084 void Z21::SendSetTurnoutMode(const Address address, const Protocol protocol)
1085 {
1086 Protocol storedProtocol = turnoutCache.GetProtocol(address);
1087 if (storedProtocol == protocol)
1088 {
1089 return;
1090 }
1091 switch (protocol)
1092 {
1093 case ProtocolMM:
1094 SendSetTurnoutModeMM(address);
1095 break;
1096
1097 case ProtocolDCC:
1098 SendSetTurnoutModeDCC(address);
1099 break;
1100
1101 default:
1102 return;
1103 }
1104 turnoutCache.SetProtocol(address, protocol);
1105 }
1106
1107 void Z21::SendSetTurnoutModeMM(const Address address)
1108 {
1109 const Address zeroBasedAddress = address - 1;
1110 SendSetMode(zeroBasedAddress, Z21Enums::CommandSetTurnoutMode, Z21Enums::ProtocolModeMM);
1111 }
1112
1113 void Z21::SendSetTurnoutModeDCC(const Address address)
1114 {
1115 const Address zeroBasedAddress = address - 1;
1116 SendSetMode(zeroBasedAddress, Z21Enums::CommandSetTurnoutMode, Z21Enums::ProtocolModeDCC);
1117 }
1118
1119 int Z21::Send(const unsigned char* buffer, const size_t bufferLength)
1120 {
1121 logger->HexOut(buffer, bufferLength);
1122 return connection.Send(buffer, bufferLength);
1123 }
1124 } // namespace
1125 } // namespace