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 if(locos_synced && proto!=MFX)
111 command("create(10)");
114 command(format("request(%d, view, control, force)", id));
117 void CentralStation::set_loco_speed(unsigned addr, unsigned speed)
122 unsigned id = map_address(locos, loco_addr, addr);
125 Locomotive &loco = locos[id];
126 if(loco.protocol==MFX && speed)
128 command(format("set(%d, speedstep[%d])", id, speed));
132 void CentralStation::set_loco_reverse(unsigned addr, bool rev)
134 unsigned id = map_address(locos, loco_addr, addr);
136 command(format("set(%d, dir[%d])", id, rev));
139 void CentralStation::set_loco_function(unsigned addr, unsigned func, bool state)
141 unsigned id = map_address(locos, loco_addr, addr);
143 command(format("set(%d, func[%d, %d])", id, func, state));
146 void CentralStation::add_turnout(unsigned addr, const TrackType &type)
152 const vector<TrackPart> &parts = type.get_parts();
153 for(vector<TrackPart>::const_iterator i=parts.begin(); i!=parts.end(); ++i)
155 TrackPoint start = i->get_point(0);
156 TrackPoint end = i->get_point(i->get_length());
157 if(end.dir>start.dir+0.01)
159 else if(end.dir<start.dir-0.01)
161 else if(start.dir<-0.01 || start.dir>0.01)
165 unsigned symbol = Turnout::LEFT;
167 symbol = Turnout::DOUBLESLIP;
168 else if(left && right)
169 symbol = Turnout::THREEWAY;
171 symbol = Turnout::LEFT;
173 symbol = Turnout::RIGHT;
175 unsigned id = map_address(turnouts, turnout_addr, addr);
180 Turnout &turnout = turnouts[id];
181 turnout.address = addr;
182 turnout.bits = type.get_state_bits();
183 turnout.symbol = symbol;
185 turnout_addr[addr] = id;
188 command("create(11, append)");
192 Turnout &turnout = turnouts[id];
193 command(format("request(%d, view, control)", id));
194 if(turnout.symbol!=symbol)
195 command(format("set(%d, symbol[%d])", symbol));
199 void CentralStation::set_turnout(unsigned addr, unsigned state)
201 unsigned id = map_address(turnouts, turnout_addr, addr);
204 Turnout &turnout = turnouts[id];
205 unsigned mask = (1<<turnout.bits)-1;
207 if(((state^turnout.state)&mask)==0 || !turnout.synced)
209 turnout.state = state;
210 signal_turnout.emit(addr, turnout.state);
214 turnout.state = (turnout.state&mask) | (state&~mask);
216 command(format("set(%d, state[%d])", id, state&mask));
220 unsigned CentralStation::get_turnout(unsigned addr) const
222 unsigned id = map_address(turnouts, turnout_addr, addr);
225 TurnoutMap::const_iterator i = turnouts.find(id);
226 if(i!=turnouts.end())
227 return i->second.state;
232 void CentralStation::add_sensor(unsigned addr)
234 sensors.insert(SensorMap::value_type(addr, Sensor()));
238 if(addr>s88.size()*16)
239 command("create(26, add[0])");
243 bool CentralStation::get_sensor(unsigned addr) const
245 SensorMap::const_iterator i = sensors.find(addr);
247 return i->second.state;
251 void CentralStation::tick()
253 while(Message msg = receive())
256 IO::print("\033[31m*** ERROR: %s: %d %s ***\033[0m\n", msg.header.value, msg.footer.code, msg.footer.value);
258 if(msg.header.type=="REPLY")
260 else if(msg.header.type=="EVENT")
265 void CentralStation::flush()
269 void CentralStation::command(const string &cmd, bool force)
271 if(pending_commands<10 || force)
273 socket.write(cmd+"\r\n");
277 cmd_queue.push_back(cmd);
280 CentralStation::Message CentralStation::receive()
282 while(IO::poll(socket, IO::P_INPUT, Time::zero))
285 unsigned len = socket.read(rbuf, sizeof(rbuf));
289 in_buffer.append(rbuf, len);
292 if(!in_buffer.empty())
294 string::iterator iter = in_buffer.begin();
295 if(Message msg = parse_message(iter, in_buffer.end()))
297 skip(iter, in_buffer.end(), "\r\n");
298 in_buffer.erase(in_buffer.begin(), iter);
300 if(msg.header.type=="REPLY" && pending_commands>0)
303 if(!cmd_queue.empty())
305 command(cmd_queue.front());
306 cmd_queue.pop_front();
317 void CentralStation::process_reply(const Message &msg)
319 if(!msg.header.value.compare(0, 4, "get("))
321 for(Message::ObjectMap::const_iterator i=msg.content.begin(); i!=msg.content.end(); ++i)
323 if(turnouts.count(i->first))
324 turnouts[i->first].synced = true;
326 process_object(i->first, i->second);
329 else if(!msg.header.value.compare(0, 16, "queryObjects(10,"))
331 for(Message::ObjectMap::const_iterator i=msg.content.begin(); i!=msg.content.end(); ++i)
333 LocoMap::iterator j = locos.find(i->first);
337 Message::AttribMap::const_iterator k = i->second.find("addr");
338 if(k!=i->second.end())
340 unsigned addr = lexical_cast<unsigned>(k->second);
342 j = locos.find(addr|0x10000);
345 command(format("request(%d, view, control, force)", i->first));
346 command(format("get(%d, dir, func[0])", i->first));
348 locos.insert(LocoMap::value_type(i->first, j->second));
356 locos.insert(LocoMap::value_type(i->first, Locomotive()));
359 process_object(i->first, i->second);
364 if(locos.lower_bound(0x10000)!=locos.end())
365 command("create(10)");
367 else if(!msg.header.value.compare(0, 16, "queryObjects(11,"))
369 for(Message::ObjectMap::const_iterator i=msg.content.begin(); i!=msg.content.end(); ++i)
371 TurnoutMap::iterator j = turnouts.find(i->first);
372 if(j==turnouts.end())
375 Message::AttribMap::const_iterator k = i->second.find("addr");
376 if(k!=i->second.end())
378 unsigned addr = lexical_cast<unsigned>(k->second);
380 j = turnouts.find(addr|0x10000);
381 if(j!=turnouts.end())
383 command(format("request(%d, view, control)", i->first));
384 command(format("set(%d, symbol[%d])", i->first, j->second.symbol));
385 command(format("get(%d, state)", i->first));
387 turnouts.insert(TurnoutMap::value_type(i->first, j->second));
395 turnouts.insert(TurnoutMap::value_type(i->first, Turnout()));
398 process_object(i->first, i->second);
401 turnouts_synced = true;
403 for(TurnoutMap::const_iterator i=turnouts.lower_bound(0x10000); i!=turnouts.end(); ++i)
404 command("create(11, append)");
406 else if(msg.header.value=="queryObjects(26)")
409 for(Message::ObjectMap::const_iterator i=msg.content.begin(); i!=msg.content.end(); ++i)
411 s88.push_back(i->first);
412 command(format("request(%d, view)", i->first));
415 sensors_synced = true;
419 unsigned high_addr = (--sensors.end())->first;
420 if(high_addr>16*s88.size())
421 command("create(26, add[0])");
424 else if(msg.header.value=="create(10)")
426 Message::ObjectMap::const_iterator i = msg.content.find(10);
427 if(i!=msg.content.end())
429 Message::AttribMap::const_iterator j = i->second.find("id");
430 if(j!=i->second.end())
432 unsigned id = lexical_cast<unsigned>(j->second);
433 LocoMap::iterator k = locos.lower_bound(0x10000);
436 command(format("request(%d, view, control)", id));
437 command(format("set(%d, addr[%d], protocol[%s], name[\"%s\"])",
438 id, k->second.address, (k->second.protocol==MM_27 ? "MM27" : "MM14"), k->second.name));
439 command("create(10, append)");
441 locos.insert(LocoMap::value_type(id, k->second));
447 if(locos.lower_bound(0x10000)!=locos.end())
448 command("create(10)");
450 else if(!msg.header.value.compare(0, 10, "create(11,"))
452 Message::ObjectMap::const_iterator i = msg.content.find(11);
453 if(i!=msg.content.end())
455 Message::AttribMap::const_iterator j = i->second.find("id");
456 if(j!=i->second.end())
458 unsigned id = lexical_cast<unsigned>(j->second);
459 TurnoutMap::iterator k = turnouts.lower_bound(0x10000);
460 if(k!=turnouts.end())
462 command(format("request(%d, view, control)", id));
463 command(format("set(%d, addr[%d], symbol[%d], name1[\"Switch\"], name2[\"%d\"], name3[\"\"])",
464 id, k->second.address, k->second.symbol, k->second.address));
465 command(format("set(%d, state[%d])", id, k->second.state&((1<<k->second.bits)-1)));
467 k->second.synced = true;
468 turnouts.insert(TurnoutMap::value_type(id, k->second));
474 else if(!msg.header.value.compare(0, 10, "create(26,"))
475 command("queryObjects(26)");
478 void CentralStation::process_event(const Message &msg)
480 for(Message::ObjectMap::const_iterator i=msg.content.begin(); i!=msg.content.end(); ++i)
481 process_object(i->first, i->second);
484 void CentralStation::process_object(unsigned id, const Message::AttribMap &attribs)
488 for(Message::AttribMap::const_iterator i=attribs.begin(); i!=attribs.end(); ++i)
489 if(i->first=="status")
491 power = (i->second=="GO");
492 signal_power.emit(power);
495 else if(locos.count(id))
497 Locomotive &loco = locos[id];
498 bool speed_changed = false;
499 unsigned funcs_changed = 0;
500 for(Message::AttribMap::const_iterator i=attribs.begin(); i!=attribs.end(); ++i)
503 loco.name = i->second.substr(1, i->second.size()-2);
504 else if(i->first=="addr")
506 loco_addr.erase(loco.address);
507 loco.address = lexical_cast<unsigned>(i->second);
508 loco_addr[loco.address] = id;
510 else if(i->first=="protocol")
514 else if(i->second=="MM27")
515 loco.protocol = MM_27;
516 else if(i->second=="MFX")
519 else if(i->first=="speedstep")
521 loco.speed = lexical_cast<unsigned>(i->second);
522 if(loco.protocol==MFX && loco.speed)
524 speed_changed = true;
526 else if(i->first=="dir")
528 loco.reverse = i->second[0]!='0';
529 speed_changed = true;
531 else if(i->first=="func")
533 vector<string> parts = split(i->second, ", ");
534 unsigned func = lexical_cast<unsigned>(parts[0]);
535 bool value = lexical_cast<unsigned>(parts[1]);
536 loco.funcs &= ~(1<<func);
538 loco.funcs |= 1<<func;
539 funcs_changed |= 1<<func;
541 else if(i->first=="msg")
543 if(i->second=="CONTROL_LOST")
544 command(format("request(%d, control, force)", id));
549 signal_loco_speed.emit(loco.address, loco.speed, loco.reverse);
550 for(unsigned i=0; funcs_changed>>i; ++i)
551 if(funcs_changed&(1<<i))
552 signal_loco_function.emit(loco.address, i, loco.funcs&(1<<i));
554 else if(turnouts.count(id))
556 Turnout &turnout = turnouts[id];
557 bool state_changed = false;
558 for(Message::AttribMap::const_iterator i=attribs.begin(); i!=attribs.end(); ++i)
562 turnout_addr.erase(turnout.address);
563 turnout.address = lexical_cast<unsigned>(i->second);
564 turnout_addr[turnout.address] = id;
566 else if(i->first=="state")
568 unsigned state = lexical_cast<unsigned>(i->second);
569 unsigned mask = (1<<turnout.bits)-1;
570 turnout.state = (turnout.state&~mask) | (state&mask);
571 state_changed = true;
576 signal_turnout.emit(turnout.address, turnout.state);
578 else if(find(s88.begin(), s88.end(), id)!=s88.end())
581 for(; (base<s88.size() && s88[base]!=id); ++base) ;
583 for(Message::AttribMap::const_iterator i=attribs.begin(); i!=attribs.end(); ++i)
585 if(i->first=="state")
587 unsigned state = lexical_cast<unsigned>(i->second, "%i");
588 for(unsigned j=0; j<16; ++j)
590 unsigned addr = base*16+j+1;
591 Sensor &sensor = sensors[addr];
592 bool s = state&(1<<j);
596 signal_sensor.emit(addr, sensor.state);
604 CentralStation::Protocol CentralStation::map_protocol(const string &name) const
608 else if(name=="MM-27")
613 throw InvalidParameterValue("Unknown protocol");
617 unsigned CentralStation::map_address(const map<unsigned, T> &omap, const AddressMap &amap, unsigned addr) const
623 AddressMap::const_iterator i = amap.find(addr);
631 void CentralStation::skip(string::iterator &iter, const string::iterator &end, const string &what) const
633 for(; (iter!=end && what.find(*iter)!=string::npos); ++iter) ;
636 string CentralStation::parse_token(string::iterator &iter, const string::iterator &end, const string &stop) const
642 skip(iter, end, stop);
644 for(; iter!=end; ++iter)
646 if(stop.find(*iter)!=string::npos && parens.empty() && !quote)
648 else if(*iter=='(' || *iter=='[')
649 parens.push_back(*iter);
650 else if((*iter==')' || *iter==']') && !parens.empty())
652 if((*iter==')' && parens.back()!='(') || (*iter==']' && parens.back()!='['))
653 IO::print("Mismatched parentheses\n");
665 CentralStation::Tag CentralStation::parse_tag(string::iterator &iter, const string::iterator &end) const
669 for(; (iter!=end && *iter!='<'); ++iter) ;
673 tag.type = parse_token(++iter, end, " >");
676 string code = parse_token(iter, end, " >");
677 tag.code = lexical_cast<unsigned>(code);
679 skip(iter, end, " ");
680 tag.value = parse_token(iter, end, ">");
688 CentralStation::Message CentralStation::parse_message(string::iterator &iter, const string::iterator &end) const
692 msg.header = parse_tag(iter, end);
696 skip(iter, end, "\r\n");
700 string id = parse_token(iter, end, " \r\n<");
701 Message::AttribMap &attribs = msg.content[lexical_cast<unsigned>(id)];
702 while(iter!=end && *iter!='\n' && *iter!='\r')
704 string attr = parse_token(iter, end, " \r\n<");
705 string::size_type open_bracket = attr.find('[');
706 if(open_bracket!=string::npos)
708 string::size_type close_bracket = attr.rfind(']');
709 attribs[attr.substr(0, open_bracket)] = attr.substr(open_bracket+1, close_bracket-open_bracket-1);
716 msg.footer = parse_tag(iter, end);
717 if(msg.footer.type.empty())
724 CentralStation::Tag::Tag():
728 CentralStation::Tag::operator bool() const
730 return !type.empty();
734 CentralStation::Message::operator bool() const
736 return header && footer;
740 CentralStation::Locomotive::Locomotive():
749 CentralStation::Turnout::Turnout():
758 CentralStation::Sensor::Sensor():