Debian Codegraph @

Manager.cpp

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 2 — not the installed (fully patched) source.
2 Debian patches touch this file
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 <future>
22 #include <iostream>
23 #include <sstream>
24 #include <unistd.h>
25
26 #include "DataModel/LayoutItem.h"
27 #include "Languages.h"
28 #include "Hardware/HardwareHandler.h"
29 #include "Hardware/HardwareParams.h"
30 #include "Hardware/Protocols/MaerklinCANCommon.h"
31 #include "Manager.h"
32 #include "RailControl.h"
33 #include "Storage/TransactionGuard.h"
34 #include "Utils/Integer.h"
35 #include "Utils/Utils.h"
36 #include "Server/CS2/CS2Server.h"
37 #include "Server/Web/WebServer.h"
38 #include "Server/Z21/Z21Server.h"
39
40 using namespace DataModel;
41 using LayoutPosition = DataModel::LayoutItem::LayoutPosition;
42 using LayoutItemSize = DataModel::LayoutItem::LayoutItemSize;
43 using LayoutRotation = DataModel::LayoutItem::LayoutRotation;
44 using Visible = DataModel::LayoutItem::Visible;
45 using Hardware::HardwareHandler;
46 using Hardware::HardwareParams;
47 using std::map;
48 using std::to_string;
49 using std::string;
50 using std::stringstream;
51 using std::vector;
52 using Storage::TransactionGuard;
53 using Storage::StorageHandler;
54 using Storage::StorageParams;
55
56 Manager::Manager(Config& config)
57 : logger(Logger::Logger::GetLogger(Languages::GetText(Languages::TextManager))),
58 boosterState(BoosterStateStop),
59 storage(nullptr),
60 startupInitLocos(StartupInitLocosAll),
61 defaultAccessoryDuration(DataModel::DefaultAccessoryPulseDuration),
62 autoAddFeedback(false),
63 stopOnFeedbackInFreeTrack(true),
64 executeAccessory(true),
65 selectRouteApproach(DataModel::SelectRouteRandom),
66 nrOfTracksToReserve(DataModel::Loco::ReserveOne),
67 run(false),
68 debounceRun(false),
69 initLocosDone(false),
70 serverEnabled(false),
71 unknownControl(Languages::GetText(Languages::TextControlDoesNotExist)),
72 unknownLoco(Languages::GetText(Languages::TextLocoDoesNotExist)),
73 unknownMultipleUnit(Languages::GetText(Languages::TextMultipleUnitDoesNotExist)),
74 unknownAccessory(Languages::GetText(Languages::TextAccessoryDoesNotExist)),
75 unknownFeedback(Languages::GetText(Languages::TextFeedbackDoesNotExist)),
76 unknownTrack(Languages::GetText(Languages::TextTrackDoesNotExist)),
77 unknownSwitch(Languages::GetText(Languages::TextSwitchDoesNotExist)),
78 unknownRoute(Languages::GetText(Languages::TextRouteDoesNotExist)),
79 unknownSignal(Languages::GetText(Languages::TextSignalDoesNotExist))
80 {
81 StorageParams storageParams;
82 storageParams.module = "Sqlite";
83 storageParams.filename = config.getStringValue("dbfilename", "railcontrol.sqlite");
84 storageParams.keepBackups = config.getIntValue("dbkeepbackups", 10);
85 storage = new StorageHandler(this, &storageParams);
86 if (!storage)
87 {
88 logger->Info(Languages::TextUnableToCreateStorageHandler);
89 return;
90 }
91
92 Logger::Logger::SetLogLevel(static_cast<Logger::Logger::Level>(Utils::Integer::StringToInteger(storage->GetSetting("LogLevel"), Logger::Logger::LevelInfo)));
93 Languages::SetDefaultLanguage(static_cast<Languages::Language>(Utils::Integer::StringToInteger(storage->GetSetting("Language"), Languages::EN)));
94 startupInitLocos = static_cast<StartupInitLocos>(Utils::Integer::StringToInteger(storage->GetSetting("StartupInitLocos"), StartupInitLocosAll));
95 defaultAccessoryDuration = Utils::Integer::StringToInteger(storage->GetSetting("DefaultAccessoryDuration"), 250);
96 autoAddFeedback = Utils::Utils::StringToBool(storage->GetSetting("AutoAddFeedback"));
97 stopOnFeedbackInFreeTrack = Utils::Utils::StringToBool(storage->GetSetting("StopOnFeedbackInFreeTrack"), true);
98 executeAccessory = Utils::Utils::StringToBool(storage->GetSetting("ExecuteAccessory"), true);
99 selectRouteApproach = static_cast<DataModel::SelectRouteApproach>(Utils::Integer::StringToInteger(storage->GetSetting("SelectRouteApproach")));
100 nrOfTracksToReserve = static_cast<DataModel::Loco::NrOfTracksToReserve>(Utils::Integer::StringToInteger(storage->GetSetting("NrOfTracksToReserve"), 2));
101
102 controls[ControlIdWebServer] = new Server::Web::WebServer(*this, config.getStringValue("webserveraddress", "any"), config.getIntValue("webserverport", 8082));
103
104 if (config.getBoolValue("z21server", false))
105 {
106 controls[ControlIdZ21Server] = new Server::Z21::Z21Server(*this, Server::Z21::Z21Server::Z21Port);
107 serverEnabled = true;
108 }
109
110 if (config.getBoolValue("cs2server", false))
111 {
112 controls[ControlIdCS2Server] = new Server::CS2::CS2Server(*this);
113 serverEnabled = true;
114 }
115
116 storage->AllHardwareParams(hardwareParams);
117 for (auto& hardwareParam : hardwareParams)
118 {
119 hardwareParam.second->SetManager(this);
120 controls[hardwareParam.second->GetControlID()] = new HardwareHandler(hardwareParam.second);
121 logger->Info(Languages::TextLoadedControl, hardwareParam.first, hardwareParam.second->GetName());
122 }
123
124 storage->AllLayers(layers);
125 for (auto& layer : layers)
126 {
127 logger->Info(Languages::TextLoadedLayer, layer.second->GetID(), layer.second->GetName());
128 }
129 if (layers.count(LayerUndeletable) != 1)
130 {
131 string result;
132 const bool initLayer1 = LayerSave(0, Languages::GetText(Languages::TextLayer1), result);
133 if (!initLayer1)
134 {
135 logger->Error(Languages::TextUnableToAddLayer1);
136 }
137 }
138
139 storage->AllTexts(texts);
140 for (auto& text : texts)
141 {
142 logger->Info(Languages::TextLoadedText, text.second->GetID(), text.second->GetName());
143 }
144
145 storage->AllAccessories(accessories);
146 for (auto& accessory : accessories)
147 {
148 logger->Info(Languages::TextLoadedAccessory, accessory.second->GetID(), accessory.second->GetName());
149 }
150
151 storage->AllFeedbacks(feedbacks);
152 for (auto& feedback : feedbacks)
153 {
154 logger->Info(Languages::TextLoadedFeedback, feedback.second->GetID(), feedback.second->GetName());
155 }
156
157 storage->AllSignals(signals);
158 for (auto& signal : signals)
159 {
160 logger->Info(Languages::TextLoadedSignal, signal.second->GetID(), signal.second->GetName());
161 }
162
163 storage->AllTracks(tracks);
164 for (auto& t : tracks)
165 {
166 Track* track = t.second;
167 track->UpdateMain();
168 Track* main = track->GetMain();
169 if (main)
170 {
171 main->AddExtension(track);
172 }
173 logger->Info(Languages::TextLoadedTrack, track->GetID(), track->GetName());
174 }
175
176 storage->AllSwitches(switches);
177 for (auto& mySwitch : switches)
178 {
179 logger->Info(Languages::TextLoadedSwitch, mySwitch.second->GetID(), mySwitch.second->GetName());
180 }
181
182 storage->AllClusters(clusters);
183 for (auto& cluster : clusters)
184 {
185 logger->Info(Languages::TextLoadedCluster, cluster.second->GetID(), cluster.second->GetName());
186 }
187
188 storage->AllRoutes(routes);
189 for (auto& route : routes)
190 {
191 logger->Info(Languages::TextLoadedRoute, route.second->GetID(), route.second->GetName());
192 }
193
194 storage->AllLocos(locos);
195 for (auto& loco : locos)
196 {
197 logger->Info(Languages::TextLoadedLoco, loco.second->GetID(), loco.second->GetName());
198 }
199
200 storage->AllMultipleUnits(multipleUnits);
201 for (auto& multipleUnit : multipleUnits)
202 {
203 logger->Info(Languages::TextLoadedMultipleUnit, multipleUnit.second->GetID(), multipleUnit.second->GetName());
204 }
205
206 debounceRun = true;
207 debounceThread = std::thread(&Manager::DebounceWorker, this);
208
209 {
210 std::lock_guard<std::mutex> guard(controlMutex);
211 for (auto& control : controls)
212 {
213 control.second->Start();
214 }
215 }
216
217 run = true;
218 InitLocos();
219 }
220
221 Manager::~Manager()
222 {
223 while (!LocoBaseStopAll())
224 {
225 Utils::Utils::SleepForSeconds(1);
226 }
227
228 debounceRun = false;
229 debounceThread.join();
230
231 Booster(ControlTypeInternal, BoosterStateStop);
232
233 run = false;
234 {
235 std::lock_guard<std::mutex> guard(controlMutex);
236 for (auto& control : controls)
237 {
238 control.second->Stop();
239 }
240 }
241 Utils::Utils::SleepForSeconds(1);
242 {
243 std::lock_guard<std::mutex> guard(controlMutex);
244 for (auto& control : controls)
245 {
246 ControlID controlID = control.first;
247 if (controlID < ControlIdFirstHardware)
248 {
249 delete control.second;
250 continue;
251 }
252 if (hardwareParams.count(controlID) != 1)
253 {
254 continue;
255 }
256 HardwareParams* params = hardwareParams.at(controlID);
257 if (!params)
258 {
259 continue;
260 }
261 logger->Info(Languages::TextUnloadingControl, controlID, params->GetName());
262 delete control.second;
263 hardwareParams.erase(controlID);
264 if (storage)
265 {
266 logger->Info(Languages::TextSaving, params->GetName());
267 TransactionGuard guard(storage);
268 storage->Save(*params);
269 }
270 delete params;
271 }
272 }
273
274 {
275 Storage::TransactionGuard guard(storage);
276 DeleteAllMapEntries(multipleUnits, multipleUnitMutex);
277 DeleteAllMapEntries(locos, locoMutex);
278 DeleteAllMapEntries(routes, routeMutex);
279 DeleteAllMapEntries(clusters, clusterMutex);
280 DeleteAllMapEntries(switches, switchMutex);
281 DeleteAllMapEntries(tracks, trackMutex);
282 DeleteAllMapEntries(signals, signalMutex);
283 DeleteAllMapEntries(feedbacks, feedbackMutex);
284 DeleteAllMapEntries(accessories, accessoryMutex);
285 DeleteAllMapEntries(texts, textMutex);
286 DeleteAllMapEntries(layers, layerMutex);
287 }
288
289 if (!storage)
290 {
291 return;
292 }
293
294 delete storage;
295 storage = nullptr;
296 }
297
298 /***************************
299 * Booster *
300 ***************************/
301
302 void Manager::Booster(const ControlType controlType, const BoosterState state)
303 {
304 if (!run)
305 {
306 return;
307 }
308 boosterState = state;
309 {
310 std::lock_guard<std::mutex> guard(controlMutex);
311 for (auto& control : controls)
312 {
313 control.second->Booster(controlType, state);
314 }
315 }
316
317 if (boosterState != BoosterStateGo || initLocosDone)
318 {
319 return;
320 }
321
322 __attribute__((unused)) auto r = std::async(std::launch::async, InitLocosStatic, this);
323 initLocosDone = true;
324 }
325
326 void Manager::InitLocos()
327 {
328 if (GetStartupInitLocos() == StartupInitLocosNone)
329 {
330 return;
331 }
332 Utils::Utils::SleepForSeconds(1);
333 map<string,LocoID> locoIds = LocoIdsByName();
334 for (auto locoId : locoIds)
335 {
336 if (!run)
337 {
338 return;
339 }
340 Loco* loco = GetLoco(locoId.second);
341 if (!loco)
342 {
343 continue;
344 }
345
346 if (GetStartupInitLocos() == StartupInitLocosSpeed)
347 {
348 std::lock_guard<std::mutex> guard(controlMutex);
349 for (auto& control : controls)
350 {
351 control.second->LocoBaseSpeed(ControlTypeInternal, loco, loco->GetSpeed());
352 control.second->LocoBaseOrientation(ControlTypeInternal, loco, loco->GetOrientation());
353 }
354 }
355 else
356 {
357 std::vector<DataModel::LocoFunctionEntry> functions = loco->GetFunctionStates();
358 std::lock_guard<std::mutex> guard(controlMutex);
359 for (auto& control : controls)
360 {
361 control.second->LocoBaseSpeedOrientationFunctions(loco, loco->GetSpeed(), loco->GetOrientation(), functions);
362 }
363 }
364 Utils::Utils::SleepForMilliseconds(10);
365 }
366 }
367
368 /***************************
369 * Control *
370 ***************************/
371
372 bool Manager::ControlSave(ControlID controlID,
373 const HardwareType& hardwareType,
374 const std::string& name,
375 const std::string& arg1,
376 const std::string& arg2,
377 const std::string& arg3,
378 const std::string& arg4,
379 const std::string& arg5,
380 string& result)
381 {
382 if (controlID != ControlIdNone && controlID < ControlIdFirstHardware)
383 {
384 result = Languages::GetText(Languages::TextInvalidControlID);
385 return false;
386 }
387
388 HardwareParams* params = GetHardware(controlID);
389 bool newControl = false;
390 if (!params)
391 {
392 params = CreateAndAddControl();
393 newControl = true;
394 }
395
396 if (!params)
397 {
398 result = Languages::GetText(Languages::TextUnableToAddControl);
399 return false;
400 }
401
402 // if we have a new object we have to update controlID
403 controlID = params->GetControlID();
404
405 params->SetName(CheckObjectName(hardwareParams, hardwareMutex, controlID, name.size() == 0 ? "C" : name));
406 params->SetHardwareType(hardwareType);
407 params->SetArg1(arg1);
408 params->SetArg2(arg2);
409 params->SetArg3(arg3);
410 params->SetArg4(arg4);
411 params->SetArg5(arg5);
412
413 if (storage)
414 {
415 TransactionGuard guard(storage);
416 storage->Save(*params);
417 }
418
419 if (newControl)
420 {
421 std::lock_guard<std::mutex> Guard(controlMutex);
422 ControlInterface* control = new HardwareHandler(params);
423 if (!control)
424 {
425 return false;
426 }
427 controls[controlID] = control;
428 return true;
429 }
430
431 ControlInterface* control = GetControl(controlID);
432 if (!control)
433 {
434 return false;
435 }
436
437 control->ReInit(params);
438 return true;
439 }
440
441 bool Manager::ControlDelete(ControlID controlID)
442 {
443 {
444 std::lock_guard<std::mutex> guard(hardwareMutex);
445 if (controlID < ControlIdFirstHardware || hardwareParams.count(controlID) != 1)
446 {
447 return false;
448 }
449
450 HardwareParams* params = hardwareParams.at(controlID);
451 if (!params)
452 {
453 return false;
454 }
455 hardwareParams.erase(controlID);
456 delete params;
457 }
458 {
459 std::lock_guard<std::mutex> guard(controlMutex);
460 if (controls.count(controlID) != 1)
461 {
462 return false;
463 }
464 ControlInterface* control = controls.at(controlID);
465 if (!control)
466 {
467 return false;
468 }
469 controls.erase(controlID);
470 delete control;
471 }
472
473 if (storage)
474 {
475 TransactionGuard guard(storage);
476 storage->DeleteHardwareParams(controlID);
477 }
478 return true;
479 }
480
481 HardwareParams* Manager::GetHardware(const ControlID controlID)
482 {
483 std::lock_guard<std::mutex> guard(hardwareMutex);
484 if (hardwareParams.count(controlID) != 1)
485 {
486 return nullptr;
487 }
488 return hardwareParams.at(controlID);
489 }
490
491 unsigned int Manager::ControlsOfHardwareType(const HardwareType hardwareType)
492 {
493 std::lock_guard<std::mutex> guard(hardwareMutex);
494 unsigned int counter = 0;
495 for (auto& hardwareParam : hardwareParams)
496 {
497 if (hardwareParam.second->GetHardwareType() == hardwareType)
498 {
499 ++counter;
500 }
501 }
502 return counter;
503 }
504
505 bool Manager::ControlIsOfHardwareType(const ControlID controlID, const HardwareType hardwareType)
506 {
507 std::lock_guard<std::mutex> guard(hardwareMutex);
508 for (auto& hardwareParam : hardwareParams)
509 {
510 if (hardwareParam.second->GetControlID() != controlID)
511 {
512 continue;
513 }
514 return hardwareParam.second->GetHardwareType() == hardwareType;
515 }
516 return false;
517 }
518
519 ControlInterface* Manager::GetControl(const ControlID controlID) const
520 {
521 std::lock_guard<std::mutex> guard(controlMutex);
522 if (controls.count(controlID) != 1)
523 {
524 return nullptr;
525 }
526 return controls.at(controlID);
527 }
528
529 const std::string Manager::GetControlName(const ControlID controlID)
530 {
531 std::lock_guard<std::mutex> guard(controlMutex);
532 if (controls.count(controlID) != 1)
533 {
534 return unknownControl;
535 }
536 ControlInterface* control = controls.at(controlID);
537 return control->GetName();
538 }
539
540 const std::map<ControlID,std::string> Manager::ControlListNames(const Hardware::Capabilities capability) const
541 {
542 std::map<ControlID,std::string> ret;
543 std::lock_guard<std::mutex> guard(hardwareMutex);
544 for (auto& hardware : hardwareParams)
545 {
546 std::lock_guard<std::mutex> guard2(controlMutex);
547 if (controls.count(hardware.second->GetControlID()) != 1)
548 {
549 continue;
550 }
551 ControlInterface* c = controls.at(hardware.second->GetControlID());
552 if (!c->CanHandle(capability))
553 {
554 continue;
555 }
556 ret[hardware.first] = hardware.second->GetName();
557 }
558 return ret;
559 }
560
561 const map<string,Hardware::HardwareParams*> Manager::ControlListByName() const
562 {
563 map<string,Hardware::HardwareParams*> out;
564 std::lock_guard<std::mutex> guard(hardwareMutex);
565 for (auto& hardware : hardwareParams)
566 {
567 out[hardware.second->GetName()] = hardware.second;
568 }
569 return out;
570 }
571
572 const std::map<std::string, Protocol> Manager::ProtocolsOfControl(const AddressType type, const ControlID controlID) const
573 {
574 std::map<std::string,Protocol> ret;
575 {
576 const ControlInterface* control = GetControl(controlID);
577 if (!control || control->GetControlType() != ControlTypeHardware)
578 {
579 ret[ProtocolSymbols[ProtocolNone]] = ProtocolNone;
580 return ret;
581 }
582
583 const HardwareHandler* hardware = static_cast<const HardwareHandler*>(control);
584 if (hardware->GetControlID() != controlID)
585 {
586 ret[ProtocolSymbols[ProtocolNone]] = ProtocolNone;
587 return ret;
588 }
589
590 std::vector<Protocol> protocols;
591 if (type == AddressTypeLoco)
592 {
593 hardware->LocoProtocols(protocols);
594 }
595 else
596 {
597 hardware->AccessoryProtocols(protocols);
598 }
599 for (auto protocol : protocols)
600 {
601 ret[ProtocolSymbols[protocol]] = protocol;
602 }
603 }
604 return ret;
605 }
606
607 /***************************
608 * Loco *
609 ***************************/
610
611 string Manager::GetLocoList() const
612 {
613 string out;
614 std::lock_guard<std::mutex> guard(locoMutex);
615 for (auto& loco : locos)
616 {
617 Loco* l = loco.second;
618 out += to_string(l->GetID()) + ";";
619 out += to_string(l->GetSpeed()) + ";";
620 out += to_string(l->GetOrientation()) + ";";
621 out += to_string(l->GetTrackId()) + ";";
622 out += l->GetName() + "\n";
623 }
624 return out;
625 }
626
627 Loco* Manager::GetLoco(const LocoID locoID) const
628 {
629 std::lock_guard<std::mutex> guard(locoMutex);
630 if (locos.count(locoID) != 1)
631 {
632 return nullptr;
633 }
634 return locos.at(locoID);
635 }
636
637 LocoConfig Manager::GetLocoOfConfigByMatchKey(const ControlID controlId, const string& matchKey) const
638 {
639 ControlInterface* control = GetControl(controlId);
640 if (!control)
641 {
642 return LocoConfig(LocoTypeLoco);
643 }
644 return control->GetLocoByMatchKey(matchKey);
645 }
646
647 Loco* Manager::GetLocoByMatchKey(const ControlID controlId, const string& matchKey) const
648 {
649 std::lock_guard<std::mutex> guard(locoMutex);
650 for (auto& loco : locos)
651 {
652 Loco* locoConfig = loco.second;
653 if (locoConfig->GetControlID() == controlId && locoConfig->GetMatchKey().compare(matchKey) == 0)
654 {
655 return loco.second;
656 }
657 }
658 return nullptr;
659 }
660
661 void Manager::LocoRemoveMatchKey(const LocoID locoId)
662 {
663 Loco* loco = GetLoco(locoId);
664 if (!loco)
665 {
666 return;
667 }
668 loco->ClearMatchKey();
669 }
670
671 void Manager::LocoReplaceMatchKey(const LocoID locoId, const std::string& newMatchKey)
672 {
673 Loco* loco = GetLoco(locoId);
674 if (!loco)
675 {
676 return;
677 }
678 loco->SetMatchKey(newMatchKey);
679 }
680
681 const map<string,LocoConfig> Manager::GetUnmatchedLocosOfControl(const ControlID controlId,
682 const std::string& matchKey) const
683 {
684 ControlInterface* control = GetControl(controlId);
685 map<string,LocoConfig> out;
686 if (!control || !control->CanHandle(Hardware::CapabilityLocoDatabase))
687 {
688 return out;
689 }
690 out = control->GetUnmatchedLocos(matchKey);
691 out[""].SetName("");
692 return out;
693 }
694
695 Loco* Manager::GetLoco(const ControlID controlID, const Protocol protocol, const Address address) const
696 {
697 std::lock_guard<std::mutex> guard(locoMutex);
698 for (auto& loco : locos)
699 {
700 if (loco.second->GetControlID() == controlID
701 && loco.second->GetProtocol() == protocol
702 && loco.second->GetAddress() == address)
703 {
704 return loco.second;
705 }
706 }
707 return nullptr;
708 }
709
710 const map<string,LocoID> Manager::LocoBaseListFree() const
711 {
712 map<string,LocoID> out;
713 {
714 std::lock_guard<std::mutex> guard(locoMutex);
715 for (auto& loco : locos)
716 {
717 if (!loco.second->IsInUse())
718 {
719 out[loco.second->GetName()] = loco.second->GetID();
720 }
721 }
722 }
723 {
724 std::lock_guard<std::mutex> guard(multipleUnitMutex);
725 for (auto& multipleUnit : multipleUnits)
726 {
727 if (!multipleUnit.second->IsInUse())
728 {
729 out[multipleUnit.second->GetName()] = multipleUnit.second->GetID() + MultipleUnitIdPrefix;
730 }
731 }
732 }
733 return out;
734 }
735
736 const map<string,DataModel::LocoConfig> Manager::LocoConfigByName() const
737 {
738 map<string,DataModel::LocoConfig> out;
739 {
740 std::lock_guard<std::mutex> guard(locoMutex);
741 for (auto& loco : locos)
742 {
743 out[loco.second->GetName()] = *(loco.second);
744 }
745 }
746 std::lock_guard<std::mutex> guard(controlMutex);
747 for (auto& control : controls)
748 {
749 control.second->AddUnmatchedLocos(out);
750 }
751
752 return out;
753 }
754
755 const map<string,LocoID> Manager::LocoIdsByName() const
756 {
757 map<string,LocoID> out;
758 {
759 std::lock_guard<std::mutex> guard(locoMutex);
760 for (auto& loco : locos)
761 {
762 Loco* locoEntry = loco.second;
763 out[locoEntry->GetName()] = locoEntry->GetID();
764 }
765 }
766 return out;
767 }
768
769 bool Manager::LocoSave(LocoID locoID,
770 const string& name,
771 const ControlID controlID,
772 const std::string& matchKey,
773 const Protocol protocol,
774 const Address address,
775 const Address serverAddress,
776 const Length length,
777 const bool pushpull,
778 const Speed maxSpeed,
779 const Speed travelSpeed,
780 const Speed reducedSpeed,
781 const Speed creepingSpeed,
782 const Propulsion propulsion,
783 const TrainType type,
784 const std::vector<DataModel::LocoFunctionEntry>& locoFunctions,
785 string& result)
786 {
787 if (!CheckControlLocoProtocolAddress(controlID, protocol, address, result))
788 {
789 return false;
790 }
791
792 Loco* loco = GetLoco(locoID);
793 if (!loco)
794 {
795 loco = CreateAndAddObject(locos, locoMutex);
796 }
797
798 if (!loco)
799 {
800 result = Languages::GetText(Languages::TextUnableToAddLoco);
801 return false;
802 }
803
804 // if we have a new object we have to update locoID
805 locoID = loco->GetID();
806
807 loco->SetName(CheckObjectName(multipleUnits, multipleUnitMutex, MultipleUnitNone, CheckObjectName(locos, locoMutex, locoID, name.size() == 0 ? "L" : name)));
808 loco->SetControlID(controlID);
809 loco->SetMatchKey(matchKey);
810 loco->SetProtocol(protocol);
811 loco->SetAddress(address);
812 loco->SetServerAddress(serverAddress);
813 loco->SetLength(length);
814 loco->SetPushpull(pushpull);
815 loco->SetMaxSpeed(maxSpeed);
816 loco->SetTravelSpeed(travelSpeed);
817 loco->SetReducedSpeed(reducedSpeed);
818 loco->SetCreepingSpeed(creepingSpeed);
819 loco->SetPropulsion(propulsion);
820 loco->SetTrainType(type);
821 loco->ConfigureFunctions(locoFunctions);
822
823 // save in db
824 LocoSave(loco);
825
826 std::lock_guard<std::mutex> guard(controlMutex);
827 for (auto& control : controls)
828 {
829 control.second->LocoSettings(locoID, name, matchKey);
830 }
831 return true;
832 }
833
834 bool Manager::LocoDelete(const LocoID locoID, string& result)
835 {
836 Loco* loco = nullptr;
837 {
838 std::lock_guard<std::mutex> guard(locoMutex);
839 if (locoID == LocoNone || locos.count(locoID) != 1)
840 {
841 result = Languages::GetText(Languages::TextLocoDoesNotExist);
842 return false;
843 }
844
845 loco = locos.at(locoID);
846 if (!loco)
847 {
848 result = Languages::GetText(Languages::TextLocoDoesNotExist);
849 return false;
850 }
851
852 if (loco->IsInUse())
853 {
854 result = Logger::Logger::Format(Languages::GetText(Languages::TextLocoIsInUse), loco->GetName());
855 return false;
856 }
857
858 locos.erase(locoID);
859 }
860
861 if (storage)
862 {
863 TransactionGuard guard(storage);
864 storage->DeleteLoco(locoID);
865 }
866 const string& name = loco->GetName();
867 const string& matchKey = loco->GetMatchKey();
868 std::lock_guard<std::mutex> guard(controlMutex);
869 for (auto& control : controls)
870 {
871 control.second->LocoDelete(locoID, name, matchKey);
872 }
873 delete loco;
874 return true;
875 }
876
877 bool Manager::LocoProtocolAddress(const LocoID locoID, ControlID& controlID, Protocol& protocol, Address& address) const
878 {
879 std::lock_guard<std::mutex> guard(locoMutex);
880 if (locos.count(locoID) != 1)
881 {
882 controlID = 0;
883 protocol = ProtocolNone;
884 address = 0;
885 return false;
886 }
887 Loco* loco = locos.at(locoID);
888 if (!loco)
889 {
890 return false;
891 }
892 controlID = loco->GetControlID();
893 protocol = loco->GetProtocol();
894 address = loco->GetAddress();
895 return true;
896 }
897
898 bool Manager::LocoBaseSpeed(const ControlType controlType,
899 LocoBase* loco,
900 const Speed speed)
901 {
902 if (!loco)
903 {
904 return false;
905 }
906 Speed newSpeed = speed;
907 if (speed > MaxSpeed)
908 {
909 newSpeed = MaxSpeed;
910 }
911 const string& locoName = loco->GetName();
912 logger->Info(Languages::TextLocoSpeedIs, locoName, newSpeed);
913 const Speed oldSpeed = loco->GetSpeed();
914 if (oldSpeed == newSpeed)
915 {
916 return true;
917 }
918 loco->SetSpeed(newSpeed);
919 std::lock_guard<std::mutex> guard(controlMutex);
920 for (auto& control : controls)
921 {
922 control.second->LocoBaseSpeed(controlType, loco, newSpeed);
923 }
924 return true;
925 }
926
927 Speed Manager::LocoSpeed(const LocoID locoID) const
928 {
929 Loco* loco = GetLoco(locoID);
930 if (!loco)
931 {
932 return MinSpeed;
933 }
934 return loco->GetSpeed();
935 }
936
937 void Manager::LocoBaseOrientation(const ControlType controlType,
938 LocoBase* loco,
939 Orientation orientation)
940 {
941 if (!loco)
942 {
943 return;
944 }
945
946 if (orientation == OrientationChange)
947 {
948 const Orientation oldOrientation = loco->GetOrientation();
949 orientation = (oldOrientation == OrientationLeft ? OrientationRight : OrientationLeft);
950 }
951
952 logger->Info(orientation ? Languages::TextLocoDirectionOfTravelIsRight : Languages::TextLocoDirectionOfTravelIsLeft, loco->GetName());
953 const Orientation oldOrientation = loco->GetOrientation();
954 if (oldOrientation == orientation)
955 {
956 return;
957 }
958 loco->SetOrientation(orientation);
959 std::lock_guard<std::mutex> guard(controlMutex);
960 for (auto& control : controls)
961 {
962 control.second->LocoBaseOrientation(controlType, loco, orientation);
963 }
964 }
965
966 void Manager::LocoBaseFunctionState(const ControlType controlType,
967 const ObjectIdentifier& locoBaseIdentifier,
968 const DataModel::LocoFunctionNr function,
969 const DataModel::LocoFunctionState on)
970 {
971 LocoBase* loco = GetLocoBase(locoBaseIdentifier);
972 if (!loco)
973 {
974 return;
975 }
976
977 DataModel::LocoFunctionNr functionInternal = function;
978 if (function >= NumberOfLocoFunctions)
979 {
980 functionInternal = loco->GetFunctionNumberFromFunctionIcon(static_cast<DataModel::LocoFunctionIcon>(function - 256));
981 }
982 LocoBaseFunctionState(controlType, loco, functionInternal, on);
983 }
984
985 void Manager::LocoBaseFunctionState(const ControlType controlType,
986 LocoBase* loco,
987 const DataModel::LocoFunctionNr function,
988 const DataModel::LocoFunctionState on)
989 {
990 if (!loco)
991 {
992 return;
993 }
994
995 logger->Info(on ? Languages::TextLocoFunctionIsOn : Languages::TextLocoFunctionIsOff, loco->GetName(), function);
996 const DataModel::LocoFunctionState oldOn = loco->GetFunctionState(function);
997 if (oldOn == on)
998 {
999 return;
1000 }
1001 loco->SetFunctionState(function, on);
1002 std::lock_guard<std::mutex> guard(controlMutex);
1003 for (auto& control : controls)
1004 {
1005 control.second->LocoBaseFunction(controlType, loco, function, on);
1006 }
1007 }
1008
1009 /***************************
1010 * MultipleUnit *
1011 ***************************/
1012
1013 MultipleUnit* Manager::GetMultipleUnit(const MultipleUnitID multipleUnitId) const
1014 {
1015 std::lock_guard<std::mutex> guard(multipleUnitMutex);
1016 if (multipleUnits.count(multipleUnitId) != 1)
1017 {
1018 return nullptr;
1019 }
1020 return multipleUnits.at(multipleUnitId);
1021 }
1022
1023 LocoConfig Manager::GetMultipleUnitOfConfigByMatchKey(const ControlID controlId, const string& matchKey) const
1024 {
1025 ControlInterface* control = GetControl(controlId);
1026 if (!control)
1027 {
1028 return LocoConfig(LocoTypeMultipleUnit);
1029 }
1030 return control->GetMultipleUnitByMatchKey(matchKey);
1031 }
1032
1033 const map<string,DataModel::LocoConfig> Manager::MultipleUnitConfigByName() const
1034 {
1035 map<string,DataModel::LocoConfig> out;
1036 {
1037 std::lock_guard<std::mutex> guard(multipleUnitMutex);
1038 for (auto& multipleUnit : multipleUnits)
1039 {
1040 out[multipleUnit.second->GetName()] = *(multipleUnit.second);
1041 }
1042 }
1043 std::lock_guard<std::mutex> guard(controlMutex);
1044 for (auto& control : controls)
1045 {
1046 control.second->AddUnmatchedMultipleUnits(out);
1047 }
1048
1049 return out;
1050 }
1051
1052 bool Manager::MultipleUnitSave(MultipleUnitID multipleUnitID,
1053 const string& name,
1054 const ControlID controlID,
1055 const std::string& matchKey,
1056 const Address address,
1057 const Address serverAddress,
1058 const Length length,
1059 const bool pushpull,
1060 const Speed maxSpeed,
1061 const Speed travelSpeed,
1062 const Speed reducedSpeed,
1063 const Speed creepingSpeed,
1064 const TrainType type,
1065 const std::vector<DataModel::LocoFunctionEntry>& locoFunctions,
1066 const std::vector<DataModel::Relation*>& slaves,
1067 string& result)
1068 {
1069 if (!CheckControlMultipleUnitProtocolAddress(controlID, address, result))
1070 {
1071 return false;
1072 }
1073
1074 MultipleUnit* multipleUnit = GetMultipleUnit(multipleUnitID);
1075 if (!multipleUnit)
1076 {
1077 multipleUnit = CreateAndAddObject(multipleUnits, multipleUnitMutex);
1078 }
1079
1080 if (!multipleUnit)
1081 {
1082 result = Languages::GetText(Languages::TextUnableToAddMultipleUnit);
1083 return false;
1084 }
1085
1086 // if we have a new object we have to update multipleUnitID
1087 if (multipleUnitID == 0)
1088 {
1089 multipleUnitID = multipleUnit->GetID();
1090 for (auto slave : slaves)
1091 {
1092 slave->ObjectID1(multipleUnitID);
1093 }
1094 }
1095
1096 // FIXME: replace "M" with language dependent word
1097 multipleUnit->SetName(CheckObjectName(locos, locoMutex, LocoNone, CheckObjectName(multipleUnits, multipleUnitMutex, multipleUnitID, name.size() == 0 ? "M" : name)));
1098 multipleUnit->SetControlID(controlID);
1099 multipleUnit->SetMatchKey(matchKey);
1100 multipleUnit->SetProtocol(ProtocolNone);
1101 multipleUnit->SetAddress(address);
1102 multipleUnit->SetServerAddress(serverAddress);
1103 multipleUnit->SetLength(length);
1104 multipleUnit->SetPushpull(pushpull);
1105 multipleUnit->SetMaxSpeed(maxSpeed);
1106 multipleUnit->SetTravelSpeed(travelSpeed);
1107 multipleUnit->SetReducedSpeed(reducedSpeed);
1108 multipleUnit->SetCreepingSpeed(creepingSpeed);
1109 multipleUnit->SetTrainType(type);
1110 multipleUnit->ConfigureFunctions(locoFunctions);
1111 multipleUnit->AssignSlaves(slaves);
1112
1113 // save in db
1114 MultipleUnitSave(multipleUnit);
1115
1116 std::lock_guard<std::mutex> guard(controlMutex);
1117 for (auto& control : controls)
1118 {
1119 control.second->MultipleUnitSettings(multipleUnitID, name, matchKey);
1120 }
1121 return true;
1122 }
1123
1124 bool Manager::MultipleUnitDelete(const MultipleUnitID multipleUnitID, string& result)
1125 {
1126 MultipleUnit* multipleUnit = nullptr;
1127 {
1128 std::lock_guard<std::mutex> guard(multipleUnitMutex);
1129 if (multipleUnitID == MultipleUnitNone || multipleUnits.count(multipleUnitID) != 1)
1130 {
1131 result = Languages::GetText(Languages::TextMultipleUnitDoesNotExist);
1132 return false;
1133 }
1134
1135 multipleUnit = multipleUnits.at(multipleUnitID);
1136 if (!multipleUnit)
1137 {
1138 result = Languages::GetText(Languages::TextMultipleUnitDoesNotExist);
1139 return false;
1140 }
1141
1142 if (multipleUnit->IsInUse())
1143 {
1144 result = Logger::Logger::Format(Languages::GetText(Languages::TextMultipleUnitIsInUse), multipleUnit->GetName());
1145 return false;
1146 }
1147
1148 multipleUnits.erase(multipleUnitID);
1149 }
1150
1151 if (storage)
1152 {
1153 TransactionGuard guard(storage);
1154 storage->DeleteMultipleUnit(multipleUnitID);
1155 }
1156 const string& name = multipleUnit->GetName();
1157 const string& matchKey = multipleUnit->GetMatchKey();
1158 std::lock_guard<std::mutex> guard(controlMutex);
1159 for (auto& control : controls)
1160 {
1161 control.second->MultipleUnitDelete(multipleUnitID, name, matchKey);
1162 }
1163 delete multipleUnit;
1164 return true;
1165 }
1166
1167 const map<string,LocoID> Manager::LocoBaseIdsByName() const
1168 {
1169 map<string,LocoID> out = LocoIdsByName();
1170 {
1171 std::lock_guard<std::mutex> guard(multipleUnitMutex);
1172 for (auto& multipleUnit : multipleUnits)
1173 {
1174 MultipleUnit* multipleUnitEntry = multipleUnit.second;
1175 out[multipleUnitEntry->GetName()] = multipleUnitEntry->GetID() + MultipleUnitIdPrefix;
1176 }
1177 }
1178 return out;
1179 }
1180
1181 const std::string& Manager::GetLocoBaseName(const ObjectIdentifier& locoBaseIdentifier) const
1182 {
1183 const LocoBase* locoBase = GetLocoBase(locoBaseIdentifier);
1184 if (!locoBase)
1185 {
1186 return unknownLoco;
1187 }
1188 return locoBase->GetName();
1189 }
1190
1191 /***************************
1192 * Accessory Base *
1193 ***************************/
1194
1195 void Manager::AccessoryBaseState(const ControlType controlType,
1196 const ControlID controlID,
1197 const Protocol protocol,
1198 const Address address,
1199 const DataModel::AccessoryState state)
1200 {
1201 Accessory* accessory = GetAccessory(controlID, protocol, address, static_cast<AddressPort>(state));
1202 if (accessory)
1203 {
1204 AccessoryState(controlType, accessory, accessory->CalculateInvertedAccessoryState(state), true);
1205 return;
1206 }
1207
1208 Switch* mySwitch = GetSwitch(controlID, protocol, address);
1209 if (mySwitch)
1210 {
1211 SwitchState(controlType, mySwitch, mySwitch->CalculateInvertedSwitchState(address, state), true);
1212 return;
1213 }
1214
1215 Signal* signal = GetSignal(controlID, protocol, address);
1216 if (signal)
1217 {
1218 SignalState(controlType, signal, signal->CalculateMappedSignalState(address, state), true);
1219 return;
1220 }
1221
1222 logger->Warning(Languages::TextAccessoryControlProtocolAddressDoesNotExist, controlID, Utils::Utils::ProtocolToString(protocol), address);
1223 }
1224
1225 void Manager::AccessoryBaseState(const ControlType controlType,
1226 const ObjectIdentifier& identifier,
1227 const DataModel::AccessoryState state)
1228 {
1229 switch (identifier.GetObjectType())
1230 {
1231 case ObjectTypeAccessory:
1232 AccessoryState(controlType, identifier.GetObjectID(), state);
1233 return;
1234
1235 case ObjectTypeSwitch:
1236 SwitchState(controlType, identifier.GetObjectID(), state);
1237 return;
1238
1239 case ObjectTypeSignal:
1240 SignalState(controlType, identifier.GetObjectID(), state);
1241 return;
1242
1243 default:
1244 return;
1245 }
1246 }
1247
1248 /***************************
1249 * Accessory *
1250 ***************************/
1251
1252 bool Manager::AccessoryState(const ControlType controlType, const AccessoryID accessoryID, const DataModel::AccessoryState state, const bool force)
1253 {
1254 if (boosterState == BoosterStateStop)
1255 {
1256 return false;
1257 }
1258 Accessory* accessory = GetAccessory(accessoryID);
1259 AccessoryState(controlType, accessory, state, force);
1260 return true;
1261 }
1262
1263 void Manager::AccessoryState(const ControlType controlType, Accessory* accessory, const DataModel::AccessoryState state, const bool force)
1264 {
1265 if (!accessory)
1266 {
1267 return;
1268 }
1269
1270 if (!force && accessory->IsInUse())
1271 {
1272 logger->Warning(Languages::TextAccessoryIsLocked, accessory->GetName());
1273 return;
1274 }
1275
1276 if (!GetExecuteAccessory())
1277 {
1278 const DataModel::AccessoryState oldState = accessory->GetAccessoryState();
1279 if (oldState == state)
1280 {
1281 return;
1282 }
1283 }
1284 accessory->SetAccessoryState(state);
1285
1286 std::lock_guard<std::mutex> guard(controlMutex);
1287 for (auto& control : controls)
1288 {
1289 control.second->AccessoryState(controlType, accessory);
1290 }
1291 }
1292
1293 const map<string,AccessoryConfig> Manager::GetUnmatchedAccessoriesOfControl(const ControlID controlId,
1294 const std::string& matchKey) const
1295 {
1296 ControlInterface* control = GetControl(controlId);
1297 map<string,AccessoryConfig> out;
1298 if (!control || !control->CanHandle(Hardware::CapabilityAccessoryDatabase))
1299 {
1300 return out;
1301 }
1302 out = control->GetUnmatchedAccessories(matchKey);
1303 out[""].SetName("");
1304 return out;
1305 }
1306
1307 Accessory* Manager::GetAccessory(const AccessoryID accessoryID) const
1308 {
1309 std::lock_guard<std::mutex> guard(accessoryMutex);
1310 if (accessories.count(accessoryID) != 1)
1311 {
1312 return nullptr;
1313 }
1314 return accessories.at(accessoryID);
1315 }
1316
1317 Accessory* Manager::GetAccessory(const ControlID controlID,
1318 const Protocol protocol,
1319 const Address address,
1320 const AddressPort port) const
1321 {
1322 std::lock_guard<std::mutex> guard(accessoryMutex);
1323 for (auto& a : accessories)
1324 {
1325 Accessory* accessory = a.second;
1326 if (accessory->GetControlID() == controlID
1327 && accessory->GetProtocol() == protocol
1328 && accessory->GetAddress() == address)
1329 {
1330 switch (accessory->GetAccessoryType() & DataModel::AccessoryTypeConnectionMask)
1331 {
1332 case AccessoryTypeOnOn:
1333 return accessory;
1334
1335 case AccessoryTypeOnPush:
1336 case AccessoryTypeOnOff:
1337 if (accessory->GetPort() == port)
1338 {
1339 return accessory;
1340 }
1341 break;
1342
1343 default:
1344 break;
1345 }
1346 }
1347 }
1348 return nullptr;
1349 }
1350
1351 const std::string& Manager::GetAccessoryName(const AccessoryID accessoryID) const
1352 {
1353 std::lock_guard<std::mutex> guard(accessoryMutex);
1354 if (accessories.count(accessoryID) != 1)
1355 {
1356 return unknownAccessory;
1357 }
1358 return accessories.at(accessoryID)->GetName();
1359 }
1360
1361 bool Manager::AccessorySave(AccessoryID accessoryID,
1362 const string& name,
1363 const LayoutPosition posX,
1364 const LayoutPosition posY,
1365 const LayoutPosition posZ,
1366 const LayoutRotation rotation,
1367 const ControlID controlID,
1368 const std::string& matchKey,
1369 const Protocol protocol,
1370 const Address address,
1371 const AddressPort port,
1372 const Address serverAddress,
1373 const DataModel::AccessoryType type,
1374 const DataModel::AccessoryPulseDuration duration,
1375 const bool inverted,
1376 string& result)
1377 {
1378 if (!CheckControlAccessoryProtocolAddress(controlID, protocol, address, result))
1379 {
1380 return false;
1381 }
1382
1383 Accessory* accessory = GetAccessory(accessoryID);
1384 if (!CheckLayoutItemPosition(accessory, posX, posY, posZ, result))
1385 {
1386 return false;
1387 }
1388
1389 if (!accessory)
1390 {
1391 accessory = CreateAndAddObject(accessories, accessoryMutex);
1392 }
1393
1394 if (!accessory)
1395 {
1396 result = Languages::GetText(Languages::TextUnableToAddAccessory);
1397 return false;
1398 }
1399
1400 // if we have a new object we have to update accessoryID
1401 accessoryID = accessory->GetID();
1402
1403 // update existing accessory
1404 accessory->SetName(CheckObjectName(accessories, accessoryMutex, accessoryID, name.size() == 0 ? "A" : name));
1405 accessory->SetPosX(posX);
1406 accessory->SetPosY(posY);
1407 accessory->SetPosZ(posZ);
1408 accessory->SetRotation(rotation);
1409 accessory->SetControlID(controlID);
1410 accessory->SetMatchKey(matchKey);
1411 accessory->SetProtocol(protocol);
1412 accessory->SetAddress(address);
1413 accessory->SetPort(port);
1414 accessory->SetServerAddress(serverAddress);
1415 accessory->SetAccessoryType(type);
1416 accessory->SetAccessoryPulseDuration(duration);
1417 accessory->SetInverted(inverted);
1418
1419 AccessorySaveAndPublishSettings(accessory);
1420 return true;
1421 }
1422
1423 bool Manager::AccessoryPosition(const AccessoryID accessoryID,
1424 const LayoutPosition posX,
1425 const LayoutPosition posY,
1426 string& result)
1427 {
1428 Accessory* accessory = GetAccessory(accessoryID);
1429 if (!accessory)
1430 {
1431 result = Languages::GetText(Languages::TextAccessoryDoesNotExist);
1432 return false;
1433 }
1434
1435 if (!CheckLayoutItemPosition(accessory, posX, posY, accessory->GetPosZ(), result))
1436 {
1437 return false;
1438 }
1439
1440 accessory->SetPosX(posX);
1441 accessory->SetPosY(posY);
1442
1443 AccessorySaveAndPublishSettings(accessory);
1444 return true;
1445 }
1446
1447 bool Manager::AccessoryRotate(const AccessoryID accessoryID,
1448 string& result)
1449 {
1450 Accessory* accessory = GetAccessory(accessoryID);
1451 if (!accessory)
1452 {
1453 result = Languages::GetText(Languages::TextAccessoryDoesNotExist);
1454 return false;
1455 }
1456
1457 LayoutRotation newRotation = accessory->GetRotation();
1458 ++newRotation;
1459 if (!CheckLayoutItemPosition(accessory, accessory->GetPosX(), accessory->GetPosY(), accessory->GetPosZ(), LayoutItem::Width1, LayoutItem::Height1, newRotation, result))
1460 {
1461 return false;
1462 }
1463
1464 accessory->SetRotation(newRotation);
1465
1466 AccessorySaveAndPublishSettings(accessory);
1467 return true;
1468 }
1469
1470 void Manager::AccessorySaveAndPublishSettings(const Accessory* const accessory)
1471 {
1472 // save in db
1473 if (storage)
1474 {
1475 TransactionGuard guard(storage);
1476 storage->Save(*accessory);
1477 }
1478
1479 std::lock_guard<std::mutex> guard(controlMutex);
1480 for (auto& control : controls)
1481 {
1482 control.second->AccessorySettings(accessory->GetID(), accessory->GetName(), accessory->GetMatchKey());
1483 }
1484 }
1485
1486 const map<string,DataModel::AccessoryConfig> Manager::AccessoryConfigByName() const
1487 {
1488 map<string,DataModel::AccessoryConfig> out;
1489 {
1490 std::lock_guard<std::mutex> guard(accessoryMutex);
1491 for (auto& accessory : accessories)
1492 {
1493 out[accessory.second->GetName()] = *(accessory.second);
1494 }
1495 }
1496
1497 std::lock_guard<std::mutex> guard(controlMutex);
1498 for (auto& control : controls)
1499 {
1500 control.second->AddUnmatchedAccessories(out);
1501 }
1502 return out;
1503 }
1504
1505 bool Manager::AccessoryDelete(const AccessoryID accessoryID,
1506 string& result)
1507 {
1508 Accessory* accessory = nullptr;
1509 {
1510 std::lock_guard<std::mutex> guard(accessoryMutex);
1511 if (accessoryID == AccessoryNone || accessories.count(accessoryID) != 1)
1512 {
1513 result = Languages::GetText(Languages::TextAccessoryDoesNotExist);
1514 return false;
1515 }
1516
1517 accessory = accessories.at(accessoryID);
1518 if (!accessory)
1519 {
1520 result = Languages::GetText(Languages::TextAccessoryDoesNotExist);
1521 return false;
1522 }
1523
1524 ObjectIdentifier accessoryIdentifier(ObjectTypeAccessory, accessoryID);
1525 if (ObjectIsPartOfRoute(accessoryIdentifier, accessory, result))
1526 {
1527 return false;
1528 }
1529
1530 accessories.erase(accessoryID);
1531 }
1532
1533 if (storage)
1534 {
1535 TransactionGuard guard(storage);
1536 storage->DeleteAccessory(accessoryID);
1537 }
1538 const string& name = accessory->GetName();
1539 const string& matchKey = accessory->GetMatchKey();
1540 std::lock_guard<std::mutex> guard(controlMutex);
1541 for (auto& control : controls)
1542 {
1543 control.second->AccessoryDelete(accessoryID, name, matchKey);
1544 }
1545 delete accessory;
1546 return true;
1547 }
1548
1549 bool Manager::AccessoryRelease(const AccessoryID accessoryID)
1550 {
1551 Accessory* accessory = GetAccessory(accessoryID);
1552 if (!accessory)
1553 {
1554 return false;
1555 }
1556 return accessory->Release(logger, accessory->GetLocoBase());
1557 }
1558
1559 AccessoryConfig Manager::GetAccessoryOfConfigByMatchKey(const ControlID controlId, const string& matchKey) const
1560 {
1561 ControlInterface* control = GetControl(controlId);
1562 if (!control)
1563 {
1564 return AccessoryConfig();
1565 }
1566 return control->GetAccessoryByMatchKey(matchKey);
1567 }
1568
1569 Accessory* Manager::GetAccessoryByMatchKey(const ControlID controlId, const string& matchKey) const
1570 {
1571 std::lock_guard<std::mutex> guard(accessoryMutex);
1572 for (auto& accessory : accessories)
1573 {
1574 Accessory* accessoryConfig = accessory.second;
1575 if (accessoryConfig->GetControlID() == controlId && accessoryConfig->GetMatchKey().compare(matchKey) == 0)
1576 {
1577 return accessoryConfig;
1578 }
1579 }
1580 return nullptr;
1581 }
1582
1583 void Manager::AccessoryRemoveMatchKey(const AccessoryID accessoryId)
1584 {
1585 Accessory* accessory = GetAccessory(accessoryId);
1586 if (!accessory)
1587 {
1588 return;
1589 }
1590 accessory->ClearMatchKey();
1591 }
1592
1593 /***************************
1594 * Feedback *
1595 ***************************/
1596
1597 void Manager::FeedbackState(const ControlID controlID, const FeedbackPin pin, const DataModel::Feedback::FeedbackState state)
1598 {
1599 Feedback* feedback = GetFeedback(controlID, pin);
1600 if (feedback)
1601 {
1602 FeedbackState(feedback, state);
1603 return;
1604 }
1605
1606 if (!GetAutoAddFeedback())
1607 {
1608 return;
1609 }
1610
1611 string name = "Feedback auto added " + std::to_string(controlID) + "/" + std::to_string(pin);
1612 logger->Info(Languages::TextAddingFeedback, name);
1613 string result;
1614
1615 FeedbackSave(FeedbackNone, name, DataModel::LayoutItem::VisibleNo, 0, 0, 0, DataModel::LayoutItem::Rotation0, controlID, "", pin, false, FeedbackTypeDefault, RouteNone, result);
1616 }
1617
1618 void Manager::FeedbackState(const FeedbackID feedbackID, const DataModel::Feedback::FeedbackState state)
1619 {
1620 Feedback* feedback = GetFeedback(feedbackID);
1621 if (!feedback)
1622 {
1623 return;
1624 }
1625 FeedbackState(feedback, state);
1626 }
1627
1628 void Manager::FeedbackPublishState(const Feedback* feedback)
1629 {
1630 if (!feedback)
1631 {
1632 return;
1633 }
1634 DataModel::Feedback::FeedbackState state = feedback->GetState();
1635 const string& feedbackName = feedback->GetName();
1636 logger->Info(state ? Languages::TextFeedbackStateIsOn : Languages::TextFeedbackStateIsOff, feedbackName);
1637 const FeedbackID feedbackID = feedback->GetID();
1638 {
1639 std::lock_guard<std::mutex> guard(controlMutex);
1640 for (auto& control : controls)
1641 {
1642 control.second->FeedbackState(feedbackName, feedbackID, state);
1643 }
1644 }
1645 }
1646
1647 Feedback* Manager::GetFeedback(const FeedbackID feedbackID) const
1648 {
1649 std::lock_guard<std::mutex> guard(feedbackMutex);
1650 return GetFeedbackUnlocked(feedbackID);
1651 }
1652
1653 Feedback* Manager::GetFeedbackUnlocked(const FeedbackID feedbackID) const
1654 {
1655 if (feedbacks.count(feedbackID) != 1)
1656 {
1657 return nullptr;
1658 }
1659 return feedbacks.at(feedbackID);
1660 }
1661
1662 Feedback* Manager::GetFeedback(const ControlID controlID, const FeedbackPin pin) const
1663 {
1664 std::lock_guard<std::mutex> guard(feedbackMutex);
1665 for (auto& feedback : feedbacks)
1666 {
1667 if (feedback.second->GetControlID() == controlID
1668 && feedback.second->GetPin() == pin)
1669 {
1670 return feedback.second;
1671 }
1672 }
1673 return nullptr;
1674 }
1675
1676 const std::string& Manager::GetFeedbackName(const FeedbackID feedbackID) const
1677 {
1678 std::lock_guard<std::mutex> guard(feedbackMutex);
1679 if (feedbacks.count(feedbackID) != 1)
1680 {
1681 return unknownFeedback;
1682 }
1683 return feedbacks.at(feedbackID)->GetName();
1684 }
1685
1686 const map<string,DataModel::FeedbackConfig> Manager::FeedbackConfigByName() const
1687 {
1688 map<string,DataModel::FeedbackConfig> out;
1689 {
1690 std::lock_guard<std::mutex> guard(feedbackMutex);
1691 for (auto& feedback : feedbacks)
1692 {
1693 out[feedback.second->GetName()] = *(feedback.second);
1694 }
1695 }
1696 std::lock_guard<std::mutex> guard(controlMutex);
1697 for (auto& control : controls)
1698 {
1699 control.second->AddUnmatchedFeedbacks(out);
1700 }
1701
1702 return out;
1703 }
1704
1705 bool Manager::FeedbackSave(FeedbackID feedbackID,
1706 const std::string& name,
1707 const Visible visible,
1708 const LayoutPosition posX,
1709 const LayoutPosition posY,
1710 const LayoutPosition posZ,
1711 const LayoutRotation rotation,
1712 const ControlID controlID,
1713 const string& matchKey,
1714 const FeedbackPin pin,
1715 const bool inverted,
1716 const FeedbackType feedbackType,
1717 const RouteID routeId,
1718 string& result)
1719 {
1720 Feedback* feedback = GetFeedback(feedbackID);
1721 if (visible && !CheckLayoutItemPosition(feedback, posX, posY, posZ, result))
1722 {
1723 return false;
1724 }
1725
1726 if (!feedback)
1727 {
1728 feedback = CreateAndAddObject(feedbacks, feedbackMutex);
1729 }
1730
1731 if (!feedback)
1732 {
1733 result = Languages::GetText(Languages::TextUnableToAddFeedback);
1734 return false;
1735 }
1736
1737 // if we have a new object we have to update feedbackID
1738 feedbackID = feedback->GetID();
1739
1740 feedback->SetName(CheckObjectName(feedbacks, feedbackMutex, feedbackID, name.size() == 0 ? "F" : name));
1741 feedback->SetVisible(visible);
1742 feedback->SetPosX(posX);
1743 feedback->SetPosY(posY);
1744 feedback->SetPosZ(posZ);
1745 feedback->SetRotation(rotation);
1746 feedback->SetControlID(controlID);
1747 feedback->SetMatchKey(matchKey);
1748 feedback->SetPin(pin);
1749 feedback->SetInverted(inverted);
1750 feedback->SetFeedbackType(feedbackType);
1751 feedback->SetRouteId(routeId);
1752
1753 FeedbackSaveAndPublishSettings(feedback);
1754 return true;
1755 }
1756
1757 bool Manager::FeedbackPosition(const FeedbackID feedbackID,
1758 const LayoutPosition posX,
1759 const LayoutPosition posY,
1760 string& result)
1761 {
1762 Feedback* feedback = GetFeedback(feedbackID);
1763 if (!feedback)
1764 {
1765 result = Languages::GetText(Languages::TextFeedbackDoesNotExist);
1766 return false;
1767 }
1768
1769 if (!feedback->GetVisible())
1770 {
1771 return false;
1772 }
1773
1774 if (!CheckLayoutItemPosition(feedback, posX, posY, feedback->GetPosZ(), result))
1775 {
1776 return false;
1777 }
1778
1779 feedback->SetPosX(posX);
1780 feedback->SetPosY(posY);
1781
1782 FeedbackSaveAndPublishSettings(feedback);
1783 return true;
1784 }
1785
1786 bool Manager::FeedbackRotate(const FeedbackID feedbackID,
1787 string& result)
1788 {
1789 Feedback* feedback = GetFeedback(feedbackID);
1790 if (!feedback)
1791 {
1792 result = Languages::GetText(Languages::TextFeedbackDoesNotExist);
1793 return false;
1794 }
1795
1796 LayoutRotation newRotation = feedback->GetRotation();
1797 ++newRotation;
1798 if (!CheckLayoutItemPosition(feedback, feedback->GetPosX(), feedback->GetPosY(), feedback->GetPosZ(), LayoutItem::Width1, LayoutItem::Height1, newRotation, result))
1799 {
1800 return false;
1801 }
1802
1803 feedback->SetRotation(newRotation);
1804
1805 FeedbackSaveAndPublishSettings(feedback);
1806 return true;
1807 }
1808
1809 void Manager::FeedbackSaveAndPublishSettings(const Feedback* const feedback)
1810 {
1811 // save in db
1812 if (storage)
1813 {
1814 TransactionGuard guard(storage);
1815 storage->Save(*feedback);
1816 }
1817 std::lock_guard<std::mutex> guard(controlMutex);
1818 for (auto& control : controls)
1819 {
1820 control.second->FeedbackSettings(feedback->GetID(), feedback->GetName());
1821 }
1822 }
1823
1824 const map<string,DataModel::Feedback*> Manager::FeedbackListByName() const
1825 {
1826 map<string,DataModel::Feedback*> out;
1827 std::lock_guard<std::mutex> guard(feedbackMutex);
1828 for (auto& feedback : feedbacks)
1829 {
1830 out[feedback.second->GetName()] = feedback.second;
1831 }
1832 return out;
1833 }
1834
1835 const map<RouteID,string> Manager::RoutesOfTrack(const TrackID trackID) const
1836 {
1837 map<RouteID,string> out;
1838 const Track* track = GetTrack(trackID);
1839 if (!track)
1840 {
1841 return out;
1842 }
1843 const vector<const Route*> routesOfTrack = track->GetRoutes();
1844 for (auto route : routesOfTrack)
1845 {
1846 out[route->GetID()] = route->GetName();
1847 }
1848 return out;
1849 }
1850
1851 const map<string,FeedbackID> Manager::FeedbacksOfTrack(const TrackID trackID) const
1852 {
1853 map<string,FeedbackID> out;
1854 const Track* track = GetTrack(trackID);
1855 if (!track)
1856 {
1857 return out;
1858 }
1859 const vector<Relation*> feedbacksOfTrack = track->GetFeedbacks();
1860 for (auto feedbackRelation: feedbacksOfTrack)
1861 {
1862 const FeedbackID feedbackID = feedbackRelation->ObjectID2();
1863 Feedback* feedback = GetFeedback(feedbackID);
1864 if (!feedback)
1865 {
1866 continue;
1867 }
1868 out[feedback->GetName()] = feedbackID;
1869 }
1870 return out;
1871 }
1872
1873 bool Manager::FeedbackDelete(const FeedbackID feedbackID,
1874 string& result)
1875 {
1876 Feedback* feedback = nullptr;
1877 {
1878 std::lock_guard<std::mutex> guard(feedbackMutex);
1879 if (feedbackID == FeedbackNone || feedbacks.count(feedbackID) != 1)
1880 {
1881 result = Languages::GetText(Languages::TextFeedbackDoesNotExist);
1882 return false;
1883 }
1884
1885 feedback = feedbacks.at(feedbackID);
1886 Track* track = feedback->GetTrack();
1887 if (track)
1888 {
1889 result = Logger::Logger::Format(Languages::GetText(Languages::TextFeedbackIsUsedByTrack), feedback->GetName(), track->GetName());
1890 return false;
1891 }
1892
1893 feedbacks.erase(feedbackID);
1894 }
1895
1896 if (storage)
1897 {
1898 TransactionGuard guard(storage);
1899 storage->DeleteFeedback(feedbackID);
1900 }
1901 const string& name = feedback->GetName();
1902 std::lock_guard<std::mutex> guard(controlMutex);
1903 for (auto& control : controls)
1904 {
1905 control.second->FeedbackDelete(feedbackID, name);
1906 }
1907 delete feedback;
1908 return true;
1909 }
1910
1911 FeedbackConfig Manager::GetFeedbackOfConfigByMatchKey(const ControlID controlId, const string& matchKey) const
1912 {
1913 ControlInterface* control = GetControl(controlId);
1914 if (!control)
1915 {
1916 return FeedbackConfig();
1917 }
1918 return control->GetFeedbackByMatchKey(matchKey);
1919 }
1920
1921 Feedback* Manager::GetFeedbackByMatchKey(const ControlID controlId, const string& matchKey) const
1922 {
1923 std::lock_guard<std::mutex> guard(feedbackMutex);
1924 for (auto& feedback : feedbacks)
1925 {
1926 Feedback* feedbackConfig = feedback.second;
1927 if (feedbackConfig->GetControlID() == controlId && feedbackConfig->GetMatchKey().compare(matchKey) == 0)
1928 {
1929 return feedback.second;
1930 }
1931 }
1932 return nullptr;
1933 }
1934
1935 void Manager::FeedbackRemoveMatchKey(const FeedbackID feedbackId)
1936 {
1937 Feedback* feedback = GetFeedback(feedbackId);
1938 if (!feedback)
1939 {
1940 return;
1941 }
1942 feedback->ClearMatchKey();
1943 }
1944
1945 void Manager::FeedbackReplaceMatchKey(const FeedbackID feedbackId, const std::string& newMatchKey)
1946 {
1947 Feedback* feedback = GetFeedback(feedbackId);
1948 if (!feedback)
1949 {
1950 return;
1951 }
1952 feedback->SetMatchKey(newMatchKey);
1953 }
1954
1955 const map<string,FeedbackConfig> Manager::GetUnmatchedFeedbacksOfControl(const ControlID controlId,
1956 const std::string& matchKey) const
1957 {
1958 ControlInterface* control = GetControl(controlId);
1959 map<string,FeedbackConfig> out;
1960 if (!control || !control->CanHandle(Hardware::CapabilityFeedbackDatabase))
1961 {
1962 return out;
1963 }
1964 out = control->GetUnmatchedFeedbacks(matchKey);
1965 out[""].SetName("");
1966 return out;
1967 }
1968
1969 /***************************
1970 * Track *
1971 ***************************/
1972
1973 Track* Manager::GetTrack(const TrackID trackID) const
1974 {
1975 std::lock_guard<std::mutex> guard(trackMutex);
1976 if (tracks.count(trackID) != 1)
1977 {
1978 return nullptr;
1979 }
1980 return tracks.at(trackID);
1981 }
1982
1983 const std::string& Manager::GetTrackName(const TrackID trackID) const
1984 {
1985 if (tracks.count(trackID) != 1)
1986 {
1987 return unknownTrack;
1988 }
1989 return tracks.at(trackID)->GetName();
1990 }
1991
1992 const map<string,DataModel::Track*> Manager::TrackListByName() const
1993 {
1994 map<string,DataModel::Track*> out;
1995 std::lock_guard<std::mutex> guard(trackMutex);
1996 for (auto& track : tracks)
1997 {
1998 out[track.second->GetName()] = track.second;
1999 }
2000 return out;
2001 }
2002
2003 const map<string,DataModel::Track*> Manager::TrackListMasterByName() const
2004 {
2005 map<string,DataModel::Track*> out;
2006 std::lock_guard<std::mutex> guard(trackMutex);
2007 for (auto& t : tracks)
2008 {
2009 Track* track = t.second;
2010 if (track && !track->GetMain())
2011 {
2012 out[track->GetName()] = track;
2013 }
2014 }
2015 return out;
2016 }
2017
2018 const map<string,TrackID> Manager::TrackListIdByName(const TrackID excludeTrackID) const
2019 {
2020 map<string,TrackID> out;
2021 std::lock_guard<std::mutex> guard(trackMutex);
2022 for (auto& t : tracks)
2023 {
2024 Track* track = t.second;
2025 const TrackID trackID = track->GetID();
2026 if (trackID == excludeTrackID)
2027 {
2028 continue;
2029 }
2030
2031 // exclude extension tracks
2032 if (track->GetMain())
2033 {
2034 continue;
2035 }
2036 out[track->GetName()] = trackID;
2037 }
2038 return out;
2039 }
2040
2041 bool Manager::TrackSave(TrackID trackID,
2042 const std::string& name,
2043 const bool showName,
2044 const std::string& displayName,
2045 const LayoutPosition posX,
2046 const LayoutPosition posY,
2047 const LayoutPosition posZ,
2048 const LayoutItemSize height,
2049 const LayoutRotation rotation,
2050 const DataModel::TrackType trackType,
2051 const TrackID main,
2052 const vector<Relation*>& newFeedbacks,
2053 const vector<Relation*>& newSignals,
2054 const DataModel::SelectRouteApproach selectRouteApproach,
2055 const bool allowLocoTurn,
2056 const bool releaseWhenFree,
2057 string& result)
2058 {
2059 Track* track = GetTrack(trackID);
2060 if (!CheckLayoutItemPosition(track, posX, posY, posZ, LayoutItem::Width1, height, rotation, result))
2061 {
2062 return false;
2063 }
2064
2065 if (!track)
2066 {
2067 track = CreateAndAddObject(tracks, trackMutex);
2068 }
2069
2070 if (!track)
2071 {
2072 result = Languages::GetText(Languages::TextUnableToAddTrack);
2073 return false;
2074 }
2075
2076 // if we have a new object we have to update trackID
2077 if (trackID == TrackNone)
2078 {
2079 trackID = track->GetID();
2080 for (auto feedback : newFeedbacks)
2081 {
2082 feedback->ObjectID1(trackID);
2083 }
2084 for (auto signal : newSignals)
2085 {
2086 signal->ObjectID1(trackID);
2087 }
2088 }
2089
2090 // update existing track
2091 track->SetName(CheckObjectName(tracks, trackMutex, trackID, name.size() == 0 ? "T" : name));
2092 track->SetShowName(showName);
2093 track->SetDisplayName(displayName);
2094 track->SetHeight(height);
2095 track->SetRotation(rotation);
2096 track->SetPosX(posX);
2097 track->SetPosY(posY);
2098 track->SetPosZ(posZ);
2099 track->SetTrackType(trackType);
2100 Track* oldMain = track->GetMain();
2101 if (oldMain)
2102 {
2103 oldMain->DeleteExtension(track);
2104 }
2105 Track* newMain = GetTrack(main);
2106 if (newMain && !newMain->GetMain() && newMain->AddExtension(track))
2107 {
2108 track->SetMain(newMain);
2109 track->SetName(newMain->GetName() + "_ext_" + to_string(trackID));
2110 }
2111 track->AssignFeedbacks(newFeedbacks);
2112 track->AssignSignals(newSignals);
2113 track->SetSelectRouteApproach(selectRouteApproach);
2114 track->SetAllowLocoTurn(allowLocoTurn);
2115 track->SetReleaseWhenFree(releaseWhenFree);
2116
2117 TrackSaveAndPublishSettings(track);
2118 return true;
2119 }
2120
2121 bool Manager::TrackPosition(const TrackID trackID,
2122 const LayoutPosition posX,
2123 const LayoutPosition posY,
2124 string& result)
2125 {
2126 Track* track = GetTrack(trackID);
2127 if (!track)
2128 {
2129 result = Languages::GetText(Languages::TextTrackDoesNotExist);
2130 return false;
2131 }
2132
2133 if (!CheckLayoutItemPosition(track, posX, posY, track->GetPosZ(), LayoutItem::Width1, track->GetHeight(), track->GetRotation(), result))
2134 {
2135 return false;
2136 }
2137
2138 track->SetPosX(posX);
2139 track->SetPosY(posY);
2140
2141 TrackSaveAndPublishSettings(track);
2142 return true;
2143 }
2144
2145 bool Manager::TrackRotate(const TrackID trackID,
2146 string& result)
2147 {
2148 Track* track = GetTrack(trackID);
2149 if (!track)
2150 {
2151 result = Languages::GetText(Languages::TextTrackDoesNotExist);
2152 return false;
2153 }
2154
2155 LayoutRotation newRotation = track->GetRotation();
2156 ++newRotation;
2157 if (!CheckLayoutItemPosition(track, track->GetPosX(), track->GetPosY(), track->GetPosZ(), LayoutItem::Width1, track->GetHeight(), newRotation, result))
2158 {
2159 return false;
2160 }
2161
2162 track->SetRotation(newRotation);
2163
2164 TrackSaveAndPublishSettings(track);
2165 return true;
2166 }
2167
2168 void Manager::TrackSaveAndPublishSettings(const Track* const track)
2169 {
2170 TrackSave(track);
2171
2172 std::lock_guard<std::mutex> guard(controlMutex);
2173 for (auto& control : controls)
2174 {
2175 control.second->TrackSettings(track->GetID(), track->GetName());
2176 }
2177 }
2178
2179 bool Manager::TrackDelete(const TrackID trackID,
2180 string& result)
2181 {
2182 Track* track = nullptr;
2183 {
2184 std::lock_guard<std::mutex> guard(trackMutex);
2185 if (trackID == TrackNone || tracks.count(trackID) != 1)
2186 {
2187 result = Languages::GetText(Languages::TextTrackDoesNotExist);
2188 return false;
2189 }
2190
2191 track = tracks.at(trackID);
2192 if (!track)
2193 {
2194 result = Languages::GetText(Languages::TextTrackDoesNotExist);
2195 return false;
2196 }
2197
2198 if (track->IsInUse())
2199 {
2200 result = Logger::Logger::Format(Languages::GetText(Languages::TextTrackIsUsedByLoco), track->GetName(), GetLocoBaseName(track->GetLocoBase()));
2201 return false;
2202 }
2203
2204 Route* route = GetFirstRouteFromOrToTrack(trackID);
2205 if (route)
2206 {
2207 result = Logger::Logger::Format(Languages::GetText(Languages::TextTrackIsUsedByRoute), track->GetName(), route->GetName());
2208 return false;
2209 }
2210
2211 ObjectIdentifier trackIdentifier(ObjectTypeTrack, trackID);
2212 if (ObjectIsPartOfRoute(trackIdentifier, track, result))
2213 {
2214 return false;
2215 }
2216
2217 tracks.erase(trackID);
2218 }
2219
2220 if (storage)
2221 {
2222 Storage::TransactionGuard guard(storage);
2223 storage->DeleteTrack(trackID);
2224 }
2225 const string& name = track->GetName();
2226 std::lock_guard<std::mutex> guard(controlMutex);
2227 for (auto& control : controls)
2228 {
2229 control.second->TrackDelete(trackID, name);
2230 }
2231
2232 Cluster* cluster = track->GetCluster();
2233 if (cluster)
2234 {
2235 cluster->DeleteTrack(track);
2236 }
2237
2238 delete track;
2239 return true;
2240 }
2241
2242 /***************************
2243 * Switch *
2244 ***************************/
2245
2246 bool Manager::SwitchState(const ControlType controlType, const SwitchID switchID, const DataModel::AccessoryState state, const bool force)
2247 {
2248 if (boosterState == BoosterStateStop)
2249 {
2250 return false;
2251 }
2252
2253 Switch* mySwitch = GetSwitch(switchID);
2254 SwitchState(controlType, mySwitch, state, force);
2255 return true;
2256 }
2257
2258 void Manager::SwitchState(const ControlType controlType, Switch* mySwitch, const DataModel::AccessoryState state, const bool force)
2259 {
2260 if (!mySwitch)
2261 {
2262 return;
2263 }
2264
2265 if (!force && mySwitch->IsInUse())
2266 {
2267 logger->Warning(Languages::TextSwitchIsLocked, mySwitch->GetName());
2268 return;
2269 }
2270
2271 if (!GetExecuteAccessory())
2272 {
2273 const DataModel::AccessoryState oldState = mySwitch->GetAccessoryState();
2274 if (oldState == state)
2275 {
2276 return;
2277 }
2278 }
2279 mySwitch->SetAccessoryState(state);
2280
2281 std::lock_guard<std::mutex> guard(controlMutex);
2282 for (auto& control : controls)
2283 {
2284 control.second->SwitchState(controlType, mySwitch);
2285 }
2286 }
2287
2288 Switch* Manager::GetSwitch(const SwitchID switchID) const
2289 {
2290 std::lock_guard<std::mutex> guard(switchMutex);
2291 if (switches.count(switchID) != 1)
2292 {
2293 return nullptr;
2294 }
2295 return switches.at(switchID);
2296 }
2297
2298 Switch* Manager::GetSwitch(const ControlID controlID, const Protocol protocol, const Address address) const
2299 {
2300 std::lock_guard<std::mutex> guard(switchMutex);
2301 for (auto& mySwitch : switches)
2302 {
2303 Switch* s = mySwitch.second;
2304 if ((s->GetControlID() == controlID)
2305 && (s->GetProtocol() == protocol)
2306 && (s->UsesAddress(address)))
2307 {
2308 return s;
2309 }
2310 }
2311 return nullptr;
2312 }
2313
2314 const std::string& Manager::GetSwitchName(const SwitchID switchID) const
2315 {
2316 if (switches.count(switchID) != 1)
2317 {
2318 return unknownSwitch;
2319 }
2320 return switches.at(switchID)->GetName();
2321 }
2322
2323 bool Manager::SwitchSave(SwitchID switchID,
2324 const string& name,
2325 const LayoutPosition posX,
2326 const LayoutPosition posY,
2327 const LayoutPosition posZ,
2328 const LayoutRotation rotation,
2329 const ControlID controlID,
2330 const string& matchKey,
2331 const Protocol protocol,
2332 const Address address,
2333 const Address serverAddress,
2334 const DataModel::AccessoryType type,
2335 const DataModel::AccessoryPulseDuration duration,
2336 const bool inverted,
2337 string& result)
2338 {
2339 if (!CheckControlAccessoryProtocolAddress(controlID, protocol, address, result))
2340 {
2341 return false;
2342 }
2343
2344 Switch* mySwitch = GetSwitch(switchID);
2345 if (!CheckLayoutItemPosition(mySwitch, posX, posY, posZ, LayoutItem::Width1, Switch::CalculateHeightFromType(type), rotation, result))
2346 {
2347 return false;
2348 }
2349
2350 if (!mySwitch)
2351 {
2352 mySwitch = CreateAndAddObject(switches, switchMutex);
2353 }
2354
2355 if (!mySwitch)
2356 {
2357 result = Languages::GetText(Languages::TextUnableToAddSwitch);
2358 return false;
2359 }
2360
2361 // if we have a new object we have to update switchID
2362 switchID = mySwitch->GetID();
2363
2364 // update existing switch
2365 mySwitch->SetName(CheckObjectName(switches, switchMutex, switchID, name.size() == 0 ? "S" : name));
2366 mySwitch->SetPosX(posX);
2367 mySwitch->SetPosY(posY);
2368 mySwitch->SetPosZ(posZ);
2369 mySwitch->SetRotation(rotation);
2370 mySwitch->SetControlID(controlID);
2371 mySwitch->SetMatchKey(matchKey);
2372 mySwitch->SetProtocol(protocol);
2373 mySwitch->SetAddress(address);
2374 mySwitch->SetServerAddress(serverAddress);
2375 mySwitch->SetAccessoryType(type);
2376 mySwitch->SetAccessoryPulseDuration(duration);
2377 mySwitch->SetInverted(inverted);
2378
2379 SwitchSaveAndPublishSettings(mySwitch);
2380 return true;
2381 }
2382
2383 bool Manager::SwitchPosition(const SwitchID switchID,
2384 const LayoutPosition posX,
2385 const LayoutPosition posY,
2386 string& result)
2387 {
2388 Switch* mySwitch = GetSwitch(switchID);
2389 if (!mySwitch)
2390 {
2391 result = Languages::GetText(Languages::TextSwitchDoesNotExist);
2392 return false;
2393 }
2394
2395 if (!CheckLayoutItemPosition(mySwitch, posX, posY, mySwitch->GetPosZ(), LayoutItem::Width1, mySwitch->GetHeight(), mySwitch->GetRotation(), result))
2396 {
2397 return false;
2398 }
2399
2400 mySwitch->SetPosX(posX);
2401 mySwitch->SetPosY(posY);
2402
2403 SwitchSaveAndPublishSettings(mySwitch);
2404 return true;
2405 }
2406
2407 bool Manager::SwitchRotate(const SwitchID switchID,
2408 string& result)
2409 {
2410 Switch* mySwitch = GetSwitch(switchID);
2411 if (!mySwitch)
2412 {
2413 result = Languages::GetText(Languages::TextSwitchDoesNotExist);
2414 return false;
2415 }
2416
2417 LayoutRotation newRotation = mySwitch->GetRotation();
2418 ++newRotation;
2419 if (!CheckLayoutItemPosition(mySwitch, mySwitch->GetPosX(), mySwitch->GetPosY(), mySwitch->GetPosZ(), LayoutItem::Width1, mySwitch->GetHeight(), newRotation, result))
2420 {
2421 return false;
2422 }
2423
2424 mySwitch->Rotate();
2425
2426 SwitchSaveAndPublishSettings(mySwitch);
2427 return true;
2428 }
2429
2430 void Manager::SwitchSaveAndPublishSettings(const Switch* const mySwitch)
2431 {
2432 if (storage)
2433 {
2434 TransactionGuard guard(storage);
2435 storage->Save(*mySwitch);
2436 }
2437
2438 std::lock_guard<std::mutex> guard(controlMutex);
2439 for (auto& control : controls)
2440 {
2441 control.second->SwitchSettings(mySwitch->GetID(), mySwitch->GetName(), mySwitch->GetMatchKey());
2442 }
2443 }
2444
2445 bool Manager::SwitchDelete(const SwitchID switchID,
2446 string& result)
2447 {
2448 Switch* mySwitch = nullptr;
2449 {
2450 std::lock_guard<std::mutex> guard(switchMutex);
2451 if (switchID == SwitchNone || switches.count(switchID) != 1)
2452 {
2453 result = Languages::GetText(Languages::TextSwitchDoesNotExist);
2454 return false;
2455 }
2456
2457 mySwitch = switches.at(switchID);
2458 if (!mySwitch)
2459 {
2460 result = Languages::GetText(Languages::TextSwitchDoesNotExist);
2461 return false;
2462 }
2463
2464 ObjectIdentifier switchIdentifier(ObjectTypeSwitch, switchID);
2465 if (ObjectIsPartOfRoute(switchIdentifier, mySwitch, result))
2466 {
2467 return false;
2468 }
2469 switches.erase(switchID);
2470 }
2471
2472 if (storage)
2473 {
2474 TransactionGuard guard(storage);
2475 storage->DeleteSwitch(switchID);
2476 }
2477
2478 const string& name = mySwitch->GetName();
2479 const string& matchKey = mySwitch->GetMatchKey();
2480 std::lock_guard<std::mutex> guard(controlMutex);
2481 for (auto& control : controls)
2482 {
2483 control.second->SwitchDelete(switchID, name, matchKey);
2484 }
2485 delete mySwitch;
2486 return true;
2487 }
2488
2489 const map<string,DataModel::AccessoryConfig> Manager::SwitchConfigByName() const
2490 {
2491 map<string,DataModel::AccessoryConfig> out;
2492 {
2493 std::lock_guard<std::mutex> guard(switchMutex);
2494 for (auto& mySwitch : switches)
2495 {
2496 out[mySwitch.second->GetName()] = *(mySwitch.second);
2497 }
2498 }
2499
2500 std::lock_guard<std::mutex> guard(controlMutex);
2501 for (auto& control : controls)
2502 {
2503 control.second->AddUnmatchedAccessories(out);
2504 }
2505 return out;
2506 }
2507
2508 bool Manager::SwitchRelease(const RouteID switchID)
2509 {
2510 Switch* mySwitch = GetSwitch(switchID);
2511 if (!mySwitch)
2512 {
2513 return false;
2514 }
2515 return mySwitch->Release(logger, mySwitch->GetLocoBase());
2516 }
2517
2518 Switch* Manager::GetSwitchByMatchKey(const ControlID controlId, const string& matchKey) const
2519 {
2520 std::lock_guard<std::mutex> guard(switchMutex);
2521 for (auto& mySwitch : switches)
2522 {
2523 Switch* switchConfig = mySwitch.second;
2524 if (switchConfig->GetControlID() == controlId && switchConfig->GetMatchKey().compare(matchKey) == 0)
2525 {
2526 return switchConfig;
2527 }
2528 }
2529 return nullptr;
2530 }
2531
2532 void Manager::SwitchRemoveMatchKey(const SwitchID switchId)
2533 {
2534 Switch* mySwitch = GetSwitch(switchId);
2535 if (!mySwitch)
2536 {
2537 return;
2538 }
2539 mySwitch->ClearMatchKey();
2540 }
2541
2542 /***************************
2543 * Route *
2544 ***************************/
2545
2546 bool Manager::RouteExecute(Logger::Logger* logger, const ObjectIdentifier& locoBaseIdentifier, const RouteID routeID)
2547 {
2548 Route* route = GetRoute(routeID);
2549 if (!route)
2550 {
2551 return false;
2552 }
2553 return route->Execute(logger, locoBaseIdentifier);
2554 }
2555
2556 void Manager::RouteExecuteAsync(Logger::Logger* logger, const RouteID routeID)
2557 {
2558 Route* route = GetRoute(routeID);
2559 if (!route)
2560 {
2561 return;
2562 }
2563 __attribute__((unused)) auto r = std::async(std::launch::async, Route::ExecuteStatic, logger, route);
2564 }
2565
2566 string Manager::GetRouteList() const
2567 {
2568 string out;
2569 std::lock_guard<std::mutex> guard(routeMutex);
2570 for (auto& route : routes)
2571 {
2572 Route* r = route.second;
2573 out += to_string(r->GetID()) + ";";
2574 out += to_string(r->GetFromTrack()) + ";";
2575 out += to_string(r->GetFromOrientation()) + ";";
2576 out += to_string(r->GetToTrack()) + ";";
2577 out += to_string(r->GetToOrientation()) + ";";
2578 out += r->GetName() + "\n";
2579 }
2580 return out;
2581 }
2582
2583 Route* Manager::GetRoute(const RouteID routeID) const
2584 {
2585 std::lock_guard<std::mutex> guard(routeMutex);
2586 if (routes.count(routeID) != 1)
2587 {
2588 return nullptr;
2589 }
2590 return routes.at(routeID);
2591 }
2592
2593 const string& Manager::GetRouteName(const RouteID routeID) const
2594 {
2595 std::lock_guard<std::mutex> guard(routeMutex);
2596 if (routes.count(routeID) != 1)
2597 {
2598 return unknownRoute;
2599 }
2600 return routes.at(routeID)->GetName();
2601 }
2602
2603 bool Manager::RouteSave(RouteID routeID,
2604 const std::string& name,
2605 const Delay delay,
2606 const Route::PushpullType pushpull,
2607 const Propulsion propulsion,
2608 const TrainType trainType,
2609 const Length minTrainLength,
2610 const Length maxTrainLength,
2611 const std::vector<DataModel::Relation*>& relationsAtLock,
2612 const std::vector<DataModel::Relation*>& relationsAtUnlock,
2613 const Visible visible,
2614 const LayoutPosition posX,
2615 const LayoutPosition posY,
2616 const LayoutPosition posZ,
2617 const Automode automode,
2618 const TrackID fromTrack,
2619 const Orientation fromOrientation,
2620 const TrackID toTrack,
2621 const Orientation toOrientation,
2622 const Route::Speed speed,
2623 const FeedbackID feedbackIdReduced,
2624 const Delay reducedDelay,
2625 const FeedbackID feedbackIdCreep,
2626 const Delay creepDelay,
2627 const FeedbackID feedbackIdStop,
2628 const Delay stopDelay,
2629 const FeedbackID feedbackIdOver,
2630 const Pause waitAfterRelease,
2631 const RouteID followUpRoute,
2632 string& result)
2633 {
2634
2635 Route* route = GetRoute(routeID);
2636 if (visible && !CheckLayoutItemPosition(route, posX, posY, posZ, result))
2637 {
2638 return false;
2639 }
2640
2641 if (!route)
2642 {
2643 route = CreateAndAddObject(routes, routeMutex);
2644 }
2645 if (!route)
2646 {
2647 result = Languages::GetText(Languages::TextUnableToAddRoute);
2648 return false;
2649 }
2650
2651 // remove route from old track
2652 Track* oldTrack = GetTrack(route->GetFromTrack());
2653 if (oldTrack)
2654 {
2655 oldTrack->DeleteRoute(route);
2656 TrackSave(oldTrack);
2657 }
2658
2659 // if we have a new object we have to update routeID
2660 if (routeID == 0)
2661 {
2662 routeID = route->GetID();
2663 for (auto atLock : relationsAtLock)
2664 {
2665 atLock->ObjectID1(routeID);
2666 }
2667 for (auto atUnlock : relationsAtUnlock)
2668 {
2669 atUnlock->ObjectID1(routeID);
2670 }
2671 }
2672
2673 // update existing route
2674 route->SetName(CheckObjectName(routes, routeMutex, routeID, name.size() == 0 ? "S" : name));
2675 route->SetDelay(delay);
2676 route->AssignRelationsAtLock(relationsAtLock);
2677 route->AssignRelationsAtUnlock(relationsAtUnlock);
2678 route->SetVisible(visible);
2679 route->SetPosX(posX);
2680 route->SetPosY(posY);
2681 route->SetPosZ(posZ);
2682 route->SetAutomode(automode);
2683 if (automode == AutomodeYes)
2684 {
2685 route->SetFromTrack(fromTrack);
2686 route->SetFromOrientation(fromOrientation);
2687 route->SetToTrack(toTrack);
2688 route->SetToOrientation(toOrientation);
2689 route->SetSpeed(speed);
2690 route->SetFeedbackIdReduced(feedbackIdReduced);
2691 route->SetReducedDelay(reducedDelay);
2692 route->SetFeedbackIdCreep(feedbackIdCreep);
2693 route->SetCreepDelay(creepDelay);
2694 route->SetFeedbackIdStop(feedbackIdStop);
2695 route->SetStopDelay(stopDelay);
2696 route->SetFeedbackIdOver(feedbackIdOver);
2697 route->SetPushpull(pushpull);
2698 route->SetPropulsion(propulsion);
2699 route->SetTrainType(trainType);
2700 route->SetMinTrainLength(minTrainLength);
2701 route->SetMaxTrainLength(maxTrainLength);
2702 route->SetWaitAfterRelease(waitAfterRelease);
2703 route->SetFollowUpRoute(followUpRoute);
2704 }
2705 else
2706 {
2707 route->SetFromTrack(TrackNone);
2708 route->SetFromOrientation(OrientationRight);
2709 route->SetToTrack(TrackNone);
2710 route->SetToOrientation(OrientationLeft);
2711 route->SetSpeed(Route::SpeedTravel);
2712 route->SetFeedbackIdReduced(FeedbackNone);
2713 route->SetReducedDelay(0);
2714 route->SetFeedbackIdCreep(FeedbackNone);
2715 route->SetCreepDelay(0);
2716 route->SetFeedbackIdStop(FeedbackNone);
2717 route->SetStopDelay(0);
2718 route->SetFeedbackIdOver(FeedbackNone);
2719 route->SetPushpull(Route::PushpullTypeBoth);
2720 route->SetPropulsion(PropulsionAll);
2721 route->SetTrainType(TrainTypeAll);
2722 route->SetMinTrainLength(0);
2723 route->SetMaxTrainLength(0);
2724 route->SetWaitAfterRelease(0);
2725 route->SetFollowUpRoute(RouteNone);
2726 }
2727
2728 // Add new route
2729 Track* newTrack = GetTrack(route->GetFromTrack());
2730 if (newTrack)
2731 {
2732 newTrack->AddRoute(route);
2733 TrackSave(newTrack);
2734 }
2735
2736 RouteSaveAndPublishSettings(route);
2737 return true;
2738 }
2739
2740 bool Manager::RoutePosition(const RouteID routeID,
2741 const LayoutPosition posX,
2742 const LayoutPosition posY,
2743 string& result)
2744 {
2745 Route* route = GetRoute(routeID);
2746 if (!route)
2747 {
2748 result = Languages::GetText(Languages::TextRouteDoesNotExist);
2749 return false;
2750 }
2751
2752 if (!route->GetVisible())
2753 {
2754 return false;
2755 }
2756
2757 if (!CheckLayoutItemPosition(route, posX, posY, route->GetPosZ(), result))
2758 {
2759 return false;
2760 }
2761
2762 route->SetPosX(posX);
2763 route->SetPosY(posY);
2764
2765 RouteSaveAndPublishSettings(route);
2766 return true;
2767 }
2768
2769 void Manager::RouteSaveAndPublishSettings(const Route* const route)
2770 {
2771 RouteSave(route);
2772
2773 std::lock_guard<std::mutex> guard(controlMutex);
2774 for (auto& control : controls)
2775 {
2776 control.second->RouteSettings(route->GetID(), route->GetName());
2777 }
2778 }
2779
2780 const map<string,DataModel::Route*> Manager::RouteListByName() const
2781 {
2782 map<string,DataModel::Route*> out;
2783 std::lock_guard<std::mutex> guard(routeMutex);
2784 for (auto& route : routes)
2785 {
2786 out[route.second->GetName()] = route.second;
2787 }
2788 return out;
2789 }
2790
2791 bool Manager::RouteDelete(const RouteID routeID,
2792 string& result)
2793 {
2794 Route* route = nullptr;
2795 {
2796 {
2797 std::lock_guard<std::mutex> guard(routeMutex);
2798 if (routeID == RouteNone || routes.count(routeID) != 1)
2799 {
2800 result = Languages::GetText(Languages::TextRouteDoesNotExist);
2801 return false;
2802 }
2803
2804 route = routes.at(routeID);
2805 if (!route)
2806 {
2807 result = Languages::GetText(Languages::TextRouteDoesNotExist);
2808 return false;
2809 }
2810
2811 if (route->IsInUse())
2812 {
2813 result = Logger::Logger::Format(Languages::GetText(Languages::TextRouteIsInUse), route->GetName());
2814 return false;
2815 }
2816 }
2817
2818 // this must not be in the lock_guard, it would be a deadlock.
2819 ObjectIdentifier routeIdentifier(ObjectTypeRoute, routeID);
2820 if (ObjectIsPartOfRoute(routeIdentifier, route, result))
2821 {
2822 return false;
2823 }
2824
2825 {
2826 std::lock_guard<std::mutex> guard(routeMutex);
2827 routes.erase(routeID);
2828 }
2829 }
2830
2831 if (storage)
2832 {
2833 TransactionGuard guard(storage);
2834 storage->DeleteRoute(routeID);
2835 }
2836
2837 const string& routeName = route->GetName();
2838 std::lock_guard<std::mutex> guard(controlMutex);
2839 for (auto& control : controls)
2840 {
2841 control.second->RouteDelete(routeID, routeName);
2842 }
2843 delete route;
2844 return true;
2845 }
2846
2847 Route* Manager::GetFirstRouteFromOrToTrack(const TrackID trackID) const
2848 {
2849 std::lock_guard<std::mutex> guard(routeMutex);
2850 for (auto& route : routes)
2851 {
2852 if (route.second->GetToTrack() == trackID || route.second->GetFromTrack() == trackID)
2853 {
2854 return route.second;
2855 }
2856 }
2857 return nullptr;
2858 }
2859
2860 Layer* Manager::GetLayer(const LayerID layerID) const
2861 {
2862 std::lock_guard<std::mutex> guard(layerMutex);
2863 if (layers.count(layerID) != 1)
2864 {
2865 return nullptr;
2866 }
2867 return layers.at(layerID);
2868 }
2869
2870 const map<string,LayerID> Manager::LayerListByName() const
2871 {
2872 map<string,LayerID> list;
2873 std::lock_guard<std::mutex> guard(layerMutex);
2874 for (auto& layer : layers)
2875 {
2876 list[layer.second->GetName()] = layer.first;
2877 }
2878 return list;
2879 }
2880
2881 const map<string,LayerID> Manager::LayerListByNameWithFeedback() const
2882 {
2883 map<string,LayerID> list = LayerListByName();
2884 std::lock_guard<std::mutex> guard(controlMutex);
2885 for (auto& control : controls)
2886 {
2887 if (!control.second->CanHandle(Hardware::CapabilityFeedback))
2888 {
2889 continue;
2890 }
2891 list["| Feedbacks of " + control.second->GetShortName()] = -control.first;
2892 }
2893 return list;
2894 }
2895
2896 bool Manager::LayerSave(LayerID layerID, const std::string&name, std::string& result)
2897 {
2898 Layer* layer = GetLayer(layerID);
2899 if (!layer)
2900 {
2901 layer = CreateAndAddObject(layers, layerMutex);
2902 }
2903
2904 if (!layer)
2905 {
2906 result = Languages::GetText(Languages::TextUnableToAddLayer);
2907 return false;
2908 }
2909
2910 // if we have a new object we have to update layerID
2911 layerID = layer->GetID();
2912
2913 // update existing layer
2914 layer->SetName(CheckObjectName(layers, layerMutex, layerID, name.size() == 0 ? "L" : name));
2915
2916 // save in db
2917 if (storage)
2918 {
2919 TransactionGuard guard(storage);
2920 storage->Save(*layer);
2921 }
2922 std::lock_guard<std::mutex> guard(controlMutex);
2923 for (auto& control : controls)
2924 {
2925 control.second->LayerSettings(layerID, name);
2926 }
2927 return true;
2928 }
2929
2930 bool Manager::LayerHasElements(const Layer* layer,
2931 string& result)
2932 {
2933 LayerID layerId = layer->GetID();
2934 for (auto& track : tracks)
2935 {
2936 if (track.second->IsVisibleOnLayer(layerId))
2937 {
2938 result = Logger::Logger::Format(Languages::GetText(Languages::TextLayerIsUsedByTrack), layer->GetName(), track.second->GetName());
2939 return true;
2940 }
2941 }
2942 for (auto& mySwitch : switches)
2943 {
2944 if (mySwitch.second->IsVisibleOnLayer(layerId))
2945 {
2946 result = Logger::Logger::Format(Languages::GetText(Languages::TextLayerIsUsedBySwitch), layer->GetName(), mySwitch.second->GetName());
2947 return true;
2948 }
2949 }
2950 for (auto& signal : signals)
2951 {
2952 if (signal.second->IsVisibleOnLayer(layerId))
2953 {
2954 result = Logger::Logger::Format(Languages::GetText(Languages::TextLayerIsUsedBySignal), layer->GetName(), signal.second->GetName());
2955 return true;
2956 }
2957 }
2958 for (auto& accessory : accessories)
2959 {
2960 if (accessory.second->IsVisibleOnLayer(layerId))
2961 {
2962 result = Logger::Logger::Format(Languages::GetText(Languages::TextLayerIsUsedByAccessory), layer->GetName(), accessory.second->GetName());
2963 return true;
2964 }
2965 }
2966 for (auto& route : routes)
2967 {
2968 if (route.second->IsVisibleOnLayer(layerId))
2969 {
2970 result = Logger::Logger::Format(Languages::GetText(Languages::TextLayerIsUsedByRoute), layer->GetName(), route.second->GetName());
2971 return true;
2972 }
2973 }
2974 for (auto& feedback : feedbacks)
2975 {
2976 if (feedback.second->IsVisibleOnLayer(layerId))
2977 {
2978 result = Logger::Logger::Format(Languages::GetText(Languages::TextLayerIsUsedByFeedback), layer->GetName(), feedback.second->GetName());
2979 return true;
2980 }
2981 }
2982 for (auto& text : texts)
2983 {
2984 if (text.second->IsVisibleOnLayer(layerId))
2985 {
2986 result = Logger::Logger::Format(Languages::GetText(Languages::TextLayerIsUsedByText), layer->GetName(), text.second->GetName());
2987 return true;
2988 }
2989 }
2990 return false;
2991 }
2992
2993 bool Manager::LayerDelete(const LayerID layerID,
2994 string& result)
2995 {
2996 if (layerID == LayerUndeletable)
2997 {
2998 result = Languages::GetText(Languages::TextLayer1IsUndeletable);
2999 return false;
3000 }
3001
3002 if (layerID == LayerNone)
3003 {
3004 result = Languages::GetText(Languages::TextLayerDoesNotExist);
3005 return false;
3006 }
3007
3008 Layer* layer = nullptr;
3009 {
3010 std::lock_guard<std::mutex> guard(layerMutex);
3011 if (layers.count(layerID) != 1)
3012 {
3013 result = Languages::GetText(Languages::TextLayerDoesNotExist);
3014 return false;
3015 }
3016
3017 layer = layers.at(layerID);
3018 if (!layer)
3019 {
3020 result = Languages::GetText(Languages::TextLayerDoesNotExist);
3021 return false;
3022 }
3023
3024 if (LayerHasElements(layer, result))
3025 {
3026 return false;
3027 }
3028
3029 layers.erase(layerID);
3030 }
3031
3032 if (storage)
3033 {
3034 TransactionGuard guard(storage);
3035 storage->DeleteLayer(layerID);
3036 }
3037
3038 const string& layerName = layer->GetName();
3039 std::lock_guard<std::mutex> guard(controlMutex);
3040 for (auto& control : controls)
3041 {
3042 control.second->LayerDelete(layerID, layerName);
3043 }
3044 delete layer;
3045 return true;
3046 }
3047
3048 /***************************
3049 * Signal *
3050 ***************************/
3051
3052 bool Manager::SignalState(const ControlType controlType, const SignalID signalID, const DataModel::AccessoryState state, const bool force)
3053 {
3054 if (boosterState == BoosterStateStop)
3055 {
3056 return false;
3057 }
3058 Signal* signal = GetSignal(signalID);
3059 if (!signal)
3060 {
3061 return false;
3062 }
3063 return SignalState(controlType, signal, state, force);
3064 }
3065
3066 bool Manager::SignalState(const ControlType controlType, Signal* signal, const DataModel::AccessoryState state, const bool force)
3067 {
3068 if (!signal)
3069 {
3070 return false;
3071 }
3072
3073 if (!force && signal->IsInUse())
3074 {
3075 logger->Warning(Languages::TextSignalIsLocked, signal->GetName());
3076 return false;
3077 }
3078
3079 const DataModel::AccessoryState oldState = signal->GetAccessoryState();
3080 if (oldState == state)
3081 {
3082 return true;
3083 }
3084 signal->SetAccessoryState(state);
3085
3086 SignalPublishState(controlType, signal);
3087 return true;
3088 }
3089
3090 void Manager::SignalPublishState(const ControlType controlType, const DataModel::Signal* signal)
3091 {
3092 std::lock_guard<std::mutex> guard(controlMutex);
3093 for (auto& control : controls)
3094 {
3095 control.second->SignalState(controlType, signal);
3096 }
3097 }
3098
3099 Signal* Manager::GetSignal(const SignalID signalID) const
3100 {
3101 std::lock_guard<std::mutex> guard(signalMutex);
3102 if (signals.count(signalID) != 1)
3103 {
3104 return nullptr;
3105 }
3106 return signals.at(signalID);
3107 }
3108
3109 Signal* Manager::GetSignal(const ControlID controlID, const Protocol protocol, const Address address) const
3110 {
3111 std::lock_guard<std::mutex> guard(signalMutex);
3112 for (auto& signal : signals)
3113 {
3114 Signal* s = signal.second;
3115 if ((s->GetControlID() == controlID)
3116 && (s->GetProtocol() == protocol)
3117 && (s->UsesAddress(address)))
3118 {
3119 return s;
3120 }
3121 }
3122 return nullptr;
3123 }
3124
3125 const std::string& Manager::GetSignalName(const SignalID signalID) const
3126 {
3127 if (signals.count(signalID) != 1)
3128 {
3129 return unknownSignal;
3130 }
3131 return signals.at(signalID)->GetName();
3132 }
3133
3134 bool Manager::SignalSave(SignalID signalID,
3135 const string& name,
3136 const LayoutPosition posX,
3137 const LayoutPosition posY,
3138 const LayoutPosition posZ,
3139 const LayoutItemSize height,
3140 const LayoutRotation rotation,
3141 const ControlID controlID,
3142 const string& matchKey,
3143 const Protocol protocol,
3144 const Address address,
3145 const Address serverAddress,
3146 const DataModel::AccessoryType type,
3147 const std::map<DataModel::AccessoryState,DataModel::AddressOffset>& offsets,
3148 const DataModel::AccessoryPulseDuration duration,
3149 const bool inverted,
3150 string& result)
3151 {
3152 if (!CheckControlAccessoryProtocolAddress(controlID, protocol, address, result))
3153 {
3154 return false;
3155 }
3156
3157 Signal* signal = GetSignal(signalID);
3158 if (!CheckLayoutItemPosition(signal, posX, posY, posZ, result))
3159 {
3160 return false;
3161 }
3162
3163 if (!signal)
3164 {
3165 signal = CreateAndAddObject(signals, signalMutex);
3166 }
3167
3168 if (!signal)
3169 {
3170 result = Languages::GetText(Languages::TextUnableToAddSignal);
3171 return false;
3172 }
3173
3174 // if we have a new object we have to update locoID
3175 signalID = signal->GetID();
3176
3177 signal->SetName(CheckObjectName(signals, signalMutex, signalID, name.size() == 0 ? "S" : name));
3178 signal->SetPosX(posX);
3179 signal->SetPosY(posY);
3180 signal->SetPosZ(posZ);
3181 signal->SetHeight(height);
3182 signal->SetRotation(rotation);
3183 signal->SetControlID(controlID);
3184 signal->SetMatchKey(matchKey);
3185 signal->SetProtocol(protocol);
3186 signal->SetAddress(address);
3187 signal->SetServerAddress(serverAddress);
3188 signal->SetAccessoryType(type);
3189 signal->SetStateAddressOffsets(offsets);
3190 signal->SetAccessoryPulseDuration(duration);
3191 signal->SetInverted(inverted);
3192
3193 SignalSaveAndPublishSettings(signal);
3194 return true;
3195 }
3196
3197 bool Manager::SignalPosition(const SignalID signalID,
3198 const LayoutPosition posX,
3199 const LayoutPosition posY,
3200 string& result)
3201 {
3202 Signal* signal = GetSignal(signalID);
3203 if (!signal)
3204 {
3205 result = Languages::GetText(Languages::TextSignalDoesNotExist);
3206 return false;
3207 }
3208
3209 if (!CheckLayoutItemPosition(signal, posX, posY, signal->GetPosZ(), result))
3210 {
3211 return false;
3212 }
3213
3214 signal->SetPosX(posX);
3215 signal->SetPosY(posY);
3216
3217 SignalSaveAndPublishSettings(signal);
3218 return true;
3219 }
3220
3221 bool Manager::SignalRotate(const SignalID signalID,
3222 string& result)
3223 {
3224 Signal* signal = GetSignal(signalID);
3225 if (!signal)
3226 {
3227 result = Languages::GetText(Languages::TextSignalDoesNotExist);
3228 return false;
3229 }
3230
3231 signal->Rotate();
3232
3233 SignalSaveAndPublishSettings(signal);
3234 return true;
3235 }
3236
3237 void Manager::SignalSaveAndPublishSettings(const Signal* const signal)
3238 {
3239 // save in db
3240 if (storage)
3241 {
3242 TransactionGuard guard(storage);
3243 storage->Save(*signal);
3244 }
3245
3246 std::lock_guard<std::mutex> guard(controlMutex);
3247 for (auto& control : controls)
3248 {
3249 control.second->SignalSettings(signal->GetID(), signal->GetName(), signal->GetMatchKey());
3250 }
3251 }
3252
3253 bool Manager::SignalDelete(const SignalID signalID,
3254 string& result)
3255 {
3256 Signal* signal = nullptr;
3257 {
3258 std::lock_guard<std::mutex> guard(signalMutex);
3259 if (signalID == SignalNone || signals.count(signalID) != 1)
3260 {
3261 result = Languages::GetText(Languages::TextSignalDoesNotExist);
3262 return false;
3263 }
3264
3265 signal = signals.at(signalID);
3266 if (!signal)
3267 {
3268 result = Languages::GetText(Languages::TextSignalDoesNotExist);
3269 return false;
3270 }
3271
3272 if (signal->IsInUse())
3273 {
3274 result = Logger::Logger::Format(Languages::GetText(Languages::TextSignalIsUsedByLoco), signal->GetName(), GetLocoBaseName(signal->GetLocoBase()));
3275 return false;
3276 }
3277
3278 Track* track = signal->GetTrack();
3279 if (track)
3280 {
3281 result = Logger::Logger::Format(Languages::GetText(Languages::TextSignalIsUsedByTrack), signal->GetName(), track->GetName());
3282 return false;
3283 }
3284
3285 ObjectIdentifier signalIdentifier(ObjectTypeSignal, signalID);
3286 if (ObjectIsPartOfRoute(signalIdentifier, signal, result))
3287 {
3288 return false;
3289 }
3290
3291 signals.erase(signalID);
3292 }
3293
3294 if (storage)
3295 {
3296 TransactionGuard guard(storage);
3297 storage->DeleteSignal(signalID);
3298 }
3299
3300 const string& name = signal->GetName();
3301 const string& matchKey = signal->GetMatchKey();
3302 std::lock_guard<std::mutex> guard(controlMutex);
3303 for (auto& control : controls)
3304 {
3305 control.second->SignalDelete(signalID, name, matchKey);
3306 }
3307
3308 delete signal;
3309 return true;
3310 }
3311
3312 const map<string,DataModel::Signal*> Manager::SignalListByName() const
3313 {
3314 map<string,DataModel::Signal*> out;
3315 std::lock_guard<std::mutex> guard(signalMutex);
3316 for (auto& signal : signals)
3317 {
3318 out[signal.second->GetName()] = signal.second;
3319 }
3320 return out;
3321 }
3322
3323 const map<string,DataModel::AccessoryConfig> Manager::SignalConfigByName() const
3324 {
3325 map<string,DataModel::AccessoryConfig> out;
3326 {
3327 std::lock_guard<std::mutex> guard(signalMutex);
3328 for (auto& signal : signals)
3329 {
3330 out[signal.second->GetName()] = *(signal.second);
3331 }
3332 }
3333
3334 std::lock_guard<std::mutex> guard(controlMutex);
3335 for (auto& control : controls)
3336 {
3337 control.second->AddUnmatchedAccessories(out);
3338 }
3339 return out;
3340 }
3341
3342 Signal* Manager::GetSignalByMatchKey(const ControlID controlId, const string& matchKey) const
3343 {
3344 std::lock_guard<std::mutex> guard(signalMutex);
3345 for (auto& signal : signals)
3346 {
3347 Signal* signalConfig = signal.second;
3348 if (signalConfig->GetControlID() == controlId && signalConfig->GetMatchKey().compare(matchKey) == 0)
3349 {
3350 return signalConfig;
3351 }
3352 }
3353 return nullptr;
3354 }
3355
3356 void Manager::SignalRemoveMatchKey(const SignalID signalId)
3357 {
3358 Signal* signal = GetSignal(signalId);
3359 if (!signal)
3360 {
3361 return;
3362 }
3363 signal->ClearMatchKey();
3364 }
3365
3366 bool Manager::SignalRelease(const SignalID signalID)
3367 {
3368 Signal* signal = GetSignal(signalID);
3369 if (!signal)
3370 {
3371 return false;
3372 }
3373 return signal->Release(logger, ObjectIdentifier());
3374 }
3375
3376 /***************************
3377 * Cluster *
3378 ***************************/
3379
3380 Cluster* Manager::GetCluster(const ClusterID clusterID) const
3381 {
3382 std::lock_guard<std::mutex> guard(clusterMutex);
3383 if (clusters.count(clusterID) != 1)
3384 {
3385 return nullptr;
3386 }
3387 return clusters.at(clusterID);
3388 }
3389
3390 const map<string,DataModel::Cluster*> Manager::ClusterListByName() const
3391 {
3392 map<string,DataModel::Cluster*> out;
3393 std::lock_guard<std::mutex> guard(clusterMutex);
3394 for (auto& cluster : clusters)
3395 {
3396 out[cluster.second->GetName()] = cluster.second;
3397 }
3398 return out;
3399 }
3400
3401 bool Manager::ClusterSave(ClusterID clusterID,
3402 const string& name,
3403 const vector<Relation*>& newTracks,
3404 string& result)
3405 {
3406 Cluster* cluster = GetCluster(clusterID);
3407 if (!cluster)
3408 {
3409 cluster = CreateAndAddObject(clusters, clusterMutex);
3410 }
3411
3412 if (!cluster)
3413 {
3414 result = Languages::GetText(Languages::TextUnableToAddCluster);
3415 return false;
3416 }
3417
3418 // if we have a new object we have to update clusterID
3419 if (clusterID == 0)
3420 {
3421 clusterID = cluster->GetID();
3422 for (auto track : newTracks)
3423 {
3424 track->ObjectID1(clusterID);
3425 }
3426 }
3427
3428 // update existing cluster
3429 cluster->SetName(CheckObjectName(clusters, clusterMutex, clusterID, name.size() == 0 ? "C" : name));
3430 cluster->AssignTracks(newTracks);
3431
3432 // save in db
3433 if (storage)
3434 {
3435 TransactionGuard guard(storage);
3436 storage->Save(*cluster);
3437 }
3438 return true;
3439 }
3440
3441 bool Manager::ClusterDelete(const ClusterID clusterID)
3442 {
3443 if (clusterID == ClusterNone)
3444 {
3445 return false;
3446 }
3447 Cluster* cluster = nullptr;
3448 {
3449 std::lock_guard<std::mutex> guard(clusterMutex);
3450 if (clusters.count(clusterID) != 1)
3451 {
3452 return false;
3453 }
3454
3455 cluster = clusters.at(clusterID);
3456 clusters.erase(clusterID);
3457 }
3458
3459 cluster->DeleteTracks();
3460
3461 if (storage)
3462 {
3463 TransactionGuard guard(storage);
3464 storage->DeleteCluster(clusterID);
3465 }
3466
3467 const string& clusterName = cluster->GetName();
3468 std::lock_guard<std::mutex> guard(controlMutex);
3469 for (auto& control : controls)
3470 {
3471 control.second->ClusterDelete(clusterID, clusterName);
3472 }
3473 delete cluster;
3474 return true;
3475 }
3476
3477 /***************************
3478 * Text *
3479 ***************************/
3480
3481 Text* Manager::GetText(const TextID textID) const
3482 {
3483 std::lock_guard<std::mutex> guard(textMutex);
3484 if (texts.count(textID) != 1)
3485 {
3486 return nullptr;
3487 }
3488 return texts.at(textID);
3489 }
3490
3491 const map<string,DataModel::Text*> Manager::TextListByName() const
3492 {
3493 map<string,DataModel::Text*> out;
3494 std::lock_guard<std::mutex> guard(textMutex);
3495 for (auto& text : texts)
3496 {
3497 out[text.second->GetName()] = text.second;
3498 }
3499 return out;
3500 }
3501
3502 bool Manager::TextSave(TextID textID,
3503 const string& name,
3504 const LayoutPosition posX,
3505 const LayoutPosition posY,
3506 const LayoutPosition posZ,
3507 const LayoutItemSize width,
3508 const LayoutRotation rotation,
3509 string& result)
3510 {
3511 Text* text = GetText(textID);
3512 if (!CheckLayoutItemPosition(text, posX, posY, posZ, width, LayoutItem::Height1, rotation, result))
3513 {
3514 return false;
3515 }
3516
3517 if (!text)
3518 {
3519 text = CreateAndAddObject(texts, textMutex);
3520 }
3521
3522 if (!text)
3523 {
3524 result = Languages::GetText(Languages::TextUnableToAddText);
3525 return false;
3526 }
3527
3528 // if we have a new object we have to update textID
3529 textID = text->GetID();
3530
3531 // update existing text
3532 text->SetName(CheckObjectName(texts, textMutex, textID, name.size() == 0 ? "T" : name));
3533 text->SetPosX(posX);
3534 text->SetPosY(posY);
3535 text->SetPosZ(posZ);
3536 text->SetWidth(width);
3537 text->SetHeight(LayoutItem::Height1);
3538 text->SetRotation(rotation);
3539
3540 TextSaveAndPublishSettings(text);
3541 return true;
3542 }
3543
3544 bool Manager::TextPosition(TextID textID,
3545 const LayoutPosition posX,
3546 const LayoutPosition posY,
3547 string& result)
3548 {
3549 Text* text = GetText(textID);
3550 if (!text)
3551 {
3552 result = Languages::GetText(Languages::TextTextDoesNotExist);
3553 return false;
3554 }
3555
3556 if (!CheckLayoutItemPosition(text, posX, posY, text->GetPosZ(), text->GetWidth(), LayoutItem::Height1, text->GetRotation(), result))
3557 {
3558 return false;
3559 }
3560
3561 text->SetPosX(posX);
3562 text->SetPosY(posY);
3563
3564 TextSaveAndPublishSettings(text);
3565 return true;
3566 }
3567
3568 bool Manager::TextRotate(TextID textID,
3569 string& result)
3570 {
3571 Text* text = GetText(textID);
3572 if (!text)
3573 {
3574 result = Languages::GetText(Languages::TextTextDoesNotExist);
3575 return false;
3576 }
3577
3578 LayoutRotation newRotation = text->GetRotation();
3579 ++newRotation;
3580 if (!CheckLayoutItemPosition(text, text->GetPosX(), text->GetPosY(), text->GetPosZ(), text->GetWidth(), LayoutItem::Height1, newRotation, result))
3581 {
3582 return false;
3583 }
3584
3585 text->SetRotation(newRotation);
3586
3587 TextSaveAndPublishSettings(text);
3588 return true;
3589 }
3590
3591 void Manager::TextSaveAndPublishSettings(const Text* const text)
3592 {
3593 // save in db
3594 if (storage)
3595 {
3596 TransactionGuard guard(storage);
3597 storage->Save(*text);
3598 }
3599
3600 std::lock_guard<std::mutex> guard(controlMutex);
3601 for (auto& control : controls)
3602 {
3603 control.second->TextSettings(text->GetID(), text->GetName());
3604 }
3605 }
3606
3607 bool Manager::TextDelete(const TextID textID, string& result)
3608 {
3609 if (textID == TextNone)
3610 {
3611 result = Languages::GetText(Languages::TextTextDoesNotExist);
3612 return false;
3613 }
3614 Text* text = nullptr;
3615 {
3616 std::lock_guard<std::mutex> guard(textMutex);
3617 if (texts.count(textID) != 1)
3618 {
3619 result = Languages::GetText(Languages::TextTextDoesNotExist);
3620 return false;
3621 }
3622
3623 text = texts.at(textID);
3624 texts.erase(textID);
3625 }
3626
3627 if (storage)
3628 {
3629 TransactionGuard guard(storage);
3630 storage->DeleteText(textID);
3631 }
3632
3633 const string& textName = text->GetName();
3634 std::lock_guard<std::mutex> guard(controlMutex);
3635 for (auto& control : controls)
3636 {
3637 control.second->TextDelete(textID, textName);
3638 }
3639 delete text;
3640 return true;
3641 }
3642
3643 /***************************
3644 * Automode *
3645 ***************************/
3646
3647 bool Manager::LocoBaseIntoTrack(Logger::Logger* logger, const ObjectIdentifier& locoBaseIdentifier, const TrackID trackID)
3648 {
3649 Track* track = GetTrack(trackID);
3650 if (!track)
3651 {
3652 return false;
3653 }
3654
3655 LocoBase* locoBase = GetLocoBase(locoBaseIdentifier);
3656 if (!locoBase)
3657 {
3658 return false;
3659 }
3660
3661 bool reserved = track->ReserveForce(logger, locoBaseIdentifier);
3662 if (!reserved)
3663 {
3664 return false;
3665 }
3666
3667 reserved = locoBase->SetTrack(trackID);
3668 if (!reserved)
3669 {
3670 track->Release(logger, locoBaseIdentifier);
3671 return false;
3672 }
3673
3674 reserved = track->Lock(logger, locoBaseIdentifier);
3675 if (!reserved)
3676 {
3677 locoBase->Release();
3678 track->Release(logger, locoBaseIdentifier);
3679 return false;
3680 }
3681
3682 const string& locoName = locoBase->GetName();
3683 const string& trackName = track->GetName();
3684 logger->Info(Languages::TextLocoIsOnTrack, locoName, trackName);
3685
3686 TrackPublishState(track);
3687 return true;
3688 }
3689
3690 bool Manager::LocoRelease(const LocoID locoID)
3691 {
3692 Loco* loco = GetLoco(locoID);
3693 if (!loco)
3694 {
3695 return false;
3696 }
3697 return LocoBaseReleaseInternal(loco);
3698 }
3699
3700 bool Manager::MultipleUnitRelease(const MultipleUnitID multipleUnitID)
3701 {
3702 MultipleUnit* multipleUnit = GetMultipleUnit(multipleUnitID);
3703 if (!multipleUnit)
3704 {
3705 return false;
3706 }
3707 return LocoBaseReleaseInternal(multipleUnit);
3708 }
3709
3710 bool Manager::LocoBaseReleaseInternal(LocoBase* locoBase)
3711 {
3712 LocoBaseSpeed(ControlTypeInternal, locoBase, MinSpeed);
3713
3714 bool ret = locoBase->Release();
3715 if (!ret)
3716 {
3717 return false;
3718 }
3719 std::lock_guard<std::mutex> guard(controlMutex);
3720 for (auto& control : controls)
3721 {
3722 control.second->LocoBaseRelease(locoBase);
3723 }
3724 return true;
3725 }
3726
3727 bool Manager::TrackRelease(const TrackID trackID)
3728 {
3729 Track* track = GetTrack(trackID);
3730 if (!track)
3731 {
3732 return false;
3733 }
3734 return track->ReleaseForce(logger, ObjectIdentifier());
3735 }
3736
3737 bool Manager::LocoBaseReleaseOnTrack(const TrackID trackID)
3738 {
3739 Track* track = GetTrack(trackID);
3740 if (!track)
3741 {
3742 return false;
3743 }
3744 const ObjectIdentifier locoBaseIdentifier = track->GetLocoBase();
3745 track->ReleaseForce(logger, locoBaseIdentifier);
3746 LocoBase* locoBase = GetLocoBase(locoBaseIdentifier);
3747 if (!locoBase)
3748 {
3749 return false;
3750 }
3751 return LocoBaseReleaseInternal(locoBase);
3752 }
3753
3754 bool Manager::TrackStartLocoBase(const TrackID trackID)
3755 {
3756 Track* track = GetTrack(trackID);
3757 if (!track)
3758 {
3759 return false;
3760 }
3761 return LocoBaseStart(track->GetLocoBase());
3762 }
3763
3764 bool Manager::TrackStopLocoBase(const TrackID trackID)
3765 {
3766 Track* track = GetTrack(trackID);
3767 if (!track)
3768 {
3769 return false;
3770 }
3771 return LocoBaseStop(track->GetLocoBase());
3772 }
3773
3774 void Manager::TrackBlock(const TrackID trackID, const bool blocked)
3775 {
3776 Track* track = GetTrack(trackID);
3777 if (!track)
3778 {
3779 return;
3780 }
3781 track->SetBlocked(blocked);
3782 TrackPublishState(track);
3783 }
3784
3785 void Manager::TrackSetLocoOrientation(const TrackID trackID, const Orientation orientation)
3786 {
3787 Track* track = GetTrack(trackID);
3788 if (!track)
3789 {
3790 return;
3791 }
3792 track->SetLocoBaseOrientation(orientation);
3793 TrackPublishState(track);
3794 }
3795
3796 void Manager::TrackPublishState(const DataModel::Track* track)
3797 {
3798 {
3799 std::lock_guard<std::mutex> guard(controlMutex);
3800 for (auto& control : controls)
3801 {
3802 control.second->TrackState(track);
3803 }
3804 }
3805 vector<Track*> extensions = track->GetExtensions();
3806 for (Track* extension : extensions)
3807 {
3808 TrackPublishState(extension);
3809 }
3810 }
3811
3812 bool Manager::RouteRelease(const RouteID routeID)
3813 {
3814 Route* route = GetRoute(routeID);
3815 if (!route)
3816 {
3817 return false;
3818 }
3819 return route->Release(logger, route->GetLocoBase());
3820 }
3821
3822 bool Manager::LocoDestinationReached(const LocoBase* loco,
3823 const Route* route,
3824 const Track* track)
3825 {
3826 std::lock_guard<std::mutex> guard(controlMutex);
3827 for (auto& control : controls)
3828 {
3829 control.second->LocoBaseDestinationReached(loco, route, track);
3830 }
3831 return true;
3832 }
3833
3834 bool Manager::LocoBaseStart(const ObjectIdentifier& locoBaseIdentifier)
3835 {
3836 LocoBase* locoBase = GetLocoBase(locoBaseIdentifier);
3837 if (!locoBase)
3838 {
3839 return false;
3840 }
3841 bool ret = locoBase->GoToAutoMode();
3842 if (!ret)
3843 {
3844 return false;
3845 }
3846 std::lock_guard<std::mutex> guard(controlMutex);
3847 for (auto& control : controls)
3848 {
3849 control.second->LocoBaseStart(locoBase);
3850 }
3851 return true;
3852 }
3853
3854 bool Manager::LocoBaseStartAll()
3855 {
3856 {
3857 std::lock_guard<std::mutex> guard(locoMutex);
3858 for (auto& loco : locos)
3859 {
3860 const bool started = loco.second->GoToAutoMode();
3861 if (!started)
3862 {
3863 continue;
3864 }
3865 Utils::Utils::SleepForMilliseconds(50);
3866 }
3867 }
3868 {
3869 std::lock_guard<std::mutex> guard(multipleUnitMutex);
3870 for (auto& multipleUnit : multipleUnits)
3871 {
3872 const bool started = multipleUnit.second->GoToAutoMode();
3873 if (!started)
3874 {
3875 continue;
3876 }
3877 Utils::Utils::SleepForMilliseconds(50);
3878 }
3879 }
3880 return true;
3881 }
3882
3883 bool Manager::LocoBaseStop(const ObjectIdentifier& locoBaseIdentifier)
3884 {
3885 LocoBase* locoBase = GetLocoBase(locoBaseIdentifier);
3886 if (!locoBase)
3887 {
3888 return false;
3889 }
3890 if (locoBase->IsInManualMode())
3891 {
3892 return true;
3893 }
3894 locoBase->RequestManualMode();
3895 while (!locoBase->GoToManualMode())
3896 {
3897 Utils::Utils::SleepForSeconds(1);
3898 }
3899 std::lock_guard<std::mutex> guard(controlMutex);
3900 for (auto& control : controls)
3901 {
3902 control.second->LocoBaseStop(locoBase);
3903 }
3904 return true;
3905 }
3906
3907 bool Manager::LocoBaseStopAll()
3908 {
3909 {
3910 std::lock_guard<std::mutex> guard(multipleUnitMutex);
3911 for (auto& multipleUnit : multipleUnits)
3912 {
3913 if (multipleUnit.second->IsInManualMode())
3914 {
3915 continue;
3916 }
3917 multipleUnit.second->RequestManualMode();
3918 }
3919 }
3920 {
3921 std::lock_guard<std::mutex> guard(locoMutex);
3922 for (auto& loco : locos)
3923 {
3924 if (!loco.second->IsInManualMode())
3925 {
3926 continue;
3927 }
3928 loco.second->RequestManualMode();
3929 }
3930 }
3931 bool anyLocosInAutoMode = true;
3932 while (anyLocosInAutoMode && !isKillRunning())
3933 {
3934 Utils::Utils::SleepForSeconds(1);
3935 anyLocosInAutoMode = false;
3936 {
3937 std::lock_guard<std::mutex> guard(multipleUnitMutex);
3938 for (auto& multipleUnit : multipleUnits)
3939 {
3940 if (multipleUnit.second->IsInManualMode())
3941 {
3942 continue;
3943 }
3944 const bool multipleUnitInManualMode = multipleUnit.second->GoToManualMode();
3945 if (!multipleUnitInManualMode)
3946 {
3947 multipleUnit.second->RequestManualMode();
3948 }
3949 anyLocosInAutoMode |= !multipleUnitInManualMode;
3950 }
3951 }
3952 {
3953 std::lock_guard<std::mutex> guard(locoMutex);
3954 for (auto& loco : locos)
3955 {
3956 if (loco.second->IsInManualMode())
3957 {
3958 continue;
3959 }
3960 const bool locoInManualMode = loco.second->GoToManualMode();
3961 if (!locoInManualMode)
3962 {
3963 loco.second->RequestManualMode();
3964 }
3965 anyLocosInAutoMode |= !locoInManualMode;
3966 }
3967 }
3968 }
3969
3970 for (auto& multipleUnit : multipleUnits)
3971 {
3972 if (multipleUnit.second->IsInManualMode())
3973 {
3974 continue;
3975 }
3976 multipleUnit.second->GetLogger()->Info(Languages::Languages::TextReleasingMultipleUnit);
3977 multipleUnit.second->Release();
3978 }
3979 for (auto& loco : locos)
3980 {
3981 if (loco.second->IsInManualMode())
3982 {
3983 continue;
3984 }
3985 loco.second->GetLogger()->Info(Languages::Languages::TextReleasingLoco);
3986 loco.second->Release();
3987 }
3988 return true;
3989 }
3990
3991 void Manager::LocoBaseStopAllImmediately(const ControlType controlType)
3992 {
3993 {
3994 std::lock_guard<std::mutex> guard(locoMutex);
3995 for (auto& loco : locos)
3996 {
3997 LocoBaseSpeed(controlType, loco.second, MinSpeed);
3998 }
3999 }
4000 {
4001 std::lock_guard<std::mutex> guard(multipleUnitMutex);
4002 for (auto& multipleUnit : multipleUnits)
4003 {
4004 LocoBaseSpeed(controlType, multipleUnit.second, MinSpeed);
4005 }
4006 }
4007 }
4008
4009 bool Manager::LocoBaseAddTimeTable(const ObjectIdentifier& locoBaseIdentifier,
4010 const RouteID routeID,
4011 const bool automode)
4012 {
4013 LocoBase* locoBase = GetLocoBase(locoBaseIdentifier);
4014 if (!locoBase)
4015 {
4016 return false;
4017 }
4018 Route* route = GetRoute(routeID);
4019 if (!route)
4020 {
4021 return false;
4022 }
4023 locoBase->AddTimeTable(route, automode ? RouteAuto : RouteStop);
4024 return true;
4025 }
4026
4027 string Manager::GetCs2Lokomotive() const
4028 {
4029 string out("[lokomotive]\nversion\n .major=0\n .minor=3\nsession\n .id=");
4030 out += "1"; // FIXME: replace with mfx-neuanmeldezähler
4031 {
4032 std::lock_guard<std::mutex> guard(locoMutex);
4033 for (auto& loco : locos)
4034 {
4035 out += "\nlokomotive";
4036 out += "\n .name=" + loco.second->GetName();
4037 out += "\n .typ=";
4038 const Address address = loco.second->GetAddress();
4039 uint32_t uid;
4040 switch(loco.second->GetProtocol())
4041 {
4042 case ProtocolMM:
4043 out += "mm2_prog";
4044 uid = address;
4045 break;
4046
4047 case ProtocolDCC:
4048 out += "dcc";
4049 uid = address + 0xC000;
4050 break;
4051
4052 case ProtocolMFX:
4053 out += "mfx";
4054 uid = address + 0x4000;
4055 break;
4056
4057 default:
4058 out += "unknown";
4059 uid = 0;
4060 break;
4061 }
4062 out += "\n .uid=0x" + Utils::Integer::IntegerToHex(uid);
4063 out += "\n .adresse=0x" + Utils::Integer::IntegerToHex(address);
4064 out += "\n .icon=";
4065 out += "\n .symbol=";
4066 out += "\n .av=0";
4067 out += "\n .bv=0";
4068 out += "\n .velocity=" + to_string(loco.second->GetSpeed());
4069 out += "\n .richtung=" + to_string(loco.second->GetOrientation());
4070 out += "\n .tachomax=120";
4071 out += "\n .vmax=255";
4072 out += "\n .vmin=1";
4073 for (LocoFunctionNr nr = 0; nr < 32; ++nr)
4074 {
4075 out += "\n .funktionen";
4076 if (nr >= 16)
4077 {
4078 out += "_2";
4079 }
4080 out += "\n ..nr=" + to_string(nr);
4081 out += "\n ..typ=" + to_string(Hardware::Protocols::MaerklinCANCommon::MapLocofunctionRailControlToCs2(nr, loco.second->GetFunctionIcon(nr)));
4082 out += "\n ..dauer=" + to_string(loco.second->GetFunctionType(nr));
4083 out += "\n ..wert=" + to_string(loco.second->GetFunctionState(nr));;
4084 }
4085 }
4086 }
4087 return out + "\n";
4088 }
4089
4090 string Manager::GetCs2Magnetartikel(const AccessoryBase* accessoryBase)
4091 {
4092 string out = "\nartikel";
4093 out += "\n .id=" + to_string(accessoryBase->GetAddress());
4094 out += "\n .name=";
4095 const Object* object = dynamic_cast<const Object*>(accessoryBase);
4096 if (object)
4097 {
4098 out += object->GetName();
4099 }
4100 else
4101 {
4102 out += to_string(accessoryBase->GetAddress());
4103 }
4104
4105 out += "\n .typ=std_rot_gruen";
4106 out += "\n .schaltzeit=" + to_string(accessoryBase->GetAccessoryPulseDuration());
4107 out += "\n .dectyp=";
4108 switch(accessoryBase->GetProtocol())
4109 {
4110 case ProtocolMM:
4111 out += "mm2";
4112 break;
4113
4114 case ProtocolDCC:
4115 out += "dcc";
4116 break;
4117
4118 default:
4119 out += "unknown";
4120 break;
4121 }
4122 return out + "\n";
4123 }
4124
4125 string Manager::GetCs2Magnetartikel() const
4126 {
4127 string out("[magnetartikel]\nversion\n. major=0\n. minor=1");
4128 {
4129 std::lock_guard<std::mutex> guard(accessoryMutex);
4130 for (auto& accessory : accessories)
4131 {
4132 out += GetCs2Magnetartikel(accessory.second);
4133 out += "\n .typ=std_rot_gruen";
4134 }
4135 }
4136 {
4137 std::lock_guard<std::mutex> guard(switchMutex);
4138 for (auto& mySwitch : switches)
4139 {
4140 out += GetCs2Magnetartikel(mySwitch.second);
4141 out += "\n .typ=";
4142 switch (mySwitch.second->GetAccessoryType())
4143 {
4144 case SwitchTypeLeft:
4145 out += "linksweiche";
4146 break;
4147
4148 case SwitchTypeRight:
4149 out += "rechtsweiche";
4150 break;
4151
4152 case SwitchTypeThreeWay:
4153 out += "dreiwegweiche";
4154 break;
4155
4156 case SwitchTypeMaerklinLeft:
4157 case SwitchTypeMaerklinRight:
4158 out += "dkw_1antrieb";
4159 break;
4160
4161 default:
4162 out += "y_weiche";
4163 break;
4164 }
4165 }
4166 }
4167 {
4168 std::lock_guard<std::mutex> guard(signalMutex);
4169 for (auto& signal : signals)
4170 {
4171 out += GetCs2Magnetartikel(signal.second);
4172 out += "\n .typ=";
4173 switch (signal.second->GetAccessoryType())
4174 {
4175 case SignalTypeChDwarf:
4176 case SignalTypeDeBlock:
4177 out += "lichtsignal_SH01";
4178 break;
4179
4180 case SignalTypeChLMain:
4181 case SignalTypeChLCombined:
4182 case SignalTypeChNMain:
4183 case SignalTypeDeCombined:
4184 case SignalTypeDeHVMain:
4185 out += "urc_lichtsignal_HP012_SH01";
4186 break;
4187
4188 case SignalTypeChLDistant:
4189 case SignalTypeChNDistant:
4190 case SignalTypeDeHVDistant:
4191 out += "lichtvorsignal_VR012";
4192 break;
4193
4194 case SignalTypeSimpleLeft:
4195 case SignalTypeSimpleRight:
4196 default:
4197 out += "lichtsignal_HP01";
4198 break;
4199 }
4200 }
4201 }
4202 return out + "\n";
4203 }
4204
4205 string Manager::GetCs2GBS() const
4206 {
4207 string out("[gleisbild]\nversion\n. major=1");
4208 {
4209 std::lock_guard<std::mutex> guard(layerMutex);
4210 for (auto& layer : layers)
4211 {
4212 out += "\nseite";
4213 if (layer.first != LayerUndeletable)
4214 {
4215 out += "\n .id=" + to_string(layer.first);
4216 }
4217 out += "\n .name=" + layer.second->GetName();
4218 }
4219 }
4220 return out + "\n";
4221 }
4222
4223 string Manager::GetCs2GBS(const signed char gbs) const
4224 {
4225 string out("[gleisbildseite]\nversion\n. major=1");
4226 unsigned int z = gbs;
4227 if (gbs == LayerUndeletable)
4228 {
4229 // default layer Z in CS2 is 0, in RailControl 1. So we map this.
4230 --z;
4231 }
4232 else
4233 {
4234 out += "\npage=" + to_string(gbs);
4235 }
4236 z <<= 16;
4237
4238 {
4239 std::lock_guard<std::mutex> guard(trackMutex);
4240 for (auto& track : tracks)
4241 {
4242 if (gbs == track.second->GetPosZ())
4243 {
4244 out += "\nelement";
4245 const unsigned int id = z + (track.second->GetPosX() << 8) + track.second->GetPosY();
4246 out += "\n .id=0x" + Utils::Integer::IntegerToHex(id);
4247 out += "\n .typ=";
4248 switch(track.second->GetTrackType())
4249 {
4250 case TrackTypeTurn:
4251 out += "bogen";
4252 break;
4253
4254 case TrackTypeEnd:
4255 case TrackTypeLink:
4256 out += "prellbock";
4257 break;
4258
4259 case TrackTypeTunnelEnd:
4260 out += "prellbock";
4261 break;
4262
4263 case TrackTypeStraight:
4264 case TrackTypeBridge:
4265 case TrackTypeTunnel:
4266 case TrackTypeCrossingLeft:
4267 case TrackTypeCrossingRight:
4268 case TrackTypeCrossingSymetric:
4269 default:
4270 out += "gerade";
4271 break;
4272 }
4273 out += "\n .drehung=" + to_string(track.second->GetRotation() & 0x01);
4274 out += "\n .artikel=-1";
4275 }
4276 }
4277 }
4278 {
4279 std::lock_guard<std::mutex> guard(accessoryMutex);
4280 for (auto& accessory : accessories)
4281 {
4282 if (gbs == accessory.second->GetPosZ())
4283 {
4284 out += "\nelement";
4285 const unsigned int id = z + (accessory.second->GetPosX() << 8) + accessory.second->GetPosY();
4286 out += "\n .id=0x" + Utils::Integer::IntegerToHex(id);
4287 out += "\n .typ=k84_einfach";
4288 out += "\n .artikel=" + to_string(accessory.second->GetAddress());
4289 }
4290 }
4291 }
4292 {
4293 std::lock_guard<std::mutex> guard(switchMutex);
4294 for (auto& mySwitch : switches)
4295 {
4296 if (gbs == mySwitch.second->GetPosZ())
4297 {
4298 out += "\nelement";
4299 const unsigned int id = z + (mySwitch.second->GetPosX() << 8) + mySwitch.second->GetPosY();
4300 out += "\n .id=0x" + Utils::Integer::IntegerToHex(id);
4301 out += "\n .typ=";
4302 switch(mySwitch.second->GetAccessoryType())
4303 {
4304 case SwitchTypeLeft:
4305 out += "linksweiche";
4306 break;
4307
4308 case SwitchTypeRight:
4309 out += "rechtsweiche";
4310 break;
4311
4312 case SwitchTypeThreeWay:
4313 out += "dreiwegweiche";
4314 break;
4315
4316 case SwitchTypeMaerklinLeft:
4317 out += "dkw3_li";
4318 break;
4319
4320 case SwitchTypeMaerklinRight:
4321 out += "dkw3_re";
4322 break;
4323
4324 default:
4325 break;
4326 }
4327 out += "\n .drehung=" + to_string(mySwitch.second->GetRotation());
4328 out += "\n .artikel=" + to_string(mySwitch.second->GetAddress());
4329 out += "\n .zustand=" + to_string(mySwitch.second->GetAccessoryState());
4330 }
4331 }
4332 }
4333 return out + "\n";
4334 }
4335
4336 /***************************
4337 * Layout *
4338 ***************************/
4339
4340 bool Manager::CheckPositionFree(const LayoutPosition posX, const LayoutPosition posY, const LayoutPosition posZ, string& result) const
4341 {
4342 return CheckLayoutPositionFree(posX, posY, posZ, result, accessories, accessoryMutex)
4343 && CheckLayoutPositionFree(posX, posY, posZ, result, tracks, trackMutex)
4344 && CheckLayoutPositionFree(posX, posY, posZ, result, feedbacks, feedbackMutex)
4345 && CheckLayoutPositionFree(posX, posY, posZ, result, switches, switchMutex)
4346 && CheckLayoutPositionFree(posX, posY, posZ, result, routes, routeMutex)
4347 && CheckLayoutPositionFree(posX, posY, posZ, result, signals, signalMutex)
4348 && CheckLayoutPositionFree(posX, posY, posZ, result, texts, textMutex);
4349 }
4350
4351 bool Manager::CheckPositionFree(const LayoutPosition posX,
4352 const LayoutPosition posY,
4353 const LayoutPosition posZ,
4354 const LayoutItemSize width,
4355 const LayoutItemSize height,
4356 const LayoutRotation rotation,
4357 string& result) const
4358 {
4359 if (width == 0)
4360 {
4361 result.assign(Languages::GetText(Languages::TextWidthIs0));
4362 return false;
4363 }
4364 if (height == 0)
4365 {
4366 result.assign(Languages::GetText(Languages::TextHeightIs0));
4367 return false;
4368 }
4369 LayoutPosition x;
4370 LayoutPosition y;
4371 LayoutPosition z = posZ;
4372 LayoutItemSize w;
4373 LayoutItemSize h;
4374 bool ret = DataModel::LayoutItem::MapPosition(posX, posY, width, height, rotation, x, y, w, h);
4375 if (!ret)
4376 {
4377 return false;
4378 }
4379 for (LayoutPosition ix = x; ix < x + w; ix++)
4380 {
4381 for (LayoutPosition iy = y; iy < y + h; iy++)
4382 {
4383 bool ret = CheckPositionFree(ix, iy, z, result);
4384 if (!ret)
4385 {
4386 return false;
4387 }
4388 }
4389 }
4390 return true;
4391 }
4392
4393 bool Manager::CheckLayoutItemPosition(const LayoutItem* item,
4394 const LayoutPosition posX,
4395 const LayoutPosition posY,
4396 const LayoutPosition posZ,
4397 string& result) const
4398 {
4399 if (item)
4400 {
4401 if (item->IsVisibleOnLayer(posZ) == DataModel::LayoutItem::VisibleNo ||
4402 item->HasPosition(posX, posY, posZ))
4403 {
4404 return true;
4405 }
4406 }
4407 return CheckPositionFree(posX, posY, posZ, DataModel::LayoutItem::Width1, DataModel::LayoutItem::Height1, DataModel::LayoutItem::Rotation0, result);
4408 }
4409
4410 bool Manager::CheckLayoutItemPosition(const LayoutItem* item,
4411 const LayoutPosition posX,
4412 const LayoutPosition posY,
4413 const LayoutPosition posZ,
4414 const LayoutItemSize width,
4415 const LayoutItemSize height,
4416 const LayoutRotation rotation,
4417 string& result) const
4418 {
4419 LayoutPosition x1;
4420 LayoutPosition y1;
4421 LayoutPosition z1 = posZ;
4422 LayoutItemSize w1;
4423 LayoutItemSize h1;
4424 bool ret = DataModel::LayoutItem::MapPosition(posX, posY, width, height, rotation, x1, y1, w1, h1);
4425 if (!ret)
4426 {
4427 result = Languages::GetText(Languages::TextUnableToCalculatePosition);
4428 return false;
4429 }
4430
4431 LayoutPosition x2 = 0;
4432 LayoutPosition y2 = 0;
4433 LayoutPosition z2 = 0;
4434 LayoutItemSize w2 = 0;
4435 LayoutItemSize h2 = 0;
4436
4437 if (item)
4438 {
4439 z2 = item->GetPosZ();
4440 ret = DataModel::LayoutItem::MapPosition(item->GetPosX(), item->GetPosY(), width, item->GetHeight(), item->GetRotation(), x2, y2, w2, h2);
4441 if (!ret)
4442 {
4443 result = Languages::GetText(Languages::TextUnableToCalculatePosition);
4444 return false;
4445 }
4446 }
4447
4448 for (LayoutPosition ix = x1; ix < x1 + w1; ++ix)
4449 {
4450 for (LayoutPosition iy = y1; iy < y1 + h1; ++iy)
4451 {
4452 ret = (ix >= x2 && ix < x2 + w2 && iy >= y2 && iy < y2 + h2 && z1 == z2);
4453 if (ret)
4454 {
4455 continue;
4456 }
4457
4458 ret = CheckPositionFree(ix, iy, z1, result);
4459 if (!ret)
4460 {
4461 return false;
4462 }
4463 }
4464 }
4465 return true;
4466 }
4467
4468 template<class Type>
4469 bool Manager::CheckLayoutPositionFree(const LayoutPosition posX, const LayoutPosition posY, const LayoutPosition posZ, string& result, const map<ObjectID, Type*>& layoutVector, std::mutex& mutex) const
4470 {
4471 std::lock_guard<std::mutex> guard(mutex);
4472 for (auto& layout : layoutVector)
4473 {
4474 if (layout.second->CheckPositionFree(posX, posY, posZ))
4475 {
4476 continue;
4477 }
4478 result.assign(Logger::Logger::Format(Languages::GetText(Languages::TextPositionAlreadyInUse), static_cast<int>(posX), static_cast<int>(posY), static_cast<int>(posZ), layout.second->GetLayoutType(), layout.second->GetName()));
4479 return false;
4480 }
4481 return true;
4482 }
4483
4484 bool Manager::CheckAddressLoco(const Protocol protocol, const Address address, string& result)
4485 {
4486 switch (protocol)
4487 {
4488 case ProtocolDCC:
4489 case ProtocolDCC14:
4490 case ProtocolDCC28:
4491 case ProtocolDCC128:
4492 if (address > 10239)
4493 {
4494 result.assign(Languages::GetText(Languages::TextLocoAddressDccTooHigh));
4495 return false;
4496 }
4497 return true;
4498
4499 case ProtocolMM1:
4500 case ProtocolMM15:
4501 if (address > 80)
4502 {
4503 result.assign(Languages::GetText(Languages::TextLocoAddressMm1TooHigh));
4504 return false;
4505 }
4506 return true;
4507
4508 case ProtocolMM:
4509 case ProtocolMM2:
4510 if (address > 255)
4511 {
4512 result.assign(Languages::GetText(Languages::TextLocoAddressMm2TooHigh));
4513 return false;
4514 }
4515 return true;
4516
4517 default:
4518 return true;
4519 }
4520 }
4521
4522 bool Manager::CheckAddressAccessory(const Protocol protocol, const Address address, string& result)
4523 {
4524 switch (protocol)
4525 {
4526 case ProtocolDCC:
4527 if (address > 2044)
4528 {
4529 result.assign(Languages::GetText(Languages::TextAccessoryAddressDccTooHigh));
4530 return false;
4531 }
4532 return true;
4533
4534 case ProtocolMM1:
4535 case ProtocolMM2:
4536 if (address > 320) {
4537 result.assign(Languages::GetText(Languages::TextAccessoryAddressMmTooHigh));
4538 return false;
4539 }
4540 return true;
4541
4542 default:
4543 return true;
4544 }
4545 }
4546
4547 bool Manager::CheckControlProtocolAddress(const AddressType type, const ControlID controlID, const Protocol protocol, const Address address, string& result)
4548 {
4549 if (address == AddressNone)
4550 {
4551 result.assign(Logger::Logger::Format(Languages::GetText(Languages::TextAddressMustBeHigherThen0)));
4552 return false;
4553 }
4554
4555 if ((type == AddressTypeMultipleUnit) && (controlID == ControlNone))
4556 {
4557 // multiple units do not need physical control
4558 return true;
4559 }
4560
4561 {
4562 std::lock_guard<std::mutex> guard(controlMutex);
4563 if (controlID < ControlIdFirstHardware || controls.count(controlID) != 1)
4564 {
4565 result.assign(Languages::GetText(Languages::TextControlDoesNotExist));
4566 return false;
4567 }
4568 ControlInterface* control = controls.at(controlID);
4569 if (!control)
4570 {
4571 result.assign(Languages::GetText(Languages::TextControlDoesNotExist));
4572 return false;
4573 }
4574 bool protocolSupported;
4575 switch (type)
4576 {
4577 case AddressTypeLoco:
4578 protocolSupported = control->LocoProtocolSupported(protocol);
4579 break;
4580
4581 case AddressTypeMultipleUnit:
4582 protocolSupported = true;
4583 break;
4584
4585 case AddressTypeAccessory:
4586 protocolSupported = control->AccessoryProtocolSupported(protocol);
4587 break;
4588
4589 default:
4590 protocolSupported = false;
4591 break;
4592 }
4593
4594 if (!protocolSupported)
4595 {
4596 string protocolText;
4597 if (protocol <= ProtocolEnd)
4598 {
4599 protocolText = ProtocolSymbols[protocol] + " ";
4600 }
4601 std::vector<Protocol> protocols;
4602 switch (type)
4603 {
4604 case AddressTypeLoco:
4605 control->LocoProtocols(protocols);
4606 break;
4607
4608 case AddressTypeAccessory:
4609 control->AccessoryProtocols(protocols);
4610 break;
4611
4612 case AddressTypeMultipleUnit:
4613 default:
4614 break;
4615 }
4616
4617 string protocolsText;
4618 for (auto p : protocols)
4619 {
4620 if (protocolsText.size() > 0)
4621 {
4622 protocolsText.append(", ");
4623 }
4624 protocolsText.append(ProtocolSymbols[p]);
4625 }
4626 result.assign(Logger::Logger::Format(Languages::GetText(Languages::TextProtocolNotSupported), protocolText, protocolsText));
4627 return false;
4628 }
4629 } // unlock controlMutex
4630
4631 switch (type)
4632 {
4633 case AddressTypeLoco:
4634 return CheckAddressLoco(protocol, address, result);
4635
4636 case AddressTypeMultipleUnit:
4637 return true;
4638
4639 case AddressTypeAccessory:
4640 return CheckAddressAccessory(protocol, address, result);
4641
4642 default:
4643 return false;
4644 }
4645 }
4646
4647 bool Manager::SettingsSave(const Languages::Language language,
4648 const StartupInitLocos startupInitLocos,
4649 const DataModel::AccessoryPulseDuration duration,
4650 const bool autoAddFeedback,
4651 const bool stopOnFeedbackInFreeTrack,
4652 const bool executeAccessoryAlways,
4653 const DataModel::SelectRouteApproach selectRouteApproach,
4654 const DataModel::Loco::NrOfTracksToReserve nrOfTracksToReserve,
4655 const Logger::Logger::Level logLevel
4656 )
4657 {
4658 Languages::SetDefaultLanguage(language);
4659 this->startupInitLocos = startupInitLocos;
4660 this->defaultAccessoryDuration = duration;
4661 this->autoAddFeedback = autoAddFeedback;
4662 this->stopOnFeedbackInFreeTrack = stopOnFeedbackInFreeTrack;
4663 this->executeAccessory = executeAccessoryAlways;
4664 this->selectRouteApproach = selectRouteApproach;
4665 this->nrOfTracksToReserve = nrOfTracksToReserve;
4666 Logger::Logger::SetLogLevel(logLevel);
4667
4668 if (!storage)
4669 {
4670 return false;
4671 }
4672 Storage::TransactionGuard guard(storage);
4673 storage->SaveSetting("Language", std::to_string(static_cast<int>(language)));
4674 storage->SaveSetting("StartupInitLocos", std::to_string(static_cast<int>(startupInitLocos)));
4675 storage->SaveSetting("DefaultAccessoryDuration", std::to_string(duration));
4676 storage->SaveSetting("AutoAddFeedback", std::to_string(autoAddFeedback));
4677 storage->SaveSetting("StopOnFeedbackInFreeTrack", std::to_string(stopOnFeedbackInFreeTrack));
4678 storage->SaveSetting("ExecuteAccessory", std::to_string(executeAccessory));
4679 storage->SaveSetting("SelectRouteApproach", std::to_string(static_cast<int>(selectRouteApproach)));
4680 storage->SaveSetting("NrOfTracksToReserve", std::to_string(static_cast<int>(nrOfTracksToReserve)));
4681 storage->SaveSetting("LogLevel", std::to_string(static_cast<int>(logLevel)));
4682 return true;
4683 }
4684
4685 void Manager::DebounceWorker()
4686 {
4687 Utils::Utils::SetThreadName(Languages::GetText(Languages::TextDebouncer));
4688 logger->Info(Languages::TextDebounceThreadStarted);
4689 while (debounceRun)
4690 {
4691 {
4692 std::lock_guard<std::mutex> guard(feedbackMutex);
4693 for (auto& feedback : feedbacks)
4694 {
4695 feedback.second->Debounce();
4696 }
4697 }
4698 Utils::Utils::SleepForMilliseconds(250);
4699 }
4700 logger->Info(Languages::TextDebounceThreadTerminated);
4701 }
4702
4703 template<class ID, class T>
4704 T* Manager::CreateAndAddObject(std::map<ID,T*>& objects, std::mutex& mutex)
4705 {
4706 std::lock_guard<std::mutex> Guard(mutex);
4707 ID newObjectID = 0;
4708 for (auto& object : objects)
4709 {
4710 if (object.first > newObjectID)
4711 {
4712 newObjectID = object.first;
4713 }
4714 }
4715 ++newObjectID;
4716 T* newObject = new T(this, newObjectID);
4717 if (!newObject)
4718 {
4719 return nullptr;
4720 }
4721 objects[newObjectID] = newObject;
4722 return newObject;
4723 }
4724
4725 ControlID Manager::GetPossibleControlForLoco() const
4726 {
4727 for (auto& control : controls)
4728 {
4729 if (control.second->CanHandle(Hardware::CapabilityLoco))
4730 {
4731 return control.first;
4732 }
4733 }
4734 return ControlIdNone;
4735 }
4736
4737 ControlID Manager::GetPossibleControlForAccessory() const
4738 {
4739 for (auto& control : controls)
4740 {
4741 if (control.second->CanHandle(Hardware::CapabilityAccessory))
4742 {
4743 return control.first;
4744 }
4745 }
4746 return ControlIdNone;
4747 }
4748
4749 ControlID Manager::GetPossibleControlForFeedback() const
4750 {
4751 for (auto& control : controls)
4752 {
4753 if (control.second->CanHandle(Hardware::CapabilityFeedback))
4754 {
4755 return control.first;
4756 }
4757 }
4758 return ControlIdNone;
4759 }
4760
4761 void Manager::ProgramCheckBooster(const ProgramMode mode)
4762 {
4763 switch (mode)
4764 {
4765 case ProgramModeDccPomLoco:
4766 case ProgramModeDccPomAccessory:
4767 if (boosterState == BoosterStateGo)
4768 {
4769 return;
4770 }
4771 Booster(ControlTypeInternal, BoosterStateGo);
4772 Utils::Utils::SleepForMilliseconds(100);
4773 return;
4774
4775 default:
4776 return;
4777 }
4778 }
4779
4780 void Manager::ProgramRead(const ControlID controlID, const ProgramMode mode, const Address address, const CvNumber cv)
4781 {
4782 ControlInterface* control = GetControl(controlID);
4783 if (!control)
4784 {
4785 return;
4786 }
4787 ProgramCheckBooster(mode);
4788 control->ProgramRead(mode, address, cv);
4789 }
4790
4791 void Manager::ProgramWrite(const ControlID controlID, const ProgramMode mode, const Address address, const CvNumber cv, const CvValue value)
4792 {
4793 ControlInterface* control = GetControl(controlID);
4794 if (!control)
4795 {
4796 return;
4797 }
4798 ProgramCheckBooster(mode);
4799 control->ProgramWrite(mode, address, cv, value);
4800 }
4801
4802 void Manager::ProgramValue(const CvNumber cv, const CvValue value)
4803 {
4804 std::lock_guard<std::mutex> guard(controlMutex);
4805 for (auto& control : controls)
4806 {
4807 control.second->ProgramValue(cv, value);;
4808 }
4809 }
4810
4811 bool Manager::CanHandle(const Hardware::Capabilities capability) const
4812 {
4813 std::lock_guard<std::mutex> guard(controlMutex);
4814 for (auto& control : controls)
4815 {
4816 bool ret = control.second->CanHandle(capability);
4817 if (ret)
4818 {
4819 return true;
4820 }
4821 }
4822 return false;
4823 }
4824
4825 bool Manager::CanHandle(const ControlID controlId, const Hardware::Capabilities capability) const
4826 {
4827 ControlInterface* control = GetControl(controlId);
4828 if (!control)
4829 {
4830 return false;
4831 }
4832 return control->CanHandle(capability);
4833 }
4834
4835 Hardware::Capabilities Manager::GetCapabilities(const ControlID controlID) const
4836 {
4837 ControlInterface* control = GetControl(controlID);
4838 if (!control)
4839 {
4840 return Hardware::CapabilityNone;
4841 }
4842 return control->GetCapabilities();
4843 }
4844
4845 bool Manager::LayoutItemRotate(const DataModel::ObjectIdentifier& identifier,
4846 string& result)
4847 {
4848 ObjectType type = identifier.GetObjectType();
4849 ObjectID id = identifier.GetObjectID();
4850 switch (type)
4851 {
4852 case ObjectTypeAccessory:
4853 return AccessoryRotate(id, result);
4854
4855 case ObjectTypeFeedback:
4856 return FeedbackRotate(id, result);
4857
4858 case ObjectTypeSignal:
4859 return SignalRotate(id, result);
4860
4861 case ObjectTypeSwitch:
4862 return SwitchRotate(id, result);
4863
4864 case ObjectTypeText:
4865 return TextRotate(id, result);
4866
4867 case ObjectTypeTrack:
4868 return TrackRotate(id, result);
4869
4870 case ObjectTypeRoute:
4871 default:
4872 return false;
4873 }
4874 }
4875
4876 bool Manager::LayoutItemNewPosition(const DataModel::ObjectIdentifier& identifier,
4877 const DataModel::LayoutItem::LayoutItemSize posX,
4878 const DataModel::LayoutItem::LayoutItemSize posY,
4879 string& result)
4880 {
4881 ObjectType type = identifier.GetObjectType();
4882 ObjectID id = identifier.GetObjectID();
4883 switch (type)
4884 {
4885 case ObjectTypeAccessory:
4886 return AccessoryPosition(id, posX, posY, result);
4887
4888 case ObjectTypeFeedback:
4889 return FeedbackPosition(id, posX, posY, result);
4890
4891 case ObjectTypeRoute:
4892 return RoutePosition(id, posX, posY, result);
4893
4894 case ObjectTypeSignal:
4895 return SignalPosition(id, posX, posY, result);
4896
4897 case ObjectTypeSwitch:
4898 return SwitchPosition(id, posX, posY, result);
4899
4900 case ObjectTypeText:
4901 return TextPosition(id, posX, posY, result);
4902
4903 case ObjectTypeTrack:
4904 return TrackPosition(id, posX, posY, result);
4905
4906 default:
4907 return false;
4908 }
4909 }
4910
4911 ObjectIdentifier Manager::GetIdentifierOfServerLocoAddress(const Address serverAddress) const
4912 {
4913 {
4914 std::lock_guard<std::mutex> guard(locoMutex);
4915 for (auto& loco : locos)
4916 {
4917 if (loco.second->GetServerAddress() == serverAddress)
4918 {
4919 return ObjectIdentifier(ObjectTypeLoco, loco.second->GetID());
4920 }
4921 }
4922 }
4923
4924 {
4925 std::lock_guard<std::mutex> guard(multipleUnitMutex);
4926 for (auto& multipleUnit : multipleUnits)
4927 {
4928 if (multipleUnit.second->GetServerAddress() == serverAddress)
4929 {
4930 return ObjectIdentifier(ObjectTypeMultipleUnit, multipleUnit.second->GetID());
4931 }
4932 }
4933 }
4934
4935 return ObjectIdentifier(ObjectTypeNone, ObjectNone);
4936 }
4937
4938 ObjectIdentifier Manager::GetIdentifierOfServerAccessoryAddress(const Address serverAddress) const
4939 {
4940 {
4941 std::lock_guard<std::mutex> guard(accessoryMutex);
4942 for (auto& accessory : accessories)
4943 {
4944 if (accessory.second->GetServerAddress() == serverAddress)
4945 {
4946 return ObjectIdentifier(ObjectTypeAccessory, accessory.second->GetID());
4947 }
4948 }
4949 }
4950
4951 {
4952 std::lock_guard<std::mutex> guard(switchMutex);
4953 for (auto& mySwitch : switches)
4954 {
4955 if (mySwitch.second->GetServerAddress() == serverAddress)
4956 {
4957 return ObjectIdentifier(ObjectTypeSwitch, mySwitch.second->GetID());
4958 }
4959 }
4960 }
4961
4962 {
4963 std::lock_guard<std::mutex> guard(signalMutex);
4964 for (auto& signal : signals)
4965 {
4966 if (signal.second->GetServerAddress() == serverAddress)
4967 {
4968 return ObjectIdentifier(ObjectTypeSignal, signal.second->GetID());
4969 }
4970 }
4971 }
4972
4973 return ObjectIdentifier(ObjectTypeNone, ObjectNone);
4974 }
4975
4976 Hardware::HardwareParams* Manager::CreateAndAddControl()
4977 {
4978 std::lock_guard<std::mutex> Guard(hardwareMutex);
4979 ControlID newObjectID = ControlIdFirstHardware - 1;
4980 for (auto& hardwareParam : hardwareParams)
4981 {
4982 if (hardwareParam.first > newObjectID)
4983 {
4984 newObjectID = hardwareParam.first;
4985 }
4986 }
4987 ++newObjectID;
4988 Hardware::HardwareParams* newParams = new Hardware::HardwareParams(this, newObjectID);
4989 if (!newParams)
4990 {
4991 return nullptr;
4992 }
4993 hardwareParams[newObjectID] = newParams;
4994 return newParams;
4995 }
4996
4997 bool Manager::ObjectIsPartOfRoute(const ObjectIdentifier& identifier,
4998 const Object* object,
4999 string& result)
5000 {
5001 std::lock_guard<std::mutex> Guard(routeMutex);
5002 for (auto& route : routes)
5003 {
5004 if (!route.second->ObjectIsPartOfRoute(identifier))
5005 {
5006 continue;
5007 }
5008
5009 Languages::TextSelector selector;
5010 switch (identifier.GetObjectType())
5011 {
5012 case ObjectTypeTrack:
5013 selector = Languages::TextTrackIsUsedByRoute;
5014 break;
5015
5016 case ObjectTypeAccessory:
5017 selector = Languages::TextAccessoryIsUsedByRoute;
5018 break;
5019
5020 case ObjectTypeSwitch:
5021 selector = Languages::TextSwitchIsUsedByRoute;
5022 break;
5023
5024 case ObjectTypeRoute:
5025 selector = Languages::TextRouteIsUsedByRoute;
5026 break;
5027
5028 case ObjectTypeSignal:
5029 selector = Languages::TextSignalIsUsedByRoute;
5030 break;
5031
5032 default:
5033 selector = Languages::TextObjectIsUsedByRoute;
5034 break;
5035 }
5036 result = Logger::Logger::Format(Languages::GetText(selector), object->GetName(), route.second->GetName());
5037 return true;
5038 }
5039 return false;
5040 }