-
Notifications
You must be signed in to change notification settings - Fork 2
/
signalk.py
52 lines (48 loc) · 1.37 KB
/
signalk.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
import urllib.request
import json
import websocket
import threading
from config import signalk_host, signalk_port
def get_state():
url = 'http://{}:{}/signalk/v1/api/vessels/self/navigation/state/value'.format(signalk_host, signalk_port)
req = urllib.request.Request(url)
try:
r = urllib.request.urlopen(req).read()
cont = json.loads(r.decode('utf-8'))
print("Initial state {}".format(cont))
return cont
except:
return None
def connect(on_message, on_error, on_open, on_close):
url = 'ws://{}:{}/signalk/v1/stream?subscribe=none'.format(signalk_host, signalk_port)
print(url)
ws = websocket.WebSocketApp(url,
on_message = on_message,
on_error = on_error,
on_open = on_open,
on_close = on_close)
wst = threading.Thread(target=ws.run_forever)
wst.start()
def subscribe(ws, paths):
# First unsubscribe from previous
ws.send(json.dumps({
'context': '*',
'unsubscribe': [
{
'path': '*'
}
]
}))
# Then subscribe to feed
subscribes = []
for path in paths:
subscribes.append({
'path': path,
'period': 3000,
'format': 'delta',
'policy': 'fixed'
})
ws.send(json.dumps({
'context': 'vessels.self',
'subscribe': subscribes
}))