1
1
import bluetooth
2
2
import time
3
+ import textwrap
3
4
4
5
5
6
class MindwaveMobileRawReader :
6
7
START_OF_PACKET_BYTE = 0xaa ;
7
8
def __init__ (self ):
8
9
self ._buffer = [];
9
10
self ._bufferPosition = 0 ;
11
+ self ._isConnected = False ;
10
12
11
13
def connectToMindWaveMobile (self ):
12
- # connecting via bluetooth RFCOMM
14
+ # First discover mindwave mobile address, then connect
15
+ # headset address of me was'9C:B7:0D:72:CD:02';
16
+ # not sure if it really can be different?
17
+ # now discovering address because of https://github.com/robintibor/python-mindwave-mobile/issues/4
18
+ mindwaveMobileAddress = self ._findMindwaveMobileAddress ()
19
+ if (mindwaveMobileAddress is not None ):
20
+ print ("Discovered Mindwave Mobile..." )
21
+ self ._connectToAddress (mindwaveMobileAddress )
22
+ else :
23
+ self ._printErrorDiscoveryMessage ()
24
+
25
+ def _findMindwaveMobileAddress (self ):
26
+ nearby_devices = bluetooth .discover_devices (lookup_names = True )
27
+ for address , name in nearby_devices :
28
+ if (name == "MindWave Mobile" ):
29
+ return address
30
+ return None
31
+
32
+ def _connectToAddress (self , mindwaveMobileAddress ):
13
33
self .mindwaveMobileSocket = bluetooth .BluetoothSocket (bluetooth .RFCOMM )
14
- mindwaveMobileAddress = '9C:B7:0D:72:CD:02' ;
15
- while (True ):
34
+ while (not self ._isConnected ):
16
35
try :
17
- self .mindwaveMobileSocket .connect ((mindwaveMobileAddress , 1 ))
18
- return ;
36
+ self .mindwaveMobileSocket .connect (
37
+ (mindwaveMobileAddress , 1 ))
38
+ self ._isConnected = True
19
39
except bluetooth .btcommon .BluetoothError as error :
20
40
print "Could not connect: " , error , "; Retrying in 5s..."
21
41
time .sleep (5 )
22
-
42
+
43
+
44
+ def isConnected (self ):
45
+ return self ._isConnected
46
+
47
+ def _printErrorDiscoveryMessage (self ):
48
+ print (textwrap .dedent ("""\
49
+ Could not discover Mindwave Mobile. Please make sure the
50
+ Mindwave Mobile device is in pairing mode and your computer
51
+ has bluetooth enabled.""" ).replace ("\n " , " " ))
52
+
23
53
def _readMoreBytesIntoBuffer (self , amountOfBytes ):
24
54
newBytes = self ._readBytesFromMindwaveMobile (amountOfBytes )
25
55
self ._buffer += newBytes
@@ -67,4 +97,4 @@ def clearAlreadyReadBuffer(self):
67
97
def _bufferSize (self ):
68
98
return len (self ._buffer );
69
99
70
- #------------------------------------------------------------------------------
100
+ #------------------------------------------------------------------------------
0 commit comments