Skip to content

Instantly share code, notes, and snippets.

@tanpinsiang
Last active April 26, 2022 15:10
Show Gist options
  • Save tanpinsiang/99cdc525baca3c415f5d4835d0f8fbaa to your computer and use it in GitHub Desktop.
Save tanpinsiang/99cdc525baca3c415f5d4835d0f8fbaa to your computer and use it in GitHub Desktop.
Sample python foxglove websocket server for sending GeoJSON.
import asyncio
import json
import time
from foxglove_websocket import run_cancellable
from foxglove_websocket.server import FoxgloveServer, FoxgloveServerListener
from foxglove_websocket.types import ChannelId
async def main():
class Listener(FoxgloveServerListener):
def on_subscribe(self, server: FoxgloveServer, channel_id: ChannelId):
print("First client subscribed to", channel_id)
def on_unsubscribe(self, server: FoxgloveServer, channel_id: ChannelId):
print("Last client unsubscribed from", channel_id)
async with FoxgloveServer("0.0.0.0", 8765, "example server") as server:
server.set_listener(Listener())
chan_id = await server.add_channel(
{
"topic": "foxglove.GeoJSON",
"encoding": "json",
"schemaName": "foxglove.GeoJSON",
"schema": json.dumps(
{
"type": "object",
"properties": {
"geojson": {"type": "string"}
},
}
),
}
)
chan_id_1 = await server.add_channel(
{
"topic": "foxglove.LocationFix",
"encoding": "json",
"schemaName": "foxglove.LocationFix",
"schema": json.dumps(
{
"type": "object",
"properties": {
"latitude": {"type": "number"},
"longitude": {"type": "number"}
},
}
),
}
)
geojson_str = {
"type":"FeatureCollection",
"features":[
{
"type":"Feature",
"properties":{},
"geometry":{
"type":"LineString",
"coordinates":[
[
2.42477416992186,
1.801374964252865
],
[
2.42082595825194,
1.7846897817763
],
[
2.4422836303711,
1.78292608704408
]
]
}
},
{
"type":"Feature",
"properties":{},
"geometry":{
"type":"Polygon",
"coordinates":[
[
[
2.44314193725585,
1.77342854582093
],
[
2.43953704833984,
1.76596533600783
],
[
2.4264907836914,
1.7694934927041
],
[
2.42700576782227,
1.77817746896081
],
[
2.44314193725585,
1.77342854582093
]
]
]
}
},
{
"type":"Feature",
"properties":{
"marker-color":"#7e7e7e",
"marker-size":"medium",
"marker-symbol":"1"
},
"geometry":{
"type":"Point",
"coordinates":[
2.43284225463867,
1.78943798147498
]
}
}
]
}
i = 0
while True:
i += 1
time_ns = time.time_ns()
await asyncio.sleep(0.2)
await server.send_message(
chan_id,
time_ns,
json.dumps(
{
"geojson": json.dumps(geojson_str)
}
).encode("utf8"),
)
await server.send_message(
chan_id_1,
time_ns,
json.dumps(
{
"latitude": 2.3284225463867,
"longitude": 1.78943798147498
}
).encode("utf8"),
)
if __name__ == "__main__":
run_cancellable(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment