Skip to content

Commit 94b8105

Browse files
committed
fix: plug and play support fixes
1 parent c9da24a commit 94b8105

File tree

9 files changed

+202
-160
lines changed

9 files changed

+202
-160
lines changed

cli.py

Lines changed: 36 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,15 @@
33
import asyncio
44
import logging
55
import sys
6+
import json
67

78
import coloredlogs
89

910
# from aiortc import RTCIceCandidate, RTCSessionDescription
1011
from peerjs.peer import Peer, PeerOptions
1112
from peerjs.peerroom import PeerRoom
1213
from peerjs.util import util
14+
from peerjs.enums import ConnectionEventType, PeerEventType
1315

1416
print(sys.version)
1517

@@ -19,9 +21,9 @@
1921

2022
peer = None
2123
myPeerId = None
22-
AMBIANIC_PNP_HOST = 'localhost' # 'ambianic-pnp.herokuapp.com'
23-
AMBIANIC_PNP_PORT = 9779 # 443
24-
AMBIANIC_PNP_SECURE = False # True
24+
AMBIANIC_PNP_HOST = 'ambianic-pnp.herokuapp.com' # 'localhost'
25+
AMBIANIC_PNP_PORT = 443 # 9779
26+
AMBIANIC_PNP_SECURE = True # False
2527
time_start = None
2628
peerConnectionStatus = None
2729
discoveryLoop = None
@@ -53,9 +55,11 @@ async def join_peer_room(peer=None):
5355

5456

5557
def _setPnPServiceConnectionHandlers(peer=None):
58+
assert peer
5659
global myPeerId
57-
@peer.on('open')
60+
@peer.on(PeerEventType.Open)
5861
async def peer_open(id):
62+
log.warning('Peer signaling connection open.')
5963
global myPeerId
6064
# Workaround for peer.reconnect deleting previous id
6165
if peer.id is None:
@@ -64,73 +68,64 @@ async def peer_open(id):
6468
else:
6569
if myPeerId != peer.id:
6670
log.info(
67-
'pnpService: Service returned new peerId. Old %s, New %s',
71+
'PNP Service returned new peerId. Old %s, New %s',
6872
myPeerId,
6973
peer.id
7074
)
7175
myPeerId = peer.id
72-
log.info('pnpService: myPeerId: ', peer.id)
76+
log.info('myPeerId: %s', peer.id)
7377

74-
@peer.on('disconnected')
75-
async def peer_disconnected():
78+
@peer.on(PeerEventType.Disconnected)
79+
async def peer_disconnected(peerId):
7680
global myPeerId
77-
log.info('pnpService: Connection lost. Please reconnect')
81+
log.info('pnpService: Peer %s disconnected from server.', peerId)
7882
# Workaround for peer.reconnect deleting previous id
7983
if not peer.id:
8084
log.info('BUG WORKAROUND: Peer lost ID. '
8185
'Resetting to last known ID.')
8286
peer._id = myPeerId
8387
peer._lastServerId = myPeerId
84-
peer.reconnect()
88+
await peer.reconnect()
8589

86-
@peer.on('close')
90+
@peer.on(PeerEventType.Close)
8791
def peer_close():
8892
# peerConnection = null
89-
log.info('pnpService: Connection closed')
93+
log.warning('Peer connection closed')
9094

91-
@peer.on('error')
95+
@peer.on(PeerEventType.Error)
9296
def peer_error(err):
93-
log.warning('pnpService %s', err)
94-
log.info('peerConnectionStatus', peerConnectionStatus)
97+
log.exception('Peer error %s', err)
98+
log.warning('peerConnectionStatus %s', peerConnectionStatus)
9599
# retry peer connection in a few seconds
96-
asyncio.call_later(3, pnp_service_connect)
100+
# loop = asyncio.get_event_loop()
101+
# loop.call_later(3, pnp_service_connect)
97102

98103
# remote peer tries to initiate connection
99-
@peer.on('connection')
104+
@peer.on(PeerEventType.Connection)
100105
async def peer_connection(peerConnection):
101-
log.info('remote peer trying to establish connection')
106+
log.warning('Remote peer trying to establish connection')
102107
_setPeerConnectionHandlers(peerConnection)
103108

104109

105110
def _setPeerConnectionHandlers(peerConnection):
106-
@peerConnection.on('open')
111+
@peerConnection.on(ConnectionEventType.Open)
107112
async def pc_open():
108-
log.info('pnpService: Connected to: %s', peerConnection.peer)
113+
log.warning('Connected to: %s', peerConnection.peer)
109114

110115
# Handle incoming data (messages only since this is the signal sender)
111-
@peerConnection.on('data')
116+
@peerConnection.on(ConnectionEventType.Data)
112117
async def pc_data(data):
113-
log.info('pnpService: data received from remote peer %r', data)
114-
pass
118+
log.warning('data received from remote peer \n%r', data)
119+
response = {'name': 'Ambianic-Edge', 'version': '1.0.2020'}
120+
rjson = json.dumps(response)
121+
log.warning('Sending response: \n%r', rjson)
122+
await peerConnection.send(rjson)
115123

116-
@peerConnection.on('close')
124+
@peerConnection.on(ConnectionEventType.Close)
117125
async def pc_close():
118126
log.info('Connection to remote peer closed')
119127

120128

121-
# async def _run_answer(pc, signaling):
122-
# await signaling.connect()
123-
# @pc.on("datachannel")
124-
# def on_datachannel(channel):
125-
# _channel_log(channel, "-", "created by remote party")
126-
# @channel.on("message")
127-
# def on_message(message):
128-
# _channel_log(channel, "<", message)
129-
# if isinstance(message, str) and message.startswith("ping"):
130-
# # reply
131-
# _channel_send(channel, "pong" + message[4:])
132-
# await _consume_signaling(pc, signaling)
133-
134129
async def pnp_service_connect() -> Peer:
135130
"""Create a Peer instance and register with PnP signaling server."""
136131
# if connection to pnp service already open, then nothing to do
@@ -167,7 +162,7 @@ async def make_discoverable(peer=None):
167162
"""Enable remote peers to find and connect to this peer."""
168163
assert peer
169164
while True:
170-
log.info('Making peer discoverable.')
165+
log.debug('Making peer discoverable.')
171166
try:
172167
# check if the websocket connection
173168
# to the signaling server is alive
@@ -180,7 +175,7 @@ async def make_discoverable(peer=None):
180175
log.info('Peer disconnected. Will try to reconnect.')
181176
await peer.reconnect()
182177
else:
183-
log.info('Peer in a strange state: %r', peer)
178+
log.info('Peer still establishing connection. %r', peer)
184179
except Exception as e:
185180
log.exception('Unable to join room. '
186181
'Will retry in a few moments. '
@@ -222,11 +217,11 @@ def _config_logger():
222217
# coro = _run_offer(pc, signaling)
223218
# else:
224219
# coro = _run_answer(pc, signaling)
225-
coro = pnp_service_connect()
220+
coro = pnp_service_connect
226221
# run event loop
227222
loop = asyncio.get_event_loop()
228223
try:
229-
loop.run_until_complete(coro)
224+
loop.run_until_complete(coro())
230225
except KeyboardInterrupt:
231226
log.info('KeyboardInterrupt detected. Exiting...')
232227
pass

run-dev.sh

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,20 @@
11
#!/bin/bash
22
# create empty line distance from previous run
33
# for improved readibility of output
4-
54
printf "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
65
printf "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
76

87
# Dir to this script, e.g. /home/user/bin/
98
SCRIPTPATH="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
109
echo $SCRIPTPATH
1110

12-
# set quick exit and verbose shell output
13-
# set -ex
14-
1511
# check if setup files have been touched recently
1612
SETUP_PY_MOD=$(expr $(expr $(date +%s) - $(date -r "$SCRIPTPATH/src/setup.py" +"%s")) / 60)
1713
SETUP_CFG_MOD=$(expr $(expr $(date +%s) - $(date -r "$SCRIPTPATH/src/setup.cfg" +"%s")) / 60)
1814

15+
# set quick exit and verbose shell output
16+
# set -ex
17+
1918
if [ 2 -gt $SETUP_PY_MOD ] || [ 2 -gt $SETUP_CFG_MOD ]; then
2019
echo "Installing peerjs"
2120
pip3 install --editable src

0 commit comments

Comments
 (0)