summaryrefslogtreecommitdiffstats
path: root/chrome/browser/extensions/api/serial/serial_api.cc
blob: ebf2a6682a0b65629aae79e7dce98e99dfb5f04e (plain)
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
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/extensions/api/serial/serial_api.h"

#include <algorithm>

#include "base/values.h"
#include "chrome/browser/extensions/extension_system.h"
#include "chrome/browser/extensions/api/serial/serial_connection.h"
#include "chrome/browser/extensions/api/serial/serial_event_dispatcher.h"
#include "chrome/browser/extensions/api/serial/serial_port_enumerator.h"
#include "chrome/common/extensions/api/serial.h"
#include "content/public/browser/browser_thread.h"

using content::BrowserThread;

namespace extensions {

namespace api {

namespace {

// It's a fool's errand to come up with a default bitrate, because we don't get
// to control both sides of the communication. Unless the other side has
// implemented auto-bitrate detection (rare), if we pick the wrong rate, then
// you're gonna have a bad time. Close doesn't count.
//
// But we'd like to pick something that has a chance of working, and 9600 is a
// good balance between popularity and speed. So 9600 it is.
const int kDefaultBufferSize = 4096;
const int kDefaultBitrate = 9600;
const serial::DataBits kDefaultDataBits = serial::DATA_BITS_EIGHT;
const serial::ParityBit kDefaultParityBit = serial::PARITY_BIT_NO;
const serial::StopBits kDefaultStopBits = serial::STOP_BITS_ONE;
const int kDefaultReceiveTimeout = 0;
const int kDefaultSendTimeout = 0;

const char kErrorOpenFailed[] = "Failed to open the port.";
const char kErrorSerialConnectionNotFound[] = "Serial connection not found.";
const char kErrorGetControlSignalsFailed[] = "Failed to get control signals.";

template <class T>
void SetDefaultScopedPtrValue(scoped_ptr<T>& ptr, const T& value) {
  if (!ptr.get())
    ptr.reset(new T(value));
}

}  // namespace

SerialAsyncApiFunction::SerialAsyncApiFunction()
    : manager_(NULL) {
}

SerialAsyncApiFunction::~SerialAsyncApiFunction() {}

bool SerialAsyncApiFunction::PrePrepare() {
  manager_ = ApiResourceManager<SerialConnection>::Get(GetProfile());
  DCHECK(manager_);
  return true;
}

bool SerialAsyncApiFunction::Respond() {
  return error_.empty();
}

SerialConnection* SerialAsyncApiFunction::GetSerialConnection(
    int api_resource_id) {
  return manager_->Get(extension_->id(), api_resource_id);
}

void SerialAsyncApiFunction::RemoveSerialConnection(int api_resource_id) {
  manager_->Remove(extension_->id(), api_resource_id);
}

SerialGetDevicesFunction::SerialGetDevicesFunction() {}

bool SerialGetDevicesFunction::Prepare() {
  set_work_thread_id(BrowserThread::FILE);
  return true;
}

void SerialGetDevicesFunction::Work() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));

  std::vector<linked_ptr<serial::DeviceInfo> > devices;
  SerialPortEnumerator::StringSet port_names =
      SerialPortEnumerator::GenerateValidSerialPortNames();
  for (SerialPortEnumerator::StringSet::const_iterator iter =
          port_names.begin();
       iter != port_names.end();
       ++iter) {
    linked_ptr<serial::DeviceInfo> info(new serial::DeviceInfo);
    info->path = *iter;
    devices.push_back(info);
  }
  results_ = serial::GetDevices::Results::Create(devices);
}

SerialOpenFunction::SerialOpenFunction() {}

SerialOpenFunction::~SerialOpenFunction() {}

bool SerialOpenFunction::Prepare() {
  params_ = serial::Open::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params_.get());

  // Fill in any omitted options to ensure a known initial configuration.
  if (!params_->options.get())
    params_->options.reset(new serial::ConnectionOptions());
  serial::ConnectionOptions* options = params_->options.get();

  SetDefaultScopedPtrValue(options->persistent, false);
  SetDefaultScopedPtrValue(options->buffer_size, kDefaultBufferSize);
  SetDefaultScopedPtrValue(options->bitrate, kDefaultBitrate);
  SetDefaultScopedPtrValue(options->cts_flow_control, false);
  SetDefaultScopedPtrValue(options->receive_timeout, kDefaultReceiveTimeout);
  SetDefaultScopedPtrValue(options->send_timeout, kDefaultSendTimeout);

  if (options->data_bits == serial::DATA_BITS_NONE)
    options->data_bits = kDefaultDataBits;
  if (options->parity_bit == serial::PARITY_BIT_NONE)
    options->parity_bit = kDefaultParityBit;
  if (options->stop_bits == serial::STOP_BITS_NONE)
    options->stop_bits = kDefaultStopBits;

  serial_event_dispatcher_ = SerialEventDispatcher::Get(GetProfile());
  DCHECK(serial_event_dispatcher_);

  return true;
}

void SerialOpenFunction::AsyncWorkStart() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  connection_ = CreateSerialConnection(params_->path, extension_->id());
  connection_->Open(base::Bind(&SerialOpenFunction::OnOpen, this));
}

void SerialOpenFunction::OnOpen(bool success) {
  DCHECK(connection_);

  if (success) {
    if (!connection_->Configure(*params_->options.get())) {
      connection_->Close();
      delete connection_;
      connection_ = NULL;
    }
  } else {
    delete connection_;
    connection_ = NULL;
  }

  BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
                          base::Bind(&SerialOpenFunction::FinishOpen, this));
}

void SerialOpenFunction::FinishOpen() {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  if (!connection_) {
    error_ = kErrorOpenFailed;
  } else {
    int id = manager_->Add(connection_);
    serial_event_dispatcher_->PollConnection(extension_->id(), id);

    serial::OpenInfo open_info;
    open_info.connection_id = id;
    results_ = serial::Open::Results::Create(open_info);
  }
  AsyncWorkCompleted();
}

SerialConnection* SerialOpenFunction::CreateSerialConnection(
    const std::string& port, const std::string& extension_id) const {
  return new SerialConnection(port, extension_id);
}

SerialUpdateFunction::SerialUpdateFunction() {}

SerialUpdateFunction::~SerialUpdateFunction() {}

bool SerialUpdateFunction::Prepare() {
  params_ = serial::Update::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params_.get());

  return true;
}

void SerialUpdateFunction::Work() {
  SerialConnection* connection = GetSerialConnection(params_->connection_id);
  if (!connection) {
    error_ = kErrorSerialConnectionNotFound;
    return;
  }
  bool success = connection->Configure(params_->options);
  results_ = serial::Update::Results::Create(success);
}

SerialCloseFunction::SerialCloseFunction() {}

SerialCloseFunction::~SerialCloseFunction() {}

bool SerialCloseFunction::Prepare() {
  params_ = serial::Close::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params_.get());

  return true;
}

void SerialCloseFunction::Work() {
  SerialConnection* connection = GetSerialConnection(params_->connection_id);
  if (!connection) {
    error_ = kErrorSerialConnectionNotFound;
    return;
  }
  connection->Close();
  RemoveSerialConnection(params_->connection_id);
  results_ = serial::Close::Results::Create(true);
}

SerialSendFunction::SerialSendFunction() {}

SerialSendFunction::~SerialSendFunction() {}

bool SerialSendFunction::Prepare() {
  params_ = serial::Send::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params_.get());

  return true;
}

void SerialSendFunction::AsyncWorkStart() {
  SerialConnection* connection = GetSerialConnection(params_->connection_id);
  if (!connection) {
    error_ = kErrorSerialConnectionNotFound;
    AsyncWorkCompleted();
    return;
  }

  if (!connection->Send(params_->data,
                        base::Bind(&SerialSendFunction::OnSendComplete,
                                   this))) {
    OnSendComplete(0, serial::SEND_ERROR_PENDING);
  }
}

void SerialSendFunction::OnSendComplete(int bytes_sent,
                                        serial::SendError error) {
  serial::SendInfo send_info;
  send_info.bytes_sent = bytes_sent;
  send_info.error = error;
  results_ = serial::Send::Results::Create(send_info);
  AsyncWorkCompleted();
}

SerialFlushFunction::SerialFlushFunction() {}

SerialFlushFunction::~SerialFlushFunction() {}

bool SerialFlushFunction::Prepare() {
  params_ = serial::Flush::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params_.get());
  return true;
}

void SerialFlushFunction::Work() {
  SerialConnection* connection = GetSerialConnection(params_->connection_id);
  if (!connection) {
    error_ = kErrorSerialConnectionNotFound;
    return;
  }

  bool success = connection->Flush();
  results_ = serial::Flush::Results::Create(success);
}

SerialSetPausedFunction::SerialSetPausedFunction() {}

SerialSetPausedFunction::~SerialSetPausedFunction() {}

bool SerialSetPausedFunction::Prepare() {
  params_ = serial::SetPaused::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params_.get());

  serial_event_dispatcher_ = SerialEventDispatcher::Get(GetProfile());
  DCHECK(serial_event_dispatcher_);
  return true;
}

void SerialSetPausedFunction::Work() {
  SerialConnection* connection = GetSerialConnection(params_->connection_id);
  if (!connection) {
    error_ = kErrorSerialConnectionNotFound;
    return;
  }

  if (params_->paused != connection->paused()) {
    connection->set_paused(params_->paused);
    if (!params_->paused) {
      serial_event_dispatcher_->PollConnection(extension_->id(),
                                               params_->connection_id);
    }
  }

  results_ = serial::SetPaused::Results::Create();
}

SerialGetInfoFunction::SerialGetInfoFunction() {}

SerialGetInfoFunction::~SerialGetInfoFunction() {}

bool SerialGetInfoFunction::Prepare() {
  params_ = serial::GetInfo::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params_.get());

  return true;
}

void SerialGetInfoFunction::Work() {
  SerialConnection* connection = GetSerialConnection(params_->connection_id);
  if (!connection) {
    error_ = kErrorSerialConnectionNotFound;
    return;
  }

  serial::ConnectionInfo info;
  info.connection_id = params_->connection_id;
  connection->GetInfo(&info);
  results_ = serial::GetInfo::Results::Create(info);
}

SerialGetConnectionsFunction::SerialGetConnectionsFunction() {}

SerialGetConnectionsFunction::~SerialGetConnectionsFunction() {}

bool SerialGetConnectionsFunction::Prepare() {
  return true;
}

void SerialGetConnectionsFunction::Work() {
  std::vector<linked_ptr<serial::ConnectionInfo> > infos;
  const base::hash_set<int>* connection_ids = manager_->GetResourceIds(
      extension_->id());
  if (connection_ids) {
    for (base::hash_set<int>::const_iterator it = connection_ids->begin();
         it != connection_ids->end(); ++it) {
      int connection_id = *it;
      SerialConnection *connection = GetSerialConnection(connection_id);
      if (connection) {
        linked_ptr<serial::ConnectionInfo> info(new serial::ConnectionInfo());
        info->connection_id = connection_id;
        connection->GetInfo(info.get());
        infos.push_back(info);
      }
    }
  }
  results_ = serial::GetConnections::Results::Create(infos);
}

SerialGetControlSignalsFunction::SerialGetControlSignalsFunction() {}

SerialGetControlSignalsFunction::~SerialGetControlSignalsFunction() {}

bool SerialGetControlSignalsFunction::Prepare() {
  params_ = serial::GetControlSignals::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params_.get());

  return true;
}

void SerialGetControlSignalsFunction::Work() {
  SerialConnection* connection = GetSerialConnection(params_->connection_id);
  if (!connection) {
    error_ = kErrorSerialConnectionNotFound;
    return;
  }

  serial::ControlSignals signals;
  if (!connection->GetControlSignals(&signals)) {
    error_ = kErrorGetControlSignalsFailed;
    return;
  }

  results_ = serial::GetControlSignals::Results::Create(signals);
}

SerialSetControlSignalsFunction::SerialSetControlSignalsFunction() {}

SerialSetControlSignalsFunction::~SerialSetControlSignalsFunction() {}

bool SerialSetControlSignalsFunction::Prepare() {
  params_ = serial::SetControlSignals::Params::Create(*args_);
  EXTENSION_FUNCTION_VALIDATE(params_.get());

  return true;
}

void SerialSetControlSignalsFunction::Work() {
  SerialConnection* connection = GetSerialConnection(params_->connection_id);
  if (!connection) {
    error_ = kErrorSerialConnectionNotFound;
    return;
  }

  bool success = connection->SetControlSignals(params_->signals);
  results_ = serial::SetControlSignals::Results::Create(success);
}

}  // namespace api

}  // namespace extensions