File: wiimote.py

package info (click to toggle)
python-whiteboard 1.0%2Bgit20111009-1
  • links: PTS
  • area: main
  • in suites: wheezy
  • size: 2,164 kB
  • sloc: python: 1,416; xml: 61; makefile: 23; sh: 1
file content (227 lines) | stat: -rw-r--r-- 5,038 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
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
154
155
156
157
158
159
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
#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys, re

import PyQt4.Qt as qt

from numpy import matrix, linalg
import cwiid, bluetooth

from configuration import Configuration
from threads import CreateThreadClass



def calculateArea(points):
	print points
	p1 = points[0]
	p2 = points[1]
	p3 = points[2]
	p4 = points[3]

	vb = [p2[0]-p1[0], p2[1]-p1[1]]
	va = [p4[0]-p1[0], p4[1]-p1[1]]

	paral_A_area = va[0]*vb[1] - va[1]*vb[0]

	va = [p2[0]-p3[0], p2[1]-p3[1]]
	vb = [p4[0]-p3[0], p4[1]-p3[1]]

	paral_B_area = va[0]*vb[1] - va[1]*vb[0]

	result = float(paral_A_area)/2 + float(paral_B_area)/2
	print paral_A_area
	print paral_B_area
	return result






class Wiimote:
	CALIBRATED, NONCALIBRATED = range(2)
	MAX_X = cwiid.IR_X_MAX
	MAX_Y = cwiid.IR_Y_MAX
	
	def __init__(self):
		self.wii = None
		self.error = False
		self.pos = None
		self.state = Wiimote.NONCALIBRATED
		self.calibrationPoints = []
		self.screenPoints = []
		self.utilization = 0.0
		self.maxIrSensitivity = int(Configuration().getValueStr("sensitivity"))
		self.funcIR = None
		self.funcBTN = None
	
	
	def create_wiimote_callback(self):
		# Closure
		def wiimote_callback(messages,buttons):
			if messages:
				for m in messages:
					if m[0] == cwiid.MESG_IR:
						data = m[1][0]
						if data:
							if data['size'] > self.maxIrSensitivity:
								continue
							if self.funcIR is not None:
								self.funcIR(self.getPos(data['pos']))
								return
					elif m[0] == cwiid.MESG_ERROR:
						self.error = True
					elif m[0] == cwiid.MESG_BTN:
						if m[1] == cwiid.BTN_A:
							if self.funcBTN is not None:
								self.funcBTN()
		
		return wiimote_callback
	
	
	def putCallbackIR(self,funcIR):
		self.funcIR = funcIR
	
	def putCallbackBTN(self,funcBTN):
		self.funcBTN = funcBTN
	
	
	def detectWiimotes(self):
		try:
			self.wiimotesDetected = []
			devices = bluetooth.discover_devices(duration=10, lookup_names=True)
			for mac,name in devices:
				if re.match('.*nintendo.*', name.lower()):
					self.wiimotesDetected.append(mac)
			return
		
		except bluetooth.BluetoothError, errString:
			self.wii = None
			self.error = True
			return
	
	
	def bind(self, addr):
		try:
			self.addr = str(addr)
			self.wii = cwiid.Wiimote(self.addr)
			self.wii.rpt_mode = cwiid.RPT_BTN | cwiid.RPT_IR
			self.wii.led = cwiid.LED1_ON
			self.error = False
			self.wii.rumble = 1
			qt.QThread.msleep(200)
			self.wii.rumble = 0
			self.wii.mesg_callback = self.create_wiimote_callback()
			return
			
		except RuntimeError, errString:
			self.wii = None
			return
		
		except:
			self.wii = None
			self.error = True
			print "Unexpected error:", sys.exc_info()[0]
			raise
	
	def isConnected(self):
		if self.wii: return True
		return False
	
	def enable(self):
		self.error = False
		self.maxIrSensitivity = int(Configuration().getValueStr("sensitivity"))
		self.wii.enable(cwiid.FLAG_MESG_IFC)
	
	def disable(self):
		self.wii.disable(cwiid.FLAG_MESG_IFC)
	
	def close(self):
		self.disable()
		qt.QThread.msleep(800)
		self.wii.close()
		self.wii = None
	
	def checkStatus(self):
		if self.wii == None or self.error == True: return False
		try:
			self.wii.request_status()
			return True
		except:
			return False
	
	def battery(self):
		return float(self.wii.state['battery']) / float(cwiid.BATTERY_MAX)
	
	def getPos(self,p):
		if self.state == Wiimote.NONCALIBRATED:
			return p
		if self.state == Wiimote.CALIBRATED:
			return [
				(self.h11*p[0] + self.h12*p[1] + self.h13) / \
				(self.h31*p[0] + self.h32*p[1] + 1),
				(self.h21*p[0] + self.h22*p[1] + self.h23) / \
				(self.h31*p[0] + self.h32*p[1] + 1) ]
	
	def calibrate(self, p_screen, p_wii):
		l = []
		for i in range(0,4):
			l.append( [p_wii[i][0], p_wii[i][1], 1, 0, 0, 0, 
				(-p_screen[i][0] * p_wii[i][0]), 
				(-p_screen[i][0] * p_wii[i][1])] )
			l.append( [0, 0, 0, p_wii[i][0], p_wii[i][1], 1, 
				(-p_screen[i][1] * p_wii[i][0]), 
				(-p_screen[i][1] * p_wii[i][1])] )

		A = matrix(l)

		x = matrix( [
			[p_screen[0][0]],
			[p_screen[0][1]],
			[p_screen[1][0]],
			[p_screen[1][1]],
			[p_screen[2][0]],
			[p_screen[2][1]],
			[p_screen[3][0]],
			[p_screen[3][1]],
		])

		self.hCoefs = linalg.solve(A, x)
		self.h11 = self.hCoefs[0]
		self.h12 = self.hCoefs[1]
		self.h13 = self.hCoefs[2]
		self.h21 = self.hCoefs[3]
		self.h22 = self.hCoefs[4]
		self.h23 = self.hCoefs[5]
		self.h31 = self.hCoefs[6]
		self.h32 = self.hCoefs[7]
		
		self.calibrationPoints = list(p_wii)
		self.screenPoints = list(p_screen)
		self.state = Wiimote.CALIBRATED
		
		area_inside = calculateArea(self.calibrationPoints)
		total_area = Wiimote.MAX_X * Wiimote.MAX_Y
		self.utilization = float(area_inside)/float(total_area)
	
	
	def createConnectThread(self, selectedmac, pool):
		def func():			
			if selectedmac == '*':
				self.detectWiimotes()
				if len(self.wiimotesDetected) == 0: return
				
				for p in self.wiimotesDetected:
					if not p in pool:
						pool.append(p)
				
			else:
				self.bind(selectedmac)
		
		thread = CreateThreadClass(func)
		return thread()