1 // Copyright (c) 2012 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 "chrome/browser/extensions/api/serial/serial_connection.h"
9 #include "base/files/file_path.h"
10 #include "base/lazy_instance.h"
11 #include "base/strings/string_util.h"
12 #include "chrome/browser/extensions/api/api_resource_manager.h"
13 #include "chrome/common/extensions/api/serial.h"
15 namespace serial = extensions::api::serial;
17 namespace extensions {
19 const char kSerialConnectionNotFoundError[] = "Serial connection not found";
21 static base::LazyInstance<ProfileKeyedAPIFactory<
22 ApiResourceManager<SerialConnection> > >
23 g_factory = LAZY_INSTANCE_INITIALIZER;
27 ProfileKeyedAPIFactory<ApiResourceManager<SerialConnection> >*
28 ApiResourceManager<SerialConnection>::GetFactoryInstance() {
29 return &g_factory.Get();
32 SerialConnection::SerialConnection(const std::string& port, int bitrate,
33 serial::DataBit databit,
34 serial::ParityBit parity,
35 serial::StopBit stopbit,
36 const std::string& owner_extension_id)
37 : ApiResource(owner_extension_id), port_(port), bitrate_(bitrate),
38 databit_(databit), parity_(parity), stopbit_(stopbit),
39 file_(base::kInvalidPlatformFileValue) {
43 SerialConnection::~SerialConnection() {
47 bool SerialConnection::Open() {
50 // It's the responsibility of the API wrapper around SerialConnection to
51 // validate the supplied path against the set of valid port names, and
52 // it is a reasonable assumption that serial port names are ASCII.
53 CHECK(IsStringASCII(port_));
54 base::FilePath file_path(
55 base::FilePath::FromUTF8Unsafe(MaybeFixUpPortName(port_)));
57 file_ = base::CreatePlatformFile(file_path,
58 base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ |
59 base::PLATFORM_FILE_WRITE | base::PLATFORM_FILE_EXCLUSIVE_READ |
60 base::PLATFORM_FILE_EXCLUSIVE_WRITE |
61 base::PLATFORM_FILE_TERMINAL_DEVICE, &created, NULL);
62 if (file_ == base::kInvalidPlatformFileValue) {
68 void SerialConnection::Close() {
69 if (file_ != base::kInvalidPlatformFileValue) {
70 base::ClosePlatformFile(file_);
71 file_ = base::kInvalidPlatformFileValue;
75 int SerialConnection::Read(scoped_refptr<net::IOBufferWithSize> io_buffer) {
76 DCHECK(io_buffer->data());
77 return base::ReadPlatformFileAtCurrentPos(file_, io_buffer->data(),
81 int SerialConnection::Write(scoped_refptr<net::IOBuffer> io_buffer,
83 DCHECK(io_buffer->data());
84 DCHECK_GE(byte_count, 0);
85 return base::WritePlatformFileAtCurrentPos(file_, io_buffer->data(),
89 void SerialConnection::Flush() {
90 base::FlushPlatformFile(file_);
93 } // namespace extensions