File: serial_port_manager.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 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 (225 lines) | stat: -rw-r--r-- 7,840 bytes parent folder | download | duplicates (9)
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
// Copyright 2018 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_port_manager.h"

#include <utility>

#include "base/functional/bind.h"
#include "base/lazy_instance.h"
#include "base/no_destructor.h"
#include "build/build_config.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/device_service.h"
#include "extensions/browser/api/serial/serial_connection.h"
#include "extensions/browser/event_router.h"
#include "extensions/browser/extensions_browser_client.h"
#include "extensions/common/extension_id.h"
#include "mojo/public/cpp/bindings/pending_remote.h"

namespace extensions {

namespace api {

namespace {

bool ShouldPauseOnReceiveError(serial::ReceiveError error) {
  return error == serial::ReceiveError::kDeviceLost ||
         error == serial::ReceiveError::kSystemError ||
         error == serial::ReceiveError::kDisconnected ||
         error == serial::ReceiveError::kBreak ||
         error == serial::ReceiveError::kFrameError ||
         error == serial::ReceiveError::kOverrun ||
         error == serial::ReceiveError::kBufferOverflow ||
         error == serial::ReceiveError::kParityError;
}

SerialPortManager::Binder& GetBinderOverride() {
  static base::NoDestructor<SerialPortManager::Binder> binder;
  return *binder;
}

}  // namespace

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

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

// static
SerialPortManager* SerialPortManager::Get(content::BrowserContext* context) {
  return BrowserContextKeyedAPIFactory<SerialPortManager>::Get(context);
}

SerialPortManager::SerialPortManager(content::BrowserContext* context)
    : context_(context) {
  ApiResourceManager<SerialConnection>* manager =
      ApiResourceManager<SerialConnection>::Get(context_);
  DCHECK(manager) << "No serial connection manager.";
  connections_ = manager->data_;
}

SerialPortManager::~SerialPortManager() = default;

SerialPortManager::ReceiveParams::ReceiveParams() = default;

SerialPortManager::ReceiveParams::ReceiveParams(const ReceiveParams& other) =
    default;

SerialPortManager::ReceiveParams::~ReceiveParams() = default;

void SerialPortManager::GetDevices(
    device::mojom::SerialPortManager::GetDevicesCallback callback) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  EnsureConnection();
  port_manager_->GetDevices(std::move(callback));
}

void SerialPortManager::OpenPort(
    const std::string& path,
    device::mojom::SerialConnectionOptionsPtr options,
    mojo::PendingRemote<device::mojom::SerialPortClient> client,
    OpenPortCallback callback) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  EnsureConnection();
  port_manager_->GetDevices(base::BindOnce(
      &SerialPortManager::OnGotDevicesToGetPort, weak_factory_.GetWeakPtr(),
      path, std::move(options), std::move(client), std::move(callback)));
}

void SerialPortManager::StartConnectionPolling(const ExtensionId& extension_id,
                                               int connection_id) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  auto* connection = connections_->Get(extension_id, connection_id);
  if (!connection)
    return;

  DCHECK_EQ(extension_id, connection->owner_extension_id());

  ReceiveParams params;
  params.browser_context_id = context_;
  params.extension_id = extension_id;
  params.connections = connections_;
  params.connection_id = connection_id;

  connection->StartPolling(base::BindRepeating(&DispatchReceiveEvent, params));
}

// static
void SerialPortManager::OverrideBinderForTesting(Binder binder) {
  GetBinderOverride() = std::move(binder);
}

// static
void SerialPortManager::DispatchReceiveEvent(const ReceiveParams& params,
                                             std::vector<uint8_t> data,
                                             serial::ReceiveError error) {
  // Note that an error (e.g. timeout) does not necessarily mean that no data
  // was read, so we may fire an onReceive regardless of any error code.
  if (data.size() > 0) {
    serial::ReceiveInfo receive_info;
    receive_info.connection_id = params.connection_id;
    receive_info.data = std::move(data);
    auto args = serial::OnReceive::Create(receive_info);
    std::unique_ptr<extensions::Event> event(
        new extensions::Event(extensions::events::SERIAL_ON_RECEIVE,
                              serial::OnReceive::kEventName, std::move(args)));
    DispatchEvent(params, std::move(event));
  }

  if (error != serial::ReceiveError::kNone) {
    if (ShouldPauseOnReceiveError(error)) {
      SerialConnection* connection =
          params.connections->Get(params.extension_id, params.connection_id);
      if (connection)
        connection->SetPaused(true);
    }
    serial::ReceiveErrorInfo error_info;
    error_info.connection_id = params.connection_id;
    error_info.error = error;
    auto args = serial::OnReceiveError::Create(error_info);
    std::unique_ptr<extensions::Event> event(new extensions::Event(
        extensions::events::SERIAL_ON_RECEIVE_ERROR,
        serial::OnReceiveError::kEventName, std::move(args)));
    DispatchEvent(params, std::move(event));
  }
}

// static
void SerialPortManager::DispatchEvent(
    const ReceiveParams& params,
    std::unique_ptr<extensions::Event> event) {
  if (!ExtensionsBrowserClient::Get()->IsValidContext(
          params.browser_context_id.get())) {
    return;
  }

  content::BrowserContext* context = reinterpret_cast<content::BrowserContext*>(
      params.browser_context_id.get());

  EventRouter* router = EventRouter::Get(context);
  if (router)
    router->DispatchEventToExtension(params.extension_id, std::move(event));
}

void SerialPortManager::EnsureConnection() {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  if (port_manager_)
    return;

  auto receiver = port_manager_.BindNewPipeAndPassReceiver();
  port_manager_.set_disconnect_handler(
      base::BindOnce(&SerialPortManager::OnPortManagerConnectionError,
                     weak_factory_.GetWeakPtr()));

  const auto& binder = GetBinderOverride();
  if (binder)
    binder.Run(std::move(receiver));
  else
    content::GetDeviceService().BindSerialPortManager(std::move(receiver));
}

void SerialPortManager::OnGotDevicesToGetPort(
    const std::string& path,
    device::mojom::SerialConnectionOptionsPtr options,
    mojo::PendingRemote<device::mojom::SerialPortClient> client,
    OpenPortCallback callback,
    std::vector<device::mojom::SerialPortInfoPtr> devices) {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);

  for (auto& device : devices) {
    if (device->path.AsUTF8Unsafe() == path) {
      port_manager_->OpenPort(device->token, /*use_alternate_path=*/false,
                              std::move(options), std::move(client),
                              /*watcher=*/mojo::NullRemote(),
                              std::move(callback));
      return;
    }

#if BUILDFLAG(IS_MAC)
    if (device->alternate_path &&
        device->alternate_path->AsUTF8Unsafe() == path) {
      port_manager_->OpenPort(device->token, /*use_alternate_path=*/true,
                              std::move(options), std::move(client),
                              /*watcher=*/mojo::NullRemote(),
                              std::move(callback));
      return;
    }
#endif  // BUILDFLAG(IS_MAC)
  }
}

void SerialPortManager::OnPortManagerConnectionError() {
  DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
  port_manager_.reset();
}

}  // namespace api

}  // namespace extensions