hr50-api/hr50api.py

126 lines
3.3 KiB
Python
Raw Normal View History

2021-11-11 18:43:19 -05:00
from flask import Flask, jsonify, request
import sys
import getopt
import time
import serial
app = Flask(__name__)
serial_port = '/dev/ttyUSB0'
baud = 19200
2021-11-12 03:09:02 -05:00
'''
2021-11-11 18:43:19 -05:00
bands = {
'6': '0',
'10': '1',
'12': '2',
'15': '3',
'17': '4',
'20': '5',
'30': '6',
'40': '7',
'60': '8',
'80': '9',
'160': '10'
}
2021-11-12 03:09:02 -05:00
'''
2021-11-11 18:43:19 -05:00
vlcd = {
'STA': '-',
'PTT': '-',
'BND': '-',
'VLT': '-',
'PEP': '-',
'AVG': '-',
'SWR': '-',
'TMP': '-'
}
2021-11-12 03:09:02 -05:00
'''
2021-11-11 18:43:19 -05:00
keying_methods = {
"off" : "0",
"ptt" : "1",
"cor" : "2",
"qrp" : "3"
}
2021-11-12 03:09:02 -05:00
'''
2021-11-11 18:43:19 -05:00
def get_serial(port, baud):
try:
ser = serial.Serial(port, baud, timeout=2)
return ser
except serial.serialutil.SerialException as e:
print("The following error has occured while opening the serial connecti on to {} with {} baud:".format(port, baud))
print(e)
sys.exit(2)
2021-11-12 03:09:02 -05:00
# sends a command to the
2021-11-11 18:43:19 -05:00
# Hardrock-50 via the serial interface
2021-11-12 03:09:02 -05:00
def send_cmd_via_serial(cmd):
2021-11-11 18:43:19 -05:00
ser = get_serial(serial_port, baud)
res = None
try:
2021-11-12 03:09:02 -05:00
command = cmd + ';'
2021-11-11 18:43:19 -05:00
ser.write(str.encode(command))
res = ser.readline().decode("utf-8").rstrip()
except Exception as e:
print("The following error has occured while sending the command {} to t he HR50:".format(port, baud))
print(e)
ser.close()
return res
# Executed two commands vie the serial interface,
# parsed the result ad polulates a dict with the
# collected information
def get_info():
ser = get_serial(serial_port, baud)
try:
ser.write(b'HRRX;')
time.sleep(0.5)
res = ser.readline().decode("utf-8").rstrip().replace(';', '').split(',')
except Exception as e:
print("The following error has occured while sending the command {} to the HR50:".format(port, baud))
print(e)
ser.close()
return None
if res and len(res) > 3:
vlcd['STA'] = res[0]
vlcd['PTT'] = res[1]
vlcd['BND'] = res[2]
vlcd['TMP'] = res[3]
vlcd['VLT'] = res[4]
ser.write(b'HRMX;')
time.sleep(0.5)
res = ser.readline().decode("utf-8").rstrip().split()
ser.close()
vlcd['PEP'] = res[1][1:]
vlcd['AVG'] = res[2][1:]
if res[3][1:] != "0":
vlcd['SWR'] = res[3][1:2] + "." + res[3][2:3]
else:
vlcd['PTT'] = "ERR"
@app.route('/status')
def get_status():
get_info()
return jsonify(vlcd)
2021-11-12 03:09:02 -05:00
@app.route('/', methods=['GET'])
def send_command():
try:
cmd = request.args.get('cmd', default="", type=str)
data = send_cmd_via_serial(cmd)
return jsonify(isError= False,
message= "Success",
statusCode= 200,
data= data), 200
except Exception as e:
return jsonify(isError= True,
message= "Error",
statusCode= 200,
data= e), 200
2021-11-11 18:43:19 -05:00