-
Notifications
You must be signed in to change notification settings - Fork 0
/
ws-tcp-relay.py
156 lines (129 loc) · 4.81 KB
/
ws-tcp-relay.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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
import asyncio
import json
import socket
import threading
import websockets
from BowlingMachine import BowlingMachineResponse
from EventEnums import Events, Devices
from EventInfo import getEventInfoObject
CONFIG_PATH = "./config.json"
fp = open(CONFIG_PATH)
config = json.load(fp)
bayId = config["bayId"]
API_KEY = config["machineApiKey"]
def tcp_client_receive(tcp_socket, websocket):
try:
while True:
message = tcp_socket.recv(1024).decode('utf-8')
if message and message.strip() != '':
print(f"Received from TCP server: {message}")
messageToBeSent = getMessageToBeSentToWebsocket(message)
if messageToBeSent:
asyncio.run(send_message_to_websocket(websocket, messageToBeSent))
except Exception as e:
print(f"TCP client receive error: {e}")
finally:
tcp_socket.close()
def send_message_to_tcp(tcp_socket, message):
try:
tcp_socket.send(message.encode('utf-8'))
except Exception as e:
print(f"Error sending message to TCP server: {e}")
def start_tcp_client(websocket):
tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
tcp_socket.connect(('192.168.4.1', 8384))
threading.Thread(target=tcp_client_receive, args=(tcp_socket, websocket)).start()
return tcp_socket
except Exception as e:
print(f"Error connecting to TCP server: {e}")
tcp_socket.close()
return None
async def websocket_client_receive(websocket, tcp_socket):
try:
async for message in websocket:
print(f"Received from WebSocket server: {message}")
messageToBeSent = getMessageToBeSentToTCP(message)
if messageToBeSent is not None:
send_message_to_tcp(tcp_socket, messageToBeSent)
except Exception as e:
print(f"WebSocket client receive error: {e}")
finally:
await websocket.close()
async def send_message_to_websocket(websocket, message):
try:
await websocket.send(json.dumps(message))
except Exception as e:
print(f"Error sending message to WebSocket server: {e}")
async def start_websocket_client():
while True:
try:
async with websockets.connect('ws://192.168.0.245:3000') as websocket:
tcp_socket = start_tcp_client(websocket)
if tcp_socket:
await websocket_client_receive(websocket, tcp_socket)
else:
await asyncio.sleep(5)
except Exception as e:
print(f"Error connecting to WebSocket server: {e}")
await asyncio.sleep(3)
def getMessageToBeSentToTCP(messageFromWebsocket):
eventInfo = getEventInfoObject(messageFromWebsocket)
if not eventInfo.header.bayInfo.isForAllBays:
if eventInfo.header.bayInfo.bayId != bayId:
return
if Devices.BOWLING_MACHINE.value in eventInfo.header.sentTo:
if Events.BOWLING_MACHINE_STATUS.value == eventInfo.header.eventName:
return f"[S/{API_KEY}/]?"
elif Events.SET_BOWLING_MACHINE_PARAMETERS.value == eventInfo.header.eventName:
return (f"[A/{API_KEY}/{eventInfo.data.value.speed}"
f"/{eventInfo.data.value.mode}/{eventInfo.data.value.swing}/]?")
elif Events.FEED_BOWLING_MACHINE.value == eventInfo.header.eventName:
return f"[F/{API_KEY}/3/]?"
def getMessageToBeSentToWebsocket(messageFromTCP):
message = json.loads(messageFromTCP)
if message["response"] == BowlingMachineResponse.BALLTRIGGERED.value:
return {
"header": {
"sentBy": Devices.TRIGGER.value,
"sentTo": [
Devices.RECORDER.value,
Devices.DETECTOR.value
],
"eventName": Events.THROW_BALL.value,
"bayInfo": {
"isForAllBays": False,
"bayId": bayId
}
},
"data": {
"value": "1"
}
}
elif message["response"] == BowlingMachineResponse.READY.value:
return {
"header": {
"sentBy": Devices.BOWLING_MACHINE.value,
"sentTo": [
Devices.PLAYER_APP.value,
"detector"
],
"eventName": Events.BOWLING_MACHINE_STATUS.value,
"bayInfo": {
"isForAllBays": False,
"bayId": bayId
}
},
"data": {
"value": {
"active": True
}
}
}
return None
def main():
loop = asyncio.get_event_loop()
loop.run_until_complete(start_websocket_client())
loop.run_forever()
if __name__ == "__main__":
main()