Add function to report devices activity

This commit is contained in:
2024-09-30 22:11:48 +02:00
parent 5608b4e610
commit 63bdeed952
17 changed files with 266 additions and 79 deletions

View File

@ -4,6 +4,7 @@ import src.constants as constants
from cryptography.x509 import load_pem_x509_certificate
from cryptography import utils
import jwt
import json
def get_secure_origin() -> str:
@ -75,13 +76,18 @@ def device_certificate() -> str:
return res.text
def jwt_sign(data: any, dev_id: str, privkey) -> str:
"""
Generate a JWT for client request
"""
return jwt.encode(data, privkey, algorithm="RS256", headers={"kid": dev_id})
def sync_device(dev_id: str, privkey):
"""
Synchronize device with backend
"""
encoded = jwt.encode(
{"info": device_info()}, privkey, algorithm="RS256", headers={"kid": dev_id}
)
encoded = jwt_sign({"info": device_info()}, dev_id=dev_id, privkey=privkey)
res = requests.post(
f"{args.secure_origin}/devices_api/mgmt/sync",
@ -89,6 +95,19 @@ def sync_device(dev_id: str, privkey):
verify=args.root_ca_path,
)
print(encoded)
print(res)
print(res.text)
return json.loads(res.text)
def report_log(severity: str, message: str, dev_id: str, privkey):
"""
Report log message to server
"""
encoded = jwt_sign(
{"severity": severity, "message": message}, dev_id=dev_id, privkey=privkey
)
requests.post(
f"{args.secure_origin}/devices_api/logging/record",
json={"payload": encoded},
verify=args.root_ca_path,
)

View File

@ -3,6 +3,10 @@ import src.api as api
import src.pki as pki
import src.utils as utils
import os
import time
# TODO : turn off all relays
# TODO : intialize GPIO
print("Check storage")
if not os.path.isdir(args.storage):
@ -88,6 +92,13 @@ if not os.path.isfile(args.dev_crt_path):
with open(args.dev_crt_path, "w") as f:
f.write(cert)
api.report_log("Info", "Starting program main loop...", args.dev_id, args.priv_key)
print("Done. ready to operate.")
api.sync_device(args.dev_id, args.priv_key)
print("Ready to operate!.")
while True:
# TODO : implement this loop more properly
res = api.sync_device(args.dev_id, args.priv_key)
print(res)
time.sleep(5)