Debian Codegraph @

Manager.cpp

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