2 #include <msp/core/refptr.h>
3 #include <msp/io/print.h>
4 #include <msp/net/resolve.h>
5 #include <msp/strings/utils.h>
6 #include <msp/time/units.h>
7 #include <msp/time/utils.h>
8 #include "centralstation.h"
10 #include "vehicletype.h"
17 CentralStation::CentralStation(const Options &opts):
23 accessories_synced(false),
26 RefPtr<Net::SockAddr> addr = Net::resolve(opts.get<string>(string())+":15471");
27 socket.connect(*addr);
29 IO::print("Connected to central station at %s\n", addr->str());
31 command("get(1, status)");
32 command("request(1, view)");
33 command("queryObjects(10, addr, name)");
34 command("queryObjects(11, addr)");
35 command("queryObjects(26)");
38 CentralStation::~CentralStation()
40 command("release(1, view)", true);
41 for(LocoMap::iterator i=locos.begin(); (i!=locos.end() && !(i->first&0x10000)); ++i)
42 command(format("release(%d, view, control)", i->first));
43 for(AccessoryMap::iterator i=accessories.begin(); (i!=accessories.end() && !(i->first&0x10000)); ++i)
44 command(format("release(%d, view, control)", i->first));
45 while(IO::poll(socket, IO::P_INPUT, 100*Time::msec))
49 void CentralStation::set_power(bool p)
52 command(format("set(1, %s)", (power ? "go" : "stop")));
55 void CentralStation::halt(bool h)
60 for(LocoMap::iterator i=locos.begin(); i!=locos.end(); ++i)
62 set_loco_speed(i->first, 0);
65 signal_halt.emit(halted);
68 const char *CentralStation::enumerate_protocols(unsigned index) const
80 unsigned CentralStation::get_protocol_speed_steps(const string &name) const
82 switch(map_protocol(name))
85 case MM_27: return 27;
91 unsigned CentralStation::add_loco(unsigned addr, const string &proto_name, const VehicleType &type)
93 Protocol proto = map_protocol(proto_name);
95 unsigned id = map_address(locos, loco_addr, addr);
98 Locomotive &loco = locos[addr|0x10000];
99 loco.name = type.get_name();
100 loco.protocol = proto;
103 const VehicleType::FunctionMap &type_funcs = type.get_functions();
104 for(VehicleType::FunctionMap::const_iterator i=type_funcs.begin(); i!=type_funcs.end(); ++i)
105 loco.func_mask |= 1<<i->first;
107 if(locos_synced && proto!=MFX)
108 command("create(10)");
111 command(format("request(%d, view, control, force)", id));
116 void CentralStation::remove_loco(unsigned addr)
118 unsigned id = map_address(locos, loco_addr, addr);
120 command(format("release(%d, view, control)", id));
123 void CentralStation::set_loco_speed(unsigned addr, unsigned speed)
128 unsigned id = map_address(locos, loco_addr, addr);
131 Locomotive &loco = locos[id];
132 if(loco.protocol==MFX && speed)
134 command(format("set(%d, speedstep[%d])", id, speed));
138 void CentralStation::set_loco_reverse(unsigned addr, bool rev)
140 unsigned id = map_address(locos, loco_addr, addr);
142 command(format("set(%d, dir[%d])", id, rev));
145 void CentralStation::set_loco_function(unsigned addr, unsigned func, bool state)
147 unsigned id = map_address(locos, loco_addr, addr);
149 command(format("set(%d, func[%d, %d])", id, func, state));
152 unsigned CentralStation::add_turnout(unsigned addr, const TrackType &type)
154 unsigned straight = type.get_paths();
159 const vector<TrackPart> &parts = type.get_parts();
160 for(vector<TrackPart>::const_iterator i=parts.begin(); i!=parts.end(); ++i)
162 OrientedPoint start = i->get_point(0);
163 OrientedPoint end = i->get_point(i->get_length());
164 if(abs(end.rotation-start.rotation).radians()<0.01)
166 (end.rotation>start.rotation ? left : right) = true;
167 straight &= ~(1<<i->get_path());
169 else if(abs(start.rotation).radians()>0.01)
173 MagnetAccessory::Symbol symbol = MagnetAccessory::TURNOUT_LEFT;
175 symbol = MagnetAccessory::TURNOUT_DOUBLESLIP;
176 else if(left && right)
177 symbol = MagnetAccessory::TURNOUT_THREEWAY;
179 symbol = (straight ? MagnetAccessory::TURNOUT_LEFT : MagnetAccessory::TURNOUT_CURVED_LEFT);
181 symbol = (straight ? MagnetAccessory::TURNOUT_RIGHT : MagnetAccessory::TURNOUT_CURVED_RIGHT);
183 MagnetAccessory &turnout = add_accessory(addr, MagnetAccessory::TURNOUT, symbol);
184 turnout.bits = type.get_state_bits();
189 void CentralStation::remove_turnout(unsigned addr)
191 remove_accessory(addr);
194 void CentralStation::set_turnout(unsigned addr, unsigned state)
196 set_accessory_state(addr, MagnetAccessory::TURNOUT, state);
199 unsigned CentralStation::get_turnout(unsigned addr) const
201 return get_accessory_state(addr, MagnetAccessory::TURNOUT);
204 unsigned CentralStation::add_signal(unsigned addr, const SignalType &)
206 add_accessory(addr, MagnetAccessory::SIGNAL, MagnetAccessory::SEMAPHORE_HOME);
210 void CentralStation::remove_signal(unsigned addr)
212 remove_accessory(addr);
215 void CentralStation::set_signal(unsigned addr, unsigned state)
217 set_accessory_state(addr, MagnetAccessory::SIGNAL, state);
220 unsigned CentralStation::get_signal(unsigned addr) const
222 return get_accessory_state(addr, MagnetAccessory::SIGNAL);
225 CentralStation::MagnetAccessory &CentralStation::add_accessory(unsigned addr, MagnetAccessory::Type type, MagnetAccessory::Symbol symbol)
227 unsigned id = map_address(accessories, accessory_addr, addr);
232 MagnetAccessory &accessory = accessories[id];
233 accessory.address = addr;
234 accessory.type = type;
235 accessory.symbol = symbol;
237 accessory_addr[addr] = id;
239 if(accessories_synced)
240 command("create(11, append)");
246 MagnetAccessory &accessory = accessories[id];
247 command(format("request(%d, view, control)", id));
248 if(accessory.symbol!=symbol)
249 command(format("set(%d, symbol[%d])", symbol));
255 void CentralStation::remove_accessory(unsigned addr)
257 unsigned id = map_address(accessories, accessory_addr, addr);
259 command(format("release(%d, view, control)", id));
262 void CentralStation::set_accessory_state(unsigned addr, MagnetAccessory::Type type, unsigned state)
264 unsigned id = map_address(accessories, accessory_addr, addr);
267 MagnetAccessory &accessory = accessories[id];
268 if(accessory.type!=type)
269 throw logic_error("accessory type conflict");
271 unsigned mask = (1<<accessory.bits)-1;
273 if(((state^accessory.state)&mask)==0 || !accessory.synced)
275 accessory.state = state;
276 accessory_state_changed(accessory);
280 accessory.state = (accessory.state&mask) | (state&~mask);
282 command(format("set(%d, state[%d])", id, state&mask));
286 unsigned CentralStation::get_accessory_state(unsigned addr, MagnetAccessory::Type type) const
288 unsigned id = map_address(accessories, accessory_addr, addr);
291 AccessoryMap::const_iterator i = accessories.find(id);
292 if(i!=accessories.end() && i->second.type==type)
293 return i->second.state;
298 void CentralStation::accessory_state_changed(const MagnetAccessory &accessory) const
300 if(accessory.type==MagnetAccessory::TURNOUT)
301 signal_turnout.emit(accessory.address, accessory.state);
302 else if(accessory.type==MagnetAccessory::SIGNAL)
303 signal_signal.emit(accessory.address, accessory.state);
306 unsigned CentralStation::add_sensor(unsigned addr)
308 sensors.insert(SensorMap::value_type(addr, Sensor()));
312 if(addr>s88.size()*16)
313 command("create(26, add[0])");
319 void CentralStation::remove_sensor(unsigned)
323 bool CentralStation::get_sensor(unsigned addr) const
325 SensorMap::const_iterator i = sensors.find(addr);
327 return i->second.state;
331 void CentralStation::tick()
333 while(Message msg = receive())
336 IO::print("\033[31m*** ERROR: %s: %d %s ***\033[0m\n", msg.header.value, msg.footer.code, msg.footer.value);
338 if(msg.header.type=="REPLY")
340 else if(msg.header.type=="EVENT")
345 void CentralStation::flush()
349 void CentralStation::command(const string &cmd, bool force)
351 if(pending_commands<10 || force)
353 socket.write(cmd+"\r\n");
357 cmd_queue.push_back(cmd);
360 CentralStation::Message CentralStation::receive()
362 while(IO::poll(socket, IO::P_INPUT, Time::zero))
365 unsigned len = socket.read(rbuf, sizeof(rbuf));
369 in_buffer.append(rbuf, len);
372 if(!in_buffer.empty())
374 string::iterator iter = in_buffer.begin();
375 if(Message msg = parse_message(iter, in_buffer.end()))
377 skip(iter, in_buffer.end(), "\r\n");
378 in_buffer.erase(in_buffer.begin(), iter);
380 if(msg.header.type=="REPLY" && pending_commands>0)
383 if(!cmd_queue.empty())
385 command(cmd_queue.front());
386 cmd_queue.pop_front();
397 void CentralStation::process_reply(const Message &msg)
399 if(!msg.header.value.compare(0, 4, "get("))
401 for(Message::ObjectMap::const_iterator i=msg.content.begin(); i!=msg.content.end(); ++i)
403 if(accessories.count(i->first))
404 accessories[i->first].synced = true;
406 process_object(i->first, i->second);
409 else if(!msg.header.value.compare(0, 16, "queryObjects(10,"))
411 for(Message::ObjectMap::const_iterator i=msg.content.begin(); i!=msg.content.end(); ++i)
413 LocoMap::iterator j = locos.find(i->first);
417 Message::AttribMap::const_iterator k = i->second.find("addr");
418 if(k!=i->second.end())
420 unsigned addr = lexical_cast<unsigned>(k->second);
422 j = locos.find(addr|0x10000);
425 command(format("request(%d, view, control, force)", i->first));
426 string cmd = format("get(%d, dir", i->first);
427 for(unsigned l=0; j->second.func_mask>>l; ++l)
428 if((j->second.func_mask>>l)&1)
429 cmd += format(", func[%d]", l);
433 locos.insert(LocoMap::value_type(i->first, j->second));
441 locos.insert(LocoMap::value_type(i->first, Locomotive()));
444 process_object(i->first, i->second);
449 if(locos.lower_bound(0x10000)!=locos.end())
450 command("create(10)");
452 else if(!msg.header.value.compare(0, 16, "queryObjects(11,"))
454 for(Message::ObjectMap::const_iterator i=msg.content.begin(); i!=msg.content.end(); ++i)
456 AccessoryMap::iterator j = accessories.find(i->first);
457 if(j==accessories.end())
460 Message::AttribMap::const_iterator k = i->second.find("addr");
461 if(k!=i->second.end())
463 unsigned addr = lexical_cast<unsigned>(k->second);
465 j = accessories.find(addr|0x10000);
466 if(j!=accessories.end())
468 command(format("request(%d, view, control)", i->first));
469 command(format("set(%d, symbol[%d])", i->first, j->second.symbol));
470 command(format("get(%d, state)", i->first));
472 accessories.insert(AccessoryMap::value_type(i->first, j->second));
473 accessories.erase(j);
480 accessories.insert(AccessoryMap::value_type(i->first, MagnetAccessory()));
483 process_object(i->first, i->second);
486 accessories_synced = true;
488 for(AccessoryMap::const_iterator i=accessories.lower_bound(0x10000); i!=accessories.end(); ++i)
489 command("create(11, append)");
491 else if(msg.header.value=="queryObjects(26)")
494 for(Message::ObjectMap::const_iterator i=msg.content.begin(); i!=msg.content.end(); ++i)
496 s88.push_back(i->first);
497 command(format("request(%d, view)", i->first));
498 command(format("get(%d, state)", i->first));
501 sensors_synced = true;
505 unsigned high_addr = (--sensors.end())->first;
506 if(high_addr>16*s88.size())
507 command("create(26, add[0])");
510 else if(msg.header.value=="create(10)")
512 Message::ObjectMap::const_iterator i = msg.content.find(10);
513 if(i!=msg.content.end())
515 Message::AttribMap::const_iterator j = i->second.find("id");
516 if(j!=i->second.end())
518 unsigned id = lexical_cast<unsigned>(j->second);
519 LocoMap::iterator k = locos.lower_bound(0x10000);
522 command(format("request(%d, view, control)", id));
523 command(format("set(%d, addr[%d], protocol[%s], name[\"%s\"])",
524 id, k->second.address, (k->second.protocol==MM_27 ? "MM27" : "MM14"), k->second.name));
525 command("create(10, append)");
527 locos.insert(LocoMap::value_type(id, k->second));
533 if(locos.lower_bound(0x10000)!=locos.end())
534 command("create(10)");
536 else if(!msg.header.value.compare(0, 10, "create(11,"))
538 Message::ObjectMap::const_iterator i = msg.content.find(11);
539 if(i!=msg.content.end())
541 Message::AttribMap::const_iterator j = i->second.find("id");
542 if(j!=i->second.end())
544 unsigned id = lexical_cast<unsigned>(j->second);
545 AccessoryMap::iterator k = accessories.lower_bound(0x10000);
546 if(k!=accessories.end())
548 command(format("request(%d, view, control)", id));
549 const char *label = (k->second.type==MagnetAccessory::SIGNAL ? "Signal" : "Switch");
550 command(format("set(%d, addr[%d], symbol[%d], name1[\"%s\"], name2[\"%d\"], name3[\"\"])",
551 id, k->second.address, k->second.symbol, label, k->second.address));
552 command(format("set(%d, state[%d])", id, k->second.state&((1<<k->second.bits)-1)));
554 k->second.synced = true;
555 accessories.insert(AccessoryMap::value_type(id, k->second));
556 accessories.erase(k);
561 else if(!msg.header.value.compare(0, 10, "create(26,"))
562 command("queryObjects(26)");
565 void CentralStation::process_event(const Message &msg)
567 for(Message::ObjectMap::const_iterator i=msg.content.begin(); i!=msg.content.end(); ++i)
568 process_object(i->first, i->second);
571 void CentralStation::process_object(unsigned id, const Message::AttribMap &attribs)
575 for(Message::AttribMap::const_iterator i=attribs.begin(); i!=attribs.end(); ++i)
576 if(i->first=="status")
578 power = (i->second=="GO");
579 signal_power.emit(power);
582 else if(locos.count(id))
584 Locomotive &loco = locos[id];
585 bool speed_changed = false;
586 unsigned funcs_changed = 0;
587 for(Message::AttribMap::const_iterator i=attribs.begin(); i!=attribs.end(); ++i)
590 loco.name = i->second.substr(1, i->second.size()-2);
591 else if(i->first=="addr")
593 loco_addr.erase(loco.address);
594 loco.address = lexical_cast<unsigned>(i->second);
595 loco_addr[loco.address] = id;
597 else if(i->first=="protocol")
601 else if(i->second=="MM27")
602 loco.protocol = MM_27;
603 else if(i->second=="MFX")
606 else if(i->first=="speedstep")
608 loco.speed = lexical_cast<unsigned>(i->second);
609 if(loco.protocol==MFX && loco.speed)
611 speed_changed = true;
613 else if(i->first=="dir")
615 loco.reverse = i->second[0]!='0';
616 speed_changed = true;
618 else if(i->first=="func")
620 vector<string> parts = split(i->second, ", ");
621 unsigned func = lexical_cast<unsigned>(parts[0]);
622 bool value = lexical_cast<unsigned>(parts[1]);
623 loco.funcs &= ~(1<<func);
625 loco.funcs |= 1<<func;
626 funcs_changed |= 1<<func;
628 else if(i->first=="msg")
630 if(i->second=="CONTROL_LOST")
631 command(format("request(%d, control, force)", id));
636 signal_loco_speed.emit(loco.address, loco.speed, loco.reverse);
637 for(unsigned i=0; funcs_changed>>i; ++i)
638 if(funcs_changed&(1<<i))
639 signal_loco_function.emit(loco.address, i, loco.funcs&(1<<i));
641 else if(accessories.count(id))
643 MagnetAccessory &accessory = accessories[id];
644 bool state_changed = false;
645 for(Message::AttribMap::const_iterator i=attribs.begin(); i!=attribs.end(); ++i)
649 accessory_addr.erase(accessory.address);
650 accessory.address = lexical_cast<unsigned>(i->second);
651 accessory_addr[accessory.address] = id;
653 else if(i->first=="state")
655 unsigned state = lexical_cast<unsigned>(i->second);
656 unsigned mask = (1<<accessory.bits)-1;
657 accessory.state = (accessory.state&~mask) | (state&mask);
658 state_changed = true;
663 accessory_state_changed(accessory);
665 else if(find(s88.begin(), s88.end(), id)!=s88.end())
668 for(; (base<s88.size() && s88[base]!=id); ++base) ;
670 for(Message::AttribMap::const_iterator i=attribs.begin(); i!=attribs.end(); ++i)
672 if(i->first=="state")
674 unsigned state = lexical_cast<unsigned>(i->second, "%i");
675 for(unsigned j=0; j<16; ++j)
677 unsigned addr = base*16+j+1;
678 Sensor &sensor = sensors[addr];
679 bool s = state&(1<<j);
683 signal_sensor.emit(addr, sensor.state);
691 CentralStation::Protocol CentralStation::map_protocol(const string &name) const
695 else if(name=="MM-27")
700 throw invalid_argument("CentralStation::map_protocol");
704 unsigned CentralStation::map_address(const map<unsigned, T> &omap, const AddressMap &amap, unsigned addr) const
710 AddressMap::const_iterator i = amap.find(addr);
718 void CentralStation::skip(string::iterator &iter, const string::iterator &end, const string &what) const
720 for(; (iter!=end && what.find(*iter)!=string::npos); ++iter) ;
723 string CentralStation::parse_token(string::iterator &iter, const string::iterator &end, const string &stop) const
729 skip(iter, end, stop);
731 for(; iter!=end; ++iter)
733 if(stop.find(*iter)!=string::npos && parens.empty() && !quote)
735 else if(*iter=='(' || *iter=='[')
736 parens.push_back(*iter);
737 else if((*iter==')' || *iter==']') && !parens.empty())
739 if((*iter==')' && parens.back()!='(') || (*iter==']' && parens.back()!='['))
740 IO::print("Mismatched parentheses\n");
752 CentralStation::Tag CentralStation::parse_tag(string::iterator &iter, const string::iterator &end) const
756 for(; (iter!=end && *iter!='<'); ++iter) ;
760 tag.type = parse_token(++iter, end, " >");
763 string code = parse_token(iter, end, " >");
764 tag.code = lexical_cast<unsigned>(code);
766 skip(iter, end, " ");
767 tag.value = parse_token(iter, end, ">");
775 CentralStation::Message CentralStation::parse_message(string::iterator &iter, const string::iterator &end) const
779 msg.header = parse_tag(iter, end);
783 skip(iter, end, "\r\n");
787 string id = parse_token(iter, end, " \r\n<");
788 Message::AttribMap &attribs = msg.content[lexical_cast<unsigned>(id)];
789 while(iter!=end && *iter!='\n' && *iter!='\r')
791 string attr = parse_token(iter, end, " \r\n<");
792 string::size_type open_bracket = attr.find('[');
793 if(open_bracket!=string::npos)
795 string::size_type close_bracket = attr.rfind(']');
796 string attr_name = attr.substr(0, open_bracket);
797 string attr_value = attr.substr(open_bracket+1, close_bracket-open_bracket-1);
798 attribs.insert(Message::AttribMap::value_type(attr_name, attr_value));
801 attribs.insert(Message::AttribMap::value_type(attr, string()));
805 msg.footer = parse_tag(iter, end);
806 if(msg.footer.type.empty())
813 CentralStation::Tag::Tag():
817 CentralStation::Tag::operator bool() const
819 return !type.empty();
823 CentralStation::Message::operator bool() const
825 return header && footer;
829 CentralStation::Locomotive::Locomotive():
839 CentralStation::MagnetAccessory::MagnetAccessory():
842 symbol(TURNOUT_LEFT),
849 CentralStation::Sensor::Sensor():