OISLIRCFactoryCreator.cpp 10.6 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
#include "OISConfig.h"
#ifdef OIS_LIRC_SUPPORT
/*
The zlib/libpng License

Copyright (c) 2005-2007 Phillip Castaneda (pjcast -- www.wreckedgames.com)

This software is provided 'as-is', without any express or implied warranty. In no event will
the authors be held liable for any damages arising from the use of this software.

Ben Hymers's avatar
Ben Hymers committed
11
Permission is granted to anyone to use this software for any purpose, including commercial
12
13
14
applications, and to alter it and redistribute it freely, subject to the following
restrictions:

Ben Hymers's avatar
Ben Hymers committed
15
16
17
    1. The origin of this software must not be misrepresented; you must not claim that
		you wrote the original software. If you use this software in a product,
		an acknowledgment in the product documentation would be appreciated but is
18
19
		not required.

Ben Hymers's avatar
Ben Hymers committed
20
    2. Altered source versions must be plainly marked as such, and must not be
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
		misrepresented as being the original software.

    3. This notice may not be removed or altered from any source distribution.
*/
#include "OISLIRCFactoryCreator.h"
#include "OISException.h"
#include <assert.h>
#include <stdlib.h>

#ifdef OIS_WIN32_PLATFORM
#  pragma warning (disable : 4996)
#  pragma warning (disable : 4267)
#  pragma warning (disable : 4554)
#  pragma warning (disable : 4996)
#  define _WIN32_WINNT 0x0500
#endif
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/thread.hpp>

#include <istream>
#include <sstream>

using namespace OIS;

//---------------------------------------------------------------------------------//
class LIRCFactoryCreator::BoostWrapper
{
public:
	LIRCFactoryCreator::BoostWrapper() : mSocket(mIOService), mThreadHandler(0)
	{
	}

	//TCP stuff
	boost::asio::io_service mIOService;
	boost::asio::ip::tcp::socket mSocket;

	//Thread Stuff
	//! Boost thread execution object (only alive when at least 1 lirc is alive)
	boost::thread *mThreadHandler;
Ben Hymers's avatar
Ben Hymers committed
61

62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
	//! Gaurds access to the active lirc list
	boost::mutex mLircListMutex;

};

//---------------------------------------------------------------------------------//
LIRCFactoryCreator::LIRCFactoryCreator() :
	mConnected(false),
	mThreadRunning(false),
	mCount(0),
	mWrapped(0)
{
	mWrapped = new BoostWrapper();

	mIP   = (getenv("OIS_LIRC_IP") != 0) ? getenv("OIS_LIRC_IP") : "127.0.0.1";
	mPort = (getenv("OIS_LIRC_PORT") != 0) ? getenv("OIS_LIRC_PORT") : "8765";

	try
	{
		enableConnection(true);
		discoverRemotes();
	}
	catch(...)
	{
		mCount = 0;
	}

	//Regardless of if there is remotes or not, we will close the conenction now.
	enableConnection(false);
}

//---------------------------------------------------------------------------------//
LIRCFactoryCreator::~LIRCFactoryCreator()
{
	enableConnectionThread(false);
	enableConnection(false);

	delete mWrapped;
}

//---------------------------------------------------------------------------------//
void LIRCFactoryCreator::discoverRemotes()
{
	//http://www.lirc.org/html/technical.html#applications
	mCount = 0;

	mWrapped->mSocket.write_some(boost::asio::buffer("LIST\n"));

	boost::asio::streambuf buffer;

	//Read all remotes
	bool start = false;
	bool data = false;
	for(;;)
	{
		boost::asio::read_until(mWrapped->mSocket, buffer, '\n');

		std::istream str(&buffer);
		std::string res;
		str >> res;

		if( res == "" )				//If nothing left, we are done
			break;
		else if( res == "ERROR" )	//If any errors, we leave immediately
			return;
		else if( res == "END" )		//We have reached the end block
			start = false;
		else if( res == "DATA" )	//After Data will be a list of remote names
		{
			start = true;
			data = true;
			continue;
		}

		//Have we  gotten the DATA word yet?
		if( start == false )
			continue;

		if( data ) //How many?
			mCount = atoi(res.c_str());
		else //What follows should now be a list of remote names
			mUnusedRemotes.push_back(res);

		data = false;
	}

	//Read information about each remote
	boost::asio::streambuf buffer2;
	for( int i = 0; i < mCount; ++i )
	{
		std::ostringstream istr;
		istr << "LIST " << mUnusedRemotes[i] << "\n";
Ben Hymers's avatar
Ben Hymers committed
154

155
156
157
158
159
		mWrapped->mSocket.write_some(boost::asio::buffer(istr.str()));
		RemoteInfo information;
		int buttonCount = 0;

		start = data = false;
Ben Hymers's avatar
Ben Hymers committed
160

161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
		for(;;)
		{
			boost::asio::read_until(mWrapped->mSocket, buffer, '\n');

			std::istream str(&buffer);
			std::string res;
			str >> res;

			if( res == "" )				//If nothing left, we are done
				break;
			else if( res == "ERROR" )	//If error, bail out
				return;
			else if( res == "END" )		//We have reached the end block
				start = false;
			else if( res == "DATA" )	//After Data will be button count
			{
				start = true;
				data = true;
				continue;
			}

			//Have we  gotten the DATA word yet?
			if( start == false )
				continue;

			if( data ) //After button count, there will be a list of button names
				information.buttons = atoi(res.c_str());
			else
				information.buttonMap[res] = buttonCount++;

			data = false;
		}

		mJoyStickInformation[mUnusedRemotes[i]] = information;
	}
}

//---------------------------------------------------------------------------------//
void LIRCFactoryCreator::enableConnection(bool enable, bool blocking)
{
	if( enable == true && mConnected == false )
	{
		boost::asio::ip::tcp::resolver resolver(mWrapped->mIOService);
		boost::asio::ip::tcp::resolver::query query(mIP, mPort);
		boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
		boost::asio::ip::tcp::resolver::iterator end;

		//Connect (trying all found connections - ip4/ip6)
		boost::asio::error result = boost::asio::error::host_not_found;
		while (result && endpoint_iterator != end)
		{
			mWrapped->mSocket.close();
			mWrapped->mSocket.connect(*endpoint_iterator++, boost::asio::assign_error(result));
		}

		if (result != boost::asio::error::success)
			throw (result);

		if( blocking == false )
		{
			mWrapped->mSocket.io_control(boost::asio::socket_base::non_blocking_io(true));
		}

		mConnected = true;
	}
	else if( enable == false )
	{
		mWrapped->mSocket.close();
		mConnected = false;
	}
}

//---------------------------------------------------------------------------------//
void LIRCFactoryCreator::enableConnectionThread(bool enable)
{
	if( enable == true && mThreadRunning == false )
	{
		mThreadRunning = true;
		mWrapped->mThreadHandler = new boost::thread(boost::bind(&LIRCFactoryCreator::threadUpdate, this));
	}
	else if( enable == false && mThreadRunning == true )
	{
		mThreadRunning = false;
		mWrapped->mThreadHandler->join();
		delete mWrapped->mThreadHandler;
		mWrapped->mThreadHandler = 0;
	}
}

//---------------------------------------------------------------------------------//
void LIRCFactoryCreator::threadUpdate()
{
	boost::xtime timer;
	boost::asio::streambuf buffer;
	std::istream stream(&buffer);
	std::string code, repeat, button, remote;


	while( mThreadRunning )
	{
		try
		{
			while(  mWrapped->mSocket.in_avail() > 0 )
			{
				boost::asio::read_until(mWrapped->mSocket, buffer, '\n');
Ben Hymers's avatar
Ben Hymers committed
266

267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
				stream >> code;   //64 bit value, ignorable
				stream >> repeat; //Repeat rate starting at zero (we ignore, for now)
				stream >> button; //Button name
				stream >> remote; //Remote name

				{	//Lock object, find out which remote sent event
					boost::mutex::scoped_lock arrayLock(mWrapped->mLircListMutex);
					std::map<std::string, LIRCControl*>::iterator i = mUpdateRemotes.find(remote);
					if( i != mUpdateRemotes.end() )
					{
						i->second->queueButtonPressed(button);
					}
				}
			}
		}
		catch(...)
		{	//Hmm, what should we do if we get a socket error here.. Ignore it I suppose,
Ben Hymers's avatar
Ben Hymers committed
284
		}	//and wait till the used remote objects get shutdown. We could try to
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
			//reconnect, but how do we know if we will even get the same remotes.

		boost::xtime_get(&timer, boost::TIME_UTC);
		timer.nsec += 300000000; // 100 000 000 ~= .3 sec
		boost::thread::sleep(timer);
	}
}

//---------------------------------------------------------------------------------//
DeviceList LIRCFactoryCreator::freeDeviceList()
{
	DeviceList list;
	for( std::vector<std::string>::iterator i = mUnusedRemotes.begin(); i != mUnusedRemotes.end(); ++i )
		list.insert(std::make_pair(OISJoyStick, *i));

	return list;
}

//---------------------------------------------------------------------------------//
int LIRCFactoryCreator::totalDevices(Type iType)
{
	if( iType == OISJoyStick )
		return mCount;
	else
		return 0;
}

//---------------------------------------------------------------------------------//
int LIRCFactoryCreator::freeDevices(Type iType)
{
	if( iType == OISJoyStick )
		return (int)mUnusedRemotes.size();
	else
		return 0;
}

//---------------------------------------------------------------------------------//
bool LIRCFactoryCreator::vendorExist(Type iType, const std::string & vendor)
{
	if( iType == OISJoyStick && std::find(mUnusedRemotes.begin(), mUnusedRemotes.end(), vendor) != mUnusedRemotes.end() )
		return true;
	else
		return false;
}

//---------------------------------------------------------------------------------//
Object* LIRCFactoryCreator::createObject(InputManager* creator, Type iType, bool bufferMode, const std::string & vendor)
{
	if( mUnusedRemotes.size() > 0 )
	{
		std::vector<std::string>::iterator remote = mUnusedRemotes.end();
		if( vendor == "" )
			remote = mUnusedRemotes.begin();
		else
			remote = std::find(mUnusedRemotes.begin(), mUnusedRemotes.end(), vendor);

		if( remote != mUnusedRemotes.end() )
		{
			//Make sure connection is established
			enableConnection(true, false);

			//Make sure connection thread is alive
			enableConnectionThread(true);

			//Create device
			LIRCControl *obj = new LIRCControl(creator, 0, bufferMode, this, mJoyStickInformation[*remote]);

			//Add to used list, and then remove from unused list
			{
				boost::mutex::scoped_lock arrayLock(mWrapped->mLircListMutex);
				mUpdateRemotes[*remote] = obj;
			}
			mUnusedRemotes.erase(remote);

			return obj;
		}
	}
Ben Hymers's avatar
Ben Hymers committed
362

363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
	OIS_EXCEPT(E_InputDeviceNonExistant, "No Device found which matches description!");
}

//---------------------------------------------------------------------------------//
void LIRCFactoryCreator::destroyObject(Object* obj)
{
	if( obj == 0 )
		return;

	int remotes_alive = 0;

	{	//Scope lock
		boost::mutex::scoped_lock arrayLock(mWrapped->mLircListMutex);

		//Find object
		std::map<std::string, LIRCControl*>::iterator i = mUpdateRemotes.begin(), e = mUpdateRemotes.end();
		bool found = false;
		for(; i != e; ++i)
		{
			if( i->second == obj )
			{
				found = true;
				break;
			}
		}

		if( found == false )
			OIS_EXCEPT(E_General, "Device not found in LIRC remote collection!");

		//Move from used to unused list
		mUnusedRemotes.push_back(i->first);
		mUpdateRemotes.erase(i);
Ben Hymers's avatar
Ben Hymers committed
395

396
397
398
399
400
401
402
403
404
405
		delete obj;

		remotes_alive = (int)mUpdateRemotes.size();
	}

	//Destroy thread if no longer in use (we do this after unlocking mutex!)
	if( remotes_alive == 0 )
		enableConnectionThread(false);
}
#endif