]> git.tdb.fi Git - r2c2.git/blob - source/libr2c2/arducontrol.cpp
Improve ArduControl task scheduling
[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(), type.get_paths());
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, 3);
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, unsigned states)
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, states));
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 || acc.uncertain)
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 void ArduControl::activate_accessory_by_mask(Accessory &acc, unsigned mask)
295 {
296         unsigned bit = mask&~(mask-1);
297         for(active_index=0; (bit>>active_index)>1; ++active_index) ;
298         acc.state.set((acc.state&~bit)|(acc.target&bit));
299         if(debug>=1)
300                 IO::print("Setting accessory %d bit %d, state=%d\n", acc.address, active_index, acc.state.pending);
301         PendingCommand cmd(acc, Accessory::ACTIVATE, active_index);
302         command_queue.push(cmd);
303         active_accessory = &acc;
304
305         monitor.reset_peak();
306 }
307
308 unsigned ArduControl::add_sensor(unsigned addr)
309 {
310         if(!addr)
311                 throw invalid_argument("ArduControl::add_sensor");
312
313         insert_unique(sensors, addr, Sensor(addr));
314         s88.grow_n_octets((addr+7)/8);
315
316         return addr;
317 }
318
319 void ArduControl::remove_sensor(unsigned addr)
320 {
321         remove_existing(sensors, addr);
322         // TODO update s88.n_octets
323 }
324
325 bool ArduControl::get_sensor(unsigned addr) const
326 {
327         return get_item(sensors, addr).state;
328 }
329
330 void ArduControl::tick()
331 {
332         Tag tag;
333         while(completed_commands.pop(tag))
334         {
335                 if(tag.type==Tag::GENERAL)
336                 {
337                         if(tag.command==POWER)
338                         {
339                                 if(power.commit(tag.serial))
340                                         signal_power.emit(power.current);
341                         }
342                         else if(tag.command==NEW_LOCO)
343                         {
344                                 MfxInfo info;
345                                 if(mfx_search.pop_info(info))
346                                 {
347                                         MfxInfoArray::iterator i = add_mfx_info(info);
348                                         save_state();
349                                         signal_locomotive_detected.emit(*i);
350                                 }
351                         }
352                 }
353                 else if(tag.type==Tag::LOCOMOTIVE)
354                 {
355                         LocomotiveMap::iterator i = locomotives.find(tag.id);
356                         if(i==locomotives.end())
357                                 continue;
358
359                         Locomotive &loco = i->second;
360                         if(tag.command==Locomotive::SPEED)
361                         {
362                                 if(loco.speed.commit(tag.serial))
363                                         signal_loco_speed.emit(loco.id, loco.speed, loco.reverse);
364                         }
365                         else if(tag.command==Locomotive::REVERSE)
366                         {
367                                 if(loco.reverse.commit(tag.serial))
368                                         signal_loco_speed.emit(loco.id, loco.speed, loco.reverse);
369                         }
370                         else if(tag.command==Locomotive::FUNCTIONS)
371                         {
372                                 unsigned old = loco.funcs;
373                                 if(loco.funcs.commit(tag.serial))
374                                 {
375                                         unsigned changed = old^loco.funcs;
376                                         for(unsigned j=0; changed>>j; ++j)
377                                                 if((changed>>j)&1)
378                                                         signal_loco_function.emit(loco.id, j, (loco.funcs>>j)&1);
379                                 }
380                         }
381                 }
382                 else if(tag.type==Tag::ACCESSORY)
383                 {
384                         AccessoryMap::iterator i = accessories.find(tag.id);
385                         if(i==accessories.end())
386                                 continue;
387
388                         Accessory &acc = i->second;
389                         if(tag.command==Accessory::ACTIVATE)
390                                 off_timeout = Time::now()+acc.active_time;
391                         else if(tag.command==Accessory::DEACTIVATE)
392                         {
393                                 if(acc.state.commit(tag.serial))
394                                 {
395                                         if(&acc==active_accessory)
396                                                 active_accessory = 0;
397                                 }
398                         }
399                 }
400                 else if(tag.type==Tag::SENSOR)
401                 {
402                         SensorMap::iterator i = sensors.find(tag.id);
403                         if(i==sensors.end())
404                                 continue;
405
406                         Sensor &sensor = i->second;
407                         if(tag.command==Sensor::STATE)
408                         {
409                                 if(sensor.state.commit(tag.serial))
410                                         signal_sensor.emit(sensor.address, sensor.state);
411                         }
412                 }
413         }
414
415         while(power && !active_accessory && !accessory_queue.empty())
416         {
417                 Accessory &acc = *accessory_queue.front();
418
419                 if(acc.uncertain)
420                 {
421                         unsigned zeroes = acc.uncertain&~acc.target;
422                         if(zeroes)
423                                 activate_accessory_by_mask(acc, zeroes);
424                         else
425                                 activate_accessory_by_mask(acc, acc.uncertain);
426                 }
427                 else if(acc.state!=acc.target)
428                 {
429                         unsigned changes = acc.state^acc.target;
430                         if(!(changes&((1<<acc.bits)-1)))
431                         {
432                                 // All remaining changes are in non-physical bits
433                                 acc.state.set(acc.state^changes);
434                                 acc.state.commit(acc.state.serial);
435                         }
436                         else
437                         {
438                                 unsigned toggle_bit = 0;
439                                 for(unsigned bit=1; (!toggle_bit && bit<=changes); bit<<=1)
440                                         if((changes&bit) && (acc.valid_states&(1<<(acc.state^bit))))
441                                                 toggle_bit = bit;
442
443                                 activate_accessory_by_mask(acc, toggle_bit);
444                         }
445                 }
446                 else
447                 {
448                         accessory_queue.pop_front();
449
450                         if(acc.state==acc.target)
451                         {
452                                 if(acc.kind==Accessory::TURNOUT)
453                                         signal_turnout.emit(acc.address, acc.state);
454                                 else if(acc.kind==Accessory::SIGNAL)
455                                         signal_signal.emit(acc.address, acc.state);
456                         }
457                 }
458         }
459
460         if(active_accessory && off_timeout)
461         {
462                 bool success = (monitor.get_peak()>0.35f && monitor.get_current()<monitor.get_peak()-0.2f);
463                 Time::TimeStamp t = Time::now();
464                 if(t>off_timeout || success)
465                 {
466                         Accessory &acc = *active_accessory;
467
468                         unsigned bit = 1<<active_index;
469
470                         // Assume success if we were uncertain of the physical setting
471                         if(acc.uncertain&bit)
472                                 acc.uncertain &= ~bit;
473                         else if(acc.kind==Accessory::TURNOUT && !success)
474                         {
475                                 if(debug>=1)
476                                         IO::print("Peak current only %.2f A\n", monitor.get_peak());
477                                 signal_turnout_failed.emit(acc.address);
478                                 acc.state.rollback();
479                                 if(acc.valid_states&(1<<(acc.target^bit)))
480                                         acc.target ^= bit;
481                                 else
482                                         acc.target = acc.state;
483                         }
484
485                         off_timeout = Time::TimeStamp();
486                         PendingCommand cmd(acc, Accessory::DEACTIVATE, active_index);
487                         command_queue.push(cmd);
488                 }
489         }
490 }
491
492 void ArduControl::flush()
493 {
494         while(!command_queue.empty() || (power && !accessory_queue.empty()))
495                 tick();
496 }
497
498 void ArduControl::save_state() const
499 {
500         FS::RedirectedPath tmp_file(state_file);
501         IO::BufferedFile out(tmp_file.str(), IO::M_WRITE);
502         DataFile::Writer writer(out);
503
504         writer.write((DataFile::Statement("mfx_announce_serial"), mfx_announce.get_serial()));
505         for(MfxInfoArray::const_iterator i=mfx_info.begin(); i!=mfx_info.end(); ++i)
506         {
507                 DataFile::Statement st("mfx_locomotive");
508                 st.append(i->id);
509                 st.sub.push_back((DataFile::Statement("address"), i->address));
510                 st.sub.push_back((DataFile::Statement("name"), i->name));
511                 writer.write(st);
512         }
513 }
514
515
516 ArduControl::Tag::Tag():
517         type(NONE),
518         command(0),
519         serial(0),
520         id(0)
521 { }
522
523
524 ArduControl::Locomotive::Locomotive(Protocol p, unsigned a):
525         id((p<<16)|a),
526         proto(p),
527         address(a),
528         speed(0),
529         reverse(false),
530         funcs(0),
531         last_change_age(0)
532 { }
533
534 unsigned ArduControl::Locomotive::create_speed_dir_command(char *buffer) const
535 {
536         if(proto==MM)
537         {
538                 buffer[0] = MOTOROLA_SPEED_DIRECTION;
539                 buffer[1] = address;
540                 buffer[2] = funcs.pending&1;
541                 buffer[3] = speed.pending+reverse.pending*0x80;
542                 return 4;
543         }
544         else if(proto==MFX)
545         {
546                 buffer[0] = MFX_SPEED;
547                 buffer[1] = address>>8;
548                 buffer[2] = address;
549                 buffer[3] = speed.pending+reverse.pending*0x80;
550                 return 4;
551         }
552         else
553                 return 0;
554 }
555
556 unsigned ArduControl::Locomotive::create_speed_func_command(unsigned f, char *buffer) const
557 {
558         if(proto==MM)
559         {
560                 if(f<1 || f>4)
561                         throw invalid_argument("Locomotive::create_speed_func_command");
562
563                 buffer[0] = MOTOROLA_SPEED_FUNCTION;
564                 buffer[1] = address;
565                 buffer[2] = (f<<4)|(((funcs.pending>>f)&1)<<1)|(funcs.pending&1);
566                 buffer[3] = speed.pending;
567                 return 4;
568         }
569         else if(proto==MFX)
570         {
571                 bool f16 = (funcs.pending>0xFF);
572                 buffer[0] = (f16 ? MFX_SPEED_FUNCS16 : MFX_SPEED_FUNCS8);
573                 buffer[1] = address>>8;
574                 buffer[2] = address;
575                 buffer[3] = speed.pending+reverse.pending*0x80;
576                 if(f16)
577                 {
578                         buffer[4] = funcs.pending>>8;
579                         buffer[5] = funcs.pending;
580                         return 6;
581                 }
582                 else
583                 {
584                         buffer[4] = funcs.pending;
585                         return 5;
586                 }
587         }
588         else
589                 return 0;
590 }
591
592
593 ArduControl::Accessory::Accessory(Kind k, unsigned a, unsigned b, unsigned s):
594         kind(k),
595         address(a),
596         bits(b),
597         valid_states(s),
598         state(0),
599         uncertain((1<<bits)-1),
600         target(0),
601         active_time((bits*700)*Time::msec)
602 { }
603
604 unsigned ArduControl::Accessory::create_state_command(unsigned b, bool c, char *buffer) const
605 {
606         if(b>=bits)
607                 throw invalid_argument("Accessory::create_state_command");
608
609         unsigned a = (address+b+3)*2;
610         if(!((state.pending>>b)&1))
611                 ++a;
612         buffer[0] = MOTOROLA_SOLENOID;
613         buffer[1] = a>>3;
614         buffer[2] = ((a&7)<<4)|c;
615         return 3;
616 }
617
618
619 ArduControl::Sensor::Sensor(unsigned a):
620         address(a),
621         state(false)
622 { }
623
624
625 ArduControl::PendingCommand::PendingCommand():
626         length(0),
627         repeat_count(1)
628 { }
629
630 ArduControl::PendingCommand::PendingCommand(GeneralCommand cmd):
631         length(0),
632         repeat_count(1)
633 {
634         tag.type = Tag::GENERAL;
635         tag.command = cmd;
636 }
637
638 ArduControl::PendingCommand::PendingCommand(Locomotive &loco, Locomotive::Command cmd, unsigned index):
639         repeat_count(8)
640 {
641         tag.type = Tag::LOCOMOTIVE;
642         tag.command = cmd;
643         tag.id = loco.id;
644         if(cmd==Locomotive::SPEED)
645         {
646                 tag.serial = loco.speed.serial;
647                 length = loco.create_speed_dir_command(command);
648         }
649         else if(cmd==Locomotive::REVERSE)
650         {
651                 tag.serial = loco.reverse.serial;
652                 length = loco.create_speed_dir_command(command);
653         }
654         else if(cmd==Locomotive::FUNCTIONS)
655         {
656                 tag.serial = loco.funcs.serial;
657                 length = loco.create_speed_func_command(index, command);
658         }
659         else
660                 throw invalid_argument("PendingCommand");
661 }
662
663 ArduControl::PendingCommand::PendingCommand(Accessory &acc, Accessory::Command cmd, unsigned index):
664         repeat_count(1)
665 {
666         tag.type = Tag::ACCESSORY;
667         tag.command = cmd;
668         tag.id = acc.address;
669         if(cmd==Accessory::ACTIVATE || cmd==Accessory::DEACTIVATE)
670         {
671                 tag.serial = acc.state.serial;
672                 length = acc.create_state_command(index, (cmd==Accessory::ACTIVATE), command);
673         }
674         else
675                 throw invalid_argument("PendingCommand");
676 }
677
678
679 template<typename T>
680 void ArduControl::Queue<T>::push(const T &item)
681 {
682         MutexLock lock(mutex);
683         items.push_back(item);
684 }
685
686 template<typename T>
687 bool ArduControl::Queue<T>::pop(T &item)
688 {
689         MutexLock lock(mutex);
690         if(items.empty())
691                 return false;
692
693         item = items.front();
694         items.pop_front();
695         return true;
696 }
697
698 template<typename T>
699 bool ArduControl::Queue<T>::empty() const
700 {
701         return items.empty();
702 }
703
704
705 bool ArduControl::CommandQueueTask::get_work(PendingCommand &cmd)
706 {
707         return queue.pop(cmd);
708 }
709
710 void ArduControl::CommandQueueTask::push(const PendingCommand &cmd)
711 {
712         queue.push(cmd);
713 }
714
715
716 ArduControl::Task::Task(const string &n, unsigned p):
717         name(n),
718         priority(p)
719 { }
720
721 void ArduControl::Task::sleep(const Time::TimeDelta &dt)
722 {
723         sleep_timeout = Time::now()+dt;
724 }
725
726
727 ArduControl::CommandQueueTask::CommandQueueTask():
728         Task("CommandQueue")
729 { }
730
731
732 ArduControl::RefreshTask::RefreshTask():
733         Task("Refresh", 2),
734         next(cycle.end()),
735         round(0),
736         loco(0),
737         phase(0)
738 { }
739
740 bool ArduControl::RefreshTask::get_work(PendingCommand &cmd)
741 {
742         if(loco && loco->proto==MM && phase==0)
743         {
744                 cmd.length = loco->create_speed_func_command(round%4+1, cmd.command);
745                 cmd.repeat_count = 2;
746                 ++phase;
747                 return true;
748         }
749
750         loco = get_next_loco();
751         if(!loco)
752                 return false;
753
754         phase = 0;
755         if(loco->proto==MM)
756         {
757                 cmd.length = loco->create_speed_dir_command(cmd.command);
758                 cmd.repeat_count = 2;
759         }
760         else if(loco->proto==MFX)
761                 cmd.length = loco->create_speed_func_command(0, cmd.command);
762         else
763                 return false;
764
765         return true;
766 }
767
768 void ArduControl::RefreshTask::add_loco(Locomotive &l)
769 {
770         MutexLock lock(mutex);
771         cycle.push_back(&l);
772         if(cycle.size()>15)
773         {
774                 LocomotivePtrList::iterator oldest = cycle.begin();
775                 for(LocomotivePtrList::iterator i=cycle.begin(); ++i!=cycle.end(); )
776                         if((*i)->last_change_age>(*oldest)->last_change_age)
777                                 oldest = i;
778                 if(oldest==next)
779                         advance();
780                 cycle.erase(oldest);
781         }
782         if(next==cycle.end())
783                 next = cycle.begin();
784 }
785
786 void ArduControl::RefreshTask::remove_loco(Locomotive &l)
787 {
788         MutexLock lock(mutex);
789         for(LocomotivePtrList::iterator i=cycle.begin(); i!=cycle.end(); ++i)
790                 if(*i==&l)
791                 {
792                         if(i==next)
793                         {
794                                 if(cycle.size()>1)
795                                         advance();
796                                 else
797                                         next = cycle.end();
798                         }
799                         cycle.erase(i);
800                         return;
801                 }
802 }
803
804 ArduControl::Locomotive *ArduControl::RefreshTask::get_next_loco()
805 {
806         MutexLock lock(mutex);
807         if(cycle.empty())
808                 return 0;
809
810         Locomotive *l = *next;
811         advance();
812         return l;
813 }
814
815 void ArduControl::RefreshTask::advance()
816 {
817         ++next;
818         if(next==cycle.end())
819         {
820                 next= cycle.begin();
821                 ++round;
822         }
823 }
824
825
826 ArduControl::S88Task::S88Task(ArduControl &c):
827         Task("S88"),
828         control(c),
829         n_octets(0),
830         octets_remaining(0)
831 { }
832
833 bool ArduControl::S88Task::get_work(PendingCommand &cmd)
834 {
835         if(octets_remaining || !n_octets)
836                 return false;
837
838         octets_remaining = n_octets;
839         cmd.command[0] = S88_READ;
840         cmd.command[1] = octets_remaining;
841         cmd.length = 2;
842
843         sleep(100*Time::msec);
844
845         return true;
846 }
847
848 void ArduControl::S88Task::process_reply(const char *reply, unsigned length)
849 {
850         unsigned char type = reply[0];
851         if(type==S88_DATA && length>2)
852         {
853                 unsigned offset = static_cast<unsigned char>(reply[1]);
854                 unsigned count = length-2;
855
856                 SensorMap::iterator begin = control.sensors.lower_bound(offset*8+1);
857                 SensorMap::iterator end = control.sensors.upper_bound((offset+count)*8);
858                 for(SensorMap::iterator i=begin; i!=end; ++i)
859                 {
860                         unsigned bit_index = i->first-1-offset*8;
861                         bool state = (reply[2+bit_index/8]>>(7-bit_index%8))&1;
862                         i->second.state.set(state);
863
864                         Tag tag;
865                         tag.type = Tag::SENSOR;
866                         tag.command = Sensor::STATE;
867                         tag.serial = i->second.state.serial;
868                         tag.id = i->first;
869                         control.completed_commands.push(tag);
870                 }
871
872                 if(count>octets_remaining)
873                         octets_remaining = 0;
874                 else
875                         octets_remaining -= count;
876         }
877 }
878
879 void ArduControl::S88Task::set_n_octets(unsigned n)
880 {
881         n_octets = n;
882 }
883
884 void ArduControl::S88Task::grow_n_octets(unsigned n)
885 {
886         if(n>n_octets)
887                 n_octets = n;
888 }
889
890
891 ArduControl::MfxAnnounceTask::MfxAnnounceTask():
892         Task("MfxAnnounce", 1),
893         serial(0)
894 { }
895
896 bool ArduControl::MfxAnnounceTask::get_work(PendingCommand &cmd)
897 {
898         cmd.command[0] = MFX_ANNOUNCE;
899         cmd.command[1] = serial>>8;
900         cmd.command[2] = serial;
901         cmd.length = 3;
902
903         sleep(400*Time::msec);
904
905         return true;
906 }
907
908 void ArduControl::MfxAnnounceTask::set_serial(unsigned s)
909 {
910         serial = s;
911 }
912
913
914 ArduControl::MfxSearchTask::MfxSearchTask(ArduControl &c):
915         Task("MfxSearch", 1),
916         control(c),
917         next_address(1),
918         size(0),
919         bits(0),
920         misses(0)
921 { }
922
923 bool ArduControl::MfxSearchTask::get_work(PendingCommand &cmd)
924 {
925         if(size>32)
926         {
927                 if(control.debug>=1)
928                         IO::print("Assigning MFX address %d to decoder %08X\n", next_address, bits);
929
930                 MfxInfo info;
931                 info.protocol = "MFX";
932                 info.address = next_address;
933                 info.name = format("%08X", bits);
934                 info.id = bits;
935                 queue.push(info);
936
937                 cmd.command[0] = MFX_ASSIGN_ADDRESS;
938                 cmd.command[1] = next_address>>8;
939                 cmd.command[2] = next_address;
940                 for(unsigned i=0; i<4; ++i)
941                         cmd.command[3+i] = bits>>(24-i*8);
942                 cmd.length = 7;
943
944                 cmd.tag.type = Tag::GENERAL;
945                 cmd.tag.command = NEW_LOCO;
946                 cmd.tag.id = bits;
947
948                 size = 0;
949                 bits = 0;
950                 ++next_address;
951
952                 return true;
953         }
954
955         cmd.command[0] = MFX_SEARCH;
956         for(unsigned i=0; i<4; ++i)
957                 cmd.command[1+i] = bits>>(24-i*8);
958         cmd.command[5] = size;
959         cmd.length = 6;
960
961         sleep(200*Time::msec);
962
963         if(control.debug>=1)
964                 IO::print("Search %08X/%d\n", bits, size);
965
966         return true;
967 }
968
969 void ArduControl::MfxSearchTask::process_reply(const char *reply, unsigned length)
970 {
971         unsigned char type = reply[0];
972         if(type==MFX_SEARCH_FEEDBACK && length==2)
973         {
974                 if(reply[1])
975                 {
976                         misses = 0;
977                         ++size;
978                 }
979                 else if(size>0 && misses<6)
980                 {
981                         ++misses;
982                         bits ^= 1<<(32-size);
983                 }
984                 else
985                 {
986                         sleep(2*Time::sec);
987                         bits = 0;
988                         size = 0;
989                         misses = 0;
990                 }
991         }
992 }
993
994 void ArduControl::MfxSearchTask::set_next_address(unsigned a)
995 {
996         next_address = a;
997 }
998
999 bool ArduControl::MfxSearchTask::pop_info(MfxInfo &info)
1000 {
1001         return queue.pop(info);
1002 }
1003
1004
1005 ArduControl::MonitorTask::MonitorTask():
1006         Task("Monitor"),
1007         voltage(0),
1008         current(0),
1009         base_level(0),
1010         peak_level(0),
1011         next_type(0)
1012 { }
1013
1014 bool ArduControl::MonitorTask::get_work(PendingCommand &cmd)
1015 {
1016         if(next_type==0)
1017                 cmd.command[0] = READ_INPUT_VOLTAGE;
1018         else
1019                 cmd.command[0] = READ_TRACK_CURRENT;
1020         cmd.length = 1;
1021
1022         sleep(200*Time::msec);
1023         next_type = (next_type+1)%5;
1024
1025         return true;
1026 }
1027
1028 void ArduControl::MonitorTask::process_reply(const char *reply, unsigned length)
1029 {
1030         unsigned char type = reply[0];
1031         if(type==INPUT_VOLTAGE && length==3)
1032                 voltage = ((static_cast<unsigned char>(reply[1])<<8) | static_cast<unsigned char>(reply[2]))/1000.0f;
1033         else if(type==TRACK_CURRENT && length==5)
1034         {
1035                 current = ((static_cast<unsigned char>(reply[1])<<8) | static_cast<unsigned char>(reply[2]))/1000.0f;
1036                 float peak = ((static_cast<unsigned char>(reply[3])<<8) | static_cast<unsigned char>(reply[4]))/1000.0f;
1037                 peak_level = max(peak_level, peak);
1038                 base_level = min(base_level, current);
1039         }
1040 }
1041
1042 void ArduControl::MonitorTask::reset_peak()
1043 {
1044         base_level = current;
1045         peak_level = current;
1046 }
1047
1048
1049 ArduControl::ControlThread::ControlThread(ArduControl &c):
1050         control(c),
1051         done(false)
1052 {
1053         tasks.push_back(&control.command_queue);
1054         tasks.push_back(&control.monitor);
1055         tasks.push_back(&control.mfx_announce);
1056         tasks.push_back(&control.mfx_search);
1057         tasks.push_back(&control.s88);
1058         tasks.push_back(&control.refresh);
1059
1060         launch();
1061 }
1062
1063 void ArduControl::ControlThread::exit()
1064 {
1065         done = true;
1066         join();
1067 }
1068
1069 void ArduControl::ControlThread::main()
1070 {
1071         init_baud_rate();
1072
1073         while(!done)
1074         {
1075                 PendingCommand cmd;
1076                 if(get_work(cmd))
1077                 {
1078                         bool success = true;
1079                         bool resync = false;
1080                         for(unsigned i=0; (success && i<cmd.repeat_count); ++i)
1081                         {
1082                                 unsigned result = do_command(cmd, control.command_timeout);
1083                                 success = (result==COMMAND_OK);
1084                                 resync = (result==0);
1085                         }
1086
1087                         if(success && cmd.tag)
1088                                 control.completed_commands.push(cmd.tag);
1089
1090                         if(resync)
1091                         {
1092                                 if(control.debug>=1)
1093                                         IO::print("Synchronization with ArduControl lost, attempting to recover\n");
1094                                 for(unsigned i=0; (resync && i<16); ++i)
1095                                 {
1096                                         control.serial.put('\xFF');
1097                                         while(IO::poll(control.serial, IO::P_INPUT, control.command_timeout))
1098                                                 resync = (control.serial.get()!=0xFF);
1099                                 }
1100                                 if(resync)
1101                                 {
1102                                         if(control.debug>=1)
1103                                                 IO::print("Resynchronization failed, giving up\n");
1104                                         done = true;
1105                                 }
1106                                 else
1107                                 {
1108                                         if(control.debug>=1)
1109                                                 IO::print("Resynchronization successful\n");
1110                                         if(cmd.tag)
1111                                                 control.command_queue.push(cmd);
1112                                 }
1113                         }
1114                 }
1115                 else
1116                         Time::sleep(10*Time::msec);
1117         }
1118 }
1119
1120 void ArduControl::ControlThread::init_baud_rate()
1121 {
1122         static unsigned rates[] = { 57600, 9600, 19200, 38400, 0 };
1123         unsigned rate = 0;
1124         control.serial.set_data_bits(8);
1125         control.serial.set_parity(IO::Serial::NONE);
1126         control.serial.set_stop_bits(1);
1127         for(unsigned i=0; rates[i]; ++i)
1128         {
1129                 control.serial.set_baud_rate(rates[i]);
1130                 control.serial.put('\xFF');
1131                 if(IO::poll(control.serial, IO::P_INPUT, 500*Time::msec))
1132                 {
1133                         int c = control.serial.get();
1134                         if(c==0xFF)
1135                         {
1136                                 rate = rates[i];
1137                                 break;
1138                         }
1139                 }
1140         }
1141
1142         if(!rate)
1143         {
1144                 if(control.debug>=1)
1145                         IO::print("ArduControl detection failed\n");
1146                 done = true;
1147                 return;
1148         }
1149
1150         if(control.debug>=1)
1151                 IO::print("ArduControl detected at %d bits/s\n", rate);
1152
1153         if(rate!=rates[0])
1154         {
1155                 PendingCommand cmd;
1156                 cmd.command[0] = SET_BAUD_RATE;
1157                 cmd.command[1] = rates[0]>>8;
1158                 cmd.command[2] = rates[0];
1159                 cmd.length = 3;
1160                 if(do_command(cmd, Time::sec)==COMMAND_OK)
1161                 {
1162                         control.serial.set_baud_rate(rates[0]);
1163                         Time::sleep(Time::sec);
1164                         if(do_command(cmd, Time::sec)==COMMAND_OK)
1165                         {
1166                                 if(control.debug>=1)
1167                                         IO::print("Rate changed to %d bits/s\n", rates[0]);
1168                         }
1169                 }
1170         }
1171 }
1172
1173 bool ArduControl::ControlThread::get_work(PendingCommand &cmd)
1174 {
1175         Time::TimeStamp t = Time::now();
1176
1177         unsigned count = 0;
1178         for(; (count<tasks.size() && tasks[count]->get_sleep_timeout()<=t); ++count) ;
1179
1180         for(; count>0; --count)
1181         {
1182                 unsigned i = 0;
1183                 for(unsigned j=1; j<count; ++j)
1184                         if(tasks[j]->get_priority()<tasks[i]->get_priority())
1185                                 i = j;
1186
1187                 Task *task = tasks[i];
1188                 bool result = task->get_work(cmd);
1189
1190                 Time::TimeStamp st = max(task->get_sleep_timeout(), t);
1191                 for(; (i+1<tasks.size() && tasks[i+1]->get_sleep_timeout()<=st); ++i)
1192                         tasks[i] = tasks[i+1];
1193                 tasks[i] = task;
1194
1195                 if(result)
1196                 {
1197                         if(control.debug>=2)
1198                                 IO::print("Scheduled task %s\n", task->get_name());
1199                         return true;
1200                 }
1201         }
1202
1203         // As fallback, send an idle packet for the MM protocol
1204         cmd.command[0] = MOTOROLA_SPEED;
1205         cmd.command[1] = 80;
1206         cmd.command[2] = 0;
1207         cmd.command[3] = 0;
1208         cmd.length = 4;
1209
1210         return true;
1211 }
1212
1213 unsigned ArduControl::ControlThread::do_command(const PendingCommand &cmd, const Time::TimeDelta &timeout)
1214 {
1215         if(control.debug>=2)
1216         {
1217                 string cmd_hex;
1218                 for(unsigned i=0; i<cmd.length; ++i)
1219                         cmd_hex += format(" %02X", static_cast<unsigned char>(cmd.command[i]));
1220                 IO::print("< %02X%s\n", cmd.length^0xFF, cmd_hex);
1221         }
1222
1223         control.serial.put(cmd.length^0xFF);
1224         control.serial.write(cmd.command, cmd.length);
1225
1226         unsigned result = 0;
1227         while(1)
1228         {
1229                 bool got_data;
1230                 if(result)
1231                         got_data = IO::poll(control.serial, IO::P_INPUT, Time::zero);
1232                 else
1233                         got_data = IO::poll(control.serial, IO::P_INPUT, timeout);
1234
1235                 if(!got_data)
1236                         break;
1237
1238                 unsigned rlength = control.serial.get()^0xFF;
1239                 if(rlength>15)
1240                 {
1241                         IO::print("Invalid length %02X\n", rlength);
1242                         continue;
1243                 }
1244
1245                 char reply[15];
1246                 unsigned pos = 0;
1247                 while(pos<rlength)
1248                 {
1249                         if(!IO::poll(control.serial, IO::P_INPUT, timeout))
1250                                 return 0;
1251                         pos += control.serial.read(reply+pos, rlength-pos);
1252                 }
1253
1254                 if(control.debug>=2)
1255                 {
1256                         string reply_hex;
1257                         for(unsigned i=0; i<rlength; ++i)
1258                                 reply_hex += format(" %02X", static_cast<unsigned char>(reply[i]));
1259                         IO::print("> %02X%s\n", rlength^0xFF, reply_hex);
1260                 }
1261
1262                 unsigned r = process_reply(reply, rlength);
1263                 if(r && !result)
1264                         result = r;
1265         }
1266
1267         return result;
1268 }
1269
1270 unsigned ArduControl::ControlThread::process_reply(const char *reply, unsigned rlength)
1271 {
1272         unsigned char type = reply[0];
1273         if((type&0xE0)==0x80)
1274         {
1275                 if(type!=COMMAND_OK)
1276                         IO::print("Error %02X\n", type);
1277                 return type;
1278         }
1279         else if(type==POWER_STATE && rlength==2)
1280                 set_power(reply[1]);
1281         else if(type==OVERCURRENT)
1282         {
1283                 set_power(false);
1284                 IO::print("Overcurrent detected!\n");
1285         }
1286         else
1287         {
1288                 for(vector<Task *>::iterator i=tasks.begin(); i!=tasks.end(); ++i)
1289                         (*i)->process_reply(reply, rlength);
1290         }
1291
1292         return 0;
1293 }
1294
1295 void ArduControl::ControlThread::set_power(bool p)
1296 {
1297         control.power.set(p);
1298
1299         Tag tag;
1300         tag.type = Tag::GENERAL;
1301         tag.command = POWER;
1302         tag.serial = control.power.serial;
1303         control.completed_commands.push(tag);
1304 }
1305
1306
1307 ArduControl::Loader::Loader(ArduControl &c):
1308         DataFile::ObjectLoader<ArduControl>(c)
1309 {
1310         add("mfx_announce_serial", &Loader::mfx_announce_serial);
1311         add("mfx_locomotive", &Loader::mfx_locomotive);
1312 }
1313
1314 void ArduControl::Loader::mfx_announce_serial(unsigned s)
1315 {
1316         obj.mfx_announce.set_serial(s);
1317 }
1318
1319 void ArduControl::Loader::mfx_locomotive(unsigned id)
1320 {
1321         MfxInfo info;
1322         info.id = id;
1323         info.protocol = "MFX";
1324         load_sub(info);
1325         obj.add_mfx_info(info);
1326 }
1327
1328
1329 ArduControl::MfxInfo::Loader::Loader(MfxInfo &i):
1330         DataFile::ObjectLoader<MfxInfo>(i)
1331 {
1332         add("address", static_cast<unsigned MfxInfo::*>(&MfxInfo::address));
1333         add("name", static_cast<string MfxInfo::*>(&MfxInfo::name));
1334 }
1335
1336 } // namespace R2C2