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 string &host):
23 accessories_synced(false),
26 RefPtr<Net::SockAddr> addr = Net::resolve(host+":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 void 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));
114 void CentralStation::remove_loco(unsigned addr)
116 unsigned id = map_address(locos, loco_addr, addr);
118 command(format("release(%d, view, control)", id));
121 void CentralStation::set_loco_speed(unsigned addr, unsigned speed)
126 unsigned id = map_address(locos, loco_addr, addr);
129 Locomotive &loco = locos[id];
130 if(loco.protocol==MFX && speed)
132 command(format("set(%d, speedstep[%d])", id, speed));
136 void CentralStation::set_loco_reverse(unsigned addr, bool rev)
138 unsigned id = map_address(locos, loco_addr, addr);
140 command(format("set(%d, dir[%d])", id, rev));
143 void CentralStation::set_loco_function(unsigned addr, unsigned func, bool state)
145 unsigned id = map_address(locos, loco_addr, addr);
147 command(format("set(%d, func[%d, %d])", id, func, state));
150 void CentralStation::add_turnout(unsigned addr, const TrackType &type)
152 unsigned straight = type.get_paths();
157 const vector<TrackPart> &parts = type.get_parts();
158 for(vector<TrackPart>::const_iterator i=parts.begin(); i!=parts.end(); ++i)
160 OrientedPoint start = i->get_point(0);
161 OrientedPoint end = i->get_point(i->get_length());
162 if(abs(end.rotation-start.rotation).radians()<0.01)
164 (end.rotation>start.rotation ? left : right) = true;
165 straight &= ~(1<<i->get_path());
167 else if(abs(start.rotation).radians()>0.01)
171 MagnetAccessory::Symbol symbol = MagnetAccessory::TURNOUT_LEFT;
173 symbol = MagnetAccessory::TURNOUT_DOUBLESLIP;
174 else if(left && right)
175 symbol = MagnetAccessory::TURNOUT_THREEWAY;
177 symbol = (straight ? MagnetAccessory::TURNOUT_LEFT : MagnetAccessory::TURNOUT_CURVED_LEFT);
179 symbol = (straight ? MagnetAccessory::TURNOUT_RIGHT : MagnetAccessory::TURNOUT_CURVED_RIGHT);
181 MagnetAccessory &turnout = add_accessory(addr, MagnetAccessory::TURNOUT, symbol);
182 turnout.bits = type.get_state_bits();
185 void CentralStation::remove_turnout(unsigned addr)
187 remove_accessory(addr);
190 void CentralStation::set_turnout(unsigned addr, unsigned state)
192 set_accessory_state(addr, MagnetAccessory::TURNOUT, state);
195 unsigned CentralStation::get_turnout(unsigned addr) const
197 return get_accessory_state(addr, MagnetAccessory::TURNOUT);
200 void CentralStation::add_signal(unsigned addr, const SignalType &)
202 add_accessory(addr, MagnetAccessory::SIGNAL, MagnetAccessory::SEMAPHORE_HOME);
205 void CentralStation::remove_signal(unsigned addr)
207 remove_accessory(addr);
210 void CentralStation::set_signal(unsigned addr, unsigned state)
212 set_accessory_state(addr, MagnetAccessory::SIGNAL, state);
215 unsigned CentralStation::get_signal(unsigned addr) const
217 return get_accessory_state(addr, MagnetAccessory::SIGNAL);
220 CentralStation::MagnetAccessory &CentralStation::add_accessory(unsigned addr, MagnetAccessory::Type type, MagnetAccessory::Symbol symbol)
222 unsigned id = map_address(accessories, accessory_addr, addr);
227 MagnetAccessory &accessory = accessories[id];
228 accessory.address = addr;
229 accessory.type = type;
230 accessory.symbol = symbol;
232 accessory_addr[addr] = id;
234 if(accessories_synced)
235 command("create(11, append)");
241 MagnetAccessory &accessory = accessories[id];
242 command(format("request(%d, view, control)", id));
243 if(accessory.symbol!=symbol)
244 command(format("set(%d, symbol[%d])", symbol));
250 void CentralStation::remove_accessory(unsigned addr)
252 unsigned id = map_address(accessories, accessory_addr, addr);
254 command(format("release(%d, view, control)", id));
257 void CentralStation::set_accessory_state(unsigned addr, MagnetAccessory::Type type, unsigned state)
259 unsigned id = map_address(accessories, accessory_addr, addr);
262 MagnetAccessory &accessory = accessories[id];
263 if(accessory.type!=type)
264 throw logic_error("accessory type conflict");
266 unsigned mask = (1<<accessory.bits)-1;
268 if(((state^accessory.state)&mask)==0 || !accessory.synced)
270 accessory.state = state;
271 accessory_state_changed(accessory);
275 accessory.state = (accessory.state&mask) | (state&~mask);
277 command(format("set(%d, state[%d])", id, state&mask));
281 unsigned CentralStation::get_accessory_state(unsigned addr, MagnetAccessory::Type type) const
283 unsigned id = map_address(accessories, accessory_addr, addr);
286 AccessoryMap::const_iterator i = accessories.find(id);
287 if(i!=accessories.end() && i->second.type==type)
288 return i->second.state;
293 void CentralStation::accessory_state_changed(const MagnetAccessory &accessory) const
295 if(accessory.type==MagnetAccessory::TURNOUT)
296 signal_turnout.emit(accessory.address, accessory.state);
297 else if(accessory.type==MagnetAccessory::SIGNAL)
298 signal_signal.emit(accessory.address, accessory.state);
301 void CentralStation::add_sensor(unsigned addr)
303 sensors.insert(SensorMap::value_type(addr, Sensor()));
307 if(addr>s88.size()*16)
308 command("create(26, add[0])");
312 void CentralStation::remove_sensor(unsigned)
316 bool CentralStation::get_sensor(unsigned addr) const
318 SensorMap::const_iterator i = sensors.find(addr);
320 return i->second.state;
324 void CentralStation::tick()
326 while(Message msg = receive())
329 IO::print("\033[31m*** ERROR: %s: %d %s ***\033[0m\n", msg.header.value, msg.footer.code, msg.footer.value);
331 if(msg.header.type=="REPLY")
333 else if(msg.header.type=="EVENT")
338 void CentralStation::flush()
342 void CentralStation::command(const string &cmd, bool force)
344 if(pending_commands<10 || force)
346 socket.write(cmd+"\r\n");
350 cmd_queue.push_back(cmd);
353 CentralStation::Message CentralStation::receive()
355 while(IO::poll(socket, IO::P_INPUT, Time::zero))
358 unsigned len = socket.read(rbuf, sizeof(rbuf));
362 in_buffer.append(rbuf, len);
365 if(!in_buffer.empty())
367 string::iterator iter = in_buffer.begin();
368 if(Message msg = parse_message(iter, in_buffer.end()))
370 skip(iter, in_buffer.end(), "\r\n");
371 in_buffer.erase(in_buffer.begin(), iter);
373 if(msg.header.type=="REPLY" && pending_commands>0)
376 if(!cmd_queue.empty())
378 command(cmd_queue.front());
379 cmd_queue.pop_front();
390 void CentralStation::process_reply(const Message &msg)
392 if(!msg.header.value.compare(0, 4, "get("))
394 for(Message::ObjectMap::const_iterator i=msg.content.begin(); i!=msg.content.end(); ++i)
396 if(accessories.count(i->first))
397 accessories[i->first].synced = true;
399 process_object(i->first, i->second);
402 else if(!msg.header.value.compare(0, 16, "queryObjects(10,"))
404 for(Message::ObjectMap::const_iterator i=msg.content.begin(); i!=msg.content.end(); ++i)
406 LocoMap::iterator j = locos.find(i->first);
410 Message::AttribMap::const_iterator k = i->second.find("addr");
411 if(k!=i->second.end())
413 unsigned addr = lexical_cast<unsigned>(k->second);
415 j = locos.find(addr|0x10000);
418 command(format("request(%d, view, control, force)", i->first));
419 string cmd = format("get(%d, dir", i->first);
420 for(unsigned l=0; j->second.func_mask>>l; ++l)
421 if((j->second.func_mask>>l)&1)
422 cmd += format(", func[%d]", l);
426 locos.insert(LocoMap::value_type(i->first, j->second));
434 locos.insert(LocoMap::value_type(i->first, Locomotive()));
437 process_object(i->first, i->second);
442 if(locos.lower_bound(0x10000)!=locos.end())
443 command("create(10)");
445 else if(!msg.header.value.compare(0, 16, "queryObjects(11,"))
447 for(Message::ObjectMap::const_iterator i=msg.content.begin(); i!=msg.content.end(); ++i)
449 AccessoryMap::iterator j = accessories.find(i->first);
450 if(j==accessories.end())
453 Message::AttribMap::const_iterator k = i->second.find("addr");
454 if(k!=i->second.end())
456 unsigned addr = lexical_cast<unsigned>(k->second);
458 j = accessories.find(addr|0x10000);
459 if(j!=accessories.end())
461 command(format("request(%d, view, control)", i->first));
462 command(format("set(%d, symbol[%d])", i->first, j->second.symbol));
463 command(format("get(%d, state)", i->first));
465 accessories.insert(AccessoryMap::value_type(i->first, j->second));
466 accessories.erase(j);
473 accessories.insert(AccessoryMap::value_type(i->first, MagnetAccessory()));
476 process_object(i->first, i->second);
479 accessories_synced = true;
481 for(AccessoryMap::const_iterator i=accessories.lower_bound(0x10000); i!=accessories.end(); ++i)
482 command("create(11, append)");
484 else if(msg.header.value=="queryObjects(26)")
487 for(Message::ObjectMap::const_iterator i=msg.content.begin(); i!=msg.content.end(); ++i)
489 s88.push_back(i->first);
490 command(format("request(%d, view)", i->first));
491 command(format("get(%d, state)", i->first));
494 sensors_synced = true;
498 unsigned high_addr = (--sensors.end())->first;
499 if(high_addr>16*s88.size())
500 command("create(26, add[0])");
503 else if(msg.header.value=="create(10)")
505 Message::ObjectMap::const_iterator i = msg.content.find(10);
506 if(i!=msg.content.end())
508 Message::AttribMap::const_iterator j = i->second.find("id");
509 if(j!=i->second.end())
511 unsigned id = lexical_cast<unsigned>(j->second);
512 LocoMap::iterator k = locos.lower_bound(0x10000);
515 command(format("request(%d, view, control)", id));
516 command(format("set(%d, addr[%d], protocol[%s], name[\"%s\"])",
517 id, k->second.address, (k->second.protocol==MM_27 ? "MM27" : "MM14"), k->second.name));
518 command("create(10, append)");
520 locos.insert(LocoMap::value_type(id, k->second));
526 if(locos.lower_bound(0x10000)!=locos.end())
527 command("create(10)");
529 else if(!msg.header.value.compare(0, 10, "create(11,"))
531 Message::ObjectMap::const_iterator i = msg.content.find(11);
532 if(i!=msg.content.end())
534 Message::AttribMap::const_iterator j = i->second.find("id");
535 if(j!=i->second.end())
537 unsigned id = lexical_cast<unsigned>(j->second);
538 AccessoryMap::iterator k = accessories.lower_bound(0x10000);
539 if(k!=accessories.end())
541 command(format("request(%d, view, control)", id));
542 const char *label = (k->second.type==MagnetAccessory::SIGNAL ? "Signal" : "Switch");
543 command(format("set(%d, addr[%d], symbol[%d], name1[\"%s\"], name2[\"%d\"], name3[\"\"])",
544 id, k->second.address, k->second.symbol, label, k->second.address));
545 command(format("set(%d, state[%d])", id, k->second.state&((1<<k->second.bits)-1)));
547 k->second.synced = true;
548 accessories.insert(AccessoryMap::value_type(id, k->second));
549 accessories.erase(k);
554 else if(!msg.header.value.compare(0, 10, "create(26,"))
555 command("queryObjects(26)");
558 void CentralStation::process_event(const Message &msg)
560 for(Message::ObjectMap::const_iterator i=msg.content.begin(); i!=msg.content.end(); ++i)
561 process_object(i->first, i->second);
564 void CentralStation::process_object(unsigned id, const Message::AttribMap &attribs)
568 for(Message::AttribMap::const_iterator i=attribs.begin(); i!=attribs.end(); ++i)
569 if(i->first=="status")
571 power = (i->second=="GO");
572 signal_power.emit(power);
575 else if(locos.count(id))
577 Locomotive &loco = locos[id];
578 bool speed_changed = false;
579 unsigned funcs_changed = 0;
580 for(Message::AttribMap::const_iterator i=attribs.begin(); i!=attribs.end(); ++i)
583 loco.name = i->second.substr(1, i->second.size()-2);
584 else if(i->first=="addr")
586 loco_addr.erase(loco.address);
587 loco.address = lexical_cast<unsigned>(i->second);
588 loco_addr[loco.address] = id;
590 else if(i->first=="protocol")
594 else if(i->second=="MM27")
595 loco.protocol = MM_27;
596 else if(i->second=="MFX")
599 else if(i->first=="speedstep")
601 loco.speed = lexical_cast<unsigned>(i->second);
602 if(loco.protocol==MFX && loco.speed)
604 speed_changed = true;
606 else if(i->first=="dir")
608 loco.reverse = i->second[0]!='0';
609 speed_changed = true;
611 else if(i->first=="func")
613 vector<string> parts = split(i->second, ", ");
614 unsigned func = lexical_cast<unsigned>(parts[0]);
615 bool value = lexical_cast<unsigned>(parts[1]);
616 loco.funcs &= ~(1<<func);
618 loco.funcs |= 1<<func;
619 funcs_changed |= 1<<func;
621 else if(i->first=="msg")
623 if(i->second=="CONTROL_LOST")
624 command(format("request(%d, control, force)", id));
629 signal_loco_speed.emit(loco.address, loco.speed, loco.reverse);
630 for(unsigned i=0; funcs_changed>>i; ++i)
631 if(funcs_changed&(1<<i))
632 signal_loco_function.emit(loco.address, i, loco.funcs&(1<<i));
634 else if(accessories.count(id))
636 MagnetAccessory &accessory = accessories[id];
637 bool state_changed = false;
638 for(Message::AttribMap::const_iterator i=attribs.begin(); i!=attribs.end(); ++i)
642 accessory_addr.erase(accessory.address);
643 accessory.address = lexical_cast<unsigned>(i->second);
644 accessory_addr[accessory.address] = id;
646 else if(i->first=="state")
648 unsigned state = lexical_cast<unsigned>(i->second);
649 unsigned mask = (1<<accessory.bits)-1;
650 accessory.state = (accessory.state&~mask) | (state&mask);
651 state_changed = true;
656 accessory_state_changed(accessory);
658 else if(find(s88.begin(), s88.end(), id)!=s88.end())
661 for(; (base<s88.size() && s88[base]!=id); ++base) ;
663 for(Message::AttribMap::const_iterator i=attribs.begin(); i!=attribs.end(); ++i)
665 if(i->first=="state")
667 unsigned state = lexical_cast<unsigned>(i->second, "%i");
668 for(unsigned j=0; j<16; ++j)
670 unsigned addr = base*16+j+1;
671 Sensor &sensor = sensors[addr];
672 bool s = state&(1<<j);
676 signal_sensor.emit(addr, sensor.state);
684 CentralStation::Protocol CentralStation::map_protocol(const string &name) const
688 else if(name=="MM-27")
693 throw invalid_argument("CentralStation::map_protocol");
697 unsigned CentralStation::map_address(const map<unsigned, T> &omap, const AddressMap &amap, unsigned addr) const
703 AddressMap::const_iterator i = amap.find(addr);
711 void CentralStation::skip(string::iterator &iter, const string::iterator &end, const string &what) const
713 for(; (iter!=end && what.find(*iter)!=string::npos); ++iter) ;
716 string CentralStation::parse_token(string::iterator &iter, const string::iterator &end, const string &stop) const
722 skip(iter, end, stop);
724 for(; iter!=end; ++iter)
726 if(stop.find(*iter)!=string::npos && parens.empty() && !quote)
728 else if(*iter=='(' || *iter=='[')
729 parens.push_back(*iter);
730 else if((*iter==')' || *iter==']') && !parens.empty())
732 if((*iter==')' && parens.back()!='(') || (*iter==']' && parens.back()!='['))
733 IO::print("Mismatched parentheses\n");
745 CentralStation::Tag CentralStation::parse_tag(string::iterator &iter, const string::iterator &end) const
749 for(; (iter!=end && *iter!='<'); ++iter) ;
753 tag.type = parse_token(++iter, end, " >");
756 string code = parse_token(iter, end, " >");
757 tag.code = lexical_cast<unsigned>(code);
759 skip(iter, end, " ");
760 tag.value = parse_token(iter, end, ">");
768 CentralStation::Message CentralStation::parse_message(string::iterator &iter, const string::iterator &end) const
772 msg.header = parse_tag(iter, end);
776 skip(iter, end, "\r\n");
780 string id = parse_token(iter, end, " \r\n<");
781 Message::AttribMap &attribs = msg.content[lexical_cast<unsigned>(id)];
782 while(iter!=end && *iter!='\n' && *iter!='\r')
784 string attr = parse_token(iter, end, " \r\n<");
785 string::size_type open_bracket = attr.find('[');
786 if(open_bracket!=string::npos)
788 string::size_type close_bracket = attr.rfind(']');
789 string attr_name = attr.substr(0, open_bracket);
790 string attr_value = attr.substr(open_bracket+1, close_bracket-open_bracket-1);
791 attribs.insert(Message::AttribMap::value_type(attr_name, attr_value));
794 attribs.insert(Message::AttribMap::value_type(attr, string()));
798 msg.footer = parse_tag(iter, end);
799 if(msg.footer.type.empty())
806 CentralStation::Tag::Tag():
810 CentralStation::Tag::operator bool() const
812 return !type.empty();
816 CentralStation::Message::operator bool() const
818 return header && footer;
822 CentralStation::Locomotive::Locomotive():
832 CentralStation::MagnetAccessory::MagnetAccessory():
835 symbol(TURNOUT_LEFT),
842 CentralStation::Sensor::Sensor():