-
Notifications
You must be signed in to change notification settings - Fork 0
/
pi_socket.py
100 lines (81 loc) · 2.38 KB
/
pi_socket.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
97
98
99
100
import socket
import threading
from collections import deque
import signal
import time
server_addr = 'E4:5F:01:FC:E7:EE'
server_port = 1
buf_size = 1024
client_sock = None
server_sock = None
sock = None
exit_event = threading.Event()
message_queue = deque([])
output = ""
dq_lock = threading.Lock()
output_lock = threading.Lock()
def handler(signum, frame):
exit_event.set()
signal.signal(signal.SIGINT, handler)
def start_client():
global server_addr
global server_port
global server_sock
global sock
global exit_event
global message_queue
global output
global dq_lock
global output_lock
server_sock = socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM)
server_sock.bind((server_addr, server_port))
server_sock.listen(1)
server_sock.settimeout(10)
sock, address = server_sock.accept()
print("Connected")
server_sock.settimeout(None)
sock.setblocking(0)
while not exit_event.is_set():
if dq_lock.acquire(blocking=False):
if(len(message_queue) > 0):
try:
sent = sock.send(bytes(message_queue[0], 'utf-8'))
except Exception as e:
exit_event.set()
continue
if sent < len(message_queue[0]):
message_queue[0] = message_queue[0][sent:]
else:
message_queue.popleft()
dq_lock.release()
if output_lock.acquire(blocking=False):
data = ""
try:
try:
data = sock.recv(1024).decode('utf-8')
except socket.error as e:
assert(1==1)
#no data
except Exception as e:
exit_event.set()
continue
output += data
output_split = output.split("\r\n")
for i in range(len(output_split) - 1):
print(output_split[i])
output = output_split[-1]
output_lock.release()
server_sock.close()
sock.close()
print("client thread end")
cth = threading.Thread(target=start_client)
cth.start()
j = 0
while not exit_event.is_set():
dq_lock.acquire()
message_queue.append("RPi " + str(j) + " \r\n")
dq_lock.release()
j += 1
time.sleep(1.5)
print("Disconnected.")
print("All done.")