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 ArduControl::ArduControl(const Options &opts):
22 serial(opts.get<string>(string(), "ttyUSB0")),
23 debug(opts.get<unsigned>("debug")),
24 state_file("arducontrol.state"),
28 command_timeout(200*Time::msec),
33 if(FS::exists(state_file))
34 DataFile::load(*this, state_file.str());
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);
42 cmd.command[0] = READ_POWER_STATE;
44 command_queue.push(cmd);
46 cmd.command[0] = MFX_SET_STATION_ID;
52 command_queue.push(cmd);
55 ArduControl::~ArduControl()
60 void ArduControl::set_power(bool p)
64 PendingCommand cmd(POWER);
65 cmd.tag.serial = power.serial;
66 cmd.command[0] = (p ? POWER_ON : POWER_OFF);
68 command_queue.push(cmd);
72 void ArduControl::halt(bool h)
80 for(LocomotiveMap::const_iterator i=locomotives.begin(); i!=locomotives.end(); ++i)
81 set_loco_speed(i->first, 0);
84 signal_halt.emit(halted);
87 const char *ArduControl::enumerate_protocols(unsigned i) const
97 ArduControl::Protocol ArduControl::map_protocol(const string &proto_name)
101 else if(proto_name=="MFX")
104 throw invalid_argument("ArduControl::map_protocol");
107 unsigned ArduControl::get_protocol_speed_steps(const string &proto_name) const
109 return protocol_info[map_protocol(proto_name)].max_speed;
112 const Driver::DetectedLocomotive *ArduControl::enumerate_detected_locos(unsigned i) const
114 if(i>=mfx_info.size())
120 unsigned ArduControl::add_loco(unsigned addr, const string &proto_name, const VehicleType &)
123 throw invalid_argument("ArduControl::add_loco");
125 Protocol proto = map_protocol(proto_name);
126 if(addr>protocol_info[proto].max_address)
127 throw invalid_argument("ArduControl::add_loco");
129 Locomotive loco(proto, addr);
130 insert_unique(locomotives, loco.id, loco);
135 ArduControl::MfxInfoArray::iterator ArduControl::add_mfx_info(const MfxInfo &info)
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())
141 mfx_info.push_back(info);
142 i = --mfx_info.end();
149 void ArduControl::remove_loco(unsigned id)
151 Locomotive &loco = get_item(locomotives, id);
152 refresh.remove_loco(loco);
153 locomotives.erase(id);
156 void ArduControl::set_loco_speed(unsigned id, unsigned speed)
158 Locomotive &loco = get_item(locomotives, id);
159 if(speed>protocol_info[loco.proto].max_speed)
160 throw invalid_argument("ArduControl::set_loco_speed");
165 if(loco.speed.set(speed))
167 PendingCommand cmd(loco, Locomotive::SPEED);
168 command_queue.push(cmd);
170 refresh.add_loco(loco);
174 void ArduControl::set_loco_reverse(unsigned id, bool rev)
176 Locomotive &loco = get_item(locomotives, id);
177 if(loco.reverse.set(rev))
179 PendingCommand cmd(loco, Locomotive::REVERSE);
180 command_queue.push(cmd);
182 refresh.add_loco(loco);
186 void ArduControl::set_loco_function(unsigned id, unsigned func, bool state)
188 Locomotive &loco = get_item(locomotives, id);
189 if(func>protocol_info[loco.proto].max_func)
190 throw invalid_argument("ArduControl::set_loco_function");
192 unsigned mask = 1<<func;
193 if(loco.funcs.set((loco.funcs&~mask)|(mask*state)))
195 if(func>0 || loco.proto!=MM)
197 PendingCommand cmd(loco, Locomotive::FUNCTIONS, func);
198 command_queue.push(cmd);
201 refresh.add_loco(loco);
205 unsigned ArduControl::add_turnout(unsigned addr, const TrackType &type)
207 if(!addr || !type.is_turnout())
208 throw invalid_argument("ArduControl::add_turnout");
210 return add_accessory(Accessory::TURNOUT, addr, type.get_state_bits(), type.get_paths());
213 void ArduControl::remove_turnout(unsigned addr)
215 remove_accessory(Accessory::TURNOUT, addr);
218 void ArduControl::set_turnout(unsigned addr, unsigned state)
220 set_accessory(Accessory::TURNOUT, addr, state);
223 unsigned ArduControl::get_turnout(unsigned addr) const
225 return get_accessory(Accessory::TURNOUT, addr);
228 unsigned ArduControl::add_signal(unsigned addr, const SignalType &)
230 return add_accessory(Accessory::SIGNAL, addr, 1, 3);
233 void ArduControl::remove_signal(unsigned addr)
235 remove_accessory(Accessory::SIGNAL, addr);
238 void ArduControl::set_signal(unsigned addr, unsigned state)
240 set_accessory(Accessory::SIGNAL, addr, state);
243 unsigned ArduControl::get_signal(unsigned addr) const
245 return get_accessory(Accessory::SIGNAL, addr);
248 unsigned ArduControl::add_accessory(Accessory::Kind kind, unsigned addr, unsigned bits, unsigned states)
250 AccessoryMap::iterator i = accessories.lower_bound(addr);
251 AccessoryMap::iterator j = accessories.upper_bound(addr+bits-1);
253 throw key_error(addr);
254 if(i!=accessories.begin())
257 if(i->first+i->second.bits>addr)
258 throw key_error(addr);
261 insert_unique(accessories, addr, Accessory(kind, addr, bits, states));
265 void ArduControl::remove_accessory(Accessory::Kind kind, unsigned addr)
267 Accessory &acc = get_item(accessories, addr);
269 throw key_error(addr);
270 accessories.erase(addr);
273 void ArduControl::set_accessory(Accessory::Kind kind, unsigned addr, unsigned state)
275 Accessory &acc = get_item(accessories, addr);
277 throw key_error(addr);
279 if(state!=acc.target || acc.uncertain)
282 accessory_queue.push_back(&acc);
286 unsigned ArduControl::get_accessory(Accessory::Kind kind, unsigned addr) const
288 const Accessory &acc = get_item(accessories, addr);
290 throw key_error(addr);
294 void ArduControl::activate_accessory_by_mask(Accessory &acc, unsigned mask)
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));
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;
305 monitor.reset_peak();
308 unsigned ArduControl::add_sensor(unsigned addr)
311 throw invalid_argument("ArduControl::add_sensor");
313 insert_unique(sensors, addr, Sensor(addr));
314 s88.grow_n_octets((addr+7)/8);
319 void ArduControl::remove_sensor(unsigned addr)
321 remove_existing(sensors, addr);
322 // TODO update s88.n_octets
325 bool ArduControl::get_sensor(unsigned addr) const
327 return get_item(sensors, addr).state;
330 float ArduControl::get_telemetry_value(const string &name) const
332 throw key_error(name);
335 void ArduControl::tick()
338 while(completed_commands.pop(tag))
340 if(tag.type==Tag::GENERAL)
342 if(tag.command==POWER)
344 if(power.commit(tag.serial))
345 signal_power.emit(power.current);
347 else if(tag.command==NEW_LOCO)
350 if(mfx_search.pop_info(info))
352 MfxInfoArray::iterator i = add_mfx_info(info);
354 signal_locomotive_detected.emit(*i);
358 else if(tag.type==Tag::LOCOMOTIVE)
360 LocomotiveMap::iterator i = locomotives.find(tag.id);
361 if(i==locomotives.end())
364 Locomotive &loco = i->second;
365 if(tag.command==Locomotive::SPEED)
367 if(loco.speed.commit(tag.serial))
368 signal_loco_speed.emit(loco.id, loco.speed, loco.reverse);
370 else if(tag.command==Locomotive::REVERSE)
372 if(loco.reverse.commit(tag.serial))
373 signal_loco_speed.emit(loco.id, loco.speed, loco.reverse);
375 else if(tag.command==Locomotive::FUNCTIONS)
377 unsigned old = loco.funcs;
378 if(loco.funcs.commit(tag.serial))
380 unsigned changed = old^loco.funcs;
381 for(unsigned j=0; changed>>j; ++j)
383 signal_loco_function.emit(loco.id, j, (loco.funcs>>j)&1);
387 else if(tag.type==Tag::ACCESSORY)
389 AccessoryMap::iterator i = accessories.find(tag.id);
390 if(i==accessories.end())
393 Accessory &acc = i->second;
394 if(tag.command==Accessory::ACTIVATE)
395 off_timeout = Time::now()+acc.active_time;
396 else if(tag.command==Accessory::DEACTIVATE)
398 if(acc.state.commit(tag.serial))
400 if(&acc==active_accessory)
401 active_accessory = 0;
405 else if(tag.type==Tag::SENSOR)
407 SensorMap::iterator i = sensors.find(tag.id);
411 Sensor &sensor = i->second;
412 if(tag.command==Sensor::STATE)
414 if(sensor.state.commit(tag.serial))
415 signal_sensor.emit(sensor.address, sensor.state);
420 while(power && !active_accessory && !accessory_queue.empty())
422 Accessory &acc = *accessory_queue.front();
426 unsigned zeroes = acc.uncertain&~acc.target;
428 activate_accessory_by_mask(acc, zeroes);
430 activate_accessory_by_mask(acc, acc.uncertain);
432 else if(acc.state!=acc.target)
434 unsigned changes = acc.state^acc.target;
435 if(!(changes&((1<<acc.bits)-1)))
437 // All remaining changes are in non-physical bits
438 acc.state.set(acc.state^changes);
439 acc.state.commit(acc.state.serial);
443 unsigned toggle_bit = 0;
444 for(unsigned bit=1; (!toggle_bit && bit<=changes); bit<<=1)
445 if((changes&bit) && (acc.valid_states&(1<<(acc.state^bit))))
448 activate_accessory_by_mask(acc, toggle_bit);
453 accessory_queue.pop_front();
455 if(acc.state==acc.target)
457 if(acc.kind==Accessory::TURNOUT)
458 signal_turnout.emit(acc.address, acc.state);
459 else if(acc.kind==Accessory::SIGNAL)
460 signal_signal.emit(acc.address, acc.state);
465 if(active_accessory && off_timeout)
467 bool success = (monitor.get_peak()>0.35f && monitor.get_current()<monitor.get_peak()-0.2f);
468 Time::TimeStamp t = Time::now();
469 if(t>off_timeout || success)
471 Accessory &acc = *active_accessory;
473 unsigned bit = 1<<active_index;
475 // Assume success if we were uncertain of the physical setting
476 if(acc.uncertain&bit)
477 acc.uncertain &= ~bit;
478 else if(acc.kind==Accessory::TURNOUT && !success)
481 IO::print("Peak current only %.2f A\n", monitor.get_peak());
482 signal_turnout_failed.emit(acc.address);
483 acc.state.rollback();
484 if(acc.valid_states&(1<<(acc.target^bit)))
487 acc.target = acc.state;
490 off_timeout = Time::TimeStamp();
491 PendingCommand cmd(acc, Accessory::DEACTIVATE, active_index);
492 command_queue.push(cmd);
497 void ArduControl::flush()
499 while(!command_queue.empty() || (power && !accessory_queue.empty()))
503 void ArduControl::save_state() const
505 FS::RedirectedPath tmp_file(state_file);
506 IO::BufferedFile out(tmp_file.str(), IO::M_WRITE);
507 DataFile::Writer writer(out);
509 writer.write((DataFile::Statement("mfx_announce_serial"), mfx_announce.get_serial()));
510 for(MfxInfoArray::const_iterator i=mfx_info.begin(); i!=mfx_info.end(); ++i)
512 DataFile::Statement st("mfx_locomotive");
514 st.sub.push_back((DataFile::Statement("address"), i->address));
515 st.sub.push_back((DataFile::Statement("name"), i->name));
521 ArduControl::Tag::Tag():
529 ArduControl::Locomotive::Locomotive(Protocol p, unsigned a):
539 unsigned ArduControl::Locomotive::create_speed_dir_command(char *buffer) const
543 buffer[0] = MOTOROLA_SPEED_DIRECTION;
545 buffer[2] = funcs.pending&1;
546 buffer[3] = speed.pending+reverse.pending*0x80;
551 buffer[0] = MFX_SPEED;
552 buffer[1] = address>>8;
554 buffer[3] = speed.pending+reverse.pending*0x80;
561 unsigned ArduControl::Locomotive::create_speed_func_command(unsigned f, char *buffer) const
566 throw invalid_argument("Locomotive::create_speed_func_command");
568 buffer[0] = MOTOROLA_SPEED_FUNCTION;
570 buffer[2] = (f<<4)|(((funcs.pending>>f)&1)<<1)|(funcs.pending&1);
571 buffer[3] = speed.pending;
576 bool f16 = (funcs.pending>0xFF);
577 buffer[0] = (f16 ? MFX_SPEED_FUNCS16 : MFX_SPEED_FUNCS8);
578 buffer[1] = address>>8;
580 buffer[3] = speed.pending+reverse.pending*0x80;
583 buffer[4] = funcs.pending>>8;
584 buffer[5] = funcs.pending;
589 buffer[4] = funcs.pending;
598 ArduControl::Accessory::Accessory(Kind k, unsigned a, unsigned b, unsigned s):
604 uncertain((1<<bits)-1),
606 active_time((bits*700)*Time::msec)
609 unsigned ArduControl::Accessory::create_state_command(unsigned b, bool c, char *buffer) const
612 throw invalid_argument("Accessory::create_state_command");
614 unsigned a = (address+b+3)*2;
615 if(!((state.pending>>b)&1))
617 buffer[0] = MOTOROLA_SOLENOID;
619 buffer[2] = ((a&7)<<4)|c;
624 ArduControl::Sensor::Sensor(unsigned a):
630 ArduControl::PendingCommand::PendingCommand():
635 ArduControl::PendingCommand::PendingCommand(GeneralCommand cmd):
639 tag.type = Tag::GENERAL;
643 ArduControl::PendingCommand::PendingCommand(Locomotive &loco, Locomotive::Command cmd, unsigned index):
646 tag.type = Tag::LOCOMOTIVE;
649 if(cmd==Locomotive::SPEED)
651 tag.serial = loco.speed.serial;
652 length = loco.create_speed_dir_command(command);
654 else if(cmd==Locomotive::REVERSE)
656 tag.serial = loco.reverse.serial;
657 length = loco.create_speed_dir_command(command);
659 else if(cmd==Locomotive::FUNCTIONS)
661 tag.serial = loco.funcs.serial;
662 length = loco.create_speed_func_command(index, command);
665 throw invalid_argument("PendingCommand");
668 ArduControl::PendingCommand::PendingCommand(Accessory &acc, Accessory::Command cmd, unsigned index):
671 tag.type = Tag::ACCESSORY;
673 tag.id = acc.address;
674 if(cmd==Accessory::ACTIVATE || cmd==Accessory::DEACTIVATE)
676 tag.serial = acc.state.serial;
677 length = acc.create_state_command(index, (cmd==Accessory::ACTIVATE), command);
680 throw invalid_argument("PendingCommand");
685 void ArduControl::Queue<T>::push(const T &item)
687 MutexLock lock(mutex);
688 items.push_back(item);
692 bool ArduControl::Queue<T>::pop(T &item)
694 MutexLock lock(mutex);
698 item = items.front();
704 bool ArduControl::Queue<T>::empty() const
706 return items.empty();
710 bool ArduControl::CommandQueueTask::get_work(PendingCommand &cmd)
712 return queue.pop(cmd);
715 void ArduControl::CommandQueueTask::push(const PendingCommand &cmd)
721 ArduControl::Task::Task(const string &n, unsigned p):
726 void ArduControl::Task::sleep(const Time::TimeDelta &dt)
728 sleep_timeout = Time::now()+dt;
732 ArduControl::CommandQueueTask::CommandQueueTask():
737 ArduControl::RefreshTask::RefreshTask():
745 bool ArduControl::RefreshTask::get_work(PendingCommand &cmd)
747 if(loco && loco->proto==MM && phase==0)
749 cmd.length = loco->create_speed_func_command(round%4+1, cmd.command);
750 cmd.repeat_count = 2;
755 loco = get_next_loco();
762 cmd.length = loco->create_speed_dir_command(cmd.command);
763 cmd.repeat_count = 2;
765 else if(loco->proto==MFX)
766 cmd.length = loco->create_speed_func_command(0, cmd.command);
773 void ArduControl::RefreshTask::add_loco(Locomotive &l)
775 MutexLock lock(mutex);
779 LocomotivePtrList::iterator oldest = cycle.begin();
780 for(LocomotivePtrList::iterator i=cycle.begin(); ++i!=cycle.end(); )
781 if((*i)->last_change_age>(*oldest)->last_change_age)
787 if(next==cycle.end())
788 next = cycle.begin();
791 void ArduControl::RefreshTask::remove_loco(Locomotive &l)
793 MutexLock lock(mutex);
794 for(LocomotivePtrList::iterator i=cycle.begin(); i!=cycle.end(); ++i)
809 ArduControl::Locomotive *ArduControl::RefreshTask::get_next_loco()
811 MutexLock lock(mutex);
815 Locomotive *l = *next;
820 void ArduControl::RefreshTask::advance()
823 if(next==cycle.end())
831 ArduControl::S88Task::S88Task(ArduControl &c):
838 bool ArduControl::S88Task::get_work(PendingCommand &cmd)
840 if(octets_remaining || !n_octets)
843 octets_remaining = n_octets;
844 cmd.command[0] = S88_READ;
845 cmd.command[1] = octets_remaining;
848 sleep(100*Time::msec);
853 void ArduControl::S88Task::process_reply(const char *reply, unsigned length)
855 unsigned char type = reply[0];
856 if(type==S88_DATA && length>2)
858 unsigned offset = static_cast<unsigned char>(reply[1]);
859 unsigned count = length-2;
861 SensorMap::iterator begin = control.sensors.lower_bound(offset*8+1);
862 SensorMap::iterator end = control.sensors.upper_bound((offset+count)*8);
863 for(SensorMap::iterator i=begin; i!=end; ++i)
865 unsigned bit_index = i->first-1-offset*8;
866 bool state = (reply[2+bit_index/8]>>(7-bit_index%8))&1;
867 i->second.state.set(state);
870 tag.type = Tag::SENSOR;
871 tag.command = Sensor::STATE;
872 tag.serial = i->second.state.serial;
874 control.completed_commands.push(tag);
877 if(count>octets_remaining)
878 octets_remaining = 0;
880 octets_remaining -= count;
884 void ArduControl::S88Task::set_n_octets(unsigned n)
889 void ArduControl::S88Task::grow_n_octets(unsigned n)
896 ArduControl::MfxAnnounceTask::MfxAnnounceTask():
897 Task("MfxAnnounce", 1),
901 bool ArduControl::MfxAnnounceTask::get_work(PendingCommand &cmd)
903 cmd.command[0] = MFX_ANNOUNCE;
904 cmd.command[1] = serial>>8;
905 cmd.command[2] = serial;
908 sleep(400*Time::msec);
913 void ArduControl::MfxAnnounceTask::set_serial(unsigned s)
919 ArduControl::MfxSearchTask::MfxSearchTask(ArduControl &c):
920 Task("MfxSearch", 1),
928 bool ArduControl::MfxSearchTask::get_work(PendingCommand &cmd)
933 IO::print("Assigning MFX address %d to decoder %08X\n", next_address, bits);
936 info.protocol = "MFX";
937 info.address = next_address;
938 info.name = format("%08X", bits);
942 cmd.command[0] = MFX_ASSIGN_ADDRESS;
943 cmd.command[1] = next_address>>8;
944 cmd.command[2] = next_address;
945 for(unsigned i=0; i<4; ++i)
946 cmd.command[3+i] = bits>>(24-i*8);
949 cmd.tag.type = Tag::GENERAL;
950 cmd.tag.command = NEW_LOCO;
960 cmd.command[0] = MFX_SEARCH;
961 for(unsigned i=0; i<4; ++i)
962 cmd.command[1+i] = bits>>(24-i*8);
963 cmd.command[5] = size;
966 sleep(200*Time::msec);
969 IO::print("Search %08X/%d\n", bits, size);
974 void ArduControl::MfxSearchTask::process_reply(const char *reply, unsigned length)
976 unsigned char type = reply[0];
977 if(type==MFX_SEARCH_FEEDBACK && length==2)
984 else if(size>0 && misses<6)
987 bits ^= 1<<(32-size);
999 void ArduControl::MfxSearchTask::set_next_address(unsigned a)
1004 bool ArduControl::MfxSearchTask::pop_info(MfxInfo &info)
1006 return queue.pop(info);
1010 ArduControl::MonitorTask::MonitorTask():
1019 bool ArduControl::MonitorTask::get_work(PendingCommand &cmd)
1022 cmd.command[0] = READ_INPUT_VOLTAGE;
1024 cmd.command[0] = READ_TRACK_CURRENT;
1027 sleep(200*Time::msec);
1028 next_type = (next_type+1)%5;
1033 void ArduControl::MonitorTask::process_reply(const char *reply, unsigned length)
1035 unsigned char type = reply[0];
1036 if(type==INPUT_VOLTAGE && length==3)
1037 voltage = ((static_cast<unsigned char>(reply[1])<<8) | static_cast<unsigned char>(reply[2]))/1000.0f;
1038 else if(type==TRACK_CURRENT && length==5)
1040 current = ((static_cast<unsigned char>(reply[1])<<8) | static_cast<unsigned char>(reply[2]))/1000.0f;
1041 float peak = ((static_cast<unsigned char>(reply[3])<<8) | static_cast<unsigned char>(reply[4]))/1000.0f;
1042 peak_level = max(peak_level, peak);
1043 base_level = min(base_level, current);
1047 void ArduControl::MonitorTask::reset_peak()
1049 base_level = current;
1050 peak_level = current;
1054 ArduControl::ControlThread::ControlThread(ArduControl &c):
1058 tasks.push_back(&control.command_queue);
1059 tasks.push_back(&control.monitor);
1060 tasks.push_back(&control.mfx_announce);
1061 tasks.push_back(&control.mfx_search);
1062 tasks.push_back(&control.s88);
1063 tasks.push_back(&control.refresh);
1068 void ArduControl::ControlThread::exit()
1074 void ArduControl::ControlThread::main()
1083 bool success = true;
1084 bool resync = false;
1085 for(unsigned i=0; (success && i<cmd.repeat_count); ++i)
1087 unsigned result = do_command(cmd, control.command_timeout);
1088 success = (result==COMMAND_OK);
1089 resync = (result==0);
1092 if(success && cmd.tag)
1093 control.completed_commands.push(cmd.tag);
1097 if(control.debug>=1)
1098 IO::print("Synchronization with ArduControl lost, attempting to recover\n");
1099 for(unsigned i=0; (resync && i<16); ++i)
1101 control.serial.put('\xFF');
1102 while(IO::poll(control.serial, IO::P_INPUT, control.command_timeout))
1103 resync = (control.serial.get()!=0xFF);
1107 if(control.debug>=1)
1108 IO::print("Resynchronization failed, giving up\n");
1113 if(control.debug>=1)
1114 IO::print("Resynchronization successful\n");
1116 control.command_queue.push(cmd);
1121 Time::sleep(10*Time::msec);
1125 void ArduControl::ControlThread::init_baud_rate()
1127 static unsigned rates[] = { 57600, 9600, 19200, 38400, 0 };
1129 control.serial.set_data_bits(8);
1130 control.serial.set_parity(IO::Serial::NONE);
1131 control.serial.set_stop_bits(1);
1132 for(unsigned i=0; rates[i]; ++i)
1134 control.serial.set_baud_rate(rates[i]);
1135 control.serial.put('\xFF');
1136 if(IO::poll(control.serial, IO::P_INPUT, 500*Time::msec))
1138 int c = control.serial.get();
1149 if(control.debug>=1)
1150 IO::print("ArduControl detection failed\n");
1155 if(control.debug>=1)
1156 IO::print("ArduControl detected at %d bits/s\n", rate);
1161 cmd.command[0] = SET_BAUD_RATE;
1162 cmd.command[1] = rates[0]>>8;
1163 cmd.command[2] = rates[0];
1165 if(do_command(cmd, Time::sec)==COMMAND_OK)
1167 control.serial.set_baud_rate(rates[0]);
1168 Time::sleep(Time::sec);
1169 if(do_command(cmd, Time::sec)==COMMAND_OK)
1171 if(control.debug>=1)
1172 IO::print("Rate changed to %d bits/s\n", rates[0]);
1178 bool ArduControl::ControlThread::get_work(PendingCommand &cmd)
1180 Time::TimeStamp t = Time::now();
1183 for(; (count<tasks.size() && tasks[count]->get_sleep_timeout()<=t); ++count) ;
1185 for(; count>0; --count)
1188 for(unsigned j=1; j<count; ++j)
1189 if(tasks[j]->get_priority()<tasks[i]->get_priority())
1192 Task *task = tasks[i];
1193 bool result = task->get_work(cmd);
1195 Time::TimeStamp st = max(task->get_sleep_timeout(), t);
1196 for(; (i+1<tasks.size() && tasks[i+1]->get_sleep_timeout()<=st); ++i)
1197 tasks[i] = tasks[i+1];
1202 if(control.debug>=2)
1203 IO::print("Scheduled task %s\n", task->get_name());
1208 // As fallback, send an idle packet for the MM protocol
1209 cmd.command[0] = MOTOROLA_SPEED;
1210 cmd.command[1] = 80;
1218 unsigned ArduControl::ControlThread::do_command(const PendingCommand &cmd, const Time::TimeDelta &timeout)
1220 if(control.debug>=2)
1223 for(unsigned i=0; i<cmd.length; ++i)
1224 cmd_hex += format(" %02X", static_cast<unsigned char>(cmd.command[i]));
1225 IO::print("< %02X%s\n", cmd.length^0xFF, cmd_hex);
1228 control.serial.put(cmd.length^0xFF);
1229 control.serial.write(cmd.command, cmd.length);
1231 unsigned result = 0;
1236 got_data = IO::poll(control.serial, IO::P_INPUT, Time::zero);
1238 got_data = IO::poll(control.serial, IO::P_INPUT, timeout);
1243 unsigned rlength = control.serial.get()^0xFF;
1246 IO::print("Invalid length %02X\n", rlength);
1254 if(!IO::poll(control.serial, IO::P_INPUT, timeout))
1256 pos += control.serial.read(reply+pos, rlength-pos);
1259 if(control.debug>=2)
1262 for(unsigned i=0; i<rlength; ++i)
1263 reply_hex += format(" %02X", static_cast<unsigned char>(reply[i]));
1264 IO::print("> %02X%s\n", rlength^0xFF, reply_hex);
1267 unsigned r = process_reply(reply, rlength);
1275 unsigned ArduControl::ControlThread::process_reply(const char *reply, unsigned rlength)
1277 unsigned char type = reply[0];
1278 if((type&0xE0)==0x80)
1280 if(type!=COMMAND_OK)
1281 IO::print("Error %02X\n", type);
1284 else if(type==POWER_STATE && rlength==2)
1285 set_power(reply[1]);
1286 else if(type==OVERCURRENT)
1289 IO::print("Overcurrent detected!\n");
1293 for(vector<Task *>::iterator i=tasks.begin(); i!=tasks.end(); ++i)
1294 (*i)->process_reply(reply, rlength);
1300 void ArduControl::ControlThread::set_power(bool p)
1302 control.power.set(p);
1305 tag.type = Tag::GENERAL;
1306 tag.command = POWER;
1307 tag.serial = control.power.serial;
1308 control.completed_commands.push(tag);
1312 ArduControl::Loader::Loader(ArduControl &c):
1313 DataFile::ObjectLoader<ArduControl>(c)
1315 add("mfx_announce_serial", &Loader::mfx_announce_serial);
1316 add("mfx_locomotive", &Loader::mfx_locomotive);
1319 void ArduControl::Loader::mfx_announce_serial(unsigned s)
1321 obj.mfx_announce.set_serial(s);
1324 void ArduControl::Loader::mfx_locomotive(unsigned id)
1328 info.protocol = "MFX";
1330 obj.add_mfx_info(info);
1334 ArduControl::MfxInfo::Loader::Loader(MfxInfo &i):
1335 DataFile::ObjectLoader<MfxInfo>(i)
1337 add("address", static_cast<unsigned MfxInfo::*>(&MfxInfo::address));
1338 add("name", static_cast<string MfxInfo::*>(&MfxInfo::name));