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);
124 command(format("set(%d, speedstep[%d])", id, speed));
127 void CentralStation::set_loco_reverse(unsigned addr, bool rev)
129 unsigned id = map_address(locos, loco_addr, addr);
131 command(format("set(%d, dir[%d])", id, rev));
134 void CentralStation::set_loco_function(unsigned addr, unsigned func, bool state)
136 unsigned id = map_address(locos, loco_addr, addr);
138 command(format("set(%d, func[%d, %d])", id, func, state));
141 void CentralStation::add_turnout(unsigned addr, const TrackType &type)
147 const vector<TrackPart> &parts = type.get_parts();
148 for(vector<TrackPart>::const_iterator i=parts.begin(); i!=parts.end(); ++i)
150 TrackPoint start = i->get_point(0);
151 TrackPoint end = i->get_point(i->get_length());
152 if(end.dir>start.dir+0.01)
154 else if(end.dir<start.dir-0.01)
156 else if(start.dir<-0.01 || start.dir>0.01)
162 symbol = Turnout::DOUBLESLIP;
163 else if(left && right)
164 symbol = Turnout::THREEWAY;
166 symbol = Turnout::LEFT;
168 symbol = Turnout::RIGHT;
170 unsigned id = map_address(turnouts, turnout_addr, addr);
175 Turnout &turnout = turnouts[id];
176 turnout.address = addr;
177 turnout.bits = type.get_state_bits();
178 turnout.symbol = symbol;
180 turnout_addr[addr] = id;
183 command("create(11, append)");
187 Turnout &turnout = turnouts[id];
188 command(format("request(%d, view, control)", id));
189 if(turnout.symbol!=symbol)
190 command(format("set(%d, symbol[%d])", symbol));
194 void CentralStation::set_turnout(unsigned addr, unsigned state)
196 unsigned id = map_address(turnouts, turnout_addr, addr);
199 Turnout &turnout = turnouts[id];
200 unsigned mask = (1<<turnout.bits)-1;
202 if(((state^turnout.state)&mask)==0 || !turnout.synced)
204 turnout.state = state;
205 signal_turnout.emit(addr, turnout.state);
209 turnout.state = (turnout.state&mask) | (state&~mask);
211 command(format("set(%d, state[%d])", id, state&mask));
215 unsigned CentralStation::get_turnout(unsigned addr) const
217 unsigned id = map_address(turnouts, turnout_addr, addr);
220 TurnoutMap::const_iterator i = turnouts.find(id);
221 if(i!=turnouts.end())
222 return i->second.state;
227 void CentralStation::add_sensor(unsigned addr)
229 sensors.insert(SensorMap::value_type(addr, Sensor()));
233 if(addr>s88.size()*16)
234 command("create(26, add[0])");
238 bool CentralStation::get_sensor(unsigned addr) const
240 SensorMap::const_iterator i = sensors.find(addr);
242 return i->second.state;
246 void CentralStation::tick()
248 Time::TimeStamp t = Time::now();
249 for(SensorMap::iterator i=sensors.begin(); i!=sensors.end(); ++i)
250 if(i->second.off_timeout && t>i->second.off_timeout)
252 i->second.state = false;
253 i->second.off_timeout = Time::TimeStamp();
254 signal_sensor.emit(i->first, i->second.state);
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 command(format("get(%d, dir, func[0])", i->first));
352 locos.insert(LocoMap::value_type(i->first, j->second));
360 locos.insert(LocoMap::value_type(i->first, Locomotive()));
363 process_object(i->first, i->second);
368 if(locos.lower_bound(0x10000)!=locos.end())
369 command("create(10)");
371 else if(!msg.header.value.compare(0, 16, "queryObjects(11,"))
373 for(Message::ObjectMap::const_iterator i=msg.content.begin(); i!=msg.content.end(); ++i)
375 TurnoutMap::iterator j = turnouts.find(i->first);
376 if(j==turnouts.end())
379 Message::AttribMap::const_iterator k = i->second.find("addr");
380 if(k!=i->second.end())
382 unsigned addr = lexical_cast<unsigned>(k->second);
384 j = turnouts.find(addr|0x10000);
385 if(j!=turnouts.end())
387 command(format("request(%d, view, control)", i->first));
388 command(format("set(%d, symbol[%d])", i->first, j->second.symbol));
389 command(format("get(%d, state)", i->first));
391 turnouts.insert(TurnoutMap::value_type(i->first, j->second));
399 turnouts.insert(TurnoutMap::value_type(i->first, Turnout()));
402 process_object(i->first, i->second);
405 turnouts_synced = true;
407 for(TurnoutMap::const_iterator i=turnouts.lower_bound(0x10000); i!=turnouts.end(); ++i)
408 command("create(11, append)");
410 else if(msg.header.value=="queryObjects(26)")
413 for(Message::ObjectMap::const_iterator i=msg.content.begin(); i!=msg.content.end(); ++i)
415 s88.push_back(i->first);
416 command(format("request(%d, view)", i->first));
419 sensors_synced = true;
423 unsigned high_addr = (--sensors.end())->first;
424 if(high_addr>16*s88.size())
425 command("create(26, add[0])");
428 else if(msg.header.value=="create(10)")
430 Message::ObjectMap::const_iterator i = msg.content.find(10);
431 if(i!=msg.content.end())
433 Message::AttribMap::const_iterator j = i->second.find("id");
434 if(j!=i->second.end())
436 unsigned id = lexical_cast<unsigned>(j->second);
437 LocoMap::iterator k = locos.lower_bound(0x10000);
440 command(format("request(%d, view, control)", id));
441 command(format("set(%d, addr[%d], protocol[%s], name[\"%s\"])",
442 id, k->second.address, (k->second.protocol==MM_27 ? "MM27" : "MM14"), k->second.name));
443 command("create(10, append)");
445 locos.insert(LocoMap::value_type(id, k->second));
451 if(locos.lower_bound(0x10000)!=locos.end())
452 command("create(10)");
454 else if(!msg.header.value.compare(0, 10, "create(11,"))
456 Message::ObjectMap::const_iterator i = msg.content.find(11);
457 if(i!=msg.content.end())
459 Message::AttribMap::const_iterator j = i->second.find("id");
460 if(j!=i->second.end())
462 unsigned id = lexical_cast<unsigned>(j->second);
463 TurnoutMap::iterator k = turnouts.lower_bound(0x10000);
464 if(k!=turnouts.end())
466 command(format("request(%d, view, control)", id));
467 command(format("set(%d, addr[%d], symbol[%d], name1[\"Switch\"], name2[\"%d\"], name3[\"\"])",
468 id, k->second.address, k->second.symbol, k->second.address));
469 command(format("set(%d, state[%d])", id, k->second.state&((1<<k->second.bits)-1)));
471 k->second.synced = true;
472 turnouts.insert(TurnoutMap::value_type(id, k->second));
478 else if(!msg.header.value.compare(0, 10, "create(26,"))
479 command("queryObjects(26)");
482 void CentralStation::process_event(const Message &msg)
484 for(Message::ObjectMap::const_iterator i=msg.content.begin(); i!=msg.content.end(); ++i)
485 process_object(i->first, i->second);
488 void CentralStation::process_object(unsigned id, const Message::AttribMap &attribs)
492 for(Message::AttribMap::const_iterator i=attribs.begin(); i!=attribs.end(); ++i)
493 if(i->first=="status")
495 power = (i->second=="GO");
496 signal_power.emit(power);
499 else if(locos.count(id))
501 Locomotive &loco = locos[id];
502 bool speed_changed = false;
503 unsigned funcs_changed = 0;
504 for(Message::AttribMap::const_iterator i=attribs.begin(); i!=attribs.end(); ++i)
507 loco.name = i->second.substr(1, i->second.size()-2);
508 else if(i->first=="addr")
510 loco_addr.erase(loco.address);
511 loco.address = lexical_cast<unsigned>(i->second);
512 loco_addr[loco.address] = id;
514 else if(i->first=="protocol")
518 else if(i->second=="MM27")
519 loco.protocol = MM_27;
520 else if(i->second=="MFX")
523 else if(i->first=="speedstep")
525 loco.speed = lexical_cast<unsigned>(i->second);
526 speed_changed = true;
528 else if(i->first=="dir")
530 loco.reverse = i->second[0]!='0';
531 speed_changed = true;
533 else if(i->first=="func")
535 vector<string> parts = split(i->second, ", ");
536 unsigned func = lexical_cast<unsigned>(parts[0]);
537 bool value = lexical_cast<unsigned>(parts[1]);
538 loco.funcs &= ~(1<<func);
540 loco.funcs |= 1<<func;
541 funcs_changed |= 1<<func;
543 else if(i->first=="msg")
545 if(i->second=="CONTROL_LOST")
546 command(format("request(%d, control, force)", id));
551 signal_loco_speed.emit(loco.address, loco.speed, loco.reverse);
552 for(unsigned i=0; funcs_changed>>i; ++i)
553 if(funcs_changed&(1<<i))
554 signal_loco_function.emit(loco.address, i, loco.funcs&(1<<i));
556 else if(turnouts.count(id))
558 Turnout &turnout = turnouts[id];
559 bool state_changed = false;
560 for(Message::AttribMap::const_iterator i=attribs.begin(); i!=attribs.end(); ++i)
564 turnout_addr.erase(turnout.address);
565 turnout.address = lexical_cast<unsigned>(i->second);
566 turnout_addr[turnout.address] = id;
568 else if(i->first=="state")
570 unsigned state = lexical_cast<unsigned>(i->second);
571 unsigned mask = (1<<turnout.bits)-1;
572 turnout.state = (turnout.state&~mask) | (state&mask);
573 state_changed = true;
578 signal_turnout.emit(turnout.address, turnout.state);
580 else if(find(s88.begin(), s88.end(), id)!=s88.end())
583 for(; (base<s88.size() && s88[base]!=id); ++base) ;
585 for(Message::AttribMap::const_iterator i=attribs.begin(); i!=attribs.end(); ++i)
587 if(i->first=="state")
589 unsigned state = lexical_cast<unsigned>(i->second, "%i");
590 for(unsigned j=0; j<16; ++j)
592 unsigned addr = base*16+j+1;
593 Sensor &sensor = sensors[addr];
594 bool s = state&(1<<j);
597 sensor.off_timeout = Time::TimeStamp();
601 signal_sensor.emit(addr, sensor.state);
604 else if(sensor.state)
605 sensor.off_timeout = Time::now()+700*Time::msec;
612 CentralStation::Protocol CentralStation::map_protocol(const string &name) const
616 else if(name=="MM-27")
621 throw InvalidParameterValue("Unknown protocol");
625 unsigned CentralStation::map_address(const map<unsigned, T> &omap, const AddressMap &amap, unsigned addr) const
631 AddressMap::const_iterator i = amap.find(addr);
639 void CentralStation::skip(string::iterator &iter, const string::iterator &end, const string &what) const
641 for(; (iter!=end && what.find(*iter)!=string::npos); ++iter) ;
644 string CentralStation::parse_token(string::iterator &iter, const string::iterator &end, const string &stop) const
650 skip(iter, end, stop);
652 for(; iter!=end; ++iter)
654 if(stop.find(*iter)!=string::npos && parens.empty() && !quote)
656 else if(*iter=='(' || *iter=='[')
657 parens.push_back(*iter);
658 else if((*iter==')' || *iter==']') && !parens.empty())
660 if((*iter==')' && parens.back()!='(') || (*iter==']' && parens.back()!='['))
661 IO::print("Mismatched parentheses\n");
673 CentralStation::Tag CentralStation::parse_tag(string::iterator &iter, const string::iterator &end) const
677 for(; (iter!=end && *iter!='<'); ++iter) ;
681 tag.type = parse_token(++iter, end, " >");
684 string code = parse_token(iter, end, " >");
685 tag.code = lexical_cast<unsigned>(code);
687 skip(iter, end, " ");
688 tag.value = parse_token(iter, end, ">");
696 CentralStation::Message CentralStation::parse_message(string::iterator &iter, const string::iterator &end) const
700 msg.header = parse_tag(iter, end);
704 skip(iter, end, "\r\n");
708 string id = parse_token(iter, end, " \r\n<");
709 Message::AttribMap &attribs = msg.content[lexical_cast<unsigned>(id)];
710 while(iter!=end && *iter!='\n' && *iter!='\r')
712 string attr = parse_token(iter, end, " \r\n<");
713 string::size_type open_bracket = attr.find('[');
714 if(open_bracket!=string::npos)
716 string::size_type close_bracket = attr.rfind(']');
717 attribs[attr.substr(0, open_bracket)] = attr.substr(open_bracket+1, close_bracket-open_bracket-1);
724 msg.footer = parse_tag(iter, end);
725 if(msg.footer.type.empty())
732 CentralStation::Tag::Tag():
736 CentralStation::Tag::operator bool() const
738 return !type.empty();
742 CentralStation::Message::operator bool() const
744 return header && footer;
748 CentralStation::Locomotive::Locomotive():
757 CentralStation::Turnout::Turnout():
766 CentralStation::Sensor::Sensor():