| 1 | // **************************************************************************
|
|---|
| 2 | /** @class Connection
|
|---|
| 3 |
|
|---|
| 4 | @brief Maintains an ansynchronous TCP/IP client connection
|
|---|
| 5 |
|
|---|
| 6 | */
|
|---|
| 7 | // **************************************************************************
|
|---|
| 8 | #include "ConnectionUSB.h"
|
|---|
| 9 |
|
|---|
| 10 | #include <boost/bind.hpp>
|
|---|
| 11 |
|
|---|
| 12 | using namespace std;
|
|---|
| 13 |
|
|---|
| 14 | namespace ba = boost::asio;
|
|---|
| 15 | namespace bs = boost::system;
|
|---|
| 16 | namespace dummy = ba::placeholders;
|
|---|
| 17 |
|
|---|
| 18 | using ba::serial_port_base;
|
|---|
| 19 |
|
|---|
| 20 | //#define DEBUG_TX
|
|---|
| 21 |
|
|---|
| 22 | // -------- Abbreviations for starting async tasks ---------
|
|---|
| 23 |
|
|---|
| 24 | int ConnectionUSB::Write(const Time &t, const string &txt, int qos)
|
|---|
| 25 | {
|
|---|
| 26 | if (fLog)
|
|---|
| 27 | return fLog->Write(t, txt, qos);
|
|---|
| 28 |
|
|---|
| 29 | return MessageImp::Write(t, txt, qos);
|
|---|
| 30 | }
|
|---|
| 31 |
|
|---|
| 32 | void ConnectionUSB::AsyncRead(const ba::mutable_buffers_1 buffers, int type, int counter)
|
|---|
| 33 | {
|
|---|
| 34 | ba::async_read(*this, buffers,
|
|---|
| 35 | boost::bind(&ConnectionUSB::HandleReceivedData, this,
|
|---|
| 36 | dummy::error, dummy::bytes_transferred, type, counter));
|
|---|
| 37 | }
|
|---|
| 38 |
|
|---|
| 39 | void ConnectionUSB::AsyncWrite(const ba::const_buffers_1 &buffers)
|
|---|
| 40 | {
|
|---|
| 41 | ba::async_write(*this, buffers,
|
|---|
| 42 | boost::bind(&ConnectionUSB::HandleSentData, this,
|
|---|
| 43 | dummy::error, dummy::bytes_transferred));
|
|---|
| 44 | }
|
|---|
| 45 |
|
|---|
| 46 | void ConnectionUSB::AsyncWait(ba::deadline_timer &timer, int millisec,
|
|---|
| 47 | void (ConnectionUSB::*handler)(const bs::error_code&))
|
|---|
| 48 | {
|
|---|
| 49 | // - The boost::asio::basic_deadline_timer::expires_from_now()
|
|---|
| 50 | // function cancels any pending asynchronous waits, and returns
|
|---|
| 51 | // the number of asynchronous waits that were cancelled. If it
|
|---|
| 52 | // returns 0 then you were too late and the wait handler has
|
|---|
| 53 | // already been executed, or will soon be executed. If it
|
|---|
| 54 | // returns 1 then the wait handler was successfully cancelled.
|
|---|
| 55 | // - If a wait handler is cancelled, the bs::error_code passed to
|
|---|
| 56 | // it contains the value bs::error::operation_aborted.
|
|---|
| 57 | timer.expires_from_now(boost::posix_time::milliseconds(millisec));
|
|---|
| 58 |
|
|---|
| 59 | timer.async_wait(boost::bind(handler, this, dummy::error));
|
|---|
| 60 | }
|
|---|
| 61 |
|
|---|
| 62 | // ------------------------ close --------------------------
|
|---|
| 63 | // close from another thread
|
|---|
| 64 | void ConnectionUSB::CloseImp(bool restart)
|
|---|
| 65 | {
|
|---|
| 66 | if (IsConnected())
|
|---|
| 67 | {
|
|---|
| 68 | ostringstream str;
|
|---|
| 69 | str << "Closing connection to " << URL() << ".";
|
|---|
| 70 | Info(str);
|
|---|
| 71 | }
|
|---|
| 72 |
|
|---|
| 73 | // Close possible open connections
|
|---|
| 74 | bs::error_code ec;
|
|---|
| 75 | cancel(ec);
|
|---|
| 76 | if (ec)
|
|---|
| 77 | Error("Cancel async requests on "+URL()+": "+ec.message());
|
|---|
| 78 |
|
|---|
| 79 | if (IsConnected())
|
|---|
| 80 | {
|
|---|
| 81 | close(ec);
|
|---|
| 82 | if (ec)
|
|---|
| 83 | Error("Closing "+URL()+": "+ec.message());
|
|---|
| 84 | else
|
|---|
| 85 | Info("Connection closed succesfully.");
|
|---|
| 86 | }
|
|---|
| 87 |
|
|---|
| 88 | // Stop deadline counters
|
|---|
| 89 | fInTimeout.cancel();
|
|---|
| 90 | fOutTimeout.cancel();
|
|---|
| 91 |
|
|---|
| 92 | // Reset the connection status
|
|---|
| 93 | fConnectionStatus = kDisconnected;
|
|---|
| 94 |
|
|---|
| 95 | // Empty output queue
|
|---|
| 96 | fOutQueue.clear();
|
|---|
| 97 |
|
|---|
| 98 | if (!restart || IsConnecting())
|
|---|
| 99 | return;
|
|---|
| 100 |
|
|---|
| 101 | // We need some timeout before reconnecting!
|
|---|
| 102 | // And we have to check if we are alreayd trying to connect
|
|---|
| 103 | // We shoudl wait until all operations in progress were canceled
|
|---|
| 104 |
|
|---|
| 105 | // Start trying to reconnect
|
|---|
| 106 | Connect();
|
|---|
| 107 | }
|
|---|
| 108 |
|
|---|
| 109 | void ConnectionUSB::PostClose(bool restart)
|
|---|
| 110 | {
|
|---|
| 111 | get_io_service().post(boost::bind(&ConnectionUSB::CloseImp, this, restart));
|
|---|
| 112 | }
|
|---|
| 113 |
|
|---|
| 114 | // ------------------------ write --------------------------
|
|---|
| 115 | void ConnectionUSB::HandleWriteTimeout(const bs::error_code &error)
|
|---|
| 116 | {
|
|---|
| 117 | if (error==ba::error::basic_errors::operation_aborted)
|
|---|
| 118 | return;
|
|---|
| 119 |
|
|---|
| 120 | // 125: Operation canceled (bs::error_code(125, bs::system_category))
|
|---|
| 121 | if (error)
|
|---|
| 122 | {
|
|---|
| 123 | ostringstream str;
|
|---|
| 124 | str << "Write timeout of " << URL() << ": " << error.message() << " (" << error << ")";// << endl;
|
|---|
| 125 | Error(str);
|
|---|
| 126 |
|
|---|
| 127 | CloseImp(false);
|
|---|
| 128 | return;
|
|---|
| 129 | }
|
|---|
| 130 |
|
|---|
| 131 | if (!is_open())
|
|---|
| 132 | {
|
|---|
| 133 | // For example: Here we could schedule a new accept if we
|
|---|
| 134 | // would not want to allow two connections at the same time.
|
|---|
| 135 | return;
|
|---|
| 136 | }
|
|---|
| 137 |
|
|---|
| 138 | // Check whether the deadline has passed. We compare the deadline
|
|---|
| 139 | // against the current time since a new asynchronous operation
|
|---|
| 140 | // may have moved the deadline before this actor had a chance
|
|---|
| 141 | // to run.
|
|---|
| 142 | if (fOutTimeout.expires_at() > ba::deadline_timer::traits_type::now())
|
|---|
| 143 | return;
|
|---|
| 144 |
|
|---|
| 145 | Error("fOutTimeout has expired, writing data to "+URL());
|
|---|
| 146 |
|
|---|
| 147 | CloseImp(false);
|
|---|
| 148 | }
|
|---|
| 149 |
|
|---|
| 150 | void ConnectionUSB::HandleSentData(const bs::error_code& error, size_t n)
|
|---|
| 151 | {
|
|---|
| 152 | if (error && error != ba::error::not_connected)
|
|---|
| 153 | {
|
|---|
| 154 | ostringstream str;
|
|---|
| 155 | str << "Writing to " << URL() << ": " << error.message() << " (" << error << ")";// << endl;
|
|---|
| 156 | Error(str);
|
|---|
| 157 |
|
|---|
| 158 | CloseImp(false);
|
|---|
| 159 | return;
|
|---|
| 160 | }
|
|---|
| 161 |
|
|---|
| 162 | if (error == ba::error::not_connected)
|
|---|
| 163 | {
|
|---|
| 164 | ostringstream msg;
|
|---|
| 165 | msg << n << " bytes could not be sent to " << URL() << " due to missing connection.";
|
|---|
| 166 | Warn(msg);
|
|---|
| 167 | }
|
|---|
| 168 | else
|
|---|
| 169 | {
|
|---|
| 170 | #ifdef DEBUG_TX
|
|---|
| 171 | ostringstream msg;
|
|---|
| 172 | msg << n << " bytes successfully sent to " << URL();
|
|---|
| 173 | Message(msg);
|
|---|
| 174 | #endif
|
|---|
| 175 | }
|
|---|
| 176 |
|
|---|
| 177 | HandleTransmittedData(n);
|
|---|
| 178 |
|
|---|
| 179 | // This is "thread" safe because SendMessage and HandleSentMessage
|
|---|
| 180 | // are serialized in the EventQueue. Note: Do not call these
|
|---|
| 181 | // functions directly from any other place then Handlers, use
|
|---|
| 182 | // PostMessage instead
|
|---|
| 183 | fOutQueue.pop_front();
|
|---|
| 184 |
|
|---|
| 185 | if (fOutQueue.empty())
|
|---|
| 186 | {
|
|---|
| 187 | // Queue went empty, remove deadline
|
|---|
| 188 | fOutTimeout.cancel();
|
|---|
| 189 | return;
|
|---|
| 190 | }
|
|---|
| 191 |
|
|---|
| 192 | // AsyncWrite + Deadline
|
|---|
| 193 | AsyncWrite(ba::const_buffers_1(fOutQueue.front().data(), fOutQueue.front().size())/*, &ConnectionUSB::HandleSentData*/);
|
|---|
| 194 | AsyncWait(fOutTimeout, 5000, &ConnectionUSB::HandleWriteTimeout);
|
|---|
| 195 | }
|
|---|
| 196 |
|
|---|
| 197 | // It is important that when SendMessageImp is called, or to be more
|
|---|
| 198 | // precise boost::bind is called, teh data is copied!
|
|---|
| 199 | void ConnectionUSB::SendMessageImp(const vector<char> msg)
|
|---|
| 200 | {
|
|---|
| 201 | /*
|
|---|
| 202 | if (!fConnectionEstablished)
|
|---|
| 203 | {
|
|---|
| 204 | UpdateWarn("SendMessageImp, but no connection to "+fAddress+":"+fPort+".");
|
|---|
| 205 | return;
|
|---|
| 206 | }*/
|
|---|
| 207 |
|
|---|
| 208 | const bool first_message_in_queue = fOutQueue.empty();
|
|---|
| 209 |
|
|---|
| 210 | // This is "thread" safe because SendMessage and HandleSentMessage
|
|---|
| 211 | // are serialized in the EventQueue. Note: Do not call these
|
|---|
| 212 | // functions directly from any other place then Handlers, use
|
|---|
| 213 | // PostMessage instead
|
|---|
| 214 | fOutQueue.push_back(msg);
|
|---|
| 215 |
|
|---|
| 216 | if (!first_message_in_queue)
|
|---|
| 217 | return;
|
|---|
| 218 |
|
|---|
| 219 | // AsyncWrite + Deadline
|
|---|
| 220 | AsyncWrite(ba::const_buffers_1(fOutQueue.front().data(), fOutQueue.front().size())/*, &ConnectionUSB::HandleSentData*/);
|
|---|
| 221 | AsyncWait(fOutTimeout, 5000, &ConnectionUSB::HandleWriteTimeout);
|
|---|
| 222 | }
|
|---|
| 223 |
|
|---|
| 224 | void ConnectionUSB::PostMessage(const void *ptr, size_t max)
|
|---|
| 225 | {
|
|---|
| 226 | const vector<char> msg(reinterpret_cast<const char*>(ptr),
|
|---|
| 227 | reinterpret_cast<const char*>(ptr)+max);
|
|---|
| 228 |
|
|---|
| 229 | get_io_service().post(boost::bind(&ConnectionUSB::SendMessageImp, this, msg));
|
|---|
| 230 | }
|
|---|
| 231 |
|
|---|
| 232 | void ConnectionUSB::PostMessage(const string &cmd, size_t max)
|
|---|
| 233 | {
|
|---|
| 234 | if (max==size_t(-1))
|
|---|
| 235 | max = cmd.length()+1;
|
|---|
| 236 |
|
|---|
| 237 | vector <char>msg(max);
|
|---|
| 238 |
|
|---|
| 239 | copy(cmd.begin(), cmd.begin()+min(cmd.length()+1, max), msg.begin());
|
|---|
| 240 |
|
|---|
| 241 | PostMessage(msg);
|
|---|
| 242 | }
|
|---|
| 243 |
|
|---|
| 244 | void ConnectionUSB::Connect()
|
|---|
| 245 | {
|
|---|
| 246 | fConnectionStatus = kConnecting;
|
|---|
| 247 |
|
|---|
| 248 | Info("Connecting to "+URL()+".");
|
|---|
| 249 |
|
|---|
| 250 | bs::error_code ec;
|
|---|
| 251 | open(URL(), ec);
|
|---|
| 252 |
|
|---|
| 253 | if (ec)
|
|---|
| 254 | {
|
|---|
| 255 | ostringstream msg;
|
|---|
| 256 | msg << "Error opening " << URL() << "... " << ec.message() << " (" << ec << ")";
|
|---|
| 257 | Error(msg);
|
|---|
| 258 | fConnectionStatus = kDisconnected;
|
|---|
| 259 | return;
|
|---|
| 260 | }
|
|---|
| 261 |
|
|---|
| 262 | Info("Connection established.");
|
|---|
| 263 |
|
|---|
| 264 | try
|
|---|
| 265 | {
|
|---|
| 266 | set_option(fBaudRate);
|
|---|
| 267 | set_option(fCharacterSize);
|
|---|
| 268 | set_option(fParity);
|
|---|
| 269 | set_option(fStopBits);
|
|---|
| 270 | set_option(fFlowControl);
|
|---|
| 271 | }
|
|---|
| 272 | catch (const bs::system_error &erc)
|
|---|
| 273 | {
|
|---|
| 274 | Error(string("Setting connection options: ")+erc.what());
|
|---|
| 275 | // CLOSE
|
|---|
| 276 | return;
|
|---|
| 277 | }
|
|---|
| 278 |
|
|---|
| 279 | fConnectionStatus = kConnected;
|
|---|
| 280 |
|
|---|
| 281 | ConnectionEstablished();
|
|---|
| 282 | }
|
|---|
| 283 |
|
|---|
| 284 | void ConnectionUSB::SetEndpoint(const string &addr)
|
|---|
| 285 | {
|
|---|
| 286 | if (fConnectionStatus>=1)
|
|---|
| 287 | Warn("Connection or connection attempt in progress. New endpoint only valid for next connection.");
|
|---|
| 288 |
|
|---|
| 289 | fAddress = "/dev/"+addr;
|
|---|
| 290 | }
|
|---|
| 291 |
|
|---|
| 292 |
|
|---|
| 293 | ConnectionUSB::ConnectionUSB(ba::io_service& ioservice, ostream &out) :
|
|---|
| 294 | MessageImp(out), ba::serial_port(ioservice), fLog(0),
|
|---|
| 295 | fBaudRate(115200),
|
|---|
| 296 | fCharacterSize(8), fParity(parity::none), fStopBits(stop_bits::one),
|
|---|
| 297 | fFlowControl(flow_control::hardware),
|
|---|
| 298 | fInTimeout(ioservice), fOutTimeout(ioservice),
|
|---|
| 299 | fConnectionStatus(kDisconnected)
|
|---|
| 300 | {
|
|---|
| 301 | }
|
|---|