3 This file is part of the MSP Märklin suite
4 Copyright © 2006-2009 Mikkosoft Productions, Mikko Rasa
5 Distributed under the GPL
10 #include <msp/strings/formatter.h>
11 #include "constants.h"
19 unsigned read_all(int fd, char *buf, unsigned size)
23 pos += read(fd, buf+pos, size-pos);
39 Reply Reply::read(int fd, Cmd cmd)
43 char *data = reinterpret_cast<char *>(result.data);
47 for(unsigned i=0; i<3; ++i)
49 result.len += read_all(fd, data+i, 1);
50 if(!(result.data[i]&0x80))
54 else if(cmd==CMD_EVENT_LOK)
56 for(unsigned i=0;; i+=5)
58 result.len += read_all(fd, data+i, 1);
60 if(result.data[i]&0x80)
63 result.len += read_all(fd, data+i+1, 4);
66 else if(cmd==CMD_EVENT_TURNOUT)
68 result.len += read_all(fd, data, 1);
69 result.len += read_all(fd, data+1, result.data[0]*2);
71 else if(cmd==CMD_EVENT_SENSOR)
73 for(unsigned i=0;; i+=3)
75 result.len += read_all(fd, data+i, 1);
80 result.len += read_all(fd, data+i+1, 2);
85 bool expect_errcode = (cmd!=CMD_STATUS);
87 unsigned expected_bytes = 0;
88 if(cmd==CMD_STATUS || cmd==CMD_FUNC_STATUS || cmd==CMD_TURNOUT_STATUS)
90 if(cmd==CMD_SENSOR_STATUS || cmd==CMD_TURNOUT_GROUP_STATUS)
92 if(cmd==CMD_LOK_STATUS)
94 if(cmd==CMD_LOK_CONFIG)
101 result.err = static_cast<Error>(c);
104 if(result.err==ERR_NO_ERROR)
105 result.len += read_all(fd, data, expected_bytes);
111 Reply Reply::simulate(Cmd cmd)
117 result.data[0] = 0x80;
122 else if(cmd==CMD_TURNOUT)
124 else if(cmd==CMD_TURNOUT_STATUS)
126 result.data[0] = 0x04;
129 else if(cmd==CMD_LOK)
131 else if(cmd==CMD_LOK_STATUS)
133 result.data[1] = 0x20;
136 else if(cmd==CMD_SENSOR_PARAM_SET)
138 else if(cmd==CMD_SENSOR_REPORT)
140 else if(cmd==CMD_POWER_ON)
142 else if(cmd==CMD_POWER_OFF)
145 result.err = ERR_SYS_ERROR;
150 ostream &operator<<(ostream &out, const Reply &reply)
153 for(unsigned i=0; i<reply.len; ++i)
154 out<<format(" %02X", static_cast<int>(reply.data[i]));
159 } // namespace Marklin