1 #include <msp/core/maputils.h>
2 #include <msp/io/print.h>
3 #include <msp/time/utils.h>
4 #include "arducontrol.h"
12 ArduControl::ProtocolInfo ArduControl::protocol_info[2] =
15 { 0x3FFF, 126, 15 } // MFX
18 ArduControl::ArduControl(const string &dev):
28 cmd.command[0] = READ_POWER_STATE;
32 cmd.command[0] = MFX_SET_STATION_ID;
41 ArduControl::~ArduControl()
46 void ArduControl::set_power(bool p)
50 PendingCommand cmd(POWER);
51 cmd.tag.serial = power.serial;
52 cmd.command[0] = (p ? POWER_ON : POWER_OFF);
58 void ArduControl::halt(bool)
62 const char *ArduControl::enumerate_protocols(unsigned i) const
72 ArduControl::Protocol ArduControl::map_protocol(const string &proto_name)
76 else if(proto_name=="MFX")
79 throw invalid_argument("ArduControl::map_protocol");
82 unsigned ArduControl::get_protocol_speed_steps(const string &proto_name) const
84 return protocol_info[map_protocol(proto_name)].max_speed;
87 unsigned ArduControl::add_loco(unsigned addr, const string &proto_name, const VehicleType &)
90 throw invalid_argument("ArduControl::add_loco");
92 Protocol proto = map_protocol(proto_name);
93 if(addr>protocol_info[proto].max_address)
94 throw invalid_argument("ArduControl::add_loco");
96 Locomotive loco(proto, addr);
97 insert_unique(locomotives, loco.id, loco);
102 void ArduControl::remove_loco(unsigned id)
104 Locomotive &loco = get_item(locomotives, id);
105 refresh.remove_loco(loco);
106 locomotives.erase(id);
109 void ArduControl::set_loco_speed(unsigned id, unsigned speed)
111 Locomotive &loco = get_item(locomotives, id);
112 if(speed>protocol_info[loco.proto].max_speed)
113 throw invalid_argument("ArduControl::set_loco_speed");
115 if(loco.speed.set(speed))
117 PendingCommand cmd(loco, Locomotive::SPEED);
120 refresh.add_loco(loco);
124 void ArduControl::set_loco_reverse(unsigned id, bool rev)
126 Locomotive &loco = get_item(locomotives, id);
127 if(loco.reverse.set(rev))
129 PendingCommand cmd(loco, Locomotive::REVERSE);
132 refresh.add_loco(loco);
136 void ArduControl::set_loco_function(unsigned id, unsigned func, bool state)
138 Locomotive &loco = get_item(locomotives, id);
139 if(func>protocol_info[loco.proto].max_func)
140 throw invalid_argument("ArduControl::set_loco_function");
142 unsigned mask = 1<<func;
143 if(loco.funcs.set((loco.funcs&~mask)|(mask*state)))
145 if(func>0 || loco.proto!=MM)
147 PendingCommand cmd(loco, Locomotive::FUNCTIONS, func);
151 refresh.add_loco(loco);
155 unsigned ArduControl::add_turnout(unsigned addr, const TrackType &type)
157 if(!addr || !type.is_turnout())
158 throw invalid_argument("ArduControl::add_turnout");
160 return add_accessory(Accessory::TURNOUT, addr, type.get_state_bits());
163 void ArduControl::remove_turnout(unsigned addr)
165 remove_accessory(Accessory::TURNOUT, addr);
168 void ArduControl::set_turnout(unsigned addr, unsigned state)
170 set_accessory(Accessory::TURNOUT, addr, state);
173 unsigned ArduControl::get_turnout(unsigned addr) const
175 return get_accessory(Accessory::TURNOUT, addr);
178 unsigned ArduControl::add_signal(unsigned addr, const SignalType &)
180 return add_accessory(Accessory::SIGNAL, addr, 1);
183 void ArduControl::remove_signal(unsigned addr)
185 remove_accessory(Accessory::SIGNAL, addr);
188 void ArduControl::set_signal(unsigned addr, unsigned state)
190 set_accessory(Accessory::SIGNAL, addr, state);
193 unsigned ArduControl::get_signal(unsigned addr) const
195 return get_accessory(Accessory::SIGNAL, addr);
198 unsigned ArduControl::add_accessory(Accessory::Kind kind, unsigned addr, unsigned bits)
200 AccessoryMap::iterator i = accessories.lower_bound(addr);
201 AccessoryMap::iterator j = accessories.upper_bound(addr+bits-1);
203 throw key_error(addr);
204 if(i!=accessories.begin())
207 if(i->first+i->second.bits>addr)
208 throw key_error(addr);
211 insert_unique(accessories, addr, Accessory(kind, addr, bits));
215 void ArduControl::remove_accessory(Accessory::Kind kind, unsigned addr)
217 Accessory &acc = get_item(accessories, addr);
219 throw key_error(addr);
220 accessories.erase(addr);
223 void ArduControl::set_accessory(Accessory::Kind kind, unsigned addr, unsigned state)
225 Accessory &acc = get_item(accessories, addr);
227 throw key_error(addr);
229 if(state!=acc.target)
232 accessory_queue.push_back(&acc);
236 unsigned ArduControl::get_accessory(Accessory::Kind kind, unsigned addr) const
238 const Accessory &acc = get_item(accessories, addr);
240 throw key_error(addr);
244 unsigned ArduControl::add_sensor(unsigned addr)
247 throw invalid_argument("ArduControl::add_sensor");
249 insert_unique(sensors, addr, Sensor(addr));
250 s88.grow_n_octets((addr+7)/8);
255 void ArduControl::remove_sensor(unsigned addr)
257 remove_existing(sensors, addr);
258 // TODO update s88.n_octets
261 bool ArduControl::get_sensor(unsigned addr) const
263 return get_item(sensors, addr).state;
266 void ArduControl::tick()
268 while(Tag tag = pop_completed_tag())
270 if(tag.type==Tag::GENERAL)
272 if(tag.command==POWER)
274 if(power.commit(tag.serial))
275 signal_power.emit(power.current);
278 else if(tag.type==Tag::LOCOMOTIVE)
280 LocomotiveMap::iterator i = locomotives.find(tag.id);
281 if(i==locomotives.end())
284 Locomotive &loco = i->second;
285 if(tag.command==Locomotive::SPEED)
287 if(loco.speed.commit(tag.serial))
288 signal_loco_speed.emit(loco.id, loco.speed, loco.reverse);
290 else if(tag.command==Locomotive::REVERSE)
292 if(loco.reverse.commit(tag.serial))
293 signal_loco_speed.emit(loco.id, loco.speed, loco.reverse);
295 else if(tag.command==Locomotive::FUNCTIONS)
297 unsigned old = loco.funcs;
298 if(loco.funcs.commit(tag.serial))
300 unsigned changed = old^loco.funcs;
301 for(unsigned j=0; changed>>j; ++j)
303 signal_loco_function.emit(loco.id, j, (loco.funcs>>j)&1);
307 else if(tag.type==Tag::ACCESSORY)
309 AccessoryMap::iterator i = accessories.find(tag.id);
310 if(i==accessories.end())
313 Accessory &acc = i->second;
314 if(tag.command==Accessory::ACTIVATE)
316 off_timeout = Time::now()+acc.active_time;
318 else if(tag.command==Accessory::DEACTIVATE)
320 if(acc.state.commit(tag.serial))
322 if(acc.state==acc.target)
324 if(acc.kind==Accessory::TURNOUT)
325 signal_turnout.emit(acc.address, acc.state);
326 else if(acc.kind==Accessory::SIGNAL)
327 signal_signal.emit(acc.address, acc.state);
329 if(&acc==active_accessory)
330 active_accessory = 0;
334 else if(tag.type==Tag::SENSOR)
336 SensorMap::iterator i = sensors.find(tag.id);
340 Sensor &sensor = i->second;
341 if(tag.command==Sensor::STATE)
343 if(sensor.state.commit(tag.serial))
344 signal_sensor.emit(sensor.address, sensor.state);
349 while(!active_accessory && !accessory_queue.empty())
351 Accessory &acc = *accessory_queue.front();
353 if(acc.state!=acc.target)
355 active_accessory = &acc;
357 unsigned changes = acc.state^acc.target;
358 unsigned lowest_bit = changes&~(changes-1);
360 for(i=0; (lowest_bit>>i)>1; ++i) ;
361 acc.state.set(acc.state^lowest_bit);
362 PendingCommand cmd(acc, Accessory::ACTIVATE, i);
366 accessory_queue.pop_front();
369 if(active_accessory && off_timeout)
371 Time::TimeStamp t = Time::now();
374 off_timeout = Time::TimeStamp();
375 PendingCommand cmd(*active_accessory, Accessory::DEACTIVATE);
381 void ArduControl::flush()
385 void ArduControl::push_command(const PendingCommand &cmd)
387 MutexLock lock(mutex);
388 command_queue.push_back(cmd);
391 bool ArduControl::pop_command(PendingCommand &cmd)
393 MutexLock lock(mutex);
394 if(command_queue.empty())
396 cmd = command_queue.front();
397 command_queue.pop_front();
401 void ArduControl::push_completed_tag(const Tag &tag)
403 MutexLock lock(mutex);
404 completed_commands.push_back(tag);
407 ArduControl::Tag ArduControl::pop_completed_tag()
409 MutexLock lock(mutex);
410 if(completed_commands.empty())
412 Tag tag = completed_commands.front();
413 completed_commands.pop_front();
418 ArduControl::Tag::Tag():
426 ArduControl::Locomotive::Locomotive(Protocol p, unsigned a):
436 unsigned ArduControl::Locomotive::create_speed_dir_command(char *buffer) const
440 buffer[0] = MOTOROLA_SPEED_DIRECTION;
442 buffer[2] = funcs.pending&1;
443 buffer[3] = speed.pending+reverse.pending*0x80;
448 buffer[0] = MFX_SPEED;
449 buffer[1] = address>>8;
451 buffer[3] = speed.pending+reverse.pending*0x80;
458 unsigned ArduControl::Locomotive::create_speed_func_command(unsigned f, char *buffer) const
463 throw invalid_argument("Locomotive::create_speed_func_command");
465 buffer[0] = MOTOROLA_SPEED_FUNCTION;
467 buffer[2] = (f<<4)|(((funcs.pending>>f)&1)<<1)|(funcs.pending&1);
468 buffer[3] = speed.pending;
473 bool f16 = (funcs.pending>0xFF);
474 buffer[0] = (f16 ? MFX_SPEED_FUNCS16 : MFX_SPEED_FUNCS8);
475 buffer[1] = address>>8;
477 buffer[3] = speed.pending+reverse.pending*0x80;
480 buffer[4] = funcs.pending>>8;
481 buffer[5] = funcs.pending;
486 buffer[4] = funcs.pending;
495 ArduControl::Accessory::Accessory(Kind k, unsigned a, unsigned b):
500 active_time(500*Time::msec)
503 unsigned ArduControl::Accessory::create_state_command(unsigned b, bool c, char *buffer) const
506 throw invalid_argument("Accessory::create_state_command");
508 unsigned a = (address+b+3)*2;
509 if(!((state.pending>>b)&1))
511 buffer[0] = MOTOROLA_SOLENOID;
513 buffer[2] = ((a&7)<<4)|c;
518 ArduControl::Sensor::Sensor(unsigned a):
524 ArduControl::PendingCommand::PendingCommand():
529 ArduControl::PendingCommand::PendingCommand(GeneralCommand cmd):
533 tag.type = Tag::GENERAL;
537 ArduControl::PendingCommand::PendingCommand(Locomotive &loco, Locomotive::Command cmd, unsigned index):
540 tag.type = Tag::LOCOMOTIVE;
543 if(cmd==Locomotive::SPEED)
545 tag.serial = loco.speed.serial;
546 length = loco.create_speed_dir_command(command);
548 else if(cmd==Locomotive::REVERSE)
550 tag.serial = loco.reverse.serial;
551 length = loco.create_speed_dir_command(command);
553 else if(cmd==Locomotive::FUNCTIONS)
555 tag.serial = loco.funcs.serial;
556 length = loco.create_speed_func_command(index, command);
559 throw invalid_argument("PendingCommand");
562 ArduControl::PendingCommand::PendingCommand(Accessory &acc, Accessory::Command cmd, unsigned index):
565 tag.type = Tag::ACCESSORY;
567 tag.id = acc.address;
568 if(cmd==Accessory::ACTIVATE || cmd==Accessory::DEACTIVATE)
570 tag.serial = acc.state.serial;
571 length = acc.create_state_command(index, (cmd==Accessory::ACTIVATE), command);
574 throw invalid_argument("PendingCommand");
578 ArduControl::RefreshTask::RefreshTask():
585 bool ArduControl::RefreshTask::get_work(PendingCommand &cmd)
587 if(loco && loco->proto==MM && phase==0)
589 cmd.length = loco->create_speed_func_command(round%4+1, cmd.command);
590 cmd.repeat_count = 2;
595 loco = get_next_loco();
602 cmd.length = loco->create_speed_dir_command(cmd.command);
603 cmd.repeat_count = 2;
605 else if(loco->proto==MFX)
606 cmd.length = loco->create_speed_func_command(0, cmd.command);
613 void ArduControl::RefreshTask::add_loco(Locomotive &l)
615 MutexLock lock(mutex);
619 LocomotivePtrList::iterator oldest = cycle.begin();
620 for(LocomotivePtrList::iterator i=cycle.begin(); ++i!=cycle.end(); )
621 if((*i)->last_change_age>(*oldest)->last_change_age)
627 if(next==cycle.end())
628 next = cycle.begin();
631 void ArduControl::RefreshTask::remove_loco(Locomotive &l)
633 MutexLock lock(mutex);
634 for(LocomotivePtrList::iterator i=cycle.begin(); i!=cycle.end(); ++i)
649 ArduControl::Locomotive *ArduControl::RefreshTask::get_next_loco()
651 MutexLock lock(mutex);
655 Locomotive *l = *next;
660 void ArduControl::RefreshTask::advance()
663 if(next==cycle.end())
671 ArduControl::S88Task::S88Task(ArduControl &c):
677 bool ArduControl::S88Task::get_work(PendingCommand &cmd)
679 if(octets_remaining || !n_octets)
682 octets_remaining = n_octets;
683 cmd.command[0] = S88_READ;
684 cmd.command[1] = octets_remaining;
690 void ArduControl::S88Task::process_reply(const char *reply, unsigned length)
692 unsigned char type = reply[0];
693 if(type==S88_DATA && length>2)
695 unsigned offset = static_cast<unsigned char>(reply[1]);
696 unsigned count = length-2;
698 SensorMap::iterator begin = control.sensors.lower_bound(offset*8+1);
699 SensorMap::iterator end = control.sensors.upper_bound((offset+count)*8);
700 for(SensorMap::iterator i=begin; i!=end; ++i)
702 unsigned bit_index = i->first-1-offset*8;
703 bool state = (reply[2+bit_index/8]>>(7-bit_index%8))&1;
704 i->second.state.set(state);
707 tag.type = Tag::SENSOR;
708 tag.command = Sensor::STATE;
709 tag.serial = i->second.state.serial;
711 control.push_completed_tag(tag);
714 if(count>octets_remaining)
715 octets_remaining = 0;
717 octets_remaining -= count;
721 void ArduControl::S88Task::set_n_octets(unsigned n)
726 void ArduControl::S88Task::grow_n_octets(unsigned n)
733 ArduControl::MfxAnnounceTask::MfxAnnounceTask():
737 bool ArduControl::MfxAnnounceTask::get_work(PendingCommand &cmd)
739 Time::TimeStamp t = Time::now();
743 cmd.command[0] = MFX_ANNOUNCE;
744 cmd.command[1] = serial>>8;
745 cmd.command[2] = serial;
747 next = t+400*Time::msec;
752 void ArduControl::MfxAnnounceTask::set_serial(unsigned s)
758 ArduControl::MfxSearchTask::MfxSearchTask(ArduControl &c):
766 bool ArduControl::MfxSearchTask::get_work(PendingCommand &cmd)
771 IO::print("Assigning MFX address %d to decoder %08X\n", next_address, bits);
773 cmd.command[0] = MFX_ASSIGN_ADDRESS;
774 cmd.command[1] = next_address>>8;
775 cmd.command[2] = next_address;
776 for(unsigned i=0; i<4; ++i)
777 cmd.command[3+i] = bits>>(24-i*8);
787 Time::TimeStamp t = Time::now();
791 cmd.command[0] = MFX_SEARCH;
792 for(unsigned i=0; i<4; ++i)
793 cmd.command[1+i] = bits>>(24-i*8);
794 cmd.command[5] = size;
797 next = t+200*Time::msec;
800 IO::print("Search %08X/%d\n", bits, size);
805 void ArduControl::MfxSearchTask::process_reply(const char *reply, unsigned length)
807 unsigned char type = reply[0];
808 if(type==MFX_SEARCH_FEEDBACK && length==2)
815 else if(size>0 && misses<6)
818 bits ^= 1<<(32-size);
822 next = Time::now()+2*Time::sec;
831 ArduControl::ControlThread::ControlThread(ArduControl &c):
835 tasks.push_back(&control.mfx_announce);
836 tasks.push_back(&control.mfx_search);
837 tasks.push_back(&control.s88);
838 tasks.push_back(&control.refresh);
843 void ArduControl::ControlThread::exit()
849 void ArduControl::ControlThread::main()
859 for(unsigned i=0; (success && i<cmd.repeat_count); ++i)
860 success = (do_command(cmd)==COMMAND_OK);
861 if(success && cmd.tag)
862 control.push_completed_tag(cmd.tag);
865 Time::sleep(10*Time::msec);
869 void ArduControl::ControlThread::init_baud_rate()
871 static unsigned rates[] = { 57600, 9600, 19200, 38400, 0 };
873 control.serial.set_data_bits(8);
874 control.serial.set_parity(IO::Serial::NONE);
875 control.serial.set_stop_bits(1);
876 for(unsigned i=0; rates[i]; ++i)
878 control.serial.set_baud_rate(rates[i]);
879 control.serial.put('\xFF');
880 if(IO::poll(control.serial, IO::P_INPUT, 500*Time::msec))
882 int c = control.serial.get();
892 IO::print("ArduControl detected at %d bits/s\n", rate);
897 cmd.command[0] = SET_BAUD_RATE;
898 cmd.command[1] = rates[0]>>8;
899 cmd.command[2] = rates[0];
901 if(do_command(cmd)==COMMAND_OK)
903 control.serial.set_baud_rate(rates[0]);
904 if(do_command(cmd)==COMMAND_OK)
906 Time::sleep(Time::sec);
908 IO::print("Rate changed to %d bits/s\n", rates[0]);
914 bool ArduControl::ControlThread::get_work(PendingCommand &cmd)
916 if(control.pop_command(cmd))
919 for(vector<Task *>::iterator i=tasks.begin(); i!=tasks.end(); ++i)
920 if((*i)->get_work(cmd))
923 // As fallback, send an idle packet for the MM protocol
924 cmd.command[0] = MOTOROLA_SPEED;
933 unsigned ArduControl::ControlThread::do_command(const PendingCommand &cmd)
938 for(unsigned i=0; i<cmd.length; ++i)
939 cmd_hex += format(" %02X", static_cast<unsigned char>(cmd.command[i]));
940 IO::print("< %02X%s\n", cmd.length^0xFF, cmd_hex);
943 control.serial.put(cmd.length^0xFF);
944 control.serial.write(cmd.command, cmd.length);
951 got_data = IO::poll(control.serial, IO::P_INPUT, Time::zero);
953 got_data = IO::poll(control.serial, IO::P_INPUT);
958 unsigned rlength = control.serial.get()^0xFF;
961 IO::print("Invalid length %02X\n", rlength);
968 pos += control.serial.read(reply+pos, rlength-pos);
973 for(unsigned i=0; i<rlength; ++i)
974 reply_hex += format(" %02X", static_cast<unsigned char>(reply[i]));
975 IO::print("> %02X%s\n", rlength^0xFF, reply_hex);
978 unsigned r = process_reply(reply, rlength);
986 unsigned ArduControl::ControlThread::process_reply(const char *reply, unsigned rlength)
988 unsigned char type = reply[0];
989 if((type&0xE0)==0x80)
992 IO::print("Error %02X\n", type);
995 else if(type==POWER_STATE && rlength==2)
997 control.power.set(reply[1]);
1000 tag.type = Tag::GENERAL;
1001 tag.command = POWER;
1002 tag.serial = control.power.serial;
1003 control.push_completed_tag(tag);
1007 for(vector<Task *>::iterator i=tasks.begin(); i!=tasks.end(); ++i)
1008 (*i)->process_reply(reply, rlength);