'''
Script to get NPM firmware version
need parameter: port
/usr/bin/python3 /var/www/moduleair_pro_4g/NPM/firmware_version.py ttyAMA5
'''

import serial
import requests
import json
import sys

parameter = sys.argv[1:]  # Exclude the script name
#print("Parameters received:")
port='/dev/'+parameter[0]

ser = serial.Serial(
    port=port,
    baudrate=115200,
    parity=serial.PARITY_EVEN,
    stopbits=serial.STOPBITS_ONE,
    bytesize=serial.EIGHTBITS,
    timeout = 1
)

ser.write(b'\x81\x17\x68')      #firmware version

while True:
    try:
        byte_data = ser.readline()
        formatted = ''.join(f'\\x{byte:02x}' for byte in byte_data)
        #print(formatted)
        
        '''
        la réponse est de type
        \x81\x17\x00\x10\x46\x12
        avec
        \x81        address
        \x17        command code
        \x00        state
        \x10\x46    firmware version
        \x12        checksum
        '''
        # Extract byte 4 and byte 5
        byte4 = byte_data[3]  # 4th byte (index 3)
        byte5 = byte_data[4]  # 5th byte (index 4)
        firmware_version = int(f"{byte4:02x}{byte5:02x}")


        data = {
            'firmware_version': firmware_version,
        }
        json_data = json.dumps(data)
        print(json_data)
        break
    except KeyboardInterrupt:
        print("User interrupt encountered. Exiting...")
        time.sleep(3)
        exit()
    except:
        # for all other kinds of error, but not specifying which one
        print("Unknown error...")
        time.sleep(3)
        exit()

