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"
15 ArduControl::ProtocolInfo ArduControl::protocol_info[2] =
18 { 0x3FFF, 126, 15 } // MFX
21 Driver::TelemetryInfo ArduControl::telemetry_info[4] =
23 { "voltage", "Voltage", "V", 1 },
24 { "current", "Current", "A", 2 },
25 { "cmd-queue-depth", "Cmd queue", "", 0 },
26 { "s88-latency", "S88 latency", "ms", 0 }
29 ArduControl::ArduControl(const Options &opts):
30 serial(opts.get<string>(string(), "ttyUSB0")),
31 debug(opts.get<unsigned>("debug")),
32 state_file("arducontrol.state"),
36 command_timeout(200*Time::msec),
41 if(FS::exists(state_file))
42 DataFile::load(*this, state_file.str());
44 unsigned max_address = 0;
45 for(MfxInfoArray::const_iterator i=mfx_info.begin(); i!=mfx_info.end(); ++i)
46 max_address = max(max_address, i->address);
47 mfx_search.set_next_address(max_address+1);
50 cmd.command[0] = READ_POWER_STATE;
52 command_queue.push(cmd);
54 cmd.command[0] = MFX_SET_STATION_ID;
60 command_queue.push(cmd);
63 ArduControl::~ArduControl()
68 void ArduControl::set_power(bool p)
72 PendingCommand cmd(POWER);
73 cmd.tag.serial = power.serial;
74 cmd.command[0] = (p ? POWER_ON : POWER_OFF);
76 command_queue.push(cmd);
80 void ArduControl::halt(bool h)
88 for(LocomotiveMap::const_iterator i=locomotives.begin(); i!=locomotives.end(); ++i)
89 set_loco_speed(i->first, 0);
92 signal_halt.emit(halted);
95 const char *ArduControl::enumerate_protocols(unsigned i) const
105 ArduControl::Protocol ArduControl::map_protocol(const string &proto_name)
109 else if(proto_name=="MFX")
112 throw invalid_argument("ArduControl::map_protocol");
115 unsigned ArduControl::get_protocol_speed_steps(const string &proto_name) const
117 return protocol_info[map_protocol(proto_name)].max_speed;
120 const Driver::DetectedLocomotive *ArduControl::enumerate_detected_locos(unsigned i) const
122 if(i>=mfx_info.size())
128 unsigned ArduControl::add_loco(unsigned addr, const string &proto_name, const VehicleType &)
131 throw invalid_argument("ArduControl::add_loco");
133 Protocol proto = map_protocol(proto_name);
134 if(addr>protocol_info[proto].max_address)
135 throw invalid_argument("ArduControl::add_loco");
137 Locomotive loco(proto, addr);
138 insert_unique(locomotives, loco.id, loco);
143 ArduControl::MfxInfoArray::iterator ArduControl::add_mfx_info(const MfxInfo &info)
145 MfxInfoArray::iterator i;
146 for(i=mfx_info.begin(); (i!=mfx_info.end() && i->id!=info.id); ++i) ;
147 if(i==mfx_info.end())
149 mfx_info.push_back(info);
150 i = --mfx_info.end();
157 void ArduControl::remove_loco(unsigned id)
159 Locomotive &loco = get_item(locomotives, id);
160 refresh.remove_loco(loco);
161 locomotives.erase(id);
164 void ArduControl::set_loco_speed(unsigned id, unsigned speed)
166 Locomotive &loco = get_item(locomotives, id);
167 if(speed>protocol_info[loco.proto].max_speed)
168 throw invalid_argument("ArduControl::set_loco_speed");
173 if(loco.speed.set(speed))
175 PendingCommand cmd(loco, Locomotive::SPEED);
176 command_queue.push(cmd);
178 refresh.add_loco(loco);
182 void ArduControl::set_loco_reverse(unsigned id, bool rev)
184 Locomotive &loco = get_item(locomotives, id);
185 if(loco.reverse.set(rev))
187 PendingCommand cmd(loco, Locomotive::REVERSE);
188 command_queue.push(cmd);
190 refresh.add_loco(loco);
194 void ArduControl::set_loco_function(unsigned id, unsigned func, bool state)
196 Locomotive &loco = get_item(locomotives, id);
197 if(func>protocol_info[loco.proto].max_func)
198 throw invalid_argument("ArduControl::set_loco_function");
200 unsigned mask = 1<<func;
201 if(loco.funcs.set((loco.funcs&~mask)|(mask*state)))
203 if(func>0 || loco.proto!=MM)
205 PendingCommand cmd(loco, Locomotive::FUNCTIONS, func);
206 command_queue.push(cmd);
209 refresh.add_loco(loco);
213 unsigned ArduControl::add_turnout(unsigned addr, const TrackType &type)
215 if(!addr || !type.is_turnout())
216 throw invalid_argument("ArduControl::add_turnout");
218 return add_accessory(Accessory::TURNOUT, addr, type.get_state_bits(), type.get_paths());
221 void ArduControl::remove_turnout(unsigned addr)
223 remove_accessory(Accessory::TURNOUT, addr);
226 void ArduControl::set_turnout(unsigned addr, unsigned state)
228 set_accessory(Accessory::TURNOUT, addr, state);
231 unsigned ArduControl::get_turnout(unsigned addr) const
233 return get_accessory(Accessory::TURNOUT, addr);
236 unsigned ArduControl::add_signal(unsigned addr, const SignalType &)
238 return add_accessory(Accessory::SIGNAL, addr, 1, 3);
241 void ArduControl::remove_signal(unsigned addr)
243 remove_accessory(Accessory::SIGNAL, addr);
246 void ArduControl::set_signal(unsigned addr, unsigned state)
248 set_accessory(Accessory::SIGNAL, addr, state);
251 unsigned ArduControl::get_signal(unsigned addr) const
253 return get_accessory(Accessory::SIGNAL, addr);
256 unsigned ArduControl::add_accessory(Accessory::Kind kind, unsigned addr, unsigned bits, unsigned states)
258 AccessoryMap::iterator i = accessories.lower_bound(addr);
259 AccessoryMap::iterator j = accessories.upper_bound(addr+bits-1);
261 throw key_error(addr);
262 if(i!=accessories.begin())
265 if(i->first+i->second.bits>addr)
266 throw key_error(addr);
269 insert_unique(accessories, addr, Accessory(kind, addr, bits, states));
273 void ArduControl::remove_accessory(Accessory::Kind kind, unsigned addr)
275 Accessory &acc = get_item(accessories, addr);
277 throw key_error(addr);
278 accessories.erase(addr);
281 void ArduControl::set_accessory(Accessory::Kind kind, unsigned addr, unsigned state)
283 Accessory &acc = get_item(accessories, addr);
285 throw key_error(addr);
287 if(state!=acc.target || acc.uncertain)
290 accessory_queue.push_back(&acc);
294 unsigned ArduControl::get_accessory(Accessory::Kind kind, unsigned addr) const
296 const Accessory &acc = get_item(accessories, addr);
298 throw key_error(addr);
302 void ArduControl::activate_accessory_by_mask(Accessory &acc, unsigned mask)
304 unsigned bit = mask&~(mask-1);
305 for(active_index=0; (bit>>active_index)>1; ++active_index) ;
306 acc.state.set((acc.state&~bit)|(acc.target&bit));
308 IO::print("Setting accessory %d bit %d, state=%d\n", acc.address, active_index, acc.state.pending);
309 PendingCommand cmd(acc, Accessory::ACTIVATE, active_index);
310 command_queue.push(cmd);
311 active_accessory = &acc;
313 monitor.reset_peak();
316 unsigned ArduControl::add_sensor(unsigned addr)
319 throw invalid_argument("ArduControl::add_sensor");
321 insert_unique(sensors, addr, Sensor(addr));
322 s88.grow_n_octets((addr+7)/8);
327 void ArduControl::remove_sensor(unsigned addr)
329 remove_existing(sensors, addr);
330 // TODO update s88.n_octets
333 bool ArduControl::get_sensor(unsigned addr) const
335 return get_item(sensors, addr).state;
338 const Driver::TelemetryInfo *ArduControl::enumerate_telemetry(unsigned i) const
341 return telemetry_info+i;
346 float ArduControl::get_telemetry_value(const string &name) const
348 if(name==telemetry_info[0].name)
349 return monitor.get_voltage();
350 else if(name==telemetry_info[1].name)
351 return monitor.get_current();
352 else if(name==telemetry_info[2].name)
353 return command_queue.size();
354 else if(name==telemetry_info[3].name)
355 return s88.get_latency()/Time::msec;
357 throw key_error(name);
360 void ArduControl::tick()
363 while(completed_commands.pop(tag))
365 if(tag.type==Tag::GENERAL)
367 if(tag.command==POWER)
369 if(power.commit(tag.serial))
370 signal_power.emit(power.current);
372 else if(tag.command==NEW_LOCO)
375 if(mfx_search.pop_info(info))
377 MfxInfoArray::iterator i = add_mfx_info(info);
379 signal_locomotive_detected.emit(*i);
383 else if(tag.type==Tag::LOCOMOTIVE)
385 LocomotiveMap::iterator i = locomotives.find(tag.id);
386 if(i==locomotives.end())
389 Locomotive &loco = i->second;
390 if(tag.command==Locomotive::SPEED)
392 if(loco.speed.commit(tag.serial))
393 signal_loco_speed.emit(loco.id, loco.speed, loco.reverse);
395 else if(tag.command==Locomotive::REVERSE)
397 if(loco.reverse.commit(tag.serial))
398 signal_loco_speed.emit(loco.id, loco.speed, loco.reverse);
400 else if(tag.command==Locomotive::FUNCTIONS)
402 unsigned old = loco.funcs;
403 if(loco.funcs.commit(tag.serial))
405 unsigned changed = old^loco.funcs;
406 for(unsigned j=0; changed>>j; ++j)
408 signal_loco_function.emit(loco.id, j, (loco.funcs>>j)&1);
412 else if(tag.type==Tag::ACCESSORY)
414 AccessoryMap::iterator i = accessories.find(tag.id);
415 if(i==accessories.end())
418 Accessory &acc = i->second;
419 if(tag.command==Accessory::ACTIVATE)
420 off_timeout = Time::now()+acc.active_time;
421 else if(tag.command==Accessory::DEACTIVATE)
423 if(acc.state.commit(tag.serial))
425 if(&acc==active_accessory)
426 active_accessory = 0;
430 else if(tag.type==Tag::SENSOR)
432 SensorMap::iterator i = sensors.find(tag.id);
436 Sensor &sensor = i->second;
437 if(tag.command==Sensor::STATE)
439 if(sensor.state.commit(tag.serial))
440 signal_sensor.emit(sensor.address, sensor.state);
445 while(power && !active_accessory && !accessory_queue.empty())
447 Accessory &acc = *accessory_queue.front();
451 unsigned zeroes = acc.uncertain&~acc.target;
453 activate_accessory_by_mask(acc, zeroes);
455 activate_accessory_by_mask(acc, acc.uncertain);
457 else if(acc.state!=acc.target)
459 unsigned changes = acc.state^acc.target;
460 if(!(changes&((1<<acc.bits)-1)))
462 // All remaining changes are in non-physical bits
463 acc.state.set(acc.state^changes);
464 acc.state.commit(acc.state.serial);
468 unsigned toggle_bit = 0;
469 for(unsigned bit=1; (!toggle_bit && bit<=changes); bit<<=1)
470 if((changes&bit) && (acc.valid_states&(1<<(acc.state^bit))))
473 activate_accessory_by_mask(acc, toggle_bit);
478 accessory_queue.pop_front();
480 if(acc.state==acc.target)
482 if(acc.kind==Accessory::TURNOUT)
483 signal_turnout.emit(acc.address, acc.state);
484 else if(acc.kind==Accessory::SIGNAL)
485 signal_signal.emit(acc.address, acc.state);
490 if(active_accessory && off_timeout)
492 bool success = (monitor.get_peak()>0.35f && monitor.get_current()<monitor.get_peak()-0.2f);
493 Time::TimeStamp t = Time::now();
494 if(t>off_timeout || success)
496 Accessory &acc = *active_accessory;
498 unsigned bit = 1<<active_index;
500 // Assume success if we were uncertain of the physical setting
501 if(acc.uncertain&bit)
502 acc.uncertain &= ~bit;
503 else if(acc.kind==Accessory::TURNOUT && !success)
506 IO::print("Peak current only %.2f A\n", monitor.get_peak());
507 signal_turnout_failed.emit(acc.address);
508 acc.state.rollback();
509 if(acc.valid_states&(1<<(acc.target^bit)))
512 acc.target = acc.state;
515 off_timeout = Time::TimeStamp();
516 PendingCommand cmd(acc, Accessory::DEACTIVATE, active_index);
517 command_queue.push(cmd);
522 void ArduControl::flush()
524 while(!command_queue.empty() || (power && !accessory_queue.empty()))
528 void ArduControl::save_state() const
530 FS::RedirectedPath tmp_file(state_file);
531 IO::BufferedFile out(tmp_file.str(), IO::M_WRITE);
532 DataFile::Writer writer(out);
534 writer.write((DataFile::Statement("mfx_announce_serial"), mfx_announce.get_serial()));
535 for(MfxInfoArray::const_iterator i=mfx_info.begin(); i!=mfx_info.end(); ++i)
537 DataFile::Statement st("mfx_locomotive");
539 st.sub.push_back((DataFile::Statement("address"), i->address));
540 st.sub.push_back((DataFile::Statement("name"), i->name));
546 ArduControl::Tag::Tag():
554 ArduControl::Locomotive::Locomotive(Protocol p, unsigned a):
564 unsigned ArduControl::Locomotive::create_speed_dir_command(char *buffer) const
568 buffer[0] = MOTOROLA_SPEED_DIRECTION;
570 buffer[2] = funcs.pending&1;
571 buffer[3] = speed.pending+reverse.pending*0x80;
576 buffer[0] = MFX_SPEED;
577 buffer[1] = address>>8;
579 buffer[3] = speed.pending+reverse.pending*0x80;
586 unsigned ArduControl::Locomotive::create_speed_func_command(unsigned f, char *buffer) const
591 throw invalid_argument("Locomotive::create_speed_func_command");
593 buffer[0] = MOTOROLA_SPEED_FUNCTION;
595 buffer[2] = (f<<4)|(((funcs.pending>>f)&1)<<1)|(funcs.pending&1);
596 buffer[3] = speed.pending;
601 bool f16 = (funcs.pending>0xFF);
602 buffer[0] = (f16 ? MFX_SPEED_FUNCS16 : MFX_SPEED_FUNCS8);
603 buffer[1] = address>>8;
605 buffer[3] = speed.pending+reverse.pending*0x80;
608 buffer[4] = funcs.pending>>8;
609 buffer[5] = funcs.pending;
614 buffer[4] = funcs.pending;
623 ArduControl::Accessory::Accessory(Kind k, unsigned a, unsigned b, unsigned s):
629 uncertain((1<<bits)-1),
631 active_time((bits*700)*Time::msec)
634 unsigned ArduControl::Accessory::create_state_command(unsigned b, bool c, char *buffer) const
637 throw invalid_argument("Accessory::create_state_command");
639 unsigned a = (address+b+3)*2;
640 if(!((state.pending>>b)&1))
642 buffer[0] = MOTOROLA_SOLENOID;
644 buffer[2] = ((a&7)<<4)|c;
649 ArduControl::Sensor::Sensor(unsigned a):
655 ArduControl::PendingCommand::PendingCommand():
660 ArduControl::PendingCommand::PendingCommand(GeneralCommand cmd):
664 tag.type = Tag::GENERAL;
668 ArduControl::PendingCommand::PendingCommand(Locomotive &loco, Locomotive::Command cmd, unsigned index):
671 tag.type = Tag::LOCOMOTIVE;
674 if(cmd==Locomotive::SPEED)
676 tag.serial = loco.speed.serial;
677 length = loco.create_speed_dir_command(command);
679 else if(cmd==Locomotive::REVERSE)
681 tag.serial = loco.reverse.serial;
682 length = loco.create_speed_dir_command(command);
684 else if(cmd==Locomotive::FUNCTIONS)
686 tag.serial = loco.funcs.serial;
687 length = loco.create_speed_func_command(index, command);
690 throw invalid_argument("PendingCommand");
693 ArduControl::PendingCommand::PendingCommand(Accessory &acc, Accessory::Command cmd, unsigned index):
696 tag.type = Tag::ACCESSORY;
698 tag.id = acc.address;
699 if(cmd==Accessory::ACTIVATE || cmd==Accessory::DEACTIVATE)
701 tag.serial = acc.state.serial;
702 length = acc.create_state_command(index, (cmd==Accessory::ACTIVATE), command);
705 throw invalid_argument("PendingCommand");
710 void ArduControl::Queue<T>::push(const T &item)
712 MutexLock lock(mutex);
713 items.push_back(item);
717 bool ArduControl::Queue<T>::pop(T &item)
719 MutexLock lock(mutex);
723 item = items.front();
729 unsigned ArduControl::Queue<T>::size() const
735 bool ArduControl::Queue<T>::empty() const
737 return items.empty();
741 bool ArduControl::CommandQueueTask::get_work(PendingCommand &cmd)
743 return queue.pop(cmd);
746 void ArduControl::CommandQueueTask::push(const PendingCommand &cmd)
752 ArduControl::Task::Task(const string &n, unsigned p):
757 void ArduControl::Task::sleep(const Time::TimeDelta &dt)
759 sleep_timeout = Time::now()+dt;
763 ArduControl::CommandQueueTask::CommandQueueTask():
768 ArduControl::RefreshTask::RefreshTask():
776 bool ArduControl::RefreshTask::get_work(PendingCommand &cmd)
778 if(loco && loco->proto==MM && phase==0)
780 cmd.length = loco->create_speed_func_command(round%4+1, cmd.command);
781 cmd.repeat_count = 2;
786 loco = get_next_loco();
793 cmd.length = loco->create_speed_dir_command(cmd.command);
794 cmd.repeat_count = 2;
796 else if(loco->proto==MFX)
797 cmd.length = loco->create_speed_func_command(0, cmd.command);
804 void ArduControl::RefreshTask::add_loco(Locomotive &l)
806 MutexLock lock(mutex);
810 LocomotivePtrList::iterator oldest = cycle.begin();
811 for(LocomotivePtrList::iterator i=cycle.begin(); ++i!=cycle.end(); )
812 if((*i)->last_change_age>(*oldest)->last_change_age)
818 if(next==cycle.end())
819 next = cycle.begin();
822 void ArduControl::RefreshTask::remove_loco(Locomotive &l)
824 MutexLock lock(mutex);
825 for(LocomotivePtrList::iterator i=cycle.begin(); i!=cycle.end(); ++i)
840 ArduControl::Locomotive *ArduControl::RefreshTask::get_next_loco()
842 MutexLock lock(mutex);
846 Locomotive *l = *next;
851 void ArduControl::RefreshTask::advance()
854 if(next==cycle.end())
856 next = cycle.begin();
862 ArduControl::S88Task::S88Task(ArduControl &c):
869 bool ArduControl::S88Task::get_work(PendingCommand &cmd)
871 if(octets_remaining || !n_octets)
874 Time::TimeStamp t = Time::now();
876 latency = t-last_poll;
879 octets_remaining = n_octets;
880 cmd.command[0] = S88_READ;
881 cmd.command[1] = octets_remaining;
884 sleep(100*Time::msec);
889 void ArduControl::S88Task::process_reply(const char *reply, unsigned length)
891 unsigned char type = reply[0];
892 if(type==S88_DATA && length>2)
894 unsigned offset = static_cast<unsigned char>(reply[1]);
895 unsigned count = length-2;
897 SensorMap::iterator begin = control.sensors.lower_bound(offset*8+1);
898 SensorMap::iterator end = control.sensors.upper_bound((offset+count)*8);
899 for(SensorMap::iterator i=begin; i!=end; ++i)
901 unsigned bit_index = i->first-1-offset*8;
902 bool state = (reply[2+bit_index/8]>>(7-bit_index%8))&1;
903 i->second.state.set(state);
906 tag.type = Tag::SENSOR;
907 tag.command = Sensor::STATE;
908 tag.serial = i->second.state.serial;
910 control.completed_commands.push(tag);
913 if(count>octets_remaining)
914 octets_remaining = 0;
916 octets_remaining -= count;
920 void ArduControl::S88Task::set_n_octets(unsigned n)
925 void ArduControl::S88Task::grow_n_octets(unsigned n)
932 ArduControl::MfxAnnounceTask::MfxAnnounceTask():
933 Task("MfxAnnounce", 1),
937 bool ArduControl::MfxAnnounceTask::get_work(PendingCommand &cmd)
939 cmd.command[0] = MFX_ANNOUNCE;
940 cmd.command[1] = serial>>8;
941 cmd.command[2] = serial;
944 sleep(400*Time::msec);
949 void ArduControl::MfxAnnounceTask::set_serial(unsigned s)
955 ArduControl::MfxSearchTask::MfxSearchTask(ArduControl &c):
956 Task("MfxSearch", 1),
964 bool ArduControl::MfxSearchTask::get_work(PendingCommand &cmd)
969 IO::print("Assigning MFX address %d to decoder %08X\n", next_address, bits);
972 info.protocol = "MFX";
973 info.address = next_address;
974 info.name = format("%08X", bits);
978 cmd.command[0] = MFX_ASSIGN_ADDRESS;
979 cmd.command[1] = next_address>>8;
980 cmd.command[2] = next_address;
981 for(unsigned i=0; i<4; ++i)
982 cmd.command[3+i] = bits>>(24-i*8);
985 cmd.tag.type = Tag::GENERAL;
986 cmd.tag.command = NEW_LOCO;
996 cmd.command[0] = MFX_SEARCH;
997 for(unsigned i=0; i<4; ++i)
998 cmd.command[1+i] = bits>>(24-i*8);
999 cmd.command[5] = size;
1002 sleep(200*Time::msec);
1004 if(control.debug>=1)
1005 IO::print("Search %08X/%d\n", bits, size);
1010 void ArduControl::MfxSearchTask::process_reply(const char *reply, unsigned length)
1012 unsigned char type = reply[0];
1013 if(type==MFX_SEARCH_FEEDBACK && length==2)
1020 else if(size>0 && misses<6)
1023 bits ^= 1<<(32-size);
1035 void ArduControl::MfxSearchTask::set_next_address(unsigned a)
1040 bool ArduControl::MfxSearchTask::pop_info(MfxInfo &info)
1042 return queue.pop(info);
1046 ArduControl::MonitorTask::MonitorTask():
1055 bool ArduControl::MonitorTask::get_work(PendingCommand &cmd)
1058 cmd.command[0] = READ_INPUT_VOLTAGE;
1060 cmd.command[0] = READ_TRACK_CURRENT;
1063 sleep(200*Time::msec);
1064 next_type = (next_type+1)%5;
1069 void ArduControl::MonitorTask::process_reply(const char *reply, unsigned length)
1071 unsigned char type = reply[0];
1072 if(type==INPUT_VOLTAGE && length==3)
1073 voltage = ((static_cast<unsigned char>(reply[1])<<8) | static_cast<unsigned char>(reply[2]))/1000.0f;
1074 else if(type==TRACK_CURRENT && length==5)
1076 current = ((static_cast<unsigned char>(reply[1])<<8) | static_cast<unsigned char>(reply[2]))/1000.0f;
1077 float peak = ((static_cast<unsigned char>(reply[3])<<8) | static_cast<unsigned char>(reply[4]))/1000.0f;
1078 peak_level = max(peak_level, peak);
1079 base_level = min(base_level, current);
1083 void ArduControl::MonitorTask::reset_peak()
1085 base_level = current;
1086 peak_level = current;
1090 ArduControl::ControlThread::ControlThread(ArduControl &c):
1094 tasks.push_back(&control.command_queue);
1095 tasks.push_back(&control.monitor);
1096 tasks.push_back(&control.mfx_announce);
1097 tasks.push_back(&control.mfx_search);
1098 tasks.push_back(&control.s88);
1099 tasks.push_back(&control.refresh);
1104 void ArduControl::ControlThread::exit()
1110 void ArduControl::ControlThread::main()
1119 bool success = true;
1120 bool resync = false;
1121 for(unsigned i=0; (success && i<cmd.repeat_count); ++i)
1123 unsigned result = do_command(cmd, control.command_timeout);
1124 success = (result==COMMAND_OK);
1125 resync = (result==0);
1128 if(success && cmd.tag)
1129 control.completed_commands.push(cmd.tag);
1133 if(control.debug>=1)
1134 IO::print("Synchronization with ArduControl lost, attempting to recover\n");
1135 for(unsigned i=0; (resync && i<16); ++i)
1137 control.serial.put('\xFF');
1138 while(IO::poll(control.serial, IO::P_INPUT, control.command_timeout))
1139 resync = (control.serial.get()!=0xFF);
1143 if(control.debug>=1)
1144 IO::print("Resynchronization failed, giving up\n");
1149 if(control.debug>=1)
1150 IO::print("Resynchronization successful\n");
1152 control.command_queue.push(cmd);
1157 Time::sleep(10*Time::msec);
1161 void ArduControl::ControlThread::init_baud_rate()
1163 static unsigned rates[] = { 57600, 9600, 19200, 38400, 0 };
1165 control.serial.set_data_bits(8);
1166 control.serial.set_parity(IO::Serial::NONE);
1167 control.serial.set_stop_bits(1);
1168 for(unsigned i=0; rates[i]; ++i)
1170 control.serial.set_baud_rate(rates[i]);
1171 control.serial.put('\xFF');
1172 if(IO::poll(control.serial, IO::P_INPUT, 500*Time::msec))
1174 int c = control.serial.get();
1185 if(control.debug>=1)
1186 IO::print("ArduControl detection failed\n");
1191 if(control.debug>=1)
1192 IO::print("ArduControl detected at %d bits/s\n", rate);
1197 cmd.command[0] = SET_BAUD_RATE;
1198 cmd.command[1] = rates[0]>>8;
1199 cmd.command[2] = rates[0];
1201 if(do_command(cmd, Time::sec)==COMMAND_OK)
1203 control.serial.set_baud_rate(rates[0]);
1204 Time::sleep(Time::sec);
1205 if(do_command(cmd, Time::sec)==COMMAND_OK)
1207 if(control.debug>=1)
1208 IO::print("Rate changed to %d bits/s\n", rates[0]);
1214 bool ArduControl::ControlThread::get_work(PendingCommand &cmd)
1216 Time::TimeStamp t = Time::now();
1219 for(; (count<tasks.size() && tasks[count]->get_sleep_timeout()<=t); ++count) ;
1221 for(; count>0; --count)
1224 for(unsigned j=1; j<count; ++j)
1225 if(tasks[j]->get_priority()<tasks[i]->get_priority())
1228 Task *task = tasks[i];
1229 bool result = task->get_work(cmd);
1231 Time::TimeStamp st = max(task->get_sleep_timeout(), t);
1232 for(; (i+1<tasks.size() && tasks[i+1]->get_sleep_timeout()<=st); ++i)
1233 tasks[i] = tasks[i+1];
1238 if(control.debug>=2)
1239 IO::print("Scheduled task %s\n", task->get_name());
1244 // As fallback, send an idle packet for the MM protocol
1245 cmd.command[0] = MOTOROLA_SPEED;
1246 cmd.command[1] = 80;
1254 unsigned ArduControl::ControlThread::do_command(const PendingCommand &cmd, const Time::TimeDelta &timeout)
1256 if(control.debug>=2)
1259 for(unsigned i=0; i<cmd.length; ++i)
1260 cmd_hex += format(" %02X", static_cast<unsigned char>(cmd.command[i]));
1261 IO::print("< %02X%s\n", cmd.length^0xFF, cmd_hex);
1264 control.serial.put(cmd.length^0xFF);
1265 control.serial.write(cmd.command, cmd.length);
1267 unsigned result = 0;
1272 got_data = IO::poll(control.serial, IO::P_INPUT, Time::zero);
1274 got_data = IO::poll(control.serial, IO::P_INPUT, timeout);
1279 unsigned rlength = control.serial.get()^0xFF;
1282 IO::print("Invalid length %02X\n", rlength);
1290 if(!IO::poll(control.serial, IO::P_INPUT, timeout))
1292 pos += control.serial.read(reply+pos, rlength-pos);
1295 if(control.debug>=2)
1298 for(unsigned i=0; i<rlength; ++i)
1299 reply_hex += format(" %02X", static_cast<unsigned char>(reply[i]));
1300 IO::print("> %02X%s\n", rlength^0xFF, reply_hex);
1303 unsigned r = process_reply(reply, rlength);
1311 unsigned ArduControl::ControlThread::process_reply(const char *reply, unsigned rlength)
1313 unsigned char type = reply[0];
1314 if((type&0xE0)==0x80)
1316 if(type!=COMMAND_OK)
1317 IO::print("Error %02X\n", type);
1320 else if(type==POWER_STATE && rlength==2)
1321 set_power(reply[1]);
1322 else if(type==OVERCURRENT)
1325 IO::print("Overcurrent detected!\n");
1329 for(vector<Task *>::iterator i=tasks.begin(); i!=tasks.end(); ++i)
1330 (*i)->process_reply(reply, rlength);
1336 void ArduControl::ControlThread::set_power(bool p)
1338 control.power.set(p);
1341 tag.type = Tag::GENERAL;
1342 tag.command = POWER;
1343 tag.serial = control.power.serial;
1344 control.completed_commands.push(tag);
1348 ArduControl::Loader::Loader(ArduControl &c):
1349 DataFile::ObjectLoader<ArduControl>(c)
1351 add("mfx_announce_serial", &Loader::mfx_announce_serial);
1352 add("mfx_locomotive", &Loader::mfx_locomotive);
1355 void ArduControl::Loader::mfx_announce_serial(unsigned s)
1357 obj.mfx_announce.set_serial(s);
1360 void ArduControl::Loader::mfx_locomotive(unsigned id)
1364 info.protocol = "MFX";
1366 obj.add_mfx_info(info);
1370 ArduControl::MfxInfo::Loader::Loader(MfxInfo &i):
1371 DataFile::ObjectLoader<MfxInfo>(i)
1373 add("address", static_cast<unsigned MfxInfo::*>(&MfxInfo::address));
1374 add("name", static_cast<string MfxInfo::*>(&MfxInfo::name));