-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBTServer.py
138 lines (104 loc) · 3.75 KB
/
BTServer.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
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
#!/usr/bin/python
import logging
import logging.handlers
import argparse
import sys
import os
import time
from bluetooth import *
class LoggerHelper(object):
def __init__(self, logger, level):
self.logger = logger
self.level = level
def write(self, message):
if message.rstrip() != "":
self.logger.log(self.level, message.rstrip())
def setup_logging():
# Default logging settings
LOG_FILE = "/var/log/raspibtsrv.log"
LOG_LEVEL = logging.INFO
# Define and parse command line arguments
argp = argparse.ArgumentParser(description="Raspberry PI Bluetooth Server")
argp.add_argument("-l", "--log", help="log (default '" + LOG_FILE + "')")
# Grab the log file from arguments
args = argp.parse_args()
if args.log:
LOG_FILE = args.log
# Setup the logger
logger = logging.getLogger(__name__)
# Set the log level
logger.setLevel(LOG_LEVEL)
# Make a rolling event log that resets at midnight and backs-up every 3 days
handler = logging.handlers.TimedRotatingFileHandler(LOG_FILE,
when="midnight",
backupCount=3)
# Log messages should include time stamp and log level
formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(message)s')
# Attach the formatter to the handler
handler.setFormatter(formatter)
# Attach the handler to the logger
logger.addHandler(handler)
# Replace stdout with logging to file at INFO level
sys.stdout = LoggerHelper(logger, logging.INFO)
# Replace stderr with logging to file at ERROR level
sys.stderr = LoggerHelper(logger, logging.ERROR)
# Main loop
def main():
# Setup logging
setup_logging()
# We need to wait until Bluetooth init is done
time.sleep(10)
# Make device visible
os.system("hciconfig hci0 piscan")
# Create a new server socket using RFCOMM protocol
server_sock = BluetoothSocket(RFCOMM)
# Bind to any port
server_sock.bind(("", PORT_ANY))
# Start listening
server_sock.listen(1)
# Get the port the server socket is listening
port = server_sock.getsockname()[1]
# The service UUID to advertise
uuid = "7be1fcb3-5776-42fb-91fd-2ee7b5bbb86d"
# Start advertising the service
advertise_service(server_sock, "RaspiBtSrv",
service_id=uuid,
service_classes=[uuid, SERIAL_PORT_CLASS],
profiles=[SERIAL_PORT_PROFILE])
# These are the operations the service supports
# Feel free to add more
operations = ["ping", "example"]
# Main Bluetooth server loop
while True:
print "Waiting for connection on RFCOMM channel %d" % port
try:
client_sock = None
# This will block until we get a new connection
client_sock, client_info = server_sock.accept()
print "Accepted connection from ", client_info
# Read the data sent by the client
data = client_sock.recv(1024)
if len(data) == 0:
break
print "Received [%s]" % data
# Handle the request
if data == "getop":
response = "op:%s" % ",".join(operations)
elif data == "ping":
response = "msg:Pong"
elif data == "example":
response = "msg:This is an example"
# Insert more here
else:
response = "msg:Not supported"
client_sock.send(response)
print "Sent back [%s]" % response
except IOError:
pass
except KeyboardInterrupt:
if client_sock is not None:
client_sock.close()
server_sock.close()
print "Server going down"
break
main()