-
Notifications
You must be signed in to change notification settings - Fork 0
/
bluetooth.py
96 lines (87 loc) · 3.8 KB
/
bluetooth.py
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
import RPi.GPIO as GPIO
import time
import pexpect
import multiprocessing
import read
import GPIObutton
from VLCplayer import VLC
import logging
def get_logger(name):
log_format = '%(asctime)s %(name)8s %(levelname)5s %(message)s'
logging.basicConfig(level=logging.DEBUG,
format=log_format,
filename='dev.log',
filemode='w')
console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
console.setFormatter(logging.Formatter(log_format))
logging.getLogger(name).addHandler(console)
return logging.getLogger(name)
logger = get_logger('main')
GPIO.setmode(GPIO.BCM)
GPIO.setup(6, GPIO.IN, pull_up_down=GPIO.PUD_UP)
#MAC address of bluetooth speaker
mac = 'B8:F6:53:9B:97:B4'
#GPIO buttons for next, previous, pause
buttons = [13, 19, 26]
#event manager
event_dict = {
'play': False,
'add_playlist': [False, '', False],
'new_playlist': [False, '', False],
'pause': False,
'next': False,
'previous': False
}
if __name__ == '__main__':
try:
while True:
with multiprocessing.Manager() as manager:
event = manager.dict(event_dict)
pool = multiprocessing.Pool(processes=5)
while True:
buttonState = GPIO.input(6)
if not buttonState:
logging.info('Button 6 Pressed')
print('Connect/Disconnect')
child = pexpect.spawn('bluetoothctl')
child.expect('Agent registered')
child.sendline('connect ' + mac)
# if 'Connected: yes' comes first, speaker is not yet connected
# if 'Connection successful' comes first, speaker is already connected
connected = child.expect(['Connected: yes', 'Connection successful'])
if connected == 0:
logging.info('Bluetooth connected')
print('Connected')
# time.sleep(3)
# player = VLC()
# player.addPlaylist("/home/pi/Music/211/", True)
# player.play()
# print('playing')
# time.sleep(15)
# add NFC reader to process pool
pool.apply_async(read.playOnNFC, args=(event, get_logger, ))
# add next, previous, pause button listeners to process pool
for button in buttons:
pool.apply_async(GPIObutton.buttonLoop, args=(button, event, get_logger, ))
# add event listener to process pool
pool.apply_async(read.eventListener, args=(event, get_logger, ))
print('pools!')
logging.info('All processes started')
# while True:
# pass
else:
child.sendline('disconnect ' + mac)
child.expect('Connected: no')
print('Disconnected')
logging.info('Bluetooth disconnected')
pool.close()
pool.terminate()
pool.join()
print('Processes joined')
logging.info('Processes joinedpy')
break
time.sleep(1)
time.sleep(0.1)
finally:
GPIO.cleanup()