Skip to content

Commit

Permalink
websocket logs
Browse files Browse the repository at this point in the history
  • Loading branch information
v00g100skr committed Feb 1, 2024
1 parent 00ba47e commit a0dd863
Showing 1 changed file with 35 additions and 19 deletions.
54 changes: 35 additions & 19 deletions deploy/websocket_server/websocket_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import json
import random
from aiomcache import Client
from geoip2 import database
from geoip2 import database, errors
from functools import partial
from datetime import datetime, timezone

Expand Down Expand Up @@ -70,42 +70,53 @@ def __init__(self):
async def alerts_data(websocket, client, shared_data):
client_ip, client_port = websocket.remote_address
while True:
match client['firmware']:
case 'unknown':
client_id = client_port
case _:
client_id = client['firmware']
try:
logger.debug(f"{client_ip}_{client_port}: check")
logger.debug(f"{client_ip}:{client_id}: check")
if client['alerts'] != shared_data.alerts:
alerts = json.dumps([int(alert) for alert in json.loads(shared_data.alerts)])
payload = '{"payload":"alerts","alerts":%s}' % alerts
await websocket.send(payload)
logger.info(f"{client_ip}_{client_port} <<< new alerts")
logger.info(f"{client_ip}:{client_id} <<< new alerts")
client['alerts'] = shared_data.alerts
if client['weather'] != shared_data.weather:
weather = json.dumps([float(weather) for weather in json.loads(shared_data.weather)])
payload = '{"payload":"weather","weather":%s}' % weather
await websocket.send(payload)
logger.info(f"{client_ip}_{client_port} <<< new weather")
logger.info(f"{client_ip}:{client_id} <<< new weather")
client['weather'] = shared_data.weather
if client['bins'] != shared_data.bins:
payload = '{"payload": "bins", "bins": %s}' % shared_data.bins
await websocket.send(payload)
logger.info(f"{client_ip}_{client_port} <<< new bins")
logger.info(f"{client_ip}:{client_id} <<< new bins")
client['bins'] = shared_data.bins
await asyncio.sleep(0.1)
except websockets.exceptions.ConnectionClosedError:
logger.warning(f"{client_ip}_{client_port} !!! data stopped")
logger.warning(f"{client_ip}:{client_id} !!! data stopped")
break
except Exception as e:
logger.warning(f"{client_ip}_{client_port}: {e}")
logger.warning(f"{client_ip}:{client_id}: {e}")


async def echo(websocket, path):
client_ip, client_port = websocket.remote_address
logger.info(f"{client_ip}_{client_port} >>> new client")
logger.info(f"{client_ip}:{client_port} >>> new client")

if client_ip in shared_data.blocked_ips:
logger.warning(f"{client_ip}_{client_port} !!! BLOCKED")
logger.warning(f"{client_ip}:{client_port} !!! BLOCKED")
return

response = geo.city(client_ip)
try:
response = geo.city(client_ip)
city = response.city.name or 'not-in-db'
region = response.subdivisions.most_specific.name or 'not-in-db'
except errors.AddressNotFoundError:
city = 'not-found'
region = 'not-found'

# if response.country.iso_code != 'UA' and response.continent.code != 'EU':
# shared_data.blocked_ips.append(client_ip)
Expand All @@ -118,8 +129,8 @@ async def echo(websocket, path):
'bins': '[]',
'firmware': 'unknown',
'chip_id': 'unknown',
'city': response.city.name or 'unknown',
'region': response.subdivisions.most_specific.name or 'unknown'
'city': city,
'region': region
}

match path:
Expand All @@ -128,7 +139,12 @@ async def echo(websocket, path):
try:
while True:
async for message in websocket:
logger.info(f"{client_ip}_{client_port} >>> {message}")
match client['firmware']:
case 'unknown':
client_id = client_port
case _:
client_id = client['firmware']
logger.info(f"{client_ip}:{client_id} >>> {message}")

def split_message(message):
parts = message.split(':', 1) # Split at most into 2 parts
Expand All @@ -142,15 +158,15 @@ def split_message(message):
district_data = await district_data_v1(int(data))
payload = json.dumps(district_data).encode('utf-8')
await websocket.send(payload)
logger.info(f"{client_ip}_{client_port} <<< district {payload} ")
logger.info(f"{client_ip}:{client_id} <<< district {payload} ")
case 'firmware':
client['firmware'] = data
logger.warning(f"{client_ip}_{client_port} >>> firmware saved")
logger.warning(f"{client_ip}:{client_id} >>> firmware saved")
case 'chip_id':
client['chip_id'] = data
logger.info(f"{client_ip}_{client_port} >>> chip_id saved")
logger.info(f"{client_ip}:{client_id} >>> chip_id saved")
case _:
logger.info(f"{client_ip}_{client_port} !!! unknown data request")
logger.info(f"{client_ip}:{client_id} !!! unknown data request")
except websockets.exceptions.ConnectionClosedError as e:
logger.error(f"Connection closed with error - {e}")
except Exception as e:
Expand All @@ -161,8 +177,8 @@ def split_message(message):
try:
await data_task
except asyncio.CancelledError:
logger.info(f"{client_ip}_{client_port} !!! tasks cancelled")
logger.info(f"{client_ip}_{client_port} !!! end")
logger.info(f"{client_ip}:{client_id} !!! tasks cancelled")
logger.info(f"{client_ip}:{client_id} !!! end")
case _:
return

Expand Down

0 comments on commit a0dd863

Please sign in to comment.