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