This repository has been archived by the owner on Apr 28, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Commander.cpp
144 lines (118 loc) · 2.31 KB
/
Commander.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
/*
* CommandReader.cpp
*
* Created on: 2011-3-31
* Author: simophin
*/
#include "Commander.h"
#include "Command.h"
#include "IODevice.h"
#include "Protocol.h"
#include <assert.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sstream>
#include "RString.h"
#include <list>
class Commander::Impl {
public:
IODevice *device;
Error lastError;
};
Commander::Commander(IODevice *device)
:d(new Commander::Impl){
setDevice(device);
}
Commander::~Commander() {
}
void Commander::setDevice(IODevice *device) {
d->device = device;
}
IODevice *Commander::
getDevice() const {
return d->device;
}
Error Commander::
readCommand(Command &cmd) {
Error rc;
IODevice *dd = d->device;
assert(dd != 0);
CommandHeader hdr;
char *buf = 0;
// Read header
{
size_t read_size;
rc = dd->read((char *)&hdr,sizeof(hdr), &read_size);
if (!rc.isSuccess()) {
return rc;
}
if( read_size != sizeof(hdr)) {
rc.setErrorType(Error::ERR_INVALID, "header corrupted");
return rc;
}
}
// Read command
{
buf = (char *)::malloc(hdr.length);
int tried_times = 0;
size_t offset = 0;
size_t read_size;
do {
rc = dd->read( (char *)(buf + offset), hdr.length-offset, &read_size);
if (!rc.isSuccess()) {
goto out;
}
offset += read_size;
}while(tried_times++ < 20 && offset < hdr.length);
}
{
String name;
std::vector<String> args;
size_t offset = 0;
name = buf;
offset += ::strlen(buf)+1;
while( (unsigned int)offset < (unsigned )hdr.length) {
args.push_back(buf+offset);
offset += ::strlen(buf+offset)+1;
}
cmd.setName(name);
cmd.setArguments(args);
}
if (buf) ::free(buf);
return rc;
out:
if (buf) ::free(buf);
return rc;
}
Error Commander::
writeCommand (const Command & cmd) {
IODevice *dd = d->device;
Error rc;
assert(dd != 0);
std::stringstream buf;
buf << cmd.getName() << '\0';
std::vector<String> args = cmd.getArguments();
for (unsigned i=0;i<args.size();i++) {
buf << args[i] << '\0';
}
String data = buf.str();
CommandHeader hdr;
// Write header
{
::memset (&hdr,0,sizeof(hdr));
hdr.length = data.size();
}
// Write data
{
rc = dd->write((char *)&hdr, sizeof(hdr));
if ( !rc.isSuccess()) {
return rc;
}
rc = dd->write(data.c_str(), data.size());
if ( !rc.isSuccess() ) {
return rc;
}
}
return rc;
}