3 This file is part of the MSP Märklin suite
4 Copyright © 2006-2008 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 ostream &operator<<(ostream &out, const Reply &reply)
114 for(unsigned i=0; i<reply.len; ++i)
115 out<<format(" %02X", static_cast<int>(reply.data[i]));
120 } // namespace Marklin