]> git.tdb.fi Git - r2c2.git/blob - source/libr2c2/arducontrol.cpp
Add a timeout to ArduControl commands
[r2c2.git] / source / libr2c2 / arducontrol.cpp
1 #include <msp/core/maputils.h>
2 #include <msp/datafile/writer.h>
3 #include <msp/fs/redirectedpath.h>
4 #include <msp/fs/stat.h>
5 #include <msp/io/print.h>
6 #include <msp/time/utils.h>
7 #include "arducontrol.h"
8 #include "tracktype.h"
9
10 using namespace std;
11 using namespace Msp;
12
13 namespace R2C2 {
14
15 ArduControl::ProtocolInfo ArduControl::protocol_info[2] =
16 {
17         { 79, 14, 4 },       // MM
18         { 0x3FFF, 126, 15 }  // MFX
19 };
20
21 ArduControl::ArduControl(const Options &opts):
22         serial(opts.get<string>(string(), "ttyUSB0")),
23         debug(opts.get<unsigned>("debug")),
24         state_file("arducontrol.state"),
25         power(false),
26         halted(false),
27         active_accessory(0),
28         command_timeout(200*Time::msec),
29         s88(*this),
30         mfx_search(*this),
31         thread(*this)
32 {
33         if(FS::exists(state_file))
34                 DataFile::load(*this, state_file.str());
35
36         unsigned max_address = 0;
37         for(MfxInfoArray::const_iterator i=mfx_info.begin(); i!=mfx_info.end(); ++i)
38                 max_address = max(max_address, i->address);
39         mfx_search.set_next_address(max_address+1);
40
41         PendingCommand cmd;
42         cmd.command[0] = READ_POWER_STATE;
43         cmd.length = 1;
44         command_queue.push(cmd);
45
46         cmd.command[0] = MFX_SET_STATION_ID;
47         cmd.command[1] = 'R';
48         cmd.command[2] = '2';
49         cmd.command[3] = 'C';
50         cmd.command[4] = '2';
51         cmd.length = 5;
52         command_queue.push(cmd);
53 }
54
55 ArduControl::~ArduControl()
56 {
57         thread.exit();
58 }
59
60 void ArduControl::set_power(bool p)
61 {
62         if(power.set(p))
63         {
64                 PendingCommand cmd(POWER);
65                 cmd.tag.serial = power.serial;
66                 cmd.command[0] = (p ? POWER_ON : POWER_OFF);
67                 cmd.length = 1;
68                 command_queue.push(cmd);
69         }
70 }
71
72 void ArduControl::halt(bool h)
73 {
74         if(h==halted)
75                 return;
76
77         halted = h;
78         if(halted)
79         {
80                 for(LocomotiveMap::const_iterator i=locomotives.begin(); i!=locomotives.end(); ++i)
81                         set_loco_speed(i->first, 0);
82         }
83
84         signal_halt.emit(halted);
85 }
86
87 const char *ArduControl::enumerate_protocols(unsigned i) const
88 {
89         if(i==0)
90                 return "MM";
91         else if(i==1)
92                 return "MFX";
93         else
94                 return 0;
95 }
96
97 ArduControl::Protocol ArduControl::map_protocol(const string &proto_name)
98 {
99         if(proto_name=="MM")
100                 return MM;
101         else if(proto_name=="MFX")
102                 return MFX;
103         else
104                 throw invalid_argument("ArduControl::map_protocol");
105 }
106
107 unsigned ArduControl::get_protocol_speed_steps(const string &proto_name) const
108 {
109         return protocol_info[map_protocol(proto_name)].max_speed;
110 }
111
112 const Driver::DetectedLocomotive *ArduControl::enumerate_detected_locos(unsigned i) const
113 {
114         if(i>=mfx_info.size())
115                 return 0;
116
117         return &mfx_info[i];
118 }
119
120 unsigned ArduControl::add_loco(unsigned addr, const string &proto_name, const VehicleType &)
121 {
122         if(!addr)
123                 throw invalid_argument("ArduControl::add_loco");
124
125         Protocol proto = map_protocol(proto_name);
126         if(addr>protocol_info[proto].max_address)
127                 throw invalid_argument("ArduControl::add_loco");
128
129         Locomotive loco(proto, addr);
130         insert_unique(locomotives, loco.id, loco);
131
132         return loco.id;
133 }
134
135 ArduControl::MfxInfoArray::iterator ArduControl::add_mfx_info(const MfxInfo &info)
136 {
137         MfxInfoArray::iterator i;
138         for(i=mfx_info.begin(); (i!=mfx_info.end() && i->id!=info.id); ++i) ;
139         if(i==mfx_info.end())
140         {
141                 mfx_info.push_back(info);
142                 i = --mfx_info.end();
143         }
144         else
145                 *i = info;
146         return i;
147 }
148
149 void ArduControl::remove_loco(unsigned id)
150 {
151         Locomotive &loco = get_item(locomotives, id);
152         refresh.remove_loco(loco);
153         locomotives.erase(id);
154 }
155
156 void ArduControl::set_loco_speed(unsigned id, unsigned speed)
157 {
158         Locomotive &loco = get_item(locomotives, id);
159         if(speed>protocol_info[loco.proto].max_speed)
160                 throw invalid_argument("ArduControl::set_loco_speed");
161
162         if(speed && halted)
163                 return;
164
165         if(loco.speed.set(speed))
166         {
167                 PendingCommand cmd(loco, Locomotive::SPEED);
168                 command_queue.push(cmd);
169
170                 refresh.add_loco(loco);
171         }
172 }
173
174 void ArduControl::set_loco_reverse(unsigned id, bool rev)
175 {
176         Locomotive &loco = get_item(locomotives, id);
177         if(loco.reverse.set(rev))
178         {
179                 PendingCommand cmd(loco, Locomotive::REVERSE);
180                 command_queue.push(cmd);
181
182                 refresh.add_loco(loco);
183         }
184 }
185
186 void ArduControl::set_loco_function(unsigned id, unsigned func, bool state)
187 {
188         Locomotive &loco = get_item(locomotives, id);
189         if(func>protocol_info[loco.proto].max_func)
190                 throw invalid_argument("ArduControl::set_loco_function");
191
192         unsigned mask = 1<<func;
193         if(loco.funcs.set((loco.funcs&~mask)|(mask*state)))
194         {
195                 if(func>0 || loco.proto!=MM)
196                 {
197                         PendingCommand cmd(loco, Locomotive::FUNCTIONS, func);
198                         command_queue.push(cmd);
199                 }
200
201                 refresh.add_loco(loco);
202         }
203 }
204
205 unsigned ArduControl::add_turnout(unsigned addr, const TrackType &type)
206 {
207         if(!addr || !type.is_turnout())
208                 throw invalid_argument("ArduControl::add_turnout");
209
210         return add_accessory(Accessory::TURNOUT, addr, type.get_state_bits());
211 }
212
213 void ArduControl::remove_turnout(unsigned addr)
214 {
215         remove_accessory(Accessory::TURNOUT, addr);
216 }
217
218 void ArduControl::set_turnout(unsigned addr, unsigned state)
219 {
220         set_accessory(Accessory::TURNOUT, addr, state);
221 }
222
223 unsigned ArduControl::get_turnout(unsigned addr) const
224 {
225         return get_accessory(Accessory::TURNOUT, addr);
226 }
227
228 unsigned ArduControl::add_signal(unsigned addr, const SignalType &)
229 {
230         return add_accessory(Accessory::SIGNAL, addr, 1);
231 }
232
233 void ArduControl::remove_signal(unsigned addr)
234 {
235         remove_accessory(Accessory::SIGNAL, addr);
236 }
237
238 void ArduControl::set_signal(unsigned addr, unsigned state)
239 {
240         set_accessory(Accessory::SIGNAL, addr, state);
241 }
242
243 unsigned ArduControl::get_signal(unsigned addr) const
244 {
245         return get_accessory(Accessory::SIGNAL, addr);
246 }
247
248 unsigned ArduControl::add_accessory(Accessory::Kind kind, unsigned addr, unsigned bits)
249 {
250         AccessoryMap::iterator i = accessories.lower_bound(addr);
251         AccessoryMap::iterator j = accessories.upper_bound(addr+bits-1);
252         if(i!=j)
253                 throw key_error(addr);
254         if(i!=accessories.begin())
255         {
256                 --i;
257                 if(i->first+i->second.bits>addr)
258                         throw key_error(addr);
259         }
260
261         insert_unique(accessories, addr, Accessory(kind, addr, bits));
262         return addr;
263 }
264
265 void ArduControl::remove_accessory(Accessory::Kind kind, unsigned addr)
266 {
267         Accessory &acc = get_item(accessories, addr);
268         if(acc.kind!=kind)
269                 throw key_error(addr);
270         accessories.erase(addr);
271 }
272
273 void ArduControl::set_accessory(Accessory::Kind kind, unsigned addr, unsigned state)
274 {
275         Accessory &acc = get_item(accessories, addr);
276         if(acc.kind!=kind)
277                 throw key_error(addr);
278
279         if(state!=acc.target)
280         {
281                 acc.target = state;
282                 accessory_queue.push_back(&acc);
283         }
284 }
285
286 unsigned ArduControl::get_accessory(Accessory::Kind kind, unsigned addr) const
287 {
288         const Accessory &acc = get_item(accessories, addr);
289         if(acc.kind!=kind)
290                 throw key_error(addr);
291         return acc.state;
292 }
293
294 unsigned ArduControl::add_sensor(unsigned addr)
295 {
296         if(!addr)
297                 throw invalid_argument("ArduControl::add_sensor");
298
299         insert_unique(sensors, addr, Sensor(addr));
300         s88.grow_n_octets((addr+7)/8);
301
302         return addr;
303 }
304
305 void ArduControl::remove_sensor(unsigned addr)
306 {
307         remove_existing(sensors, addr);
308         // TODO update s88.n_octets
309 }
310
311 bool ArduControl::get_sensor(unsigned addr) const
312 {
313         return get_item(sensors, addr).state;
314 }
315
316 void ArduControl::tick()
317 {
318         Tag tag;
319         while(completed_commands.pop(tag))
320         {
321                 if(tag.type==Tag::GENERAL)
322                 {
323                         if(tag.command==POWER)
324                         {
325                                 if(power.commit(tag.serial))
326                                         signal_power.emit(power.current);
327                         }
328                         else if(tag.command==NEW_LOCO)
329                         {
330                                 MfxInfo info;
331                                 if(mfx_search.pop_info(info))
332                                 {
333                                         MfxInfoArray::iterator i = add_mfx_info(info);
334                                         save_state();
335                                         signal_locomotive_detected.emit(*i);
336                                 }
337                         }
338                 }
339                 else if(tag.type==Tag::LOCOMOTIVE)
340                 {
341                         LocomotiveMap::iterator i = locomotives.find(tag.id);
342                         if(i==locomotives.end())
343                                 continue;
344
345                         Locomotive &loco = i->second;
346                         if(tag.command==Locomotive::SPEED)
347                         {
348                                 if(loco.speed.commit(tag.serial))
349                                         signal_loco_speed.emit(loco.id, loco.speed, loco.reverse);
350                         }
351                         else if(tag.command==Locomotive::REVERSE)
352                         {
353                                 if(loco.reverse.commit(tag.serial))
354                                         signal_loco_speed.emit(loco.id, loco.speed, loco.reverse);
355                         }
356                         else if(tag.command==Locomotive::FUNCTIONS)
357                         {
358                                 unsigned old = loco.funcs;
359                                 if(loco.funcs.commit(tag.serial))
360                                 {
361                                         unsigned changed = old^loco.funcs;
362                                         for(unsigned j=0; changed>>j; ++j)
363                                                 if((changed>>j)&1)
364                                                         signal_loco_function.emit(loco.id, j, (loco.funcs>>j)&1);
365                                 }
366                         }
367                 }
368                 else if(tag.type==Tag::ACCESSORY)
369                 {
370                         AccessoryMap::iterator i = accessories.find(tag.id);
371                         if(i==accessories.end())
372                                 continue;
373
374                         Accessory &acc = i->second;
375                         if(tag.command==Accessory::ACTIVATE)
376                                 off_timeout = Time::now()+acc.active_time;
377                         else if(tag.command==Accessory::DEACTIVATE)
378                         {
379                                 if(acc.state.commit(tag.serial))
380                                 {
381                                         if(acc.state==acc.target)
382                                         {
383                                                 if(acc.kind==Accessory::TURNOUT)
384                                                         signal_turnout.emit(acc.address, acc.state);
385                                                 else if(acc.kind==Accessory::SIGNAL)
386                                                         signal_signal.emit(acc.address, acc.state);
387                                         }
388                                         if(&acc==active_accessory)
389                                                 active_accessory = 0;
390                                 }
391                         }
392                 }
393                 else if(tag.type==Tag::SENSOR)
394                 {
395                         SensorMap::iterator i = sensors.find(tag.id);
396                         if(i==sensors.end())
397                                 continue;
398
399                         Sensor &sensor = i->second;
400                         if(tag.command==Sensor::STATE)
401                         {
402                                 if(sensor.state.commit(tag.serial))
403                                         signal_sensor.emit(sensor.address, sensor.state);
404                         }
405                 }
406         }
407
408         while(power && !active_accessory && !accessory_queue.empty())
409         {
410                 Accessory &acc = *accessory_queue.front();
411
412                 if(acc.state!=acc.target)
413                 {
414                         active_accessory = &acc;
415
416                         unsigned changes = acc.state^acc.target;
417                         unsigned lowest_bit = changes&~(changes-1);
418                         unsigned i;
419                         for(i=0; (lowest_bit>>i)>1; ++i) ;
420                         active_index = i;
421                         acc.state.set(acc.state^lowest_bit);
422                         PendingCommand cmd(acc, Accessory::ACTIVATE, i);
423                         command_queue.push(cmd);
424
425                         monitor.reset_peak();
426                 }
427                 else
428                         accessory_queue.pop_front();
429         }
430
431         if(active_accessory && off_timeout)
432         {
433                 Time::TimeStamp t = Time::now();
434                 if(t>off_timeout)
435                 {
436                         Accessory &acc = *active_accessory;
437
438                         if(acc.kind==Accessory::TURNOUT && monitor.get_peak()<0.5f)
439                         {
440                                 unsigned bit = 1<<active_index;
441                                 if(acc.uncertain&bit)
442                                         acc.uncertain &= ~bit;
443                                 else
444                                 {
445                                         signal_turnout_failed.emit(acc.address);
446                                         acc.state.rollback();
447                                         acc.target ^= bit;
448                                 }
449                         }
450
451                         off_timeout = Time::TimeStamp();
452                         PendingCommand cmd(acc, Accessory::DEACTIVATE, active_index);
453                         command_queue.push(cmd);
454                 }
455         }
456 }
457
458 void ArduControl::flush()
459 {
460         while(!command_queue.empty() || !accessory_queue.empty())
461                 tick();
462 }
463
464 void ArduControl::save_state() const
465 {
466         FS::RedirectedPath tmp_file(state_file);
467         IO::BufferedFile out(tmp_file.str(), IO::M_WRITE);
468         DataFile::Writer writer(out);
469
470         writer.write((DataFile::Statement("mfx_announce_serial"), mfx_announce.get_serial()));
471         for(MfxInfoArray::const_iterator i=mfx_info.begin(); i!=mfx_info.end(); ++i)
472         {
473                 DataFile::Statement st("mfx_locomotive");
474                 st.append(i->id);
475                 st.sub.push_back((DataFile::Statement("address"), i->address));
476                 st.sub.push_back((DataFile::Statement("name"), i->name));
477                 writer.write(st);
478         }
479 }
480
481
482 ArduControl::Tag::Tag():
483         type(NONE),
484         command(0),
485         serial(0),
486         id(0)
487 { }
488
489
490 ArduControl::Locomotive::Locomotive(Protocol p, unsigned a):
491         id((p<<16)|a),
492         proto(p),
493         address(a),
494         speed(0),
495         reverse(false),
496         funcs(0),
497         last_change_age(0)
498 { }
499
500 unsigned ArduControl::Locomotive::create_speed_dir_command(char *buffer) const
501 {
502         if(proto==MM)
503         {
504                 buffer[0] = MOTOROLA_SPEED_DIRECTION;
505                 buffer[1] = address;
506                 buffer[2] = funcs.pending&1;
507                 buffer[3] = speed.pending+reverse.pending*0x80;
508                 return 4;
509         }
510         else if(proto==MFX)
511         {
512                 buffer[0] = MFX_SPEED;
513                 buffer[1] = address>>8;
514                 buffer[2] = address;
515                 buffer[3] = speed.pending+reverse.pending*0x80;
516                 return 4;
517         }
518         else
519                 return 0;
520 }
521
522 unsigned ArduControl::Locomotive::create_speed_func_command(unsigned f, char *buffer) const
523 {
524         if(proto==MM)
525         {
526                 if(f<1 || f>4)
527                         throw invalid_argument("Locomotive::create_speed_func_command");
528
529                 buffer[0] = MOTOROLA_SPEED_FUNCTION;
530                 buffer[1] = address;
531                 buffer[2] = (f<<4)|(((funcs.pending>>f)&1)<<1)|(funcs.pending&1);
532                 buffer[3] = speed.pending;
533                 return 4;
534         }
535         else if(proto==MFX)
536         {
537                 bool f16 = (funcs.pending>0xFF);
538                 buffer[0] = (f16 ? MFX_SPEED_FUNCS16 : MFX_SPEED_FUNCS8);
539                 buffer[1] = address>>8;
540                 buffer[2] = address;
541                 buffer[3] = speed.pending+reverse.pending*0x80;
542                 if(f16)
543                 {
544                         buffer[4] = funcs.pending>>8;
545                         buffer[5] = funcs.pending;
546                         return 6;
547                 }
548                 else
549                 {
550                         buffer[4] = funcs.pending;
551                         return 5;
552                 }
553         }
554         else
555                 return 0;
556 }
557
558
559 ArduControl::Accessory::Accessory(Kind k, unsigned a, unsigned b):
560         kind(k),
561         address(a),
562         bits(b),
563         state(0),
564         uncertain((1<<bits)-1),
565         target(0),
566         active_time(500*Time::msec)
567 { }
568
569 unsigned ArduControl::Accessory::create_state_command(unsigned b, bool c, char *buffer) const
570 {
571         if(b>=bits)
572                 throw invalid_argument("Accessory::create_state_command");
573
574         unsigned a = (address+b+3)*2;
575         if(!((state.pending>>b)&1))
576                 ++a;
577         buffer[0] = MOTOROLA_SOLENOID;
578         buffer[1] = a>>3;
579         buffer[2] = ((a&7)<<4)|c;
580         return 3;
581 }
582
583
584 ArduControl::Sensor::Sensor(unsigned a):
585         address(a),
586         state(false)
587 { }
588
589
590 ArduControl::PendingCommand::PendingCommand():
591         length(0),
592         repeat_count(1)
593 { }
594
595 ArduControl::PendingCommand::PendingCommand(GeneralCommand cmd):
596         length(0),
597         repeat_count(1)
598 {
599         tag.type = Tag::GENERAL;
600         tag.command = cmd;
601 }
602
603 ArduControl::PendingCommand::PendingCommand(Locomotive &loco, Locomotive::Command cmd, unsigned index):
604         repeat_count(8)
605 {
606         tag.type = Tag::LOCOMOTIVE;
607         tag.command = cmd;
608         tag.id = loco.id;
609         if(cmd==Locomotive::SPEED)
610         {
611                 tag.serial = loco.speed.serial;
612                 length = loco.create_speed_dir_command(command);
613         }
614         else if(cmd==Locomotive::REVERSE)
615         {
616                 tag.serial = loco.reverse.serial;
617                 length = loco.create_speed_dir_command(command);
618         }
619         else if(cmd==Locomotive::FUNCTIONS)
620         {
621                 tag.serial = loco.funcs.serial;
622                 length = loco.create_speed_func_command(index, command);
623         }
624         else
625                 throw invalid_argument("PendingCommand");
626 }
627
628 ArduControl::PendingCommand::PendingCommand(Accessory &acc, Accessory::Command cmd, unsigned index):
629         repeat_count(1)
630 {
631         tag.type = Tag::ACCESSORY;
632         tag.command = cmd;
633         tag.id = acc.address;
634         if(cmd==Accessory::ACTIVATE || cmd==Accessory::DEACTIVATE)
635         {
636                 tag.serial = acc.state.serial;
637                 length = acc.create_state_command(index, (cmd==Accessory::ACTIVATE), command);
638         }
639         else
640                 throw invalid_argument("PendingCommand");
641 }
642
643
644 template<typename T>
645 void ArduControl::Queue<T>::push(const T &item)
646 {
647         MutexLock lock(mutex);
648         items.push_back(item);
649 }
650
651 template<typename T>
652 bool ArduControl::Queue<T>::pop(T &item)
653 {
654         MutexLock lock(mutex);
655         if(items.empty())
656                 return false;
657
658         item = items.front();
659         items.pop_front();
660         return true;
661 }
662
663 template<typename T>
664 bool ArduControl::Queue<T>::empty() const
665 {
666         return items.empty();
667 }
668
669
670 ArduControl::RefreshTask::RefreshTask():
671         next(cycle.end()),
672         round(0),
673         loco(0),
674         phase(0)
675 { }
676
677 bool ArduControl::RefreshTask::get_work(PendingCommand &cmd)
678 {
679         if(loco && loco->proto==MM && phase==0)
680         {
681                 cmd.length = loco->create_speed_func_command(round%4+1, cmd.command);
682                 cmd.repeat_count = 2;
683                 ++phase;
684                 return true;
685         }
686
687         loco = get_next_loco();
688         if(!loco)
689                 return false;
690
691         phase = 0;
692         if(loco->proto==MM)
693         {
694                 cmd.length = loco->create_speed_dir_command(cmd.command);
695                 cmd.repeat_count = 2;
696         }
697         else if(loco->proto==MFX)
698                 cmd.length = loco->create_speed_func_command(0, cmd.command);
699         else
700                 return false;
701
702         return true;
703 }
704
705 void ArduControl::RefreshTask::add_loco(Locomotive &l)
706 {
707         MutexLock lock(mutex);
708         cycle.push_back(&l);
709         if(cycle.size()>15)
710         {
711                 LocomotivePtrList::iterator oldest = cycle.begin();
712                 for(LocomotivePtrList::iterator i=cycle.begin(); ++i!=cycle.end(); )
713                         if((*i)->last_change_age>(*oldest)->last_change_age)
714                                 oldest = i;
715                 if(oldest==next)
716                         advance();
717                 cycle.erase(oldest);
718         }
719         if(next==cycle.end())
720                 next = cycle.begin();
721 }
722
723 void ArduControl::RefreshTask::remove_loco(Locomotive &l)
724 {
725         MutexLock lock(mutex);
726         for(LocomotivePtrList::iterator i=cycle.begin(); i!=cycle.end(); ++i)
727                 if(*i==&l)
728                 {
729                         if(i==next)
730                         {
731                                 if(cycle.size()>1)
732                                         advance();
733                                 else
734                                         next = cycle.end();
735                         }
736                         cycle.erase(i);
737                         return;
738                 }
739 }
740
741 ArduControl::Locomotive *ArduControl::RefreshTask::get_next_loco()
742 {
743         MutexLock lock(mutex);
744         if(cycle.empty())
745                 return 0;
746
747         Locomotive *l = *next;
748         advance();
749         return l;
750 }
751
752 void ArduControl::RefreshTask::advance()
753 {
754         ++next;
755         if(next==cycle.end())
756         {
757                 next= cycle.begin();
758                 ++round;
759         }
760 }
761
762
763 ArduControl::S88Task::S88Task(ArduControl &c):
764         control(c),
765         n_octets(0),
766         octets_remaining(0),
767         delay(0)
768 { }
769
770 bool ArduControl::S88Task::get_work(PendingCommand &cmd)
771 {
772         if(delay)
773         {
774                 --delay;
775                 return false;
776         }
777         if(octets_remaining || !n_octets)
778                 return false;
779
780         octets_remaining = n_octets;
781         cmd.command[0] = S88_READ;
782         cmd.command[1] = octets_remaining;
783         cmd.length = 2;
784
785         delay = 4;
786
787         return true;
788 }
789
790 void ArduControl::S88Task::process_reply(const char *reply, unsigned length)
791 {
792         unsigned char type = reply[0];
793         if(type==S88_DATA && length>2)
794         {
795                 unsigned offset = static_cast<unsigned char>(reply[1]);
796                 unsigned count = length-2;
797
798                 SensorMap::iterator begin = control.sensors.lower_bound(offset*8+1);
799                 SensorMap::iterator end = control.sensors.upper_bound((offset+count)*8);
800                 for(SensorMap::iterator i=begin; i!=end; ++i)
801                 {
802                         unsigned bit_index = i->first-1-offset*8;
803                         bool state = (reply[2+bit_index/8]>>(7-bit_index%8))&1;
804                         i->second.state.set(state);
805
806                         Tag tag;
807                         tag.type = Tag::SENSOR;
808                         tag.command = Sensor::STATE;
809                         tag.serial = i->second.state.serial;
810                         tag.id = i->first;
811                         control.completed_commands.push(tag);
812                 }
813
814                 if(count>octets_remaining)
815                         octets_remaining = 0;
816                 else
817                         octets_remaining -= count;
818         }
819 }
820
821 void ArduControl::S88Task::set_n_octets(unsigned n)
822 {
823         n_octets = n;
824 }
825
826 void ArduControl::S88Task::grow_n_octets(unsigned n)
827 {
828         if(n>n_octets)
829                 n_octets = n;
830 }
831
832
833 ArduControl::MfxAnnounceTask::MfxAnnounceTask():
834         serial(0)
835 { }
836
837 bool ArduControl::MfxAnnounceTask::get_work(PendingCommand &cmd)
838 {
839         Time::TimeStamp t = Time::now();
840         if(t<next)
841                 return false;
842
843         cmd.command[0] = MFX_ANNOUNCE;
844         cmd.command[1] = serial>>8;
845         cmd.command[2] = serial;
846         cmd.length = 3;
847         next = t+400*Time::msec;
848
849         return true;
850 }
851
852 void ArduControl::MfxAnnounceTask::set_serial(unsigned s)
853 {
854         serial = s;
855 }
856
857
858 ArduControl::MfxSearchTask::MfxSearchTask(ArduControl &c):
859         control(c),
860         next_address(1),
861         size(0),
862         bits(0),
863         misses(0)
864 { }
865
866 bool ArduControl::MfxSearchTask::get_work(PendingCommand &cmd)
867 {
868         if(size>32)
869         {
870                 if(control.debug>=1)
871                         IO::print("Assigning MFX address %d to decoder %08X\n", next_address, bits);
872
873                 MfxInfo info;
874                 info.protocol = "MFX";
875                 info.address = next_address;
876                 info.name = format("%08X", bits);
877                 info.id = bits;
878                 queue.push(info);
879
880                 cmd.command[0] = MFX_ASSIGN_ADDRESS;
881                 cmd.command[1] = next_address>>8;
882                 cmd.command[2] = next_address;
883                 for(unsigned i=0; i<4; ++i)
884                         cmd.command[3+i] = bits>>(24-i*8);
885                 cmd.length = 7;
886
887                 cmd.tag.type = Tag::GENERAL;
888                 cmd.tag.command = NEW_LOCO;
889                 cmd.tag.id = bits;
890
891                 size = 0;
892                 bits = 0;
893                 ++next_address;
894
895                 return true;
896         }
897
898         Time::TimeStamp t = Time::now();
899         if(t<next)
900                 return false;
901
902         cmd.command[0] = MFX_SEARCH;
903         for(unsigned i=0; i<4; ++i)
904                 cmd.command[1+i] = bits>>(24-i*8);
905         cmd.command[5] = size;
906         cmd.length = 6;
907
908         next = t+200*Time::msec;
909
910         if(control.debug>=1)
911                 IO::print("Search %08X/%d\n", bits, size);
912
913         return true;
914 }
915
916 void ArduControl::MfxSearchTask::process_reply(const char *reply, unsigned length)
917 {
918         unsigned char type = reply[0];
919         if(type==MFX_SEARCH_FEEDBACK && length==2)
920         {
921                 if(reply[1])
922                 {
923                         misses = 0;
924                         ++size;
925                 }
926                 else if(size>0 && misses<6)
927                 {
928                         ++misses;
929                         bits ^= 1<<(32-size);
930                 }
931                 else
932                 {
933                         next = Time::now()+2*Time::sec;
934                         bits = 0;
935                         size = 0;
936                         misses = 0;
937                 }
938         }
939 }
940
941 void ArduControl::MfxSearchTask::set_next_address(unsigned a)
942 {
943         next_address = a;
944 }
945
946 bool ArduControl::MfxSearchTask::pop_info(MfxInfo &info)
947 {
948         return queue.pop(info);
949 }
950
951
952 ArduControl::MonitorTask::MonitorTask():
953         voltage(0),
954         current(0),
955         base_level(0),
956         peak_level(0),
957         next_type(0)
958 { }
959
960 bool ArduControl::MonitorTask::get_work(PendingCommand &cmd)
961 {
962         Time::TimeStamp t = Time::now();
963         if(t<next_poll)
964                 return false;
965
966         if(next_type==0)
967                 cmd.command[0] = READ_INPUT_VOLTAGE;
968         else
969                 cmd.command[0] = READ_TRACK_CURRENT;
970         cmd.length = 1;
971
972         next_poll = t+200*Time::msec;
973         next_type = (next_type+1)%5;
974
975         return true;
976 }
977
978 void ArduControl::MonitorTask::process_reply(const char *reply, unsigned length)
979 {
980         unsigned char type = reply[0];
981         if(type==INPUT_VOLTAGE && length==3)
982                 voltage = ((static_cast<unsigned char>(reply[1])<<8) | static_cast<unsigned char>(reply[2]))/1000.0f;
983         else if(type==TRACK_CURRENT && length==5)
984         {
985                 current = ((static_cast<unsigned char>(reply[1])<<8) | static_cast<unsigned char>(reply[2]))/1000.0f;
986                 float peak = ((static_cast<unsigned char>(reply[3])<<8) | static_cast<unsigned char>(reply[4]))/1000.0f;
987                 peak_level = max(peak_level, peak);
988                 base_level = min(base_level, current);
989         }
990 }
991
992 void ArduControl::MonitorTask::reset_peak()
993 {
994         base_level = current;
995         peak_level = current;
996 }
997
998
999 ArduControl::ControlThread::ControlThread(ArduControl &c):
1000         control(c),
1001         done(false)
1002 {
1003         tasks.push_back(&control.monitor);
1004         tasks.push_back(&control.mfx_announce);
1005         tasks.push_back(&control.mfx_search);
1006         tasks.push_back(&control.s88);
1007         tasks.push_back(&control.refresh);
1008
1009         launch();
1010 }
1011
1012 void ArduControl::ControlThread::exit()
1013 {
1014         done = true;
1015         join();
1016 }
1017
1018 void ArduControl::ControlThread::main()
1019 {
1020         init_baud_rate();
1021
1022         while(!done)
1023         {
1024                 PendingCommand cmd;
1025                 if(get_work(cmd))
1026                 {
1027                         bool success = true;
1028                         for(unsigned i=0; (success && i<cmd.repeat_count); ++i)
1029                                 success = (do_command(cmd)==COMMAND_OK);
1030                         if(success && cmd.tag)
1031                                 control.completed_commands.push(cmd.tag);
1032                 }
1033                 else
1034                         Time::sleep(10*Time::msec);
1035         }
1036 }
1037
1038 void ArduControl::ControlThread::init_baud_rate()
1039 {
1040         static unsigned rates[] = { 57600, 9600, 19200, 38400, 0 };
1041         unsigned rate = 0;
1042         control.serial.set_data_bits(8);
1043         control.serial.set_parity(IO::Serial::NONE);
1044         control.serial.set_stop_bits(1);
1045         for(unsigned i=0; rates[i]; ++i)
1046         {
1047                 control.serial.set_baud_rate(rates[i]);
1048                 control.serial.put('\xFF');
1049                 if(IO::poll(control.serial, IO::P_INPUT, 500*Time::msec))
1050                 {
1051                         int c = control.serial.get();
1052                         if(c==0xFF)
1053                         {
1054                                 rate = rates[i];
1055                                 break;
1056                         }
1057                 }
1058         }
1059
1060         if(!rate)
1061         {
1062                 if(control.debug>=1)
1063                         IO::print("ArduControl detection failed\n");
1064                 done = true;
1065                 return;
1066         }
1067
1068         if(control.debug>=1)
1069                 IO::print("ArduControl detected at %d bits/s\n", rate);
1070
1071         if(rate!=rates[0])
1072         {
1073                 PendingCommand cmd;
1074                 cmd.command[0] = SET_BAUD_RATE;
1075                 cmd.command[1] = rates[0]>>8;
1076                 cmd.command[2] = rates[0];
1077                 cmd.length = 3;
1078                 if(do_command(cmd, Time::sec)==COMMAND_OK)
1079                 {
1080                         control.serial.set_baud_rate(rates[0]);
1081                         Time::sleep(Time::sec);
1082                         if(do_command(cmd, Time::sec)==COMMAND_OK)
1083                         {
1084                                 if(control.debug>=1)
1085                                         IO::print("Rate changed to %d bits/s\n", rates[0]);
1086                         }
1087                 }
1088         }
1089 }
1090
1091 bool ArduControl::ControlThread::get_work(PendingCommand &cmd)
1092 {
1093         if(control.command_queue.pop(cmd))
1094                 return true;
1095
1096         for(vector<Task *>::iterator i=tasks.begin(); i!=tasks.end(); ++i)
1097                 if((*i)->get_work(cmd))
1098                         return true;
1099
1100         // As fallback, send an idle packet for the MM protocol
1101         cmd.command[0] = MOTOROLA_SPEED;
1102         cmd.command[1] = 80;
1103         cmd.command[2] = 0;
1104         cmd.command[3] = 0;
1105         cmd.length = 4;
1106
1107         return true;
1108 }
1109
1110 unsigned ArduControl::ControlThread::do_command(const PendingCommand &cmd, const Time::TimeDelta &timeout)
1111 {
1112         if(control.debug>=2)
1113         {
1114                 string cmd_hex;
1115                 for(unsigned i=0; i<cmd.length; ++i)
1116                         cmd_hex += format(" %02X", static_cast<unsigned char>(cmd.command[i]));
1117                 IO::print("< %02X%s\n", cmd.length^0xFF, cmd_hex);
1118         }
1119
1120         control.serial.put(cmd.length^0xFF);
1121         control.serial.write(cmd.command, cmd.length);
1122
1123         unsigned result = 0;
1124         while(1)
1125         {
1126                 bool got_data;
1127                 if(result)
1128                         got_data = IO::poll(control.serial, IO::P_INPUT, Time::zero);
1129                 else
1130                         got_data = IO::poll(control.serial, IO::P_INPUT, timeout);
1131
1132                 if(!got_data)
1133                         break;
1134
1135                 unsigned rlength = control.serial.get()^0xFF;
1136                 if(rlength>15)
1137                 {
1138                         IO::print("Invalid length %02X\n", rlength);
1139                         continue;
1140                 }
1141
1142                 char reply[15];
1143                 unsigned pos = 0;
1144                 while(pos<rlength)
1145                 {
1146                         if(!IO::poll(control.serial, IO::P_INPUT, timeout))
1147                                 return 0;
1148                         pos += control.serial.read(reply+pos, rlength-pos);
1149                 }
1150
1151                 if(control.debug>=2)
1152                 {
1153                         string reply_hex;
1154                         for(unsigned i=0; i<rlength; ++i)
1155                                 reply_hex += format(" %02X", static_cast<unsigned char>(reply[i]));
1156                         IO::print("> %02X%s\n", rlength^0xFF, reply_hex);
1157                 }
1158
1159                 unsigned r = process_reply(reply, rlength);
1160                 if(r && !result)
1161                         result = r;
1162         }
1163
1164         return result;
1165 }
1166
1167 unsigned ArduControl::ControlThread::process_reply(const char *reply, unsigned rlength)
1168 {
1169         unsigned char type = reply[0];
1170         if((type&0xE0)==0x80)
1171         {
1172                 if(type!=COMMAND_OK)
1173                         IO::print("Error %02X\n", type);
1174                 return type;
1175         }
1176         else if(type==POWER_STATE && rlength==2)
1177         {
1178                 control.power.set(reply[1]);
1179
1180                 Tag tag;
1181                 tag.type = Tag::GENERAL;
1182                 tag.command = POWER;
1183                 tag.serial = control.power.serial;
1184                 control.completed_commands.push(tag);
1185         }
1186         else
1187         {
1188                 for(vector<Task *>::iterator i=tasks.begin(); i!=tasks.end(); ++i)
1189                         (*i)->process_reply(reply, rlength);
1190         }
1191
1192         return 0;
1193 }
1194
1195
1196 ArduControl::Loader::Loader(ArduControl &c):
1197         DataFile::ObjectLoader<ArduControl>(c)
1198 {
1199         add("mfx_announce_serial", &Loader::mfx_announce_serial);
1200         add("mfx_locomotive", &Loader::mfx_locomotive);
1201 }
1202
1203 void ArduControl::Loader::mfx_announce_serial(unsigned s)
1204 {
1205         obj.mfx_announce.set_serial(s);
1206 }
1207
1208 void ArduControl::Loader::mfx_locomotive(unsigned id)
1209 {
1210         MfxInfo info;
1211         info.id = id;
1212         info.protocol = "MFX";
1213         load_sub(info);
1214         obj.add_mfx_info(info);
1215 }
1216
1217
1218 ArduControl::MfxInfo::Loader::Loader(MfxInfo &i):
1219         DataFile::ObjectLoader<MfxInfo>(i)
1220 {
1221         add("address", static_cast<unsigned MfxInfo::*>(&MfxInfo::address));
1222         add("name", static_cast<string MfxInfo::*>(&MfxInfo::name));
1223 }
1224
1225 } // namespace R2C2