-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathsignaling_race.py
195 lines (158 loc) · 5.63 KB
/
signaling_race.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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
import argparse
import asyncio
import json
import logging
import os
import random
import sys
from aiortc import RTCIceCandidate, RTCSessionDescription
from aiortc.sdp import candidate_from_sdp, candidate_to_sdp
import socketio
import time
import hashlib
try:
import aiohttp
except ImportError: # pragma: no cover
aiohttp = None
logger = logging.getLogger("signaling_race")
BYE = object()
start_timer = None
roomName = 'TestRoom-123456' #replace this with your room name and password
passCode = '123456' #defailt password in mobile app
parser = argparse.ArgumentParser(description="RaceOSSDC")
parser.add_argument('-r','--room', type=str, default=roomName)
args, unknown = parser.parse_known_args()
if args.room:
roomName = args.room
droneRoomName = hashlib.md5((roomName+'-'+passCode).encode("utf-8")).hexdigest()
debug=False
def debug_print(*argv):
if(debug):
debug_print(*argv)
sio = socketio.AsyncClient()
sio_messages = []
@sio.on(droneRoomName+'.members',namespace='/')
async def on_room_members(data):
print("on_room_members",data)
sio_messages.append(data)
@sio.on(droneRoomName+'.message',namespace='/')
async def on_room_message(data):
if data["sender"] == sio.eio.sid:
return
debug_print("on_room_message",data)
sio_messages.append(data)
@sio.on('ping',namespace='/')
async def onping_message(data):
debug_print("onping_message",data)
sendMessage("{'pong': true}")
@sio.on
async def on_message(sid,data):
if sid==sio.eio.sid:
return
debug_print("on_message",data)
sio_messages.append(data)
@sio.event
async def connect():
debug_print('connection established')
debug_print("sid", sio.eio.sid)
async def sendMessage(message):
message = {"roomName": droneRoomName, "message": message}
debug_print("sendMessage msg",message)
res = await sio.emit('publish', message)
debug_print("sendMessage res",res)
async def sendSubscribeMessage():
debug_print("sendSubscribeMessage", droneRoomName)
await sio.emit('subscribe', droneRoomName)
async def sendUnSubscribeMessage():
debug_print("sendUnSubscribeMessage", droneRoomName)
await sio.emit('unsubscribe', droneRoomName)
async def object_from_string(message_str):
if(isinstance(message_str,list)):
return message_str
message = None;
if(isinstance(message_str,dict)):
if "sdp" in message_str["message"]:
message = message_str["message"]["sdp"]
if "candidate" in message_str["message"]:
message = message_str["message"] #["candidate"]
if "stick" in message_str["message"]:
message = message_str["message"]
else:
message = json.loads(message_str)
if message is not None:
if "type" in message and message["type"] in ["answer", "offer"]:
return RTCSessionDescription(**message)
elif ("type" in message and message["type"] == "candidate" and message["candidate"]) or message["candidate"]:
candidate = None
if(isinstance(message["candidate"], dict )):
candidate = candidate_from_sdp(message["candidate"]["candidate"].split(":", 1)[1])
else:
candidate = candidate_from_sdp(message["candidate"].split(":", 1)[1])
if(isinstance(message["candidate"], dict )):
candidate.sdpMid = message["candidate"]["sdpMid"]
candidate.sdpMLineIndex = message["candidate"]["sdpMLineIndex"]
else:
candidate.sdpMid = message["id"]
candidate.sdpMLineIndex = message["label"]
return candidate
elif message["type"] == "bye":
return BYE
return message
async def object_to_string(obj):
if isinstance(obj, RTCSessionDescription):
message = {"sdp": {"sdp": obj.sdp, "type": obj.type}}
elif isinstance(obj, RTCIceCandidate):
if hasattr(obj, 'label'):
message = {
"candidate": "candidate:" + candidate_to_sdp(obj),
"id": obj.id, #obj.sdpMid,
"label": obj.label, #obj.sdpMLineIndex,
"type": "candidate",
}
else:
message = {
"candidate": "candidate:" + candidate_to_sdp(obj),
"id": obj.sdpMid,
"label": obj.sdpMLineIndex,
"type": "candidate",
}
else:
return obj
return message
class RaceOssdcSignaling:
def __init__(self, room):
self._http = None
self._origin = "https://race.ossdc.org"
self._room = room
self._room = roomName
self.trackEnded = False
async def connect(self):
join_url = self._origin + "/join/#" + self._room
for i in range (5):
try:
#print("SocketIO connect to ",join_url)
await sio.connect(self._origin)
print("SocketIO connected")
break
except Exception as e:
print("SocketIO error ", e)
if i<5:
continue
#await sio.connect(self._origin)
params = {}
params["is_initiator"] = "true"
self.__is_initiator = params["is_initiator"] == "true"
return params
async def receive(self):
global sio_messages
while(not sio_messages):
if self.trackEnded:
return None
await sio.sleep(1)
if sio_messages:
message = sio_messages.pop(0)
debug_print("receive",message)
return await object_from_string(message)
async def send(self, obj):
message = await object_to_string(obj)
await sendMessage(message)