File: serial_connection.cc

package info (click to toggle)
chromium 139.0.7258.127-2
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 6,122,156 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (668 lines) | stat: -rw-r--r-- 22,279 bytes parent folder | download | duplicates (7)
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "extensions/browser/api/serial/serial_connection.h"

#include <algorithm>
#include <memory>
#include <string>
#include <tuple>
#include <utility>
#include <vector>

#include "base/files/file_path.h"
#include "base/functional/bind.h"
#include "base/lazy_instance.h"
#include "base/location.h"
#include "base/task/single_thread_task_runner.h"
#include "extensions/browser/api/api_resource_manager.h"
#include "extensions/browser/api/serial/serial_port_manager.h"
#include "extensions/common/api/serial.h"
#include "mojo/public/cpp/bindings/callback_helpers.h"
#include "mojo/public/cpp/bindings/pending_remote.h"

namespace extensions {

namespace {

const int kDefaultBufferSize = 4096;

api::serial::SendError ConvertSendErrorFromMojo(
    device::mojom::SerialSendError input) {
  switch (input) {
    case device::mojom::SerialSendError::NONE:
      return api::serial::SendError::kNone;
    case device::mojom::SerialSendError::DISCONNECTED:
      return api::serial::SendError::kDisconnected;
    case device::mojom::SerialSendError::SYSTEM_ERROR:
      return api::serial::SendError::kSystemError;
  }
  return api::serial::SendError::kNone;
}

api::serial::ReceiveError ConvertReceiveErrorFromMojo(
    device::mojom::SerialReceiveError input) {
  switch (input) {
    case device::mojom::SerialReceiveError::NONE:
      return api::serial::ReceiveError::kNone;
    case device::mojom::SerialReceiveError::DISCONNECTED:
      return api::serial::ReceiveError::kDisconnected;
    case device::mojom::SerialReceiveError::DEVICE_LOST:
      return api::serial::ReceiveError::kDeviceLost;
    case device::mojom::SerialReceiveError::BREAK:
      return api::serial::ReceiveError::kBreak;
    case device::mojom::SerialReceiveError::FRAME_ERROR:
      return api::serial::ReceiveError::kFrameError;
    case device::mojom::SerialReceiveError::OVERRUN:
      return api::serial::ReceiveError::kOverrun;
    case device::mojom::SerialReceiveError::BUFFER_OVERFLOW:
      return api::serial::ReceiveError::kBufferOverflow;
    case device::mojom::SerialReceiveError::PARITY_ERROR:
      return api::serial::ReceiveError::kParityError;
    case device::mojom::SerialReceiveError::SYSTEM_ERROR:
      return api::serial::ReceiveError::kSystemError;
  }
  return api::serial::ReceiveError::kNone;
}

api::serial::DataBits ConvertDataBitsFromMojo(
    device::mojom::SerialDataBits input) {
  switch (input) {
    case device::mojom::SerialDataBits::NONE:
      return api::serial::DataBits::kNone;
    case device::mojom::SerialDataBits::SEVEN:
      return api::serial::DataBits::kSeven;
    case device::mojom::SerialDataBits::EIGHT:
      return api::serial::DataBits::kEight;
  }
  return api::serial::DataBits::kNone;
}

device::mojom::SerialDataBits ConvertDataBitsToMojo(
    api::serial::DataBits input) {
  switch (input) {
    case api::serial::DataBits::kNone:
      return device::mojom::SerialDataBits::NONE;
    case api::serial::DataBits::kSeven:
      return device::mojom::SerialDataBits::SEVEN;
    case api::serial::DataBits::kEight:
      return device::mojom::SerialDataBits::EIGHT;
  }
  return device::mojom::SerialDataBits::NONE;
}

api::serial::ParityBit ConvertParityBitFromMojo(
    device::mojom::SerialParityBit input) {
  switch (input) {
    case device::mojom::SerialParityBit::NONE:
      return api::serial::ParityBit::kNone;
    case device::mojom::SerialParityBit::ODD:
      return api::serial::ParityBit::kOdd;
    case device::mojom::SerialParityBit::NO_PARITY:
      return api::serial::ParityBit::kNo;
    case device::mojom::SerialParityBit::EVEN:
      return api::serial::ParityBit::kEven;
  }
  return api::serial::ParityBit::kNone;
}

device::mojom::SerialParityBit ConvertParityBitToMojo(
    api::serial::ParityBit input) {
  switch (input) {
    case api::serial::ParityBit::kNone:
      return device::mojom::SerialParityBit::NONE;
    case api::serial::ParityBit::kNo:
      return device::mojom::SerialParityBit::NO_PARITY;
    case api::serial::ParityBit::kOdd:
      return device::mojom::SerialParityBit::ODD;
    case api::serial::ParityBit::kEven:
      return device::mojom::SerialParityBit::EVEN;
  }
  return device::mojom::SerialParityBit::NONE;
}

api::serial::StopBits ConvertStopBitsFromMojo(
    device::mojom::SerialStopBits input) {
  switch (input) {
    case device::mojom::SerialStopBits::NONE:
      return api::serial::StopBits::kNone;
    case device::mojom::SerialStopBits::ONE:
      return api::serial::StopBits::kOne;
    case device::mojom::SerialStopBits::TWO:
      return api::serial::StopBits::kTwo;
  }
  return api::serial::StopBits::kNone;
}

device::mojom::SerialStopBits ConvertStopBitsToMojo(
    api::serial::StopBits input) {
  switch (input) {
    case api::serial::StopBits::kNone:
      return device::mojom::SerialStopBits::NONE;
    case api::serial::StopBits::kOne:
      return device::mojom::SerialStopBits::ONE;
    case api::serial::StopBits::kTwo:
      return device::mojom::SerialStopBits::TWO;
  }
  return device::mojom::SerialStopBits::NONE;
}

}  // namespace

static base::LazyInstance<BrowserContextKeyedAPIFactory<
    ApiResourceManager<SerialConnection>>>::DestructorAtExit g_factory =
    LAZY_INSTANCE_INITIALIZER;

// static
template <>
BrowserContextKeyedAPIFactory<ApiResourceManager<SerialConnection> >*
ApiResourceManager<SerialConnection>::GetFactoryInstance() {
  return g_factory.Pointer();
}

SerialConnection::SerialConnection(const std::string& owner_extension_id)
    : ApiResource(owner_extension_id),
      persistent_(false),
      buffer_size_(kDefaultBufferSize),
      receive_timeout_(0),
      send_timeout_(0),
      paused_(true),
      read_error_(std::nullopt),
      bytes_written_(0),
      receive_pipe_watcher_(FROM_HERE,
                            mojo::SimpleWatcher::ArmingPolicy::MANUAL),
      send_pipe_watcher_(FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::MANUAL) {
}

SerialConnection::~SerialConnection() = default;

bool SerialConnection::IsPersistent() const {
  return persistent();
}

void SerialConnection::set_buffer_size(int buffer_size) {
  buffer_size_ = buffer_size;
}

void SerialConnection::set_receive_timeout(int receive_timeout) {
  receive_timeout_ = receive_timeout;
}

void SerialConnection::set_send_timeout(int send_timeout) {
  send_timeout_ = send_timeout;
}

void SerialConnection::SetPaused(bool paused) {
  DCHECK(serial_port_);
  if (paused_ == paused)
    return;

  paused_ = paused;
  if (paused_) {
    // Make sure no pending timeout task fires.
    receive_timeout_task_.Cancel();
  } else {
    // If |receive_pipe_| is closed and there is no pending ReceiveError event,
    // try to reconnect the data pipe.
    if (!receive_pipe_ && !read_error_)
      SetUpReceiveDataPipe();
    receive_pipe_watcher_.ArmOrNotify();
    receive_timeout_task_.Cancel();
    SetTimeoutCallback();
  }
}

void SerialConnection::SetConnectionErrorHandler(
    base::OnceClosure connection_error_handler) {
  if (!serial_port_.is_connected()) {
    // Already being disconnected, run client's error handler immediatelly.
    std::move(connection_error_handler).Run();
    return;
  }
  connection_error_handler_ = std::move(connection_error_handler);
}

void SerialConnection::Open(api::SerialPortManager* port_manager,
                            const std::string& path,
                            const api::serial::ConnectionOptions& options,
                            OpenCompleteCallback callback) {
  DCHECK(!serial_port_);
  DCHECK(!send_pipe_);
  DCHECK(!receive_pipe_);

  if (options.persistent)
    set_persistent(*options.persistent);
  if (options.name)
    set_name(*options.name);
  if (options.buffer_size)
    set_buffer_size(*options.buffer_size);
  if (options.receive_timeout)
    set_receive_timeout(*options.receive_timeout);
  if (options.send_timeout)
    set_send_timeout(*options.send_timeout);

  mojo::PendingRemote<device::mojom::SerialPortClient> client;
  auto client_receiver = client.InitWithNewPipeAndPassReceiver();
  port_manager->OpenPort(
      path, device::mojom::SerialConnectionOptions::From(options),
      std::move(client),
      mojo::WrapCallbackWithDefaultInvokeIfNotRun(
          base::BindOnce(&SerialConnection::OnOpen, weak_factory_.GetWeakPtr(),
                         std::move(client_receiver), std::move(callback)),
          mojo::NullRemote()));
}

void SerialConnection::CreatePipe(
    mojo::ScopedDataPipeProducerHandle* producer,
    mojo::ScopedDataPipeConsumerHandle* consumer) {
  MojoCreateDataPipeOptions options;
  options.struct_size = sizeof(MojoCreateDataPipeOptions);
  options.flags = MOJO_CREATE_DATA_PIPE_FLAG_NONE;
  options.element_num_bytes = 1;
  options.capacity_num_bytes = buffer_size_;

  CHECK_EQ(MOJO_RESULT_OK,
           mojo::CreateDataPipe(&options, *producer, *consumer));
}

void SerialConnection::SetUpReceiveDataPipe() {
  mojo::ScopedDataPipeProducerHandle producer;
  CreatePipe(&producer, &receive_pipe_);

  serial_port_->StartReading(std::move(producer));

  receive_pipe_watcher_.Watch(
      receive_pipe_.get(),
      MOJO_HANDLE_SIGNAL_READABLE | MOJO_HANDLE_SIGNAL_PEER_CLOSED,
      MOJO_TRIGGER_CONDITION_SIGNALS_SATISFIED,
      base::BindRepeating(&SerialConnection::OnReadPipeReadableOrClosed,
                          weak_factory_.GetWeakPtr()));
}

void SerialConnection::SetUpSendDataPipe() {
  mojo::ScopedDataPipeConsumerHandle consumer;
  CreatePipe(&send_pipe_, &consumer);

  serial_port_->StartWriting(std::move(consumer));

  send_pipe_watcher_.Watch(
      send_pipe_.get(),
      MOJO_HANDLE_SIGNAL_WRITABLE | MOJO_HANDLE_SIGNAL_PEER_CLOSED,
      MOJO_TRIGGER_CONDITION_SIGNALS_SATISFIED,
      base::BindRepeating(&SerialConnection::OnSendPipeWritableOrClosed,
                          weak_factory_.GetWeakPtr()));
}

void SerialConnection::OnReadError(device::mojom::SerialReceiveError error) {
  DCHECK_NE(device::mojom::SerialReceiveError::NONE, error);
  if (receive_pipe_) {
    // Wait for remaining data to be read from the pipe before signaling an
    // error.
    read_error_ = error;
    return;
  }
  // Dispatch OnReceiveError event when the data pipe has been closed.
  receive_event_cb_.Run(std::vector<uint8_t>(),
                        ConvertReceiveErrorFromMojo(error));
}

void SerialConnection::OnSendError(device::mojom::SerialSendError error) {
  DCHECK_NE(device::mojom::SerialSendError::NONE, error);
  send_pipe_watcher_.Cancel();
  send_pipe_.reset();

  // Invoking `send_complete_` may free `this`.
  size_t bytes_written = bytes_written_;
  bytes_written_ = 0;

  if (send_complete_) {
    // Respond the send request with bytes written currently.
    std::move(send_complete_)
        .Run(bytes_written, ConvertSendErrorFromMojo(error));
  }
}

void SerialConnection::OnOpen(
    mojo::PendingReceiver<device::mojom::SerialPortClient> client_receiver,
    OpenCompleteCallback callback,
    mojo::PendingRemote<device::mojom::SerialPort> serial_port) {
  if (!serial_port.is_valid()) {
    std::move(callback).Run(false);
    return;
  }

  serial_port_.Bind(std::move(serial_port));
  serial_port_.set_disconnect_handler(base::BindOnce(
      &SerialConnection::OnConnectionError, base::Unretained(this)));

  SetUpReceiveDataPipe();
  SetUpSendDataPipe();
  client_receiver_.Bind(std::move(client_receiver));
  client_receiver_.set_disconnect_handler(base::BindOnce(
      &SerialConnection::OnClientReceiverClosed, weak_factory_.GetWeakPtr()));
  std::move(callback).Run(true);
}

void SerialConnection::OnReadPipeClosed() {
  receive_pipe_watcher_.Cancel();
  receive_pipe_.reset();

  if (read_error_) {
    // Dispatch OnReceiveError if there is a pending error.
    auto error = ConvertReceiveErrorFromMojo(read_error_.value());
    read_error_.reset();
    receive_event_cb_.Run(std::vector<uint8_t>(), error);
  }
}

void SerialConnection::OnReadPipeReadableOrClosed(
    MojoResult result,
    const mojo::HandleSignalsState& state) {
  // Data pipe disconnected.
  if (result != MOJO_RESULT_OK) {
    OnReadPipeClosed();
    return;
  }
  // Return when it is paused, the watcher will be disarmed.
  if (paused_)
    return;

  DCHECK(receive_pipe_);
  base::span<const uint8_t> buffer;
  result = receive_pipe_->BeginReadData(MOJO_READ_DATA_FLAG_NONE, buffer);
  if (result == MOJO_RESULT_SHOULD_WAIT) {
    receive_pipe_watcher_.ArmOrNotify();
    return;
  }
  // For remote pipe producer handle has been closed.
  if (result == MOJO_RESULT_FAILED_PRECONDITION) {
    OnReadPipeClosed();
    return;
  }
  std::vector<uint8_t> data(buffer.begin(), buffer.end());
  result = receive_pipe_->EndReadData(buffer.size());
  DCHECK_EQ(MOJO_RESULT_OK, result);

  // Reset the timeout timer and arm the watcher in preparation for the next
  // read. This will be undone if |receive_event_cb_| calls SetPaused(true).
  receive_timeout_task_.Cancel();
  SetTimeoutCallback();
  receive_pipe_watcher_.ArmOrNotify();

  receive_event_cb_.Run(std::move(data), api::serial::ReceiveError::kNone);
}

void SerialConnection::StartPolling(const ReceiveEventCallback& callback) {
  receive_event_cb_ = callback;
  DCHECK(receive_event_cb_);
  DCHECK(receive_pipe_);
  DCHECK(paused_);
  SetPaused(false);
}

void SerialConnection::Send(const std::vector<uint8_t>& data,
                            SendCompleteCallback callback) {
  if (send_complete_) {
    base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
        FROM_HERE, base::BindOnce(std::move(callback), 0,
                                  api::serial::SendError::kPending));
    return;
  }

  DCHECK(serial_port_);
  bytes_written_ = 0;
  send_complete_ = std::move(callback);

  DCHECK(data_to_send_.empty());
  data_to_send_.assign(data.begin(), data.end());

  if (!send_pipe_)
    SetUpSendDataPipe();
  send_pipe_watcher_.ArmOrNotify();

  send_timeout_task_.Cancel();
  if (send_timeout_ > 0) {
    send_timeout_task_.Reset(base::BindOnce(&SerialConnection::OnSendTimeout,
                                            weak_factory_.GetWeakPtr()));
    base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
        FROM_HERE, send_timeout_task_.callback(),
        base::Milliseconds(send_timeout_));
  }
}

void SerialConnection::Configure(const api::serial::ConnectionOptions& options,
                                 ConfigureCompleteCallback callback) {
  DCHECK(serial_port_);
  if (options.persistent)
    set_persistent(*options.persistent);
  if (options.name)
    set_name(*options.name);
  if (options.buffer_size)
    set_buffer_size(*options.buffer_size);
  if (options.receive_timeout)
    set_receive_timeout(*options.receive_timeout);
  if (options.send_timeout)
    set_send_timeout(*options.send_timeout);
  serial_port_->ConfigurePort(
      device::mojom::SerialConnectionOptions::From(options),
      mojo::WrapCallbackWithDefaultInvokeIfNotRun(std::move(callback), false));
}

void SerialConnection::GetInfo(GetInfoCompleteCallback callback) const {
  DCHECK(serial_port_);

  auto info = std::make_unique<api::serial::ConnectionInfo>();
  info->paused = paused_;
  info->persistent = persistent_;
  info->name = name_;
  info->buffer_size = buffer_size_;
  info->receive_timeout = receive_timeout_;
  info->send_timeout = send_timeout_;

  auto resp_callback = base::BindOnce(
      [](GetInfoCompleteCallback callback,
         std::unique_ptr<api::serial::ConnectionInfo> info,
         device::mojom::SerialConnectionInfoPtr port_info) {
        if (!port_info) {
          // Even without remote port info, return partial info and indicate
          // that it's not complete info.
          std::move(callback).Run(false, std::move(info));
          return;
        }
        info->bitrate = port_info->bitrate;
        info->data_bits = ConvertDataBitsFromMojo(port_info->data_bits);
        info->parity_bit = ConvertParityBitFromMojo(port_info->parity_bit);
        info->stop_bits = ConvertStopBitsFromMojo(port_info->stop_bits);
        info->cts_flow_control = port_info->cts_flow_control;
        std::move(callback).Run(true, std::move(info));
      },
      std::move(callback), std::move(info));
  serial_port_->GetPortInfo(mojo::WrapCallbackWithDefaultInvokeIfNotRun(
      std::move(resp_callback), nullptr));
}

void SerialConnection::Flush(device::mojom::SerialPortFlushMode mode,
                             FlushCompleteCallback callback) const {
  DCHECK(serial_port_);
  return serial_port_->Flush(
      mode, mojo::WrapCallbackWithDefaultInvokeIfNotRun(std::move(callback)));
}

void SerialConnection::GetControlSignals(
    GetControlSignalsCompleteCallback callback) const {
  DCHECK(serial_port_);
  auto resp_callback = base::BindOnce(
      [](GetControlSignalsCompleteCallback callback,
         device::mojom::SerialPortControlSignalsPtr signals) {
        if (!signals) {
          std::move(callback).Run(nullptr);
          return;
        }
        auto control_signals =
            std::make_unique<api::serial::DeviceControlSignals>();
        control_signals->dcd = signals->dcd;
        control_signals->cts = signals->cts;
        control_signals->ri = signals->ri;
        control_signals->dsr = signals->dsr;
        std::move(callback).Run(std::move(control_signals));
      },
      std::move(callback));
  serial_port_->GetControlSignals(mojo::WrapCallbackWithDefaultInvokeIfNotRun(
      std::move(resp_callback), nullptr));
}

void SerialConnection::SetControlSignals(
    device::mojom::SerialHostControlSignalsPtr signals,
    SetControlSignalsCompleteCallback callback) {
  DCHECK(serial_port_);
  serial_port_->SetControlSignals(
      std::move(signals),
      mojo::WrapCallbackWithDefaultInvokeIfNotRun(std::move(callback), false));
}

void SerialConnection::Close(base::OnceClosure callback) {
  DCHECK(serial_port_);
  serial_port_->Close(
      /*flush=*/false,
      mojo::WrapCallbackWithDefaultInvokeIfNotRun(std::move(callback)));
}

void SerialConnection::InitSerialPortForTesting() {
  std::ignore = serial_port_.BindNewPipeAndPassReceiver();
}

void SerialConnection::SetTimeoutCallback() {
  if (receive_timeout_ > 0) {
    receive_timeout_task_.Reset(base::BindOnce(
        &SerialConnection::OnReceiveTimeout, weak_factory_.GetWeakPtr()));
    base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
        FROM_HERE, receive_timeout_task_.callback(),
        base::Milliseconds(receive_timeout_));
  }
}

void SerialConnection::OnReceiveTimeout() {
  DCHECK(serial_port_);
  receive_event_cb_.Run(std::vector<uint8_t>(),
                        api::serial::ReceiveError::kTimeout);
}

void SerialConnection::OnSendTimeout() {
  DCHECK(serial_port_);
  if (send_complete_) {
    send_pipe_watcher_.Cancel();

    // Invoking `send_complete_` may free `this`.
    size_t bytes_written = bytes_written_;
    bytes_written_ = 0;

    // Respond the send request with bytes_written without closing the data
    // pipe.
    std::move(send_complete_)
        .Run(bytes_written, api::serial::SendError::kTimeout);
  }
}

void SerialConnection::OnSendPipeWritableOrClosed(
    MojoResult result,
    const mojo::HandleSignalsState& state) {
  // Data pipe disconnected.
  if (result != MOJO_RESULT_OK) {
    OnSendPipeClosed();
    return;
  }
  // There is no send task.
  if (!send_complete_) {
    return;
  }

  DCHECK(send_pipe_);
  size_t actually_sent_bytes = 0;
  result = send_pipe_->WriteData(data_to_send_, MOJO_WRITE_DATA_FLAG_NONE,
                                 actually_sent_bytes);
  if (result == MOJO_RESULT_SHOULD_WAIT) {
    send_pipe_watcher_.ArmOrNotify();
    return;
  }

  // For remote pipe producer handle has been closed.
  if (result == MOJO_RESULT_FAILED_PRECONDITION) {
    OnSendPipeClosed();
    return;
  }

  // For result == MOJO_RESULT_OK case.
  data_to_send_.erase(data_to_send_.begin(),
                      data_to_send_.begin() + actually_sent_bytes);
  bytes_written_ += actually_sent_bytes;

  if (data_to_send_.empty()) {
    send_timeout_task_.Cancel();
    std::move(send_complete_)
        .Run(bytes_written_, api::serial::SendError::kNone);
  } else {
    // Wait for next cycle to send the remaining bytes.
    send_pipe_watcher_.ArmOrNotify();
  }
}

void SerialConnection::OnSendPipeClosed() {
  OnSendError(device::mojom::SerialSendError::DISCONNECTED);
}

void SerialConnection::OnConnectionError() {
  // Run client's error handler if existing.
  if (connection_error_handler_) {
    std::move(connection_error_handler_).Run();
  }
}

void SerialConnection::OnClientReceiverClosed() {
  client_receiver_.reset();
  OnReadError(device::mojom::SerialReceiveError::DISCONNECTED);
  OnSendError(device::mojom::SerialSendError::DISCONNECTED);
}

}  // namespace extensions

namespace mojo {

// static
device::mojom::SerialHostControlSignalsPtr
TypeConverter<device::mojom::SerialHostControlSignalsPtr,
              extensions::api::serial::HostControlSignals>::
    Convert(const extensions::api::serial::HostControlSignals& input) {
  device::mojom::SerialHostControlSignalsPtr output(
      device::mojom::SerialHostControlSignals::New());
  if (input.dtr) {
    output->has_dtr = true;
    output->dtr = *input.dtr;
  }
  if (input.rts) {
    output->has_rts = true;
    output->rts = *input.rts;
  }
  return output;
}

// static
device::mojom::SerialConnectionOptionsPtr
TypeConverter<device::mojom::SerialConnectionOptionsPtr,
              extensions::api::serial::ConnectionOptions>::
    Convert(const extensions::api::serial::ConnectionOptions& input) {
  device::mojom::SerialConnectionOptionsPtr output(
      device::mojom::SerialConnectionOptions::New());
  if (input.bitrate && *input.bitrate > 0)
    output->bitrate = *input.bitrate;
  output->data_bits = extensions::ConvertDataBitsToMojo(input.data_bits);
  output->parity_bit = extensions::ConvertParityBitToMojo(input.parity_bit);
  output->stop_bits = extensions::ConvertStopBitsToMojo(input.stop_bits);
  if (input.cts_flow_control) {
    output->has_cts_flow_control = true;
    output->cts_flow_control = *input.cts_flow_control;
  }
  return output;
}

}  // namespace mojo