source: trunk/FACT++/src/ConnectionUSB.cc@ 12459

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