-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
63 lines (47 loc) · 2.27 KB
/
server.py
File metadata and controls
63 lines (47 loc) · 2.27 KB
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
import json
from websocket_server import WebsocketServer # pip package, in python 3.5 you may have to do `pip install -U websocket-server`
import http_server
import networktables_client
with open("config.json", "r") as config_file:
config = json.load(config_file)
shared_dict = {
"robot_status": "disconnected",
"form": {}
}
http_server.setup(config["http_port"])
# Create a WS Server, this allows push/pull between the web-browsers (interfaces)
# Called for every client connecting (after handshake)
def new_client(client, server):
print("New client connected and was given id %d" % client['id'])
server.send_message(client, json.dumps(shared_dict))
# Called when a client sends a message
def message_received(client, server, message):
if message != "PING":
print("Client(%d) said: %s" % (client['id'], message))
shared_dict["form"] = json.loads(message)
server.send_message_to_all(json.dumps(shared_dict))
for key, value in shared_dict["form"].items():
networktable.putValue(key, value)
ws_server = WebsocketServer(config['ws_port'])
ws_server.set_fn_new_client(new_client)
ws_server.set_fn_message_received(message_received)
class ConnectionListener:
def __init__(self):
self._first_disconnect = True # we want to ignore the first disconnect event as it's always disconnected at init
def connected(self, table):
print("NetworksTables connected to", table)
shared_dict["robot_status"] = "connected"
ws_server.send_message_to_all(json.dumps(shared_dict))
# we may have form data to send to the table while we were disconnected, so update it
for key, value in shared_dict["form"].items():
table.putValue(key, value)
def disconnected(self, table):
if self._first_disconnect:
self._first_disconnect = False
return
print("NetworkTabes disconnected from", table)
shared_dict["robot_status"] = "disconnected"
ws_server.send_message_to_all(json.dumps(shared_dict))
networktable = networktables_client.setup(config["robot_ip"], config["networktable"], ConnectionListener)
ws_server.run_forever() # we could throw this off to a seperate thread too, but then the main thread would have nothing to do
print("Exiting")