disable two ClientCertStoreChromeOSTest.* unit_tests on Valgrind bots
[chromium-blink-merge.git] / device / serial / serial_io_handler_win.cc
blobcd1045107fe746e285d1bf422297236228339638
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include <windows.h>
7 #include "device/serial/serial_io_handler_win.h"
9 namespace device {
11 namespace {
13 int BitrateToSpeedConstant(int bitrate) {
14 #define BITRATE_TO_SPEED_CASE(x) \
15 case x: \
16 return CBR_##x;
17 switch (bitrate) {
18 BITRATE_TO_SPEED_CASE(110);
19 BITRATE_TO_SPEED_CASE(300);
20 BITRATE_TO_SPEED_CASE(600);
21 BITRATE_TO_SPEED_CASE(1200);
22 BITRATE_TO_SPEED_CASE(2400);
23 BITRATE_TO_SPEED_CASE(4800);
24 BITRATE_TO_SPEED_CASE(9600);
25 BITRATE_TO_SPEED_CASE(14400);
26 BITRATE_TO_SPEED_CASE(19200);
27 BITRATE_TO_SPEED_CASE(38400);
28 BITRATE_TO_SPEED_CASE(57600);
29 BITRATE_TO_SPEED_CASE(115200);
30 BITRATE_TO_SPEED_CASE(128000);
31 BITRATE_TO_SPEED_CASE(256000);
32 default:
33 // If the bitrate doesn't match that of one of the standard
34 // index constants, it may be provided as-is to the DCB
35 // structure, according to MSDN.
36 return bitrate;
38 #undef BITRATE_TO_SPEED_CASE
41 int DataBitsEnumToConstant(serial::DataBits data_bits) {
42 switch (data_bits) {
43 case serial::DATA_BITS_SEVEN:
44 return 7;
45 case serial::DATA_BITS_EIGHT:
46 default:
47 return 8;
51 int ParityBitEnumToConstant(serial::ParityBit parity_bit) {
52 switch (parity_bit) {
53 case serial::PARITY_BIT_EVEN:
54 return EVENPARITY;
55 case serial::PARITY_BIT_ODD:
56 return ODDPARITY;
57 case serial::PARITY_BIT_NO:
58 default:
59 return NOPARITY;
63 int StopBitsEnumToConstant(serial::StopBits stop_bits) {
64 switch (stop_bits) {
65 case serial::STOP_BITS_TWO:
66 return TWOSTOPBITS;
67 case serial::STOP_BITS_ONE:
68 default:
69 return ONESTOPBIT;
73 int SpeedConstantToBitrate(int speed) {
74 #define SPEED_TO_BITRATE_CASE(x) \
75 case CBR_##x: \
76 return x;
77 switch (speed) {
78 SPEED_TO_BITRATE_CASE(110);
79 SPEED_TO_BITRATE_CASE(300);
80 SPEED_TO_BITRATE_CASE(600);
81 SPEED_TO_BITRATE_CASE(1200);
82 SPEED_TO_BITRATE_CASE(2400);
83 SPEED_TO_BITRATE_CASE(4800);
84 SPEED_TO_BITRATE_CASE(9600);
85 SPEED_TO_BITRATE_CASE(14400);
86 SPEED_TO_BITRATE_CASE(19200);
87 SPEED_TO_BITRATE_CASE(38400);
88 SPEED_TO_BITRATE_CASE(57600);
89 SPEED_TO_BITRATE_CASE(115200);
90 SPEED_TO_BITRATE_CASE(128000);
91 SPEED_TO_BITRATE_CASE(256000);
92 default:
93 // If it's not one of the standard index constants,
94 // it should be an integral baud rate, according to
95 // MSDN.
96 return speed;
98 #undef SPEED_TO_BITRATE_CASE
101 serial::DataBits DataBitsConstantToEnum(int data_bits) {
102 switch (data_bits) {
103 case 7:
104 return serial::DATA_BITS_SEVEN;
105 case 8:
106 default:
107 return serial::DATA_BITS_EIGHT;
111 serial::ParityBit ParityBitConstantToEnum(int parity_bit) {
112 switch (parity_bit) {
113 case EVENPARITY:
114 return serial::PARITY_BIT_EVEN;
115 case ODDPARITY:
116 return serial::PARITY_BIT_ODD;
117 case NOPARITY:
118 default:
119 return serial::PARITY_BIT_NO;
123 serial::StopBits StopBitsConstantToEnum(int stop_bits) {
124 switch (stop_bits) {
125 case TWOSTOPBITS:
126 return serial::STOP_BITS_TWO;
127 case ONESTOPBIT:
128 default:
129 return serial::STOP_BITS_ONE;
133 } // namespace
135 // static
136 scoped_refptr<SerialIoHandler> SerialIoHandler::Create(
137 scoped_refptr<base::SingleThreadTaskRunner> file_thread_task_runner,
138 scoped_refptr<base::SingleThreadTaskRunner> ui_thread_task_runner) {
139 return new SerialIoHandlerWin(file_thread_task_runner, ui_thread_task_runner);
142 bool SerialIoHandlerWin::PostOpen() {
143 DCHECK(!comm_context_);
144 DCHECK(!read_context_);
145 DCHECK(!write_context_);
147 base::MessageLoopForIO::current()->RegisterIOHandler(file().GetPlatformFile(),
148 this);
150 comm_context_.reset(new base::MessageLoopForIO::IOContext());
151 comm_context_->handler = this;
152 memset(&comm_context_->overlapped, 0, sizeof(comm_context_->overlapped));
154 read_context_.reset(new base::MessageLoopForIO::IOContext());
155 read_context_->handler = this;
156 memset(&read_context_->overlapped, 0, sizeof(read_context_->overlapped));
158 write_context_.reset(new base::MessageLoopForIO::IOContext());
159 write_context_->handler = this;
160 memset(&write_context_->overlapped, 0, sizeof(write_context_->overlapped));
162 // A ReadIntervalTimeout of MAXDWORD will cause async reads to complete
163 // immediately with any data that's available, even if there is none.
164 // This is OK because we never issue a read request until WaitCommEvent
165 // signals that data is available.
166 COMMTIMEOUTS timeouts = {0};
167 timeouts.ReadIntervalTimeout = MAXDWORD;
168 if (!::SetCommTimeouts(file().GetPlatformFile(), &timeouts)) {
169 VPLOG(1) << "Failed to set serial timeouts";
170 return false;
173 return true;
176 void SerialIoHandlerWin::ReadImpl() {
177 DCHECK(CalledOnValidThread());
178 DCHECK(pending_read_buffer());
179 DCHECK(file().IsValid());
181 if (!SetCommMask(file().GetPlatformFile(), EV_RXCHAR)) {
182 VPLOG(1) << "Failed to set serial event flags";
185 event_mask_ = 0;
186 BOOL ok = ::WaitCommEvent(
187 file().GetPlatformFile(), &event_mask_, &comm_context_->overlapped);
188 if (!ok && GetLastError() != ERROR_IO_PENDING) {
189 VPLOG(1) << "Failed to receive serial event";
190 QueueReadCompleted(0, serial::RECEIVE_ERROR_SYSTEM_ERROR);
192 is_comm_pending_ = true;
195 void SerialIoHandlerWin::WriteImpl() {
196 DCHECK(CalledOnValidThread());
197 DCHECK(pending_write_buffer());
198 DCHECK(file().IsValid());
200 BOOL ok = ::WriteFile(file().GetPlatformFile(),
201 pending_write_buffer(),
202 pending_write_buffer_len(),
203 NULL,
204 &write_context_->overlapped);
205 if (!ok && GetLastError() != ERROR_IO_PENDING) {
206 VPLOG(1) << "Write failed";
207 QueueWriteCompleted(0, serial::SEND_ERROR_SYSTEM_ERROR);
211 void SerialIoHandlerWin::CancelReadImpl() {
212 DCHECK(CalledOnValidThread());
213 DCHECK(file().IsValid());
214 ::CancelIo(file().GetPlatformFile());
217 void SerialIoHandlerWin::CancelWriteImpl() {
218 DCHECK(CalledOnValidThread());
219 DCHECK(file().IsValid());
220 ::CancelIo(file().GetPlatformFile());
223 bool SerialIoHandlerWin::ConfigurePortImpl() {
224 DCB config = {0};
225 config.DCBlength = sizeof(config);
226 if (!GetCommState(file().GetPlatformFile(), &config)) {
227 VPLOG(1) << "Failed to get serial port info";
228 return false;
231 // Set up some sane default options that are not configurable.
232 config.fBinary = TRUE;
233 config.fParity = TRUE;
234 config.fAbortOnError = TRUE;
235 config.fOutxDsrFlow = FALSE;
236 config.fDtrControl = DTR_CONTROL_ENABLE;
237 config.fDsrSensitivity = FALSE;
238 config.fOutX = FALSE;
239 config.fInX = FALSE;
241 DCHECK(options().bitrate);
242 config.BaudRate = BitrateToSpeedConstant(options().bitrate);
244 DCHECK(options().data_bits != serial::DATA_BITS_NONE);
245 config.ByteSize = DataBitsEnumToConstant(options().data_bits);
247 DCHECK(options().parity_bit != serial::PARITY_BIT_NONE);
248 config.Parity = ParityBitEnumToConstant(options().parity_bit);
250 DCHECK(options().stop_bits != serial::STOP_BITS_NONE);
251 config.StopBits = StopBitsEnumToConstant(options().stop_bits);
253 DCHECK(options().has_cts_flow_control);
254 if (options().cts_flow_control) {
255 config.fOutxCtsFlow = TRUE;
256 config.fRtsControl = RTS_CONTROL_HANDSHAKE;
257 } else {
258 config.fOutxCtsFlow = FALSE;
259 config.fRtsControl = RTS_CONTROL_ENABLE;
262 if (!SetCommState(file().GetPlatformFile(), &config)) {
263 VPLOG(1) << "Failed to set serial port info";
264 return false;
266 return true;
269 SerialIoHandlerWin::SerialIoHandlerWin(
270 scoped_refptr<base::SingleThreadTaskRunner> file_thread_task_runner,
271 scoped_refptr<base::SingleThreadTaskRunner> ui_thread_task_runner)
272 : SerialIoHandler(file_thread_task_runner, ui_thread_task_runner),
273 event_mask_(0),
274 is_comm_pending_(false) {
277 SerialIoHandlerWin::~SerialIoHandlerWin() {
280 void SerialIoHandlerWin::OnIOCompleted(
281 base::MessageLoopForIO::IOContext* context,
282 DWORD bytes_transferred,
283 DWORD error) {
284 DCHECK(CalledOnValidThread());
285 if (context == comm_context_) {
286 DWORD errors;
287 COMSTAT status;
288 if (!ClearCommError(file().GetPlatformFile(), &errors, &status) ||
289 errors != 0) {
290 if (errors & CE_BREAK) {
291 ReadCompleted(0, serial::RECEIVE_ERROR_BREAK);
292 } else if (errors & CE_FRAME) {
293 ReadCompleted(0, serial::RECEIVE_ERROR_FRAME_ERROR);
294 } else if (errors & CE_OVERRUN) {
295 ReadCompleted(0, serial::RECEIVE_ERROR_OVERRUN);
296 } else if (errors & CE_RXOVER) {
297 ReadCompleted(0, serial::RECEIVE_ERROR_BUFFER_OVERFLOW);
298 } else if (errors & CE_RXPARITY) {
299 ReadCompleted(0, serial::RECEIVE_ERROR_PARITY_ERROR);
300 } else {
301 ReadCompleted(0, serial::RECEIVE_ERROR_SYSTEM_ERROR);
303 return;
306 if (read_canceled()) {
307 ReadCompleted(bytes_transferred, read_cancel_reason());
308 } else if (error != ERROR_SUCCESS && error != ERROR_OPERATION_ABORTED) {
309 ReadCompleted(0, serial::RECEIVE_ERROR_SYSTEM_ERROR);
310 } else if (pending_read_buffer()) {
311 BOOL ok = ::ReadFile(file().GetPlatformFile(),
312 pending_read_buffer(),
313 pending_read_buffer_len(),
314 NULL,
315 &read_context_->overlapped);
316 if (!ok && GetLastError() != ERROR_IO_PENDING) {
317 VPLOG(1) << "Read failed";
318 ReadCompleted(0, serial::RECEIVE_ERROR_SYSTEM_ERROR);
321 } else if (context == read_context_) {
322 if (read_canceled()) {
323 ReadCompleted(bytes_transferred, read_cancel_reason());
324 } else if (error != ERROR_SUCCESS && error != ERROR_OPERATION_ABORTED) {
325 ReadCompleted(0, serial::RECEIVE_ERROR_SYSTEM_ERROR);
326 } else {
327 ReadCompleted(bytes_transferred,
328 error == ERROR_SUCCESS
329 ? serial::RECEIVE_ERROR_NONE
330 : serial::RECEIVE_ERROR_SYSTEM_ERROR);
332 } else if (context == write_context_) {
333 DCHECK(pending_write_buffer());
334 if (write_canceled()) {
335 WriteCompleted(0, write_cancel_reason());
336 } else if (error != ERROR_SUCCESS && error != ERROR_OPERATION_ABORTED) {
337 WriteCompleted(0, serial::SEND_ERROR_SYSTEM_ERROR);
338 if (error == ERROR_GEN_FAILURE && IsReadPending()) {
339 // For devices using drivers such as FTDI, CP2xxx, when device is
340 // disconnected, the context is comm_context_ and the error is
341 // ERROR_OPERATION_ABORTED.
342 // However, for devices using CDC-ACM driver, when device is
343 // disconnected, the context is write_context_ and the error is
344 // ERROR_GEN_FAILURE. In this situation, in addition to a write error
345 // signal, also need to generate a read error signal
346 // serial::OnReceiveError which will notify the app about the
347 // disconnection.
348 CancelRead(serial::RECEIVE_ERROR_SYSTEM_ERROR);
350 } else {
351 WriteCompleted(bytes_transferred,
352 error == ERROR_SUCCESS ? serial::SEND_ERROR_NONE
353 : serial::SEND_ERROR_SYSTEM_ERROR);
355 } else {
356 NOTREACHED() << "Invalid IOContext";
360 bool SerialIoHandlerWin::Flush() const {
361 if (!PurgeComm(file().GetPlatformFile(), PURGE_RXCLEAR | PURGE_TXCLEAR)) {
362 VPLOG(1) << "Failed to flush serial port";
363 return false;
365 return true;
368 serial::DeviceControlSignalsPtr SerialIoHandlerWin::GetControlSignals() const {
369 DWORD status;
370 if (!GetCommModemStatus(file().GetPlatformFile(), &status)) {
371 VPLOG(1) << "Failed to get port control signals";
372 return serial::DeviceControlSignalsPtr();
375 serial::DeviceControlSignalsPtr signals(serial::DeviceControlSignals::New());
376 signals->dcd = (status & MS_RLSD_ON) != 0;
377 signals->cts = (status & MS_CTS_ON) != 0;
378 signals->dsr = (status & MS_DSR_ON) != 0;
379 signals->ri = (status & MS_RING_ON) != 0;
380 return signals.Pass();
383 bool SerialIoHandlerWin::SetControlSignals(
384 const serial::HostControlSignals& signals) {
385 if (signals.has_dtr) {
386 if (!EscapeCommFunction(file().GetPlatformFile(),
387 signals.dtr ? SETDTR : CLRDTR)) {
388 VPLOG(1) << "Failed to configure DTR signal";
389 return false;
392 if (signals.has_rts) {
393 if (!EscapeCommFunction(file().GetPlatformFile(),
394 signals.rts ? SETRTS : CLRRTS)) {
395 VPLOG(1) << "Failed to configure RTS signal";
396 return false;
399 return true;
402 serial::ConnectionInfoPtr SerialIoHandlerWin::GetPortInfo() const {
403 DCB config = {0};
404 config.DCBlength = sizeof(config);
405 if (!GetCommState(file().GetPlatformFile(), &config)) {
406 VPLOG(1) << "Failed to get serial port info";
407 return serial::ConnectionInfoPtr();
409 serial::ConnectionInfoPtr info(serial::ConnectionInfo::New());
410 info->bitrate = SpeedConstantToBitrate(config.BaudRate);
411 info->data_bits = DataBitsConstantToEnum(config.ByteSize);
412 info->parity_bit = ParityBitConstantToEnum(config.Parity);
413 info->stop_bits = StopBitsConstantToEnum(config.StopBits);
414 info->cts_flow_control = config.fOutxCtsFlow != 0;
415 return info.Pass();
418 bool SerialIoHandlerWin::SetBreak() {
419 if (!SetCommBreak(file().GetPlatformFile())) {
420 VPLOG(1) << "Failed to set break";
421 return false;
423 return true;
426 bool SerialIoHandlerWin::ClearBreak() {
427 if (!ClearCommBreak(file().GetPlatformFile())) {
428 VPLOG(1) << "Failed to clear break";
429 return false;
431 return true;
434 std::string SerialIoHandler::MaybeFixUpPortName(const std::string& port_name) {
435 // For COM numbers less than 9, CreateFile is called with a string such as
436 // "COM1". For numbers greater than 9, a prefix of "\\\\.\\" must be added.
437 if (port_name.length() > std::string("COM9").length())
438 return std::string("\\\\.\\").append(port_name);
440 return port_name;
443 } // namespace device