3 /// Support classes for the pluggable socket routing system.
7 Copyright (C) 2005-2008, Net Direct Inc. (http://www.netdirect.ca/)
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
18 See the GNU General Public License in the COPYING file at the
19 root directory of this project for more details.
22 #ifndef __BARRY_ROUTER_H__
23 #define __BARRY_ROUTER_H__
31 #include "dataqueue.h"
34 namespace Usb
{ class Device
; }
40 class BXEXPORT SocketRoutingQueue
42 friend class DataHandle
;
45 // Interface class for socket data callbacks
46 // See RegisterInterest() for more information.
47 class BXEXPORT SocketDataHandler
50 // Called when data is received on the socket
51 // for which interest has been registered.
53 // The lifetime of the data parameter is only valid
54 // for the duration of this method call.
55 virtual void DataReceived(Data
& data
) = 0;
57 // Called when an error has occured on the socket
58 // for which interest has been registered.
60 // The lifetime of the error parameter is only valid
61 // for the lifetime of this method call.
62 virtual void Error(Barry::Error
&error
);
64 virtual ~SocketDataHandler();
67 typedef std::tr1::shared_ptr
<SocketDataHandler
> SocketDataHandlerPtr
;
69 // Simple wrapper template class for SocketDataHandler which provides a basic data recieved callback
70 template<typename T
> class SimpleSocketDataHandler
: public SocketDataHandler
72 void (*m_callback
)(T
&, Data
*);
75 SimpleSocketDataHandler
<T
>(T
& context
, void (*callback
)(T
& context
, Data
* data
))
76 : m_callback(callback
)
79 virtual void DataReceived(Data
& data
)
81 m_callback(m_context
, &data
);
87 SocketDataHandlerPtr m_handler
;
90 QueueEntry(SocketDataHandlerPtr h
)
94 typedef std::tr1::shared_ptr
<QueueEntry
> QueueEntryPtr
;
95 typedef uint16_t SocketId
;
96 typedef std::map
<SocketId
, QueueEntryPtr
> SocketQueueMap
;
99 Usb::Device
* volatile m_dev
;
100 volatile int m_writeEp
, m_readEp
;
102 volatile bool m_interest
; // true if at least one socket has an interest.
103 // used to optimize the reading
105 mutable pthread_mutex_t m_mutex
;// controls access to local data, but not
106 // DataQueues, as they have their own
109 pthread_mutex_t m_readwaitMutex
;
110 pthread_cond_t m_readwaitCond
;
111 bool m_seen_usb_error
;
112 SocketDataHandlerPtr m_usb_error_dev_callback
;
116 SocketQueueMap m_socketQueues
;
119 pthread_t m_usb_read_thread
;
120 volatile bool m_continue_reading
;// set to true when the thread is created,
121 // then set to false in the destructor
122 // to signal the end of the thread
123 // and handle the join
126 // Provides a method of returning a buffer to the free queue
127 // after processing. The DataHandle class calls this automatically
128 // from its destructor.
129 void ReturnBuffer(Data
*buf
);
131 // Thread function for the simple read behaviour... thread is
132 // created in the SpinoffSimpleReadThread() member below.
133 static void *SimpleReadThread(void *userptr
);
135 // Notifies all registered handlers of an error.
136 // Intended to be called by error handling code within threads which
137 // aren't the main thread.
138 void NotifyHandlersOfError(Barry::Error
&error
);
141 SocketRoutingQueue(int prealloc_buffer_count
= 4);
142 ~SocketRoutingQueue();
147 int GetWriteEp() const { return m_writeEp
; }
148 int GetReadEp() const { return m_readEp
; }
151 // These functions connect the router to an external Usb::Device
152 // object. Normally this is handled automatically by the
153 // Controller class, but are public here in case they are needed.
155 // If DoRead encounters an error, it sets a flag and stops
156 // reading. To recover, you should handle the Error() call in
157 // the callback, fix the USB device, and then call
158 // ClearUsbError() to clear the flag.
160 void SetUsbDevice(Usb::Device
*dev
, int writeEp
, int readEp
,
161 SocketDataHandlerPtr callback
= SocketDataHandlerPtr());
162 void ClearUsbDevice();
163 bool UsbDeviceReady();
164 Usb::Device
* GetUsbDevice() { return m_dev
; }
165 void ClearUsbError();
168 // This class starts out with no buffers, and will grow one buffer
169 // at a time if needed. Call this to allocate count buffers
170 // all at once and place them on the free queue.
171 void AllocateBuffers(int count
);
173 // Returns the data for the next unregistered socket.
174 // Blocks until timeout or data is available.
175 // Returns false (or null pointer) on timeout and no data.
176 // With the return version of the function, there is no
177 // copying performed.
178 bool DefaultRead(Data
&receive
, int timeout
= -1);
179 DataHandle
DefaultRead(int timeout
= -1);
181 // Register an interest in data from a certain socket. To read
182 // from that socket, use the SocketRead() function from then on.
183 // Any non-registered socket goes in the default queue
184 // and must be read by DefaultRead()
185 // If not null, handler is called when new data is read. It will
186 // be called in the same thread instance that DoRead() is called from.
187 // Handler is passed the DataQueue Data object, and so no
188 // copying is done. Once the handler returns, the data is
189 // considered processed and not added to the interested queue,
190 // but instead returned to m_free.
191 void RegisterInterest(SocketId socket
, SocketDataHandlerPtr handler
);
193 // Unregisters interest in data from the given socket, and discards
194 // any existing data in its interest queue. Any new incoming data
195 // for this socket will be placed in the default queue.
196 void UnregisterInterest(SocketId socket
);
198 // Reads data from the interested socket cache. Can only read
199 // from sockets that have been previously registered.
200 // Blocks until timeout or data is available.
201 // Returns false (or null pointer) on timeout and no data.
202 // With the return version of the function, there is no
203 // copying performed.
204 bool SocketRead(SocketId socket
, Data
&receive
, int timeout
= -1);
205 DataHandle
SocketRead(SocketId socket
, int timeout
= -1);
207 // Returns true if data is available for that socket.
208 bool IsAvailable(SocketId socket
) const;
210 // Called by the application's "read thread" to read the next usb
211 // packet and route it to the correct queue. Returns after every
212 // read, even if a handler is associated with a queue.
213 // Note: this function is safe to call before SetUsbDevice() is
214 // called... it just doesn't do anything if there is no usb
215 // device to work with.
217 // Timeout is in milliseconds.
218 void DoRead(int timeout
= -1);
220 // Utility function to make it easier for the user to create the
221 // USB pure-read thread. If the user wants anything more complicated
222 // in this background thread, he can implement it himself and call
223 // the above DoRead() in a loop. If only the basics are needed,
224 // then this makes it easy.
225 // Throws Barry::ErrnoError on thread creation error.
226 void SpinoffSimpleReadThread();
233 /// std::auto_ptr like class that handles pointers to Data, but instead of
234 /// freeing them completely, the Data objects are turned to the
235 /// SocketRoutingQueue from whence they came.
237 class BXEXPORT DataHandle
240 SocketRoutingQueue
&m_queue
;
241 mutable Data
*m_data
;
247 m_queue
.ReturnBuffer(m_data
);
253 DataHandle(SocketRoutingQueue
&q
, Data
*data
)
259 DataHandle(const DataHandle
&other
)
260 : m_queue(other
.m_queue
)
261 , m_data(other
.m_data
)
263 // we now own the pointer
277 Data
* release() // no longer owns the pointer
289 const Data
* operator->() const
294 DataHandle
& operator=(const DataHandle
&other
)
296 if( &m_queue
!= &other
.m_queue
)
297 throw std::logic_error("Trying to copy DataHandles of different queues!");
299 // remove our current data
303 m_data
= other
.m_data
;