lib: wrap shared_ptr<> in a typedef as SocketDataHandlerPtr
[barry.git] / src / router.h
blob86b3cba3ae596632631887fe33a5c71ed90f07f4
1 ///
2 /// \file router.h
3 /// Support classes for the pluggable socket routing system.
4 ///
6 /*
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__
25 #include "dll.h"
26 #include <stdint.h>
27 #include <map>
28 #include <tr1/memory>
29 #include <stdexcept>
30 #include <pthread.h>
31 #include "dataqueue.h"
32 #include "error.h"
34 namespace Usb { class Device; }
36 namespace Barry {
38 class DataHandle;
40 class BXEXPORT SocketRoutingQueue
42 friend class DataHandle;
44 public:
45 // Interface class for socket data callbacks
46 // See RegisterInterest() for more information.
47 class BXEXPORT SocketDataHandler
49 public:
50 // Called when data is received on the socket
51 // for which interest has been registered.
52 //
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*);
73 T& m_context;
74 public:
75 SimpleSocketDataHandler<T>(T& context, void (*callback)(T& context, Data* data))
76 : m_callback(callback)
77 , m_context(context)
79 virtual void DataReceived(Data& data)
81 m_callback(m_context, &data);
85 struct QueueEntry
87 SocketDataHandlerPtr m_handler;
88 DataQueue m_queue;
90 QueueEntry(SocketDataHandlerPtr h)
91 : m_handler(h)
94 typedef std::tr1::shared_ptr<QueueEntry> QueueEntryPtr;
95 typedef uint16_t SocketId;
96 typedef std::map<SocketId, QueueEntryPtr> SocketQueueMap;
98 private:
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
107 // locking per queue
109 pthread_mutex_t m_readwaitMutex;
110 pthread_cond_t m_readwaitCond;
111 bool m_seen_usb_error;
113 DataQueue m_free;
114 DataQueue m_default;
115 SocketQueueMap m_socketQueues;
117 // thread state
118 pthread_t m_usb_read_thread;
119 volatile bool m_continue_reading;// set to true when the thread is created,
120 // then set to false in the destructor
121 // to signal the end of the thread
122 // and handle the join
124 protected:
125 // Provides a method of returning a buffer to the free queue
126 // after processing. The DataHandle class calls this automatically
127 // from its destructor.
128 void ReturnBuffer(Data *buf);
130 // Thread function for the simple read behaviour... thread is
131 // created in the SpinoffSimpleReadThread() member below.
132 static void *SimpleReadThread(void *userptr);
134 public:
135 SocketRoutingQueue(int prealloc_buffer_count = 4);
136 ~SocketRoutingQueue();
139 // data access
141 int GetWriteEp() const { return m_writeEp; }
142 int GetReadEp() const { return m_readEp; }
145 // These functions connect the router to an external Usb::Device
146 // object. Normally this is handled automatically by the
147 // Controller class, but are public here in case they are needed.
148 void SetUsbDevice(Usb::Device *dev, int writeEp, int readEp);
149 void ClearUsbDevice();
150 bool UsbDeviceReady();
151 Usb::Device* GetUsbDevice() { return m_dev; }
153 // This class starts out with no buffers, and will grow one buffer
154 // at a time if needed. Call this to allocate count buffers
155 // all at once and place them on the free queue.
156 void AllocateBuffers(int count);
158 // Returns the data for the next unregistered socket.
159 // Blocks until timeout or data is available.
160 // Returns false (or null pointer) on timeout and no data.
161 // With the return version of the function, there is no
162 // copying performed.
163 bool DefaultRead(Data &receive, int timeout = -1);
164 DataHandle DefaultRead(int timeout = -1);
166 // Register an interest in data from a certain socket. To read
167 // from that socket, use the SocketRead() function from then on.
168 // Any non-registered socket goes in the default queue
169 // and must be read by DefaultRead()
170 // If not null, handler is called when new data is read. It will
171 // be called in the same thread instance that DoRead() is called from.
172 // Handler is passed the DataQueue Data object, and so no
173 // copying is done. Once the handler returns, the data is
174 // considered processed and not added to the interested queue,
175 // but instead returned to m_free.
176 void RegisterInterest(SocketId socket, SocketDataHandlerPtr handler);
178 // Unregisters interest in data from the given socket, and discards
179 // any existing data in its interest queue. Any new incoming data
180 // for this socket will be placed in the default queue.
181 void UnregisterInterest(SocketId socket);
183 // Reads data from the interested socket cache. Can only read
184 // from sockets that have been previously registered.
185 // Blocks until timeout or data is available.
186 // Returns false (or null pointer) on timeout and no data.
187 // With the return version of the function, there is no
188 // copying performed.
189 bool SocketRead(SocketId socket, Data &receive, int timeout = -1);
190 DataHandle SocketRead(SocketId socket, int timeout = -1);
192 // Returns true if data is available for that socket.
193 bool IsAvailable(SocketId socket) const;
195 // Called by the application's "read thread" to read the next usb
196 // packet and route it to the correct queue. Returns after every
197 // read, even if a handler is associated with a queue.
198 // Note: this function is safe to call before SetUsbDevice() is
199 // called... it just doesn't do anything if there is no usb
200 // device to work with.
202 // Timeout is in milliseconds.
203 void DoRead(int timeout = -1);
205 // Utility function to make it easier for the user to create the
206 // USB pure-read thread. If the user wants anything more complicated
207 // in this background thread, he can implement it himself and call
208 // the above DoRead() in a loop. If only the basics are needed,
209 // then this makes it easy.
210 // Throws Barry::ErrnoError on thread creation error.
211 void SpinoffSimpleReadThread();
216 // DataHandle
218 /// std::auto_ptr like class that handles pointers to Data, but instead of
219 /// freeing them completely, the Data objects are turned to the
220 /// SocketRoutingQueue from whence they came.
222 class BXEXPORT DataHandle
224 private:
225 SocketRoutingQueue &m_queue;
226 mutable Data *m_data;
228 protected:
229 void clear()
231 if( m_data ) {
232 m_queue.ReturnBuffer(m_data);
233 m_data = 0;
237 public:
238 DataHandle(SocketRoutingQueue &q, Data *data)
239 : m_queue(q)
240 , m_data(data)
244 DataHandle(const DataHandle &other)
245 : m_queue(other.m_queue)
246 , m_data(other.m_data)
248 // we now own the pointer
249 other.m_data = 0;
252 ~DataHandle()
254 clear();
257 Data* get()
259 return m_data;
262 Data* release() // no longer owns the pointer
264 Data *ret = m_data;
265 m_data = 0;
266 return ret;
269 Data* operator->()
271 return m_data;
274 const Data* operator->() const
276 return m_data;
279 DataHandle& operator=(const DataHandle &other)
281 if( &m_queue != &other.m_queue )
282 throw std::logic_error("Trying to copy DataHandles of different queues!");
284 // remove our current data
285 clear();
287 // accept the new
288 m_data = other.m_data;
290 // we now own it
291 other.m_data = 0;
293 return *this;
299 } // namespace Barry
301 #endif