# -*- coding: utf-8 -*- # Receiving APNEA CHECK data from the USB Serial com port # by ik-gadgets import sys import re import os import serial import serial.tools.list_ports import codecs def auto_detect_serial_port(): ports = list(serial.tools.list_ports.comports()) print("### Search results ###") for p in ports: print(" ",p) if 'USB Serial Port' in p.description: return p.device return None def Rx_byte(ser): while True: bytesWaiting = ser.inWaiting() if bytesWaiting != 0: onebyte = ser.read(1) oneint = int.from_bytes(onebyte,'big') return oneint def main(): rx_list = [] print() serial_port_name = None file_name_list = [] wfile_name = "" if len(sys.argv) >= 2: for file_name in sys.argv[1:]: if re.search(r'\.txt$',file_name): wfile_name = file_name sep = " " elif re.search(r'\.csv$',file_name): wfile_name = file_name sep = "," elif re.search(r'^(com)|(COM)[0-9]+$',file_name): serial_port_name = file_name print() if wfile_name: wfile = codecs.open(wfile_name, 'w', 'utf-8') if not serial_port_name: serial_port_name = auto_detect_serial_port() if not serial_port_name: print() print("### ERROR ### USB-Serial port not recognized") print(" Please check the connection or specify the USB-Serial port name") print(" ex. python APNEA_Rx.py com3") print() sys.exit() print() print("### Try to communicate",serial_port_name,"###") print() ser = serial.Serial(serial_port_name,9600) sec = 0 stop_cnt = 0 stop_sum = 0 stop_max = 0 sensitivity = Rx_byte(ser) while True: prev_sec = sec sec = Rx_byte(ser) * 256 sec += Rx_byte(ser) h = sec//3600 m = sec%3600 m //= 60 s = sec%60 stop_sec = Rx_byte(ser) if stop_sec == 0: print("") print("MEASURE PERIOD %d:%d:%d" % (h,m,s)) if wfile_name: wfile.write("\n") wfile.write("MEASURE PERIOD" + sep + "{0:d}:{1:d}:{2:d}\n".format(h,m,s)) if stop_cnt > 0: print("STOP COUNT ",stop_cnt) print("STOP MAX ",stop_max) print("STOP AVERAGE %.2f" % (stop_sum/stop_cnt)) print("STOP COUNT/Hour %.2f" % (stop_cnt/(sec/3600))) print("SENSITIVITY ",sensitivity) if wfile_name: wfile.write("STOP COUNT" + sep + str(stop_cnt) + "\n") wfile.write("STOP MAX" + sep + str(stop_max) + "\n") wfile.write("STOP AVERAGE" + sep +"{:.2f}\n".format(stop_sum/stop_cnt)) wfile.write("STOP COUNT/Hour" + sep + "{:.2f}\n".format(stop_cnt/(sec/3600))) wfile.write("SENSITIVITY" + sep + str(sensitivity) + "\n") else: print("STOP COUNT 0") if wfile_name: wfile.write("STOP COUNT" + sep + "0\n\n") print("") sys.exit() else: print("%d:%d:%d %d" % (h,m,s,stop_sec)) if wfile_name: wfile.write(str(h) + ":" + str(m) + ":" + str(s) + sep + str(stop_sec) + "\n") stop_cnt += 1 stop_sum += stop_sec if stop_max < stop_sec: stop_max = stop_sec if __name__ == '__main__': main()