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),
969 bool ArduControl::MfxSearchTask::get_work(PendingCommand &cmd)
973 cmd.command[0] = MFX_READ;
974 cmd.command[1] = pending_info->address>>8;
975 cmd.command[2] = pending_info->address;
976 unsigned index = read_array*0x40+read_offset;
977 cmd.command[3] = index>>8;
978 cmd.command[4] = index;
979 unsigned length = (read_length>=4 ? 4 : read_length>=2 ? 2 : 1);
980 cmd.command[5] = length;
983 sleep(100*Time::msec);
987 else if(pending_info)
989 queue.push(*pending_info);
991 tag.type = Tag::GENERAL;
992 tag.command = NEW_LOCO;
993 tag.id = pending_info->id;
994 control.completed_commands.push(tag);
997 IO::print("Completed processing locomotive %s at address %d\n", pending_info->name, pending_info->address);
1005 if(control.debug>=1)
1006 IO::print("Assigning MFX address %d to decoder %08X\n", next_address, bits);
1008 pending_info = new MfxInfo;
1009 pending_info->protocol = "MFX";
1010 pending_info->address = next_address;
1011 pending_info->name = format("%08X", bits);
1012 pending_info->id = bits;
1014 cmd.command[0] = MFX_ASSIGN_ADDRESS;
1015 cmd.command[1] = next_address>>8;
1016 cmd.command[2] = next_address;
1017 for(unsigned i=0; i<4; ++i)
1018 cmd.command[3+i] = bits>>(24-i*8);
1033 cmd.command[0] = MFX_SEARCH;
1034 for(unsigned i=0; i<4; ++i)
1035 cmd.command[1+i] = bits>>(24-i*8);
1036 cmd.command[5] = size;
1039 sleep(100*Time::msec);
1041 if(control.debug>=1)
1042 IO::print("Search %08X/%d\n", bits, size);
1047 void ArduControl::MfxSearchTask::process_reply(const char *reply, unsigned length)
1049 unsigned char type = reply[0];
1050 if(type==MFX_SEARCH_FEEDBACK && length==2)
1057 else if(size>0 && misses<6)
1060 bits ^= 1<<(32-size);
1070 else if(type==MFX_READ_FEEDBACK && length>=3)
1076 for(unsigned i=2; i<length; ++i)
1077 read_data[read_offset+i-2] = reply[i];
1078 read_offset += length-2;
1079 read_length -= length-2;
1084 block_size = static_cast<unsigned char>(read_data[4])*static_cast<unsigned char>(read_data[5]);
1086 bool array_handled = false;
1087 if(read_data[0]==0x18)
1089 for(unsigned i=1; i<read_offset; ++i)
1092 pending_info->name = string(read_data+1, i-1);
1093 array_handled = true;
1101 array_handled = true;
1103 if(array_handled && control.debug>=1)
1105 IO::print("MFX CA %03X:", read_array);
1106 for(unsigned i=0; i<read_offset; ++i)
1107 IO::print(" %02X", static_cast<unsigned char>(read_data[i]));
1111 if(array_handled && read_array<block_size)
1124 if(control.debug>=1)
1125 IO::print("Failed to read MFX configuration from %d\n", pending_info->address);
1132 void ArduControl::MfxSearchTask::set_next_address(unsigned a)
1137 bool ArduControl::MfxSearchTask::pop_info(MfxInfo &info)
1139 return queue.pop(info);
1143 ArduControl::MonitorTask::MonitorTask():
1152 bool ArduControl::MonitorTask::get_work(PendingCommand &cmd)
1155 cmd.command[0] = READ_INPUT_VOLTAGE;
1157 cmd.command[0] = READ_TRACK_CURRENT;
1160 sleep(200*Time::msec);
1161 next_type = (next_type+1)%5;
1166 void ArduControl::MonitorTask::process_reply(const char *reply, unsigned length)
1168 unsigned char type = reply[0];
1169 if(type==INPUT_VOLTAGE && length==3)
1170 voltage = ((static_cast<unsigned char>(reply[1])<<8) | static_cast<unsigned char>(reply[2]))/1000.0f;
1171 else if(type==TRACK_CURRENT && length==5)
1173 current = ((static_cast<unsigned char>(reply[1])<<8) | static_cast<unsigned char>(reply[2]))/1000.0f;
1174 float peak = ((static_cast<unsigned char>(reply[3])<<8) | static_cast<unsigned char>(reply[4]))/1000.0f;
1175 peak_level = max(peak_level, peak);
1176 base_level = min(base_level, current);
1180 void ArduControl::MonitorTask::reset_peak()
1182 base_level = current;
1183 peak_level = current;
1187 ArduControl::ControlThread::ControlThread(ArduControl &c):
1191 tasks.push_back(&control.command_queue);
1192 tasks.push_back(&control.monitor);
1193 tasks.push_back(&control.mfx_announce);
1194 tasks.push_back(&control.mfx_search);
1195 tasks.push_back(&control.s88);
1196 tasks.push_back(&control.refresh);
1201 void ArduControl::ControlThread::exit()
1207 void ArduControl::ControlThread::main()
1216 bool success = true;
1217 bool resync = false;
1218 for(unsigned i=0; (success && i<cmd.repeat_count); ++i)
1220 unsigned result = do_command(cmd, control.command_timeout);
1221 success = (result==COMMAND_OK);
1222 resync = (result==0);
1225 if(success && cmd.tag)
1226 control.completed_commands.push(cmd.tag);
1230 if(control.debug>=1)
1231 IO::print("Synchronization with ArduControl lost, attempting to recover\n");
1232 for(unsigned i=0; (resync && i<16); ++i)
1234 control.serial.put('\xFF');
1235 while(IO::poll(control.serial, IO::P_INPUT, control.command_timeout))
1236 resync = (control.serial.get()!=0xFF);
1240 if(control.debug>=1)
1241 IO::print("Resynchronization failed, giving up\n");
1246 if(control.debug>=1)
1247 IO::print("Resynchronization successful\n");
1249 control.command_queue.push(cmd);
1254 Time::sleep(10*Time::msec);
1258 void ArduControl::ControlThread::init_baud_rate()
1260 static unsigned rates[] = { 57600, 9600, 19200, 38400, 0 };
1262 control.serial.set_data_bits(8);
1263 control.serial.set_parity(IO::Serial::NONE);
1264 control.serial.set_stop_bits(1);
1265 for(unsigned i=0; rates[i]; ++i)
1267 control.serial.set_baud_rate(rates[i]);
1268 control.serial.put('\xFF');
1269 if(IO::poll(control.serial, IO::P_INPUT, 500*Time::msec))
1271 int c = control.serial.get();
1282 if(control.debug>=1)
1283 IO::print("ArduControl detection failed\n");
1288 if(control.debug>=1)
1289 IO::print("ArduControl detected at %d bits/s\n", rate);
1294 cmd.command[0] = SET_BAUD_RATE;
1295 cmd.command[1] = rates[0]>>8;
1296 cmd.command[2] = rates[0];
1298 if(do_command(cmd, Time::sec)==COMMAND_OK)
1300 control.serial.set_baud_rate(rates[0]);
1301 Time::sleep(Time::sec);
1302 if(do_command(cmd, Time::sec)==COMMAND_OK)
1304 if(control.debug>=1)
1305 IO::print("Rate changed to %d bits/s\n", rates[0]);
1311 bool ArduControl::ControlThread::get_work(PendingCommand &cmd)
1313 Time::TimeStamp t = Time::now();
1316 for(; (count<tasks.size() && tasks[count]->get_sleep_timeout()<=t); ++count) ;
1318 for(; count>0; --count)
1321 for(unsigned j=1; j<count; ++j)
1322 if(tasks[j]->get_priority()<tasks[i]->get_priority())
1325 Task *task = tasks[i];
1326 bool result = task->get_work(cmd);
1328 Time::TimeStamp st = max(task->get_sleep_timeout(), t);
1329 for(; (i+1<tasks.size() && tasks[i+1]->get_sleep_timeout()<=st); ++i)
1330 tasks[i] = tasks[i+1];
1335 if(control.debug>=2)
1336 IO::print("Scheduled task %s\n", task->get_name());
1341 // As fallback, send an idle packet for the MM protocol
1342 cmd.command[0] = MOTOROLA_SPEED;
1343 cmd.command[1] = 80;
1351 unsigned ArduControl::ControlThread::do_command(const PendingCommand &cmd, const Time::TimeDelta &timeout)
1353 if(control.debug>=2)
1356 for(unsigned i=0; i<cmd.length; ++i)
1357 cmd_hex += format(" %02X", static_cast<unsigned char>(cmd.command[i]));
1358 IO::print("< %02X%s\n", cmd.length^0xFF, cmd_hex);
1361 control.serial.put(cmd.length^0xFF);
1362 control.serial.write(cmd.command, cmd.length);
1364 unsigned result = 0;
1369 got_data = IO::poll(control.serial, IO::P_INPUT, Time::zero);
1371 got_data = IO::poll(control.serial, IO::P_INPUT, timeout);
1376 unsigned rlength = control.serial.get()^0xFF;
1379 IO::print("Invalid length %02X\n", rlength);
1387 if(!IO::poll(control.serial, IO::P_INPUT, timeout))
1389 pos += control.serial.read(reply+pos, rlength-pos);
1392 if(control.debug>=2)
1395 for(unsigned i=0; i<rlength; ++i)
1396 reply_hex += format(" %02X", static_cast<unsigned char>(reply[i]));
1397 IO::print("> %02X%s\n", rlength^0xFF, reply_hex);
1400 unsigned r = process_reply(reply, rlength);
1408 unsigned ArduControl::ControlThread::process_reply(const char *reply, unsigned rlength)
1410 unsigned char type = reply[0];
1411 if((type&0xE0)==0x80)
1413 if(type!=COMMAND_OK)
1414 IO::print("Error %02X\n", type);
1417 else if(type==POWER_STATE && rlength==2)
1418 set_power(reply[1]);
1419 else if(type==OVERCURRENT)
1422 IO::print("Overcurrent detected!\n");
1426 for(vector<Task *>::iterator i=tasks.begin(); i!=tasks.end(); ++i)
1427 (*i)->process_reply(reply, rlength);
1433 void ArduControl::ControlThread::set_power(bool p)
1435 control.power.set(p);
1438 tag.type = Tag::GENERAL;
1439 tag.command = POWER;
1440 tag.serial = control.power.serial;
1441 control.completed_commands.push(tag);
1445 ArduControl::Loader::Loader(ArduControl &c):
1446 DataFile::ObjectLoader<ArduControl>(c)
1448 add("mfx_announce_serial", &Loader::mfx_announce_serial);
1449 add("mfx_locomotive", &Loader::mfx_locomotive);
1452 void ArduControl::Loader::mfx_announce_serial(unsigned s)
1454 obj.mfx_announce.set_serial(s);
1457 void ArduControl::Loader::mfx_locomotive(unsigned id)
1461 info.protocol = "MFX";
1463 obj.add_mfx_info(info);
1467 ArduControl::MfxInfo::Loader::Loader(MfxInfo &i):
1468 DataFile::ObjectLoader<MfxInfo>(i)
1470 add("address", static_cast<unsigned MfxInfo::*>(&MfxInfo::address));
1471 add("name", static_cast<string MfxInfo::*>(&MfxInfo::name));