diff --git a/ground-station.py b/ground-station.py index bf275d5..5968fb5 100644 --- a/ground-station.py +++ b/ground-station.py @@ -16,6 +16,15 @@ BOAT_STATE_TERMINATED = -1 Boats = [] Clients = [] +async def sendToClient(client, msg): + if client['state'] != 'terminated' and client['ws'].connected: + await client['ws'].send(msg) + elif client['state'] != 'kicked': + client['state'] = 'terminated' + if client['boat'] is not None: + client['boat']['state'] = BOAT_STATE_AVAILABLE + client['boat'] = None + async def sendToBoat(boat, cmd): boat['log'].append({"t": datetime.timestamp(datetime.now()), "type": "tx", "msg": cmd}) await boat['ws'].send(cmd) @@ -31,7 +40,7 @@ async def echo_boats(client): data += 'available:' elif boat["state"] == BOAT_STATE_INCTRL: data += 'inctrl:' - await client['ws'].send(data) + await sendToClient(client, data) async def echo_locked_boats(client): """echo list of all locked boats to client""" @@ -40,7 +49,7 @@ async def echo_locked_boats(client): for boat in Boats: if boat['state'] == BOAT_STATE_LOCKED: data += str(boat['id']) + ";" + str(boat['name']) + ";locked:" - await client['ws'].send(data + '\n') + await sendToClient(client, data) async def echo_clients(client): """echo list of all clients to client""" @@ -54,7 +63,7 @@ async def echo_clients(client): if (clie['boat'] is not None): boatId = clie['boat']['id'] data += clientId + ";" + boatId + ";" + str(clie['state']) + ":" - await client['ws'].send(data + '\n') + await sendToClient(client, data) async def take_controll(client, boat): """let a client take controll a boat""" @@ -67,18 +76,18 @@ async def take_controll(client, boat): b["state"] = BOAT_STATE_INCTRL print("take controll: " + str(client["id"]) + " -> " + b["name"]) client["boat"] = b - await client['ws'].send("OK") + await sendToClient(client, "OK") return else: break - await client['ws'].send("FAIL") + await sendToClient(client, "FAIL") async def free_boat(boat): """make boat available for next client""" for client in Clients: if client["boat"] is not None and client["boat"]['id'] == boat: client["boat"] = None - await client['ws'].send("FAIL") + await sendToClient(client, "FAIL") break for b in Boats: if b['id'] == boat and b['state'] != BOAT_STATE_TERMINATED: @@ -90,7 +99,7 @@ async def lock_boat(boat): for client in Clients: if client["boat"] is not None and client["boat"]['id'] == boat: client["boat"] = None - await client['ws'].send("FAIL") + await sendToClient(client, "FAIL") break for b in Boats: if b['id'] == boat and b['state'] != BOAT_STATE_TERMINATED: @@ -101,7 +110,7 @@ async def getlog(client, data): """send boat log to client""" for b in Boats: if b['id'] == data[2]: - await client['ws'].send("log;" + b['id'] + ";" + json.dumps(b['log'])) + await sendToClient(client, "log;" + b['id'] + ";" + json.dumps(b['log'])) return async def sendcmd(data):