3 This file is part of R²C²
4 Copyright © 2010 Mikkosoft Productions, Mikko Rasa
5 Distributed under the GPL
9 #include <msp/core/refptr.h>
10 #include <msp/io/print.h>
11 #include <msp/net/resolve.h>
12 #include <msp/strings/utils.h>
13 #include <msp/time/units.h>
14 #include <msp/time/utils.h>
15 #include "centralstation.h"
16 #include "tracktype.h"
17 #include "vehicletype.h"
24 CentralStation::CentralStation(const string &host):
30 turnouts_synced(false),
33 RefPtr<Net::SockAddr> addr = Net::resolve(host+":15471");
34 socket.connect(*addr);
36 IO::print("Connected to central station at %s\n", addr->str());
38 command("get(1, status)");
39 command("request(1, view)");
40 command("queryObjects(10, addr, name)");
41 command("queryObjects(11, addr)");
42 command("queryObjects(26)");
45 CentralStation::~CentralStation()
47 command("release(1, view)", true);
48 for(LocoMap::iterator i=locos.begin(); (i!=locos.end() && !(i->first&0x10000)); ++i)
49 command(format("release(%d, view, control)", i->first));
50 for(TurnoutMap::iterator i=turnouts.begin(); (i!=turnouts.end() && !(i->first&0x10000)); ++i)
51 command(format("release(%d, view, control)", i->first));
52 while(IO::poll(socket, IO::P_INPUT, 100*Time::msec))
56 void CentralStation::set_power(bool p)
59 command(format("set(1, %s)", (power ? "go" : "stop")));
62 void CentralStation::halt(bool h)
67 for(LocoMap::iterator i=locos.begin(); i!=locos.end(); ++i)
69 set_loco_speed(i->first, 0);
72 signal_halt.emit(halted);
75 const char *CentralStation::enumerate_protocols(unsigned index) const
87 unsigned CentralStation::get_protocol_speed_steps(const string &name) const
89 switch(map_protocol(name))
92 case MM_27: return 27;
98 void CentralStation::add_loco(unsigned addr, const string &proto_name, const VehicleType &type)
100 Protocol proto = map_protocol(proto_name);
102 unsigned id = map_address(locos, loco_addr, addr);
105 Locomotive &loco = locos[addr|0x10000];
106 loco.name = type.get_name();
107 loco.protocol = proto;
110 const VehicleType::FunctionMap &type_funcs = type.get_functions();
111 for(VehicleType::FunctionMap::const_iterator i=type_funcs.begin(); i!=type_funcs.end(); ++i)
112 loco.func_mask |= 1<<i->first;
114 if(locos_synced && proto!=MFX)
115 command("create(10)");
118 command(format("request(%d, view, control, force)", 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)
156 const vector<TrackPart> &parts = type.get_parts();
157 for(vector<TrackPart>::const_iterator i=parts.begin(); i!=parts.end(); ++i)
159 TrackPoint start = i->get_point(0);
160 TrackPoint end = i->get_point(i->get_length());
161 if(end.dir>start.dir+0.01)
163 else if(end.dir<start.dir-0.01)
165 else if(start.dir<-0.01 || start.dir>0.01)
169 unsigned symbol = Turnout::LEFT;
171 symbol = Turnout::DOUBLESLIP;
172 else if(left && right)
173 symbol = Turnout::THREEWAY;
175 symbol = Turnout::LEFT;
177 symbol = Turnout::RIGHT;
179 unsigned id = map_address(turnouts, turnout_addr, addr);
184 Turnout &turnout = turnouts[id];
185 turnout.address = addr;
186 turnout.bits = type.get_state_bits();
187 turnout.symbol = symbol;
189 turnout_addr[addr] = id;
192 command("create(11, append)");
196 Turnout &turnout = turnouts[id];
197 command(format("request(%d, view, control)", id));
198 if(turnout.symbol!=symbol)
199 command(format("set(%d, symbol[%d])", symbol));
203 void CentralStation::set_turnout(unsigned addr, unsigned state)
205 unsigned id = map_address(turnouts, turnout_addr, addr);
208 Turnout &turnout = turnouts[id];
209 unsigned mask = (1<<turnout.bits)-1;
211 if(((state^turnout.state)&mask)==0 || !turnout.synced)
213 turnout.state = state;
214 signal_turnout.emit(addr, turnout.state);
218 turnout.state = (turnout.state&mask) | (state&~mask);
220 command(format("set(%d, state[%d])", id, state&mask));
224 unsigned CentralStation::get_turnout(unsigned addr) const
226 unsigned id = map_address(turnouts, turnout_addr, addr);
229 TurnoutMap::const_iterator i = turnouts.find(id);
230 if(i!=turnouts.end())
231 return i->second.state;
236 void CentralStation::add_sensor(unsigned addr)
238 sensors.insert(SensorMap::value_type(addr, Sensor()));
242 if(addr>s88.size()*16)
243 command("create(26, add[0])");
247 bool CentralStation::get_sensor(unsigned addr) const
249 SensorMap::const_iterator i = sensors.find(addr);
251 return i->second.state;
255 void CentralStation::tick()
257 while(Message msg = receive())
260 IO::print("\033[31m*** ERROR: %s: %d %s ***\033[0m\n", msg.header.value, msg.footer.code, msg.footer.value);
262 if(msg.header.type=="REPLY")
264 else if(msg.header.type=="EVENT")
269 void CentralStation::flush()
273 void CentralStation::command(const string &cmd, bool force)
275 if(pending_commands<10 || force)
277 socket.write(cmd+"\r\n");
281 cmd_queue.push_back(cmd);
284 CentralStation::Message CentralStation::receive()
286 while(IO::poll(socket, IO::P_INPUT, Time::zero))
289 unsigned len = socket.read(rbuf, sizeof(rbuf));
293 in_buffer.append(rbuf, len);
296 if(!in_buffer.empty())
298 string::iterator iter = in_buffer.begin();
299 if(Message msg = parse_message(iter, in_buffer.end()))
301 skip(iter, in_buffer.end(), "\r\n");
302 in_buffer.erase(in_buffer.begin(), iter);
304 if(msg.header.type=="REPLY" && pending_commands>0)
307 if(!cmd_queue.empty())
309 command(cmd_queue.front());
310 cmd_queue.pop_front();
321 void CentralStation::process_reply(const Message &msg)
323 if(!msg.header.value.compare(0, 4, "get("))
325 for(Message::ObjectMap::const_iterator i=msg.content.begin(); i!=msg.content.end(); ++i)
327 if(turnouts.count(i->first))
328 turnouts[i->first].synced = true;
330 process_object(i->first, i->second);
333 else if(!msg.header.value.compare(0, 16, "queryObjects(10,"))
335 for(Message::ObjectMap::const_iterator i=msg.content.begin(); i!=msg.content.end(); ++i)
337 LocoMap::iterator j = locos.find(i->first);
341 Message::AttribMap::const_iterator k = i->second.find("addr");
342 if(k!=i->second.end())
344 unsigned addr = lexical_cast<unsigned>(k->second);
346 j = locos.find(addr|0x10000);
349 command(format("request(%d, view, control, force)", i->first));
350 string cmd = format("get(%d, dir", i->first);
351 for(unsigned l=0; j->second.func_mask>>l; ++l)
352 if((j->second.func_mask>>l)&1)
353 cmd += format(", func[%d]", l);
357 locos.insert(LocoMap::value_type(i->first, j->second));
365 locos.insert(LocoMap::value_type(i->first, Locomotive()));
368 process_object(i->first, i->second);
373 if(locos.lower_bound(0x10000)!=locos.end())
374 command("create(10)");
376 else if(!msg.header.value.compare(0, 16, "queryObjects(11,"))
378 for(Message::ObjectMap::const_iterator i=msg.content.begin(); i!=msg.content.end(); ++i)
380 TurnoutMap::iterator j = turnouts.find(i->first);
381 if(j==turnouts.end())
384 Message::AttribMap::const_iterator k = i->second.find("addr");
385 if(k!=i->second.end())
387 unsigned addr = lexical_cast<unsigned>(k->second);
389 j = turnouts.find(addr|0x10000);
390 if(j!=turnouts.end())
392 command(format("request(%d, view, control)", i->first));
393 command(format("set(%d, symbol[%d])", i->first, j->second.symbol));
394 command(format("get(%d, state)", i->first));
396 turnouts.insert(TurnoutMap::value_type(i->first, j->second));
404 turnouts.insert(TurnoutMap::value_type(i->first, Turnout()));
407 process_object(i->first, i->second);
410 turnouts_synced = true;
412 for(TurnoutMap::const_iterator i=turnouts.lower_bound(0x10000); i!=turnouts.end(); ++i)
413 command("create(11, append)");
415 else if(msg.header.value=="queryObjects(26)")
418 for(Message::ObjectMap::const_iterator i=msg.content.begin(); i!=msg.content.end(); ++i)
420 s88.push_back(i->first);
421 command(format("request(%d, view)", i->first));
422 command(format("get(%d, state)", i->first));
425 sensors_synced = true;
429 unsigned high_addr = (--sensors.end())->first;
430 if(high_addr>16*s88.size())
431 command("create(26, add[0])");
434 else if(msg.header.value=="create(10)")
436 Message::ObjectMap::const_iterator i = msg.content.find(10);
437 if(i!=msg.content.end())
439 Message::AttribMap::const_iterator j = i->second.find("id");
440 if(j!=i->second.end())
442 unsigned id = lexical_cast<unsigned>(j->second);
443 LocoMap::iterator k = locos.lower_bound(0x10000);
446 command(format("request(%d, view, control)", id));
447 command(format("set(%d, addr[%d], protocol[%s], name[\"%s\"])",
448 id, k->second.address, (k->second.protocol==MM_27 ? "MM27" : "MM14"), k->second.name));
449 command("create(10, append)");
451 locos.insert(LocoMap::value_type(id, k->second));
457 if(locos.lower_bound(0x10000)!=locos.end())
458 command("create(10)");
460 else if(!msg.header.value.compare(0, 10, "create(11,"))
462 Message::ObjectMap::const_iterator i = msg.content.find(11);
463 if(i!=msg.content.end())
465 Message::AttribMap::const_iterator j = i->second.find("id");
466 if(j!=i->second.end())
468 unsigned id = lexical_cast<unsigned>(j->second);
469 TurnoutMap::iterator k = turnouts.lower_bound(0x10000);
470 if(k!=turnouts.end())
472 command(format("request(%d, view, control)", id));
473 command(format("set(%d, addr[%d], symbol[%d], name1[\"Switch\"], name2[\"%d\"], name3[\"\"])",
474 id, k->second.address, k->second.symbol, k->second.address));
475 command(format("set(%d, state[%d])", id, k->second.state&((1<<k->second.bits)-1)));
477 k->second.synced = true;
478 turnouts.insert(TurnoutMap::value_type(id, k->second));
484 else if(!msg.header.value.compare(0, 10, "create(26,"))
485 command("queryObjects(26)");
488 void CentralStation::process_event(const Message &msg)
490 for(Message::ObjectMap::const_iterator i=msg.content.begin(); i!=msg.content.end(); ++i)
491 process_object(i->first, i->second);
494 void CentralStation::process_object(unsigned id, const Message::AttribMap &attribs)
498 for(Message::AttribMap::const_iterator i=attribs.begin(); i!=attribs.end(); ++i)
499 if(i->first=="status")
501 power = (i->second=="GO");
502 signal_power.emit(power);
505 else if(locos.count(id))
507 Locomotive &loco = locos[id];
508 bool speed_changed = false;
509 unsigned funcs_changed = 0;
510 for(Message::AttribMap::const_iterator i=attribs.begin(); i!=attribs.end(); ++i)
513 loco.name = i->second.substr(1, i->second.size()-2);
514 else if(i->first=="addr")
516 loco_addr.erase(loco.address);
517 loco.address = lexical_cast<unsigned>(i->second);
518 loco_addr[loco.address] = id;
520 else if(i->first=="protocol")
524 else if(i->second=="MM27")
525 loco.protocol = MM_27;
526 else if(i->second=="MFX")
529 else if(i->first=="speedstep")
531 loco.speed = lexical_cast<unsigned>(i->second);
532 if(loco.protocol==MFX && loco.speed)
534 speed_changed = true;
536 else if(i->first=="dir")
538 loco.reverse = i->second[0]!='0';
539 speed_changed = true;
541 else if(i->first=="func")
543 vector<string> parts = split(i->second, ", ");
544 unsigned func = lexical_cast<unsigned>(parts[0]);
545 bool value = lexical_cast<unsigned>(parts[1]);
546 loco.funcs &= ~(1<<func);
548 loco.funcs |= 1<<func;
549 funcs_changed |= 1<<func;
551 else if(i->first=="msg")
553 if(i->second=="CONTROL_LOST")
554 command(format("request(%d, control, force)", id));
559 signal_loco_speed.emit(loco.address, loco.speed, loco.reverse);
560 for(unsigned i=0; funcs_changed>>i; ++i)
561 if(funcs_changed&(1<<i))
562 signal_loco_function.emit(loco.address, i, loco.funcs&(1<<i));
564 else if(turnouts.count(id))
566 Turnout &turnout = turnouts[id];
567 bool state_changed = false;
568 for(Message::AttribMap::const_iterator i=attribs.begin(); i!=attribs.end(); ++i)
572 turnout_addr.erase(turnout.address);
573 turnout.address = lexical_cast<unsigned>(i->second);
574 turnout_addr[turnout.address] = id;
576 else if(i->first=="state")
578 unsigned state = lexical_cast<unsigned>(i->second);
579 unsigned mask = (1<<turnout.bits)-1;
580 turnout.state = (turnout.state&~mask) | (state&mask);
581 state_changed = true;
586 signal_turnout.emit(turnout.address, turnout.state);
588 else if(find(s88.begin(), s88.end(), id)!=s88.end())
591 for(; (base<s88.size() && s88[base]!=id); ++base) ;
593 for(Message::AttribMap::const_iterator i=attribs.begin(); i!=attribs.end(); ++i)
595 if(i->first=="state")
597 unsigned state = lexical_cast<unsigned>(i->second, "%i");
598 for(unsigned j=0; j<16; ++j)
600 unsigned addr = base*16+j+1;
601 Sensor &sensor = sensors[addr];
602 bool s = state&(1<<j);
606 signal_sensor.emit(addr, sensor.state);
614 CentralStation::Protocol CentralStation::map_protocol(const string &name) const
618 else if(name=="MM-27")
623 throw InvalidParameterValue("Unknown protocol");
627 unsigned CentralStation::map_address(const map<unsigned, T> &omap, const AddressMap &amap, unsigned addr) const
633 AddressMap::const_iterator i = amap.find(addr);
641 void CentralStation::skip(string::iterator &iter, const string::iterator &end, const string &what) const
643 for(; (iter!=end && what.find(*iter)!=string::npos); ++iter) ;
646 string CentralStation::parse_token(string::iterator &iter, const string::iterator &end, const string &stop) const
652 skip(iter, end, stop);
654 for(; iter!=end; ++iter)
656 if(stop.find(*iter)!=string::npos && parens.empty() && !quote)
658 else if(*iter=='(' || *iter=='[')
659 parens.push_back(*iter);
660 else if((*iter==')' || *iter==']') && !parens.empty())
662 if((*iter==')' && parens.back()!='(') || (*iter==']' && parens.back()!='['))
663 IO::print("Mismatched parentheses\n");
675 CentralStation::Tag CentralStation::parse_tag(string::iterator &iter, const string::iterator &end) const
679 for(; (iter!=end && *iter!='<'); ++iter) ;
683 tag.type = parse_token(++iter, end, " >");
686 string code = parse_token(iter, end, " >");
687 tag.code = lexical_cast<unsigned>(code);
689 skip(iter, end, " ");
690 tag.value = parse_token(iter, end, ">");
698 CentralStation::Message CentralStation::parse_message(string::iterator &iter, const string::iterator &end) const
702 msg.header = parse_tag(iter, end);
706 skip(iter, end, "\r\n");
710 string id = parse_token(iter, end, " \r\n<");
711 Message::AttribMap &attribs = msg.content[lexical_cast<unsigned>(id)];
712 while(iter!=end && *iter!='\n' && *iter!='\r')
714 string attr = parse_token(iter, end, " \r\n<");
715 string::size_type open_bracket = attr.find('[');
716 if(open_bracket!=string::npos)
718 string::size_type close_bracket = attr.rfind(']');
719 string attr_name = attr.substr(0, open_bracket);
720 string attr_value = attr.substr(open_bracket+1, close_bracket-open_bracket-1);
721 attribs.insert(Message::AttribMap::value_type(attr_name, attr_value));
724 attribs.insert(Message::AttribMap::value_type(attr, string()));
728 msg.footer = parse_tag(iter, end);
729 if(msg.footer.type.empty())
736 CentralStation::Tag::Tag():
740 CentralStation::Tag::operator bool() const
742 return !type.empty();
746 CentralStation::Message::operator bool() const
748 return header && footer;
752 CentralStation::Locomotive::Locomotive():
762 CentralStation::Turnout::Turnout():
771 CentralStation::Sensor::Sensor():