Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(895)

Side by Side Diff: tools/battor_agent/battor_connection_impl.cc

Issue 1567683002: Makes the BattOrConnection read messages instead of bytes (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Code review Created 4 years, 11 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright 2015 The Chromium Authors. All rights reserved. 1 // Copyright 2015 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "tools/battor_agent/battor_connection_impl.h" 5 #include "tools/battor_agent/battor_connection_impl.h"
6 6
7 #include "base/bind.h" 7 #include "base/bind.h"
8 #include "base/callback.h" 8 #include "base/callback.h"
9 #include "device/serial/buffer.h" 9 #include "device/serial/buffer.h"
10 #include "device/serial/serial_io_handler.h" 10 #include "device/serial/serial_io_handler.h"
11 #include "net/base/io_buffer.h" 11 #include "net/base/io_buffer.h"
12 12
13 using std::vector; 13 using std::vector;
14 14
15 namespace battor { 15 namespace battor {
16 16
17 namespace { 17 namespace {
18 18
19 // Serial configuration parameters for the BattOr. 19 // Serial configuration parameters for the BattOr.
20 const uint32_t kBattOrBitrate = 2000000; 20 const uint32_t kBattOrBitrate = 2000000;
21 const device::serial::DataBits kBattOrDataBits = 21 const device::serial::DataBits kBattOrDataBits =
22 device::serial::DATA_BITS_EIGHT; 22 device::serial::DATA_BITS_EIGHT;
23 const device::serial::ParityBit kBattOrParityBit = 23 const device::serial::ParityBit kBattOrParityBit =
24 device::serial::PARITY_BIT_NONE; 24 device::serial::PARITY_BIT_NONE;
25 const device::serial::StopBits kBattOrStopBit = device::serial::STOP_BITS_ONE; 25 const device::serial::StopBits kBattOrStopBit = device::serial::STOP_BITS_ONE;
26 const bool kBattOrCtsFlowControl = true; 26 const bool kBattOrCtsFlowControl = true;
27 const bool kBattOrHasCtsFlowControl = true; 27 const bool kBattOrHasCtsFlowControl = true;
28 const uint32_t kMaxMessageSize = 50000; 28 // The maximum BattOr message is 50kB long.
29 const size_t kMaxMessageSizeBytes = 50000;
29 30
30 // MessageHealth describes the possible healthiness states that a partially 31 // Returns the maximum number of bytes that could be required to read a message
31 // received message could be in. 32 // of the specified type.
32 enum class MessageHealth { 33 size_t GetMaxBytesForMessageType(BattOrMessageType type) {
33 INVALID, 34 switch (type) {
34 INCOMPLETE, 35 case BATTOR_MESSAGE_TYPE_CONTROL:
35 COMPLETE, 36 return 2 * sizeof(BattOrControlMessage) + 3;
36 }; 37 case BATTOR_MESSAGE_TYPE_CONTROL_ACK:
37 38 return 2 * sizeof(BattOrControlMessageAck) + 3;
38 // Parses the specified message. 39 case BATTOR_MESSAGE_TYPE_SAMPLES:
39 // - message: The incoming message that needs to be parsed. 40 return 2 * kMaxMessageSizeBytes + 3;
40 // - parsed_content: Output argument for the message content after removal of 41 default:
41 // any start, end, type, and escape bytes. 42 return 0;
42 // - health: Output argument for the health of the message.
43 // - type: Output argument for the type of message being parsed.
44 // - escape_byte_count: Output argument for the number of escape bytes
45 // removed from the parsed content.
46 void ParseMessage(const vector<char>& message,
47 vector<char>* parsed_content,
48 MessageHealth* health,
49 BattOrMessageType* type,
50 size_t* escape_byte_count) {
51 *health = MessageHealth::INCOMPLETE;
52 *type = BATTOR_MESSAGE_TYPE_CONTROL;
53 *escape_byte_count = 0;
54 parsed_content->reserve(message.size());
55
56 if (message.size() == 0)
57 return;
58
59 // The first byte is the start byte.
60 if (message[0] != BATTOR_CONTROL_BYTE_START) {
61 *health = MessageHealth::INVALID;
62 return;
63 }
64
65 if (message.size() == 1)
66 return;
67
68 // The second byte specifies the message type.
69 *type = static_cast<BattOrMessageType>(message[1]);
70
71 if (*type < static_cast<uint8_t>(BATTOR_MESSAGE_TYPE_CONTROL) ||
72 *type > static_cast<uint8_t>(BATTOR_MESSAGE_TYPE_PRINT)) {
73 *health = MessageHealth::INVALID;
74 return;
75 }
76
77 // After that comes the message data.
78 bool escape_next_byte = false;
79 for (size_t i = 2; i < message.size(); i++) {
80 if (i >= kMaxMessageSize) {
81 *health = MessageHealth::INVALID;
82 return;
83 }
84
85 char next_byte = message[i];
86
87 if (escape_next_byte) {
88 parsed_content->push_back(next_byte);
89 escape_next_byte = false;
90 continue;
91 }
92
93 switch (next_byte) {
94 case BATTOR_CONTROL_BYTE_START:
95 // Two start bytes in a message is invalid.
96 *health = MessageHealth::INVALID;
97 return;
98
99 case BATTOR_CONTROL_BYTE_END:
100 if (i != message.size() - 1) {
101 // We're only parsing a single message here. If we received more bytes
102 // after the end byte, what we've received so far is *not* valid.
103 *health = MessageHealth::INVALID;
104 return;
105 }
106
107 *health = MessageHealth::COMPLETE;
108 return;
109
110 case BATTOR_CONTROL_BYTE_ESCAPE:
111 escape_next_byte = true;
112 (*escape_byte_count)++;
113 continue;
114
115 default:
116 parsed_content->push_back(next_byte);
117 }
118 } 43 }
119 } 44 }
120 45
121 } // namespace 46 } // namespace
122 47
123 BattOrConnectionImpl::BattOrConnectionImpl( 48 BattOrConnectionImpl::BattOrConnectionImpl(
124 const std::string& path, 49 const std::string& path,
125 BattOrConnection::Listener* listener, 50 BattOrConnection::Listener* listener,
126 scoped_refptr<base::SingleThreadTaskRunner> file_thread_task_runner, 51 scoped_refptr<base::SingleThreadTaskRunner> file_thread_task_runner,
127 scoped_refptr<base::SingleThreadTaskRunner> ui_thread_task_runner) 52 scoped_refptr<base::SingleThreadTaskRunner> ui_thread_task_runner)
(...skipping 33 matching lines...) Expand 10 before | Expand all | Expand 10 after
161 86
162 void BattOrConnectionImpl::Close() { 87 void BattOrConnectionImpl::Close() {
163 io_handler_ = nullptr; 88 io_handler_ = nullptr;
164 } 89 }
165 90
166 void BattOrConnectionImpl::SendBytes(BattOrMessageType type, 91 void BattOrConnectionImpl::SendBytes(BattOrMessageType type,
167 const void* buffer, 92 const void* buffer,
168 size_t bytes_to_send) { 93 size_t bytes_to_send) {
169 const char* bytes = reinterpret_cast<const char*>(buffer); 94 const char* bytes = reinterpret_cast<const char*>(buffer);
170 95
171 // Reserve a send buffer with 3 extra bytes (start, type, and end byte) and 96 // Reserve a send buffer with enough extra bytes for the start, type, end, and
172 // twice as many bytes as we're actually sending, because each raw data byte 97 // escape bytes.
173 // might need to be escaped.
174 vector<char> data; 98 vector<char> data;
175 data.reserve(2 * bytes_to_send + 3); 99 data.reserve(2 * bytes_to_send + 3);
176 100
177 data.push_back(BATTOR_CONTROL_BYTE_START); 101 data.push_back(BATTOR_CONTROL_BYTE_START);
178 data.push_back(type); 102 data.push_back(type);
179 103
180 for (size_t i = 0; i < bytes_to_send; i++) { 104 for (size_t i = 0; i < bytes_to_send; i++) {
181 if (bytes[i] == BATTOR_CONTROL_BYTE_START || 105 if (bytes[i] == BATTOR_CONTROL_BYTE_START ||
182 bytes[i] == BATTOR_CONTROL_BYTE_END) { 106 bytes[i] == BATTOR_CONTROL_BYTE_END) {
183 data.push_back(BATTOR_CONTROL_BYTE_ESCAPE); 107 data.push_back(BATTOR_CONTROL_BYTE_ESCAPE);
184 } 108 }
185 109
186 data.push_back(bytes[i]); 110 data.push_back(bytes[i]);
187 } 111 }
188 112
189 data.push_back(BATTOR_CONTROL_BYTE_END); 113 data.push_back(BATTOR_CONTROL_BYTE_END);
190 114
191 pending_write_length_ = data.size(); 115 pending_write_length_ = data.size();
192 io_handler_->Write(make_scoped_ptr(new device::SendBuffer( 116 io_handler_->Write(make_scoped_ptr(new device::SendBuffer(
193 data, base::Bind(&BattOrConnectionImpl::OnBytesSent, AsWeakPtr())))); 117 data, base::Bind(&BattOrConnectionImpl::OnBytesSent, AsWeakPtr()))));
194 } 118 }
195 119
196 void BattOrConnectionImpl::ReadBytes(size_t bytes_to_read) { 120 void BattOrConnectionImpl::ReadMessage(BattOrMessageType type) {
197 // Allocate a read buffer and reserve enough space in it to account for the 121 pending_read_message_type_ = type;
198 // start, type, end, and escape bytes. 122 size_t max_bytes_to_read = GetMaxBytesForMessageType(type);
199 pending_read_buffer_.reset(new vector<char>());
200 pending_read_buffer_->reserve(2 * bytes_to_read + 3);
201 pending_read_escape_byte_count_ = 0;
202 123
203 // Add 3 bytes to however many bytes the caller requested because we know 124 // Check the left-over bytes from the last read to make sure that we don't
204 // we'll have to read the start, type, and end bytes. 125 // already have a full message.
205 bytes_to_read += 3; 126 BattOrMessageType parsed_type;
127 scoped_ptr<vector<char>> bytes(new vector<char>());
128 bytes->reserve(max_bytes_to_read);
206 129
207 ReadMoreBytes(bytes_to_read); 130 if (ParseMessage(&parsed_type, bytes.get())) {
131 listener_->OnMessageRead(true, parsed_type, std::move(bytes));
132 return;
133 }
134
135 BeginReadBytes(max_bytes_to_read - already_read_buffer_.size());
208 } 136 }
209 137
210 void BattOrConnectionImpl::Flush() { 138 void BattOrConnectionImpl::Flush() {
211 io_handler_->Flush(); 139 io_handler_->Flush();
140 already_read_buffer_.clear();
212 } 141 }
213 142
214 scoped_refptr<device::SerialIoHandler> BattOrConnectionImpl::CreateIoHandler() { 143 scoped_refptr<device::SerialIoHandler> BattOrConnectionImpl::CreateIoHandler() {
215 return device::SerialIoHandler::Create(file_thread_task_runner_, 144 return device::SerialIoHandler::Create(file_thread_task_runner_,
216 ui_thread_task_runner_); 145 ui_thread_task_runner_);
217 } 146 }
218 147
219 void BattOrConnectionImpl::ReadMoreBytes(size_t bytes_to_read) { 148 void BattOrConnectionImpl::BeginReadBytes(size_t max_bytes_to_read) {
220 last_read_buffer_ = make_scoped_refptr(new net::IOBuffer(bytes_to_read)); 149 pending_read_buffer_ =
150 make_scoped_refptr(new net::IOBuffer(max_bytes_to_read));
151
221 auto on_receive_buffer_filled = 152 auto on_receive_buffer_filled =
222 base::Bind(&BattOrConnectionImpl::OnBytesRead, AsWeakPtr()); 153 base::Bind(&BattOrConnectionImpl::OnBytesRead, AsWeakPtr());
223 154
224 pending_read_length_ = bytes_to_read;
225 io_handler_->Read(make_scoped_ptr(new device::ReceiveBuffer( 155 io_handler_->Read(make_scoped_ptr(new device::ReceiveBuffer(
226 last_read_buffer_, bytes_to_read, on_receive_buffer_filled))); 156 pending_read_buffer_, max_bytes_to_read, on_receive_buffer_filled)));
227 } 157 }
228 158
229 void BattOrConnectionImpl::OnBytesRead(int bytes_read, 159 void BattOrConnectionImpl::OnBytesRead(int bytes_read,
230 device::serial::ReceiveError error) { 160 device::serial::ReceiveError error) {
231 if ((static_cast<size_t>(bytes_read) < pending_read_length_) || 161 if (bytes_read == 0 || error != device::serial::RECEIVE_ERROR_NONE) {
232 (error != device::serial::RECEIVE_ERROR_NONE)) { 162 // If we didn't have a message before, and we weren't able to read any
233 listener_->OnBytesRead(false, BATTOR_MESSAGE_TYPE_CONTROL, nullptr); 163 // additional bytes, then there's no valid message available.
164 EndReadBytes(false, BATTOR_MESSAGE_TYPE_CONTROL, nullptr);
234 return; 165 return;
235 } 166 }
236 167
237 pending_read_buffer_->insert(pending_read_buffer_->end(), 168 already_read_buffer_.insert(already_read_buffer_.end(),
238 last_read_buffer_->data(), 169 pending_read_buffer_->data(),
239 last_read_buffer_->data() + bytes_read); 170 pending_read_buffer_->data() + bytes_read);
240 171
241 scoped_ptr<vector<char>> parsed_content(new vector<char>());
242 MessageHealth health;
243 BattOrMessageType type; 172 BattOrMessageType type;
244 size_t escape_byte_count; 173 scoped_ptr<vector<char>> bytes(new vector<char>());
174 bytes->reserve(GetMaxBytesForMessageType(pending_read_message_type_));
245 175
246 ParseMessage(*pending_read_buffer_, parsed_content.get(), &health, &type, 176 if (!ParseMessage(&type, bytes.get())) {
247 &escape_byte_count); 177 // Even after reading the max number of bytes, we still don't have a valid
248 178 // message.
249 if (health == MessageHealth::INVALID) { 179 EndReadBytes(false, BATTOR_MESSAGE_TYPE_CONTROL, nullptr);
250 // If we already have an invalid message, there's no sense in continuing to
251 // process it.
252 listener_->OnBytesRead(false, BATTOR_MESSAGE_TYPE_CONTROL, nullptr);
253 return; 180 return;
254 } 181 }
255 182
256 size_t new_escape_bytes = escape_byte_count - pending_read_escape_byte_count_; 183 if (type != pending_read_message_type_) {
257 pending_read_escape_byte_count_ = escape_byte_count; 184 // We received a complete message, but it wasn't the type we were expecting.
258 185 EndReadBytes(false, BATTOR_MESSAGE_TYPE_CONTROL, nullptr);
259 if (new_escape_bytes > 0) {
260 // When the caller requested that we read X additional bytes, they weren't
261 // taking into account any escape bytes that we received. Because we got
262 // some escape bytes, we need to fire off another read to get the rest of
263 // the data.
264 ReadMoreBytes(new_escape_bytes);
265 return; 186 return;
266 } 187 }
267 188
268 if (health == MessageHealth::INCOMPLETE) 189 EndReadBytes(true, type, std::move(bytes));
269 // If everything is valid and we didn't see any escape bytes, then we should 190 }
270 // have the whole message. If we don't, the message was malformed.
271 listener_->OnBytesRead(false, BATTOR_MESSAGE_TYPE_CONTROL, nullptr);
272 191
273 // If we've gotten this far, we've received the whole, well-formed message. 192 void BattOrConnectionImpl::EndReadBytes(bool success,
274 listener_->OnBytesRead(true, type, std::move(parsed_content)); 193 BattOrMessageType type,
194 scoped_ptr<std::vector<char>> bytes) {
195 pending_read_buffer_ = nullptr;
196
197 listener_->OnMessageRead(success, type, std::move(bytes));
198 }
199
200 bool BattOrConnectionImpl::ParseMessage(BattOrMessageType* type,
201 vector<char>* bytes) {
202 if (already_read_buffer_.size() <= 3)
203 return false;
204
205 // The first byte is the start byte.
206 if (already_read_buffer_[0] != BATTOR_CONTROL_BYTE_START) {
207 return false;
208 }
209
210 // The second byte specifies the message type.
211 *type = static_cast<BattOrMessageType>(already_read_buffer_[1]);
212
213 if (*type < static_cast<uint8_t>(BATTOR_MESSAGE_TYPE_CONTROL) ||
214 *type > static_cast<uint8_t>(BATTOR_MESSAGE_TYPE_PRINT)) {
215 return false;
216 }
217
218 // After that comes the message bytes.
219 bool escape_next_byte = false;
220 for (size_t i = 2; i < already_read_buffer_.size(); i++) {
221 char next_byte = already_read_buffer_[i];
222
223 if (escape_next_byte) {
224 bytes->push_back(next_byte);
225 escape_next_byte = false;
226 continue;
227 }
228
229 switch (next_byte) {
230 case BATTOR_CONTROL_BYTE_START:
231 // Two start bytes in a message is invalid.
232 return false;
233
234 case BATTOR_CONTROL_BYTE_END:
235 already_read_buffer_.erase(already_read_buffer_.begin(),
236 already_read_buffer_.begin() + i + 1);
237 return true;
238
239 case BATTOR_CONTROL_BYTE_ESCAPE:
240 escape_next_byte = true;
241 continue;
242
243 default:
244 bytes->push_back(next_byte);
245 }
246 }
247
248 // If we made it to the end of the read buffer and no end byte was seen, then
249 // we don't have a complete message.
250 return false;
275 } 251 }
276 252
277 void BattOrConnectionImpl::OnBytesSent(int bytes_sent, 253 void BattOrConnectionImpl::OnBytesSent(int bytes_sent,
278 device::serial::SendError error) { 254 device::serial::SendError error) {
279 bool success = (error == device::serial::SEND_ERROR_NONE) && 255 bool success = (error == device::serial::SEND_ERROR_NONE) &&
280 (pending_write_length_ == static_cast<size_t>(bytes_sent)); 256 (pending_write_length_ == static_cast<size_t>(bytes_sent));
281 listener_->OnBytesSent(success); 257 listener_->OnBytesSent(success);
282 } 258 }
283 259
284 } // namespace battor 260 } // namespace battor
OLDNEW
« no previous file with comments | « tools/battor_agent/battor_connection_impl.h ('k') | tools/battor_agent/battor_connection_impl_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698