1 // Copyright 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. 4 5 #ifndef CHROME_BROWSER_EXTENSIONS_API_SERIAL_SERIAL_CONNECTION_H_ 6 #define CHROME_BROWSER_EXTENSIONS_API_SERIAL_SERIAL_CONNECTION_H_ 7 8 #include <set> 9 #include <string> 10 11 #include "base/callback.h" 12 #include "base/files/file.h" 13 #include "base/memory/ref_counted.h" 14 #include "base/memory/weak_ptr.h" 15 #include "base/message_loop/message_loop.h" 16 #include "base/time/time.h" 17 #include "chrome/browser/extensions/api/serial/serial_io_handler.h" 18 #include "chrome/common/extensions/api/serial.h" 19 #include "content/public/browser/browser_thread.h" 20 #include "extensions/browser/api/api_resource.h" 21 #include "extensions/browser/api/api_resource_manager.h" 22 #include "net/base/file_stream.h" 23 24 using content::BrowserThread; 25 26 namespace extensions { 27 28 // Encapsulates an open serial port. Platform-specific implementations are in 29 // _win and _posix versions of the the .cc file. 30 // NOTE: Instances of this object should only be constructed on the IO thread, 31 // and all methods should only be called on the IO thread unless otherwise 32 // noted. 33 class SerialConnection : public ApiResource, 34 public base::SupportsWeakPtr<SerialConnection> { 35 public: 36 typedef base::Callback<void(bool success)> OpenCompleteCallback; 37 38 // This is the callback type expected by Receive. Note that an error result 39 // does not necessarily imply an empty |data| string, since a receive may 40 // complete partially before being interrupted by an error condition. 41 typedef base::Callback< 42 void(const std::string& data, api::serial::ReceiveError error)> 43 ReceiveCompleteCallback; 44 45 // This is the callback type expected by Send. Note that an error result 46 // does not necessarily imply 0 bytes sent, since a send may complete 47 // partially before being interrupted by an error condition. 48 typedef base::Callback<void(int bytes_sent, api::serial::SendError error)> 49 SendCompleteCallback; 50 51 SerialConnection(const std::string& port, 52 const std::string& owner_extension_id); 53 virtual ~SerialConnection(); 54 55 // ApiResource override. 56 virtual bool IsPersistent() const OVERRIDE; 57 set_persistent(bool persistent)58 void set_persistent(bool persistent) { persistent_ = persistent; } persistent()59 bool persistent() const { return persistent_; } 60 set_name(const std::string & name)61 void set_name(const std::string& name) { name_ = name; } name()62 const std::string& name() const { return name_; } 63 64 void set_buffer_size(int buffer_size); buffer_size()65 int buffer_size() const { return buffer_size_; } 66 67 void set_receive_timeout(int receive_timeout); receive_timeout()68 int receive_timeout() const { return receive_timeout_; } 69 70 void set_send_timeout(int send_timeout); send_timeout()71 int send_timeout() const { return send_timeout_; } 72 73 void set_paused(bool paused); paused()74 bool paused() const { return paused_; } 75 76 // Initiates an asynchronous Open of the device. It is the caller's 77 // responsibility to ensure that this SerialConnection stays alive 78 // until |callback| is run. 79 virtual void Open(const OpenCompleteCallback& callback); 80 81 // Initiate a Close of the device. The SerialConnection instance will 82 // have its internal state reset synchronously upon calling this, but 83 // the underlying OS handle will be closed asynchronously. 84 virtual void Close(); 85 86 // Begins an asynchronous receive operation. Calling this while a Receive 87 // is already pending is a no-op and returns |false| without calling 88 // |callback|. 89 virtual bool Receive(const ReceiveCompleteCallback& callback); 90 91 // Begins an asynchronous send operation. Calling this while a Send 92 // is already pending is a no-op and returns |false| without calling 93 // |callback|. 94 virtual bool Send(const std::string& data, 95 const SendCompleteCallback& callback); 96 97 // Flushes input and output buffers. 98 virtual bool Flush() const; 99 100 // Configures some subset of port options for this connection. 101 // Omitted options are unchanged. Returns |true| iff the configuration 102 // changes were successful. 103 virtual bool Configure(const api::serial::ConnectionOptions& options); 104 105 // Connection configuration query. Fills values in an existing 106 // ConnectionInfo. Returns |true| iff the connection's information 107 // was successfully retrieved. 108 virtual bool GetInfo(api::serial::ConnectionInfo* info) const; 109 110 // Reads current control signals (DCD, CTS, etc.) into an existing 111 // DeviceControlSignals structure. Returns |true| iff the signals were 112 // successfully read. 113 virtual bool GetControlSignals( 114 api::serial::DeviceControlSignals* control_signals) const; 115 116 // Sets one or more control signals (DTR and/or RTS). Returns |true| iff 117 // the signals were successfully set. Unininitialized flags in the 118 // HostControlSignals structure are left unchanged. 119 virtual bool SetControlSignals( 120 const api::serial::HostControlSignals& control_signals); 121 122 static const BrowserThread::ID kThreadId = BrowserThread::IO; 123 124 protected: 125 // Overrides |io_handler_| for testing. 126 virtual void SetIoHandlerForTest(scoped_refptr<SerialIoHandler> handler); 127 128 // Performs platform-specific, one-time port configuration on open. 129 bool PostOpen(); 130 131 // Performs platform-specific port configuration. Returns |true| iff 132 // configuration was successful. 133 bool ConfigurePort(const api::serial::ConnectionOptions& options); 134 135 // Performs a platform-specific port configuration query. Fills values in an 136 // existing ConnectionInfo. Returns |true| iff port configuration was 137 // successfully retrieved. 138 bool GetPortInfo(api::serial::ConnectionInfo* info) const; 139 140 // Possibly fixes up a serial port path name in a platform-specific manner. 141 static std::string MaybeFixUpPortName(const std::string& port_name); 142 143 private: 144 friend class ApiResourceManager<SerialConnection>; service_name()145 static const char* service_name() { return "SerialConnectionManager"; } 146 147 // Encapsulates a cancelable, delayed timeout task. Posts a delayed 148 // task upon construction and implicitly cancels the task upon 149 // destruction if it hasn't run yet. 150 class TimeoutTask { 151 public: 152 TimeoutTask(const base::Closure& closure, const base::TimeDelta& delay); 153 ~TimeoutTask(); 154 155 private: 156 void Run() const; 157 158 base::WeakPtrFactory<TimeoutTask> weak_factory_; 159 base::Closure closure_; 160 base::TimeDelta delay_; 161 }; 162 163 // Continues an Open operation on the FILE thread. 164 void StartOpen(); 165 166 // Finalizes an Open operation (continued from StartOpen) on the IO thread. 167 void FinishOpen(base::File file); 168 169 // Continues a Close operation on the FILE thread. 170 static void DoClose(base::File port); 171 172 // Handles a receive timeout. 173 void OnReceiveTimeout(); 174 175 // Handles a send timeout. 176 void OnSendTimeout(); 177 178 // Receives read completion notification from the |io_handler_|. 179 void OnAsyncReadComplete(const std::string& data, 180 api::serial::ReceiveError error); 181 182 // Receives write completion notification from the |io_handler_|. 183 void OnAsyncWriteComplete(int bytes_sent, api::serial::SendError error); 184 185 // The pathname of the serial device. 186 std::string port_; 187 188 // File for the opened serial device. This value is only modified from the IO 189 // thread. 190 base::File file_; 191 192 // Flag indicating whether or not the connection should persist when 193 // its host app is suspended. 194 bool persistent_; 195 196 // User-specified connection name. 197 std::string name_; 198 199 // Size of the receive buffer. 200 int buffer_size_; 201 202 // Amount of time (in ms) to wait for a Read to succeed before triggering a 203 // timeout response via onReceiveError. 204 int receive_timeout_; 205 206 // Amount of time (in ms) to wait for a Write to succeed before triggering 207 // a timeout response. 208 int send_timeout_; 209 210 // Flag indicating that the connection is paused. A paused connection will not 211 // raise new onReceive events. 212 bool paused_; 213 214 // Callback to handle the completion of a pending Open() request. 215 OpenCompleteCallback open_complete_; 216 217 // Callback to handle the completion of a pending Receive() request. 218 ReceiveCompleteCallback receive_complete_; 219 220 // Callback to handle the completion of a pending Send() request. 221 SendCompleteCallback send_complete_; 222 223 // Closure which will trigger a receive timeout unless cancelled. Reset on 224 // initialization and after every successful Receive(). 225 scoped_ptr<TimeoutTask> receive_timeout_task_; 226 227 // Write timeout closure. Reset on initialization and after every successful 228 // Send(). 229 scoped_ptr<TimeoutTask> send_timeout_task_; 230 231 // Asynchronous I/O handler. 232 scoped_refptr<SerialIoHandler> io_handler_; 233 }; 234 235 } // namespace extensions 236 237 #endif // CHROME_BROWSER_EXTENSIONS_API_SERIAL_SERIAL_CONNECTION_H_ 238