-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlight_server.py
113 lines (58 loc) · 1.94 KB
/
light_server.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
101
102
103
104
105
106
107
108
109
110
import socket
import threading
import time
import bluetooth
bind_ip = "192.168.1.114"
bind_port = 46000
bluetooth_MAC = '98:D3:31:30:77:53'
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((bind_ip, bind_port))
#listen on port 46000 with max connection baglog = 5
server.listen(30)
print "[*] Listening on %s:%d" % (bind_ip, bind_port)
def bt_connect(address, channel):
while(True):
try:
btSocket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
btSocket.connect((address, channel))
break
except:
btSocket.close()
print "Could not establish bluetooth connection: Retrying in 1s..."
time.sleep(1)
return btSocket
def bt_disconnect(bt_socket):
bt_socket.close()
def turn_off_lights():
switchSocket = bt_connect(bluetooth_MAC, 1)
switchSocket.send('0')
bt_disconnect(switchSocket)
def turn_on_lights():
switchSocket = bt_connect(bluetooth_MAC, 1)
switchSocket.send('1')
bt_disconnect(switchSocket)
# client handling thread
def handle_client(client_socket):
request = client_socket.recv(1024)
if request != '':
print "[*] Received: %s" % (request)
client_socket.send("ACK!")
client_socket.close()
request_params = request.splitlines()
path = request_params[0].split()[1]
if path == '/lights-on':
print path
turn_on_lights()
elif path == '/lights-off':
print path
turn_off_lights()
else:
client_socket.send("ACK!")
client_socket.close()
#Main server loop
while True:
client, addr = server.accept()
print "[*] Accepted connection from %s:%d" % (addr[0], addr[1])
#spin up client thread to pass off connection
client_handler = threading.Thread(target=handle_client, args=(client,))
client_handler.start()