]> git.tdb.fi Git - r2c2.git/blob - source/libr2c2/centralstation.cpp
Strip Id tags and copyright notices from files
[r2c2.git] / source / libr2c2 / centralstation.cpp
1 #include <algorithm>
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"
9 #include "tracktype.h"
10 #include "vehicletype.h"
11
12 using namespace std;
13 using namespace Msp;
14
15 namespace R2C2 {
16
17 CentralStation::CentralStation(const string &host):
18         socket(Net::INET),
19         pending_commands(0),
20         power(false),
21         halted(false),
22         locos_synced(false),
23         turnouts_synced(false),
24         sensors_synced(false)
25 {
26         RefPtr<Net::SockAddr> addr = Net::resolve(host+":15471");
27         socket.connect(*addr);
28
29         IO::print("Connected to central station at %s\n", addr->str());
30
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)");
36 }
37
38 CentralStation::~CentralStation()
39 {
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(TurnoutMap::iterator i=turnouts.begin(); (i!=turnouts.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))
46                 while(receive()) ;
47 }
48
49 void CentralStation::set_power(bool p)
50 {
51         power = p;
52         command(format("set(1, %s)", (power ? "go" : "stop")));
53 }
54
55 void CentralStation::halt(bool h)
56 {
57         halted = h;
58         if(halted)
59         {
60                 for(LocoMap::iterator i=locos.begin(); i!=locos.end(); ++i)
61                         if(i->second.speed)
62                                 set_loco_speed(i->first, 0);
63         }
64
65         signal_halt.emit(halted);
66 }
67
68 const char *CentralStation::enumerate_protocols(unsigned index) const
69 {
70         if(index==MM)
71                 return "MM";
72         else if(index==MM_27)
73                 return "MM-27";
74         else if(index==MFX)
75                 return "MFX";
76         else
77                 return 0;
78 }
79
80 unsigned CentralStation::get_protocol_speed_steps(const string &name) const
81 {
82         switch(map_protocol(name))
83         {
84         case MM: return 14;
85         case MM_27: return 27;
86         case MFX: return 126;
87         default: return 0;
88         }
89 }
90
91 void CentralStation::add_loco(unsigned addr, const string &proto_name, const VehicleType &type)
92 {
93         Protocol proto = map_protocol(proto_name);
94
95         unsigned id = map_address(locos, loco_addr, addr);
96         if(!id)
97         {
98                 Locomotive &loco = locos[addr|0x10000];
99                 loco.name = type.get_name();
100                 loco.protocol = proto;
101                 loco.address = addr;
102
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;
106
107                 if(locos_synced && proto!=MFX)
108                         command("create(10)");
109         }
110         else
111                 command(format("request(%d, view, control, force)", id));
112 }
113
114 void CentralStation::set_loco_speed(unsigned addr, unsigned speed)
115 {
116         if(speed && halted)
117                 return;
118
119         unsigned id = map_address(locos, loco_addr, addr);
120         if(id)
121         {
122                 Locomotive &loco = locos[id];
123                 if(loco.protocol==MFX && speed)
124                         ++speed;
125                 command(format("set(%d, speedstep[%d])", id, speed));
126         }
127 }
128
129 void CentralStation::set_loco_reverse(unsigned addr, bool rev)
130 {
131         unsigned id = map_address(locos, loco_addr, addr);
132         if(id)
133                 command(format("set(%d, dir[%d])", id, rev));
134 }
135
136 void CentralStation::set_loco_function(unsigned addr, unsigned func, bool state)
137 {
138         unsigned id = map_address(locos, loco_addr, addr);
139         if(id)
140                 command(format("set(%d, func[%d, %d])", id, func, state));
141 }
142
143 void CentralStation::add_turnout(unsigned addr, const TrackType &type)
144 {
145         bool left = false;
146         bool right = false;
147         bool cross = false;
148
149         const vector<TrackPart> &parts = type.get_parts();
150         for(vector<TrackPart>::const_iterator i=parts.begin(); i!=parts.end(); ++i)
151         {
152                 TrackPoint start = i->get_point(0);
153                 TrackPoint end = i->get_point(i->get_length());
154                 if(end.dir>start.dir+0.01)
155                         left = true;
156                 else if(end.dir<start.dir-0.01)
157                         right = true;
158                 else if(start.dir<-0.01 || start.dir>0.01)
159                         cross = true;
160         }
161
162         unsigned symbol = Turnout::LEFT;
163         if(cross)
164                 symbol = Turnout::DOUBLESLIP;
165         else if(left && right)
166                 symbol = Turnout::THREEWAY;
167         else if(left)
168                 symbol = Turnout::LEFT;
169         else if(right)
170                 symbol = Turnout::RIGHT;
171
172         unsigned id = map_address(turnouts, turnout_addr, addr);
173         if(!id)
174         {
175                 id = addr|0x10000;
176
177                 Turnout &turnout = turnouts[id];
178                 turnout.address = addr;
179                 turnout.bits = type.get_state_bits();
180                 turnout.symbol = symbol;
181
182                 turnout_addr[addr] = id;
183
184                 if(turnouts_synced)
185                         command("create(11, append)");
186         }
187         else
188         {
189                 Turnout &turnout = turnouts[id];
190                 command(format("request(%d, view, control)", id));
191                 if(turnout.symbol!=symbol)
192                         command(format("set(%d, symbol[%d])", symbol));
193         }
194 }
195
196 void CentralStation::set_turnout(unsigned addr, unsigned state)
197 {
198         unsigned id = map_address(turnouts, turnout_addr, addr);
199         if(id)
200         {
201                 Turnout &turnout = turnouts[id];
202                 unsigned mask = (1<<turnout.bits)-1;
203
204                 if(((state^turnout.state)&mask)==0 || !turnout.synced)
205                 {
206                         turnout.state = state;
207                         signal_turnout.emit(addr, turnout.state);
208                         return;
209                 }
210
211                 turnout.state = (turnout.state&mask) | (state&~mask);
212
213                 command(format("set(%d, state[%d])", id, state&mask));
214         }
215 }
216
217 unsigned CentralStation::get_turnout(unsigned addr) const
218 {
219         unsigned id = map_address(turnouts, turnout_addr, addr);
220         if(id)
221         {
222                 TurnoutMap::const_iterator i = turnouts.find(id);
223                 if(i!=turnouts.end())
224                         return i->second.state;
225         }
226         return 0;
227 }
228
229 void CentralStation::add_sensor(unsigned addr)
230 {
231         sensors.insert(SensorMap::value_type(addr, Sensor()));
232
233         if(sensors_synced)
234         {
235                 if(addr>s88.size()*16)
236                         command("create(26, add[0])");
237         }
238 }
239
240 bool CentralStation::get_sensor(unsigned addr) const
241 {
242         SensorMap::const_iterator i = sensors.find(addr);
243         if(i!=sensors.end())
244                 return i->second.state;
245         return false;
246 }
247
248 void CentralStation::tick()
249 {
250         while(Message msg = receive())
251         {
252                 if(msg.footer.code)
253                         IO::print("\033[31m*** ERROR: %s: %d %s ***\033[0m\n", msg.header.value, msg.footer.code, msg.footer.value);
254
255                 if(msg.header.type=="REPLY")
256                         process_reply(msg);
257                 else if(msg.header.type=="EVENT")
258                         process_event(msg);
259         }
260 }
261
262 void CentralStation::flush()
263 {
264 }
265
266 void CentralStation::command(const string &cmd, bool force)
267 {
268         if(pending_commands<10 || force)
269         {
270                 socket.write(cmd+"\r\n");
271                 ++pending_commands;
272         }
273         else
274                 cmd_queue.push_back(cmd);
275 }
276
277 CentralStation::Message CentralStation::receive()
278 {
279         while(IO::poll(socket, IO::P_INPUT, Time::zero))
280         {
281                 char rbuf[1024];
282                 unsigned len = socket.read(rbuf, sizeof(rbuf));
283                 if(!len)
284                         return Message();
285
286                 in_buffer.append(rbuf, len);
287         }
288
289         if(!in_buffer.empty())
290         {
291                 string::iterator iter = in_buffer.begin();
292                 if(Message msg = parse_message(iter, in_buffer.end()))
293                 {
294                         skip(iter, in_buffer.end(), "\r\n");
295                         in_buffer.erase(in_buffer.begin(), iter);
296
297                         if(msg.header.type=="REPLY" && pending_commands>0)
298                         {
299                                 --pending_commands;
300                                 if(!cmd_queue.empty())
301                                 {
302                                         command(cmd_queue.front());
303                                         cmd_queue.pop_front();
304                                 }
305                         }
306
307                         return msg;
308                 }
309         }
310
311         return Message();
312 }
313
314 void CentralStation::process_reply(const Message &msg)
315 {
316         if(!msg.header.value.compare(0, 4, "get("))
317         {
318                 for(Message::ObjectMap::const_iterator i=msg.content.begin(); i!=msg.content.end(); ++i)
319                 {
320                         if(turnouts.count(i->first))
321                                 turnouts[i->first].synced = true;
322
323                         process_object(i->first, i->second);
324                 }
325         }
326         else if(!msg.header.value.compare(0, 16, "queryObjects(10,"))
327         {
328                 for(Message::ObjectMap::const_iterator i=msg.content.begin(); i!=msg.content.end(); ++i)
329                 {
330                         LocoMap::iterator j = locos.find(i->first);
331                         if(j==locos.end())
332                         {
333                                 bool found = false;
334                                 Message::AttribMap::const_iterator k = i->second.find("addr");
335                                 if(k!=i->second.end())
336                                 {
337                                         unsigned addr = lexical_cast<unsigned>(k->second);
338
339                                         j = locos.find(addr|0x10000);
340                                         if(j!=locos.end())
341                                         {
342                                                 command(format("request(%d, view, control, force)", i->first));
343                                                 string cmd = format("get(%d, dir", i->first);
344                                                 for(unsigned l=0; j->second.func_mask>>l; ++l)
345                                                         if((j->second.func_mask>>l)&1)
346                                                                 cmd += format(", func[%d]", l);
347                                                 cmd += ')';
348                                                 command(cmd);
349
350                                                 locos.insert(LocoMap::value_type(i->first, j->second));
351                                                 locos.erase(j);
352
353                                                 found = true;
354                                         }
355                                 }
356
357                                 if(!found)
358                                         locos.insert(LocoMap::value_type(i->first, Locomotive()));
359                         }
360
361                         process_object(i->first, i->second);
362                 }
363
364                 locos_synced = true;
365
366                 if(locos.lower_bound(0x10000)!=locos.end())
367                         command("create(10)");
368         }
369         else if(!msg.header.value.compare(0, 16, "queryObjects(11,"))
370         {
371                 for(Message::ObjectMap::const_iterator i=msg.content.begin(); i!=msg.content.end(); ++i)
372                 {
373                         TurnoutMap::iterator j = turnouts.find(i->first);
374                         if(j==turnouts.end())
375                         {
376                                 bool found = false;
377                                 Message::AttribMap::const_iterator k = i->second.find("addr");
378                                 if(k!=i->second.end())
379                                 {
380                                         unsigned addr = lexical_cast<unsigned>(k->second);
381
382                                         j = turnouts.find(addr|0x10000);
383                                         if(j!=turnouts.end())
384                                         {
385                                                 command(format("request(%d, view, control)", i->first));
386                                                 command(format("set(%d, symbol[%d])", i->first, j->second.symbol));
387                                                 command(format("get(%d, state)", i->first));
388
389                                                 turnouts.insert(TurnoutMap::value_type(i->first, j->second));
390                                                 turnouts.erase(j);
391
392                                                 found = true;
393                                         }
394                                 }
395
396                                 if(!found)
397                                         turnouts.insert(TurnoutMap::value_type(i->first, Turnout()));
398                         }
399
400                         process_object(i->first, i->second);
401                 }
402
403                 turnouts_synced = true;
404
405                 for(TurnoutMap::const_iterator i=turnouts.lower_bound(0x10000); i!=turnouts.end(); ++i)
406                         command("create(11, append)");
407         }
408         else if(msg.header.value=="queryObjects(26)")
409         {
410                 s88.clear();
411                 for(Message::ObjectMap::const_iterator i=msg.content.begin(); i!=msg.content.end(); ++i)
412                 {
413                         s88.push_back(i->first);
414                         command(format("request(%d, view)", i->first));
415                         command(format("get(%d, state)", i->first));
416                 }
417
418                 sensors_synced = true;
419
420                 if(!sensors.empty())
421                 {
422                         unsigned high_addr = (--sensors.end())->first;
423                         if(high_addr>16*s88.size())
424                                 command("create(26, add[0])");
425                 }
426         }
427         else if(msg.header.value=="create(10)")
428         {
429                 Message::ObjectMap::const_iterator i = msg.content.find(10);
430                 if(i!=msg.content.end())
431                 {
432                         Message::AttribMap::const_iterator j = i->second.find("id");
433                         if(j!=i->second.end())
434                         {
435                                 unsigned id = lexical_cast<unsigned>(j->second);
436                                 LocoMap::iterator k = locos.lower_bound(0x10000);
437                                 if(k!=locos.end())
438                                 {
439                                         command(format("request(%d, view, control)", id));
440                                         command(format("set(%d, addr[%d], protocol[%s], name[\"%s\"])",
441                                                 id, k->second.address, (k->second.protocol==MM_27 ? "MM27" : "MM14"), k->second.name));
442                                         command("create(10, append)");
443
444                                         locos.insert(LocoMap::value_type(id, k->second));
445                                         locos.erase(k);
446                                 }
447                         }
448                 }
449
450                 if(locos.lower_bound(0x10000)!=locos.end())
451                         command("create(10)");
452         }
453         else if(!msg.header.value.compare(0, 10, "create(11,"))
454         {
455                 Message::ObjectMap::const_iterator i = msg.content.find(11);
456                 if(i!=msg.content.end())
457                 {
458                         Message::AttribMap::const_iterator j = i->second.find("id");
459                         if(j!=i->second.end())
460                         {
461                                 unsigned id = lexical_cast<unsigned>(j->second);
462                                 TurnoutMap::iterator k = turnouts.lower_bound(0x10000);
463                                 if(k!=turnouts.end())
464                                 {
465                                         command(format("request(%d, view, control)", id));
466                                         command(format("set(%d, addr[%d], symbol[%d], name1[\"Switch\"], name2[\"%d\"], name3[\"\"])",
467                                                 id, k->second.address, k->second.symbol, k->second.address));
468                                         command(format("set(%d, state[%d])", id, k->second.state&((1<<k->second.bits)-1)));
469
470                                         k->second.synced = true;
471                                         turnouts.insert(TurnoutMap::value_type(id, k->second));
472                                         turnouts.erase(k);
473                                 }
474                         }
475                 }
476         }
477         else if(!msg.header.value.compare(0, 10, "create(26,"))
478                 command("queryObjects(26)");
479 }
480
481 void CentralStation::process_event(const Message &msg)
482 {
483         for(Message::ObjectMap::const_iterator i=msg.content.begin(); i!=msg.content.end(); ++i)
484                 process_object(i->first, i->second);
485 }
486
487 void CentralStation::process_object(unsigned id, const Message::AttribMap &attribs)
488 {
489         if(id==1)
490         {
491                 for(Message::AttribMap::const_iterator i=attribs.begin(); i!=attribs.end(); ++i)
492                         if(i->first=="status")
493                         {
494                                 power = (i->second=="GO");
495                                 signal_power.emit(power);
496                         }
497         }
498         else if(locos.count(id))
499         {
500                 Locomotive &loco = locos[id];
501                 bool speed_changed = false;
502                 unsigned funcs_changed = 0;
503                 for(Message::AttribMap::const_iterator i=attribs.begin(); i!=attribs.end(); ++i)
504                 {
505                         if(i->first=="name")
506                                 loco.name = i->second.substr(1, i->second.size()-2);
507                         else if(i->first=="addr")
508                         {
509                                 loco_addr.erase(loco.address);
510                                 loco.address = lexical_cast<unsigned>(i->second);
511                                 loco_addr[loco.address] = id;
512                         }
513                         else if(i->first=="protocol")
514                         {
515                                 if(i->second=="MM")
516                                         loco.protocol = MM;
517                                 else if(i->second=="MM27")
518                                         loco.protocol = MM_27;
519                                 else if(i->second=="MFX")
520                                         loco.protocol = MFX;
521                         }
522                         else if(i->first=="speedstep")
523                         {
524                                 loco.speed = lexical_cast<unsigned>(i->second);
525                                 if(loco.protocol==MFX && loco.speed)
526                                         --loco.speed;
527                                 speed_changed = true;
528                         }
529                         else if(i->first=="dir")
530                         {
531                                 loco.reverse = i->second[0]!='0';
532                                 speed_changed = true;
533                         }
534                         else if(i->first=="func")
535                         {
536                                 vector<string> parts = split(i->second, ", ");
537                                 unsigned func = lexical_cast<unsigned>(parts[0]);
538                                 bool value = lexical_cast<unsigned>(parts[1]);
539                                 loco.funcs &= ~(1<<func);
540                                 if(value)
541                                         loco.funcs |= 1<<func;
542                                 funcs_changed |= 1<<func;
543                         }
544                         else if(i->first=="msg")
545                         {
546                                 if(i->second=="CONTROL_LOST")
547                                         command(format("request(%d, control, force)", id));
548                         }
549                 }
550
551                 if(speed_changed)
552                         signal_loco_speed.emit(loco.address, loco.speed, loco.reverse);
553                 for(unsigned i=0; funcs_changed>>i; ++i)
554                         if(funcs_changed&(1<<i))
555                                 signal_loco_function.emit(loco.address, i, loco.funcs&(1<<i));
556         }
557         else if(turnouts.count(id))
558         {
559                 Turnout &turnout = turnouts[id];
560                 bool state_changed = false;
561                 for(Message::AttribMap::const_iterator i=attribs.begin(); i!=attribs.end(); ++i)
562                 {
563                         if(i->first=="addr")
564                         {
565                                 turnout_addr.erase(turnout.address);
566                                 turnout.address = lexical_cast<unsigned>(i->second);
567                                 turnout_addr[turnout.address] = id;
568                         }
569                         else if(i->first=="state")
570                         {
571                                 unsigned state = lexical_cast<unsigned>(i->second);
572                                 unsigned mask = (1<<turnout.bits)-1;
573                                 turnout.state = (turnout.state&~mask) | (state&mask);
574                                 state_changed = true;
575                         }
576                 }
577
578                 if(state_changed)
579                         signal_turnout.emit(turnout.address, turnout.state);
580         }
581         else if(find(s88.begin(), s88.end(), id)!=s88.end())
582         {
583                 unsigned base = 0;
584                 for(; (base<s88.size() && s88[base]!=id); ++base) ;
585
586                 for(Message::AttribMap::const_iterator i=attribs.begin(); i!=attribs.end(); ++i)
587                 {
588                         if(i->first=="state")
589                         {
590                                 unsigned state = lexical_cast<unsigned>(i->second, "%i");
591                                 for(unsigned j=0; j<16; ++j)
592                                 {
593                                         unsigned addr = base*16+j+1;
594                                         Sensor &sensor = sensors[addr];
595                                         bool s = state&(1<<j);
596                                         if(s!=sensor.state)
597                                         {
598                                                 sensor.state = s;
599                                                 signal_sensor.emit(addr, sensor.state);
600                                         }
601                                 }
602                         }
603                 }
604         }
605 }
606
607 CentralStation::Protocol CentralStation::map_protocol(const string &name) const
608 {
609         if(name=="MM")
610                 return MM;
611         else if(name=="MM-27")
612                 return MM_27;
613         else if(name=="MFX")
614                 return MFX;
615         else
616                 throw InvalidParameterValue("Unknown protocol");
617 }
618
619 template<typename T>
620 unsigned CentralStation::map_address(const map<unsigned, T> &omap, const AddressMap &amap, unsigned addr) const
621 {
622         if(omap.count(addr))
623                 return addr;
624         else
625         {
626                 AddressMap::const_iterator i = amap.find(addr);
627                 if(i!=amap.end())
628                         return i->second;
629                 else
630                         return 0;
631         }
632 }
633
634 void CentralStation::skip(string::iterator &iter, const string::iterator &end, const string &what) const
635 {
636         for(; (iter!=end && what.find(*iter)!=string::npos); ++iter) ;
637 }
638
639 string CentralStation::parse_token(string::iterator &iter, const string::iterator &end, const string &stop) const
640 {
641         vector<char> parens;
642         bool quote = false;
643         string token;
644
645         skip(iter, end, stop);
646
647         for(; iter!=end; ++iter)
648         {
649                 if(stop.find(*iter)!=string::npos && parens.empty() && !quote)
650                         break;
651                 else if(*iter=='(' || *iter=='[')
652                         parens.push_back(*iter);
653                 else if((*iter==')' || *iter==']') && !parens.empty())
654                 {
655                         if((*iter==')' && parens.back()!='(') || (*iter==']' && parens.back()!='['))
656                                 IO::print("Mismatched parentheses\n");
657                         parens.pop_back();
658                 }
659                 else if(*iter=='"')
660                         quote = !quote;
661
662                 token += *iter;
663         }
664
665         return token;
666 }
667
668 CentralStation::Tag CentralStation::parse_tag(string::iterator &iter, const string::iterator &end) const
669 {
670         Tag tag;
671
672         for(; (iter!=end && *iter!='<'); ++iter) ;
673         if(iter==end)
674                 return Tag();
675
676         tag.type = parse_token(++iter, end, " >");
677         if(tag.type=="END")
678         {
679                 string code = parse_token(iter, end, " >");
680                 tag.code = lexical_cast<unsigned>(code);
681         }
682         skip(iter, end, " ");
683         tag.value = parse_token(iter, end, ">");
684         if(iter==end)
685                 return Tag();
686         ++iter;
687
688         return tag;
689 }
690
691 CentralStation::Message CentralStation::parse_message(string::iterator &iter, const string::iterator &end) const
692 {
693         Message msg;
694
695         msg.header = parse_tag(iter, end);
696
697         while(iter!=end)
698         {
699                 skip(iter, end, "\r\n");
700                 if(*iter=='<')
701                         break;
702
703                 string id = parse_token(iter, end, " \r\n<");
704                 Message::AttribMap &attribs = msg.content[lexical_cast<unsigned>(id)];
705                 while(iter!=end && *iter!='\n' && *iter!='\r')
706                 {
707                         string attr = parse_token(iter, end, " \r\n<");
708                         string::size_type open_bracket = attr.find('[');
709                         if(open_bracket!=string::npos)
710                         {
711                                 string::size_type close_bracket = attr.rfind(']');
712                                 string attr_name = attr.substr(0, open_bracket);
713                                 string attr_value = attr.substr(open_bracket+1, close_bracket-open_bracket-1);
714                                 attribs.insert(Message::AttribMap::value_type(attr_name, attr_value));
715                         }
716                         else
717                                 attribs.insert(Message::AttribMap::value_type(attr, string()));
718                 }
719         }
720
721         msg.footer = parse_tag(iter, end);
722         if(msg.footer.type.empty())
723                 return Message();
724
725         return msg;
726 }
727
728
729 CentralStation::Tag::Tag():
730         code(0)
731 { }
732
733 CentralStation::Tag::operator bool() const
734 {
735         return !type.empty();
736 }
737
738
739 CentralStation::Message::operator bool() const
740 {
741         return header && footer;
742 }
743
744
745 CentralStation::Locomotive::Locomotive():
746         address(0),
747         speed(0),
748         reverse(false),
749         func_mask(0),
750         funcs(0),
751         control(false)
752 { }
753
754
755 CentralStation::Turnout::Turnout():
756         address(0),
757         symbol(0),
758         state(0),
759         bits(0),
760         synced(false)
761 { }
762
763
764 CentralStation::Sensor::Sensor():
765         state(false)
766 { }
767
768 } // namespace R2C2