#!/usr/bin/env python3

import time
import websocket
import argparse
import zlib

parser = argparse.ArgumentParser(description='Update fiatlux firmware via websocket.')
parser.add_argument("binfile")

args = parser.parse_args()

with open(args.binfile, "rb") as f:
    try:
        ws = websocket.WebSocket()
        ws.connect("ws://172.16.0.1")
        i = 0
        rolling = 0
        total = 0
        while True:
            bytes = f.read(512)
            rolling = zlib.crc32(bytes, rolling)
            total += len(bytes)
            msg = b'F\x00\x00\x00'
            msg += i.to_bytes(2, 'big')
            msg += len(bytes).to_bytes(2, 'big')
            msg += (zlib.crc32(bytes) & 0xffffffff).to_bytes(4, 'big')
            msg += bytes
            ws.send(msg)
            reply = ws.recv()
            time.sleep(0.05)
            i += 1
            if len(bytes) != 512:
                break
        msg = b'C\x00\x00\x00'
        msg += total.to_bytes(4, 'big')
        msg += rolling.to_bytes(4, 'big')
        ws.send(msg)
        print(ws.recv())
        ws.close()
    except ConnectionResetError:
        pass
    except KeyboardInterrupt:
        pass
