#!/usr/bin/env python

"""
Minirobots Python Serial Monitor.

https://gitlab.com/minirobots/minirobots-python


Author: Leo Vidarte <https://minirobots.com.ar>

This is free software:
you can redistribute it and/or modify it
under the terms of the GPL version 3
as published by the Free Software Foundation.


PySerial:

 - https://pyserial.readthedocs.io/en/latest/pyserial_api.html

"""

import sys
import signal

import serial


def signal_handler(sig, frame):
    print('\nBye!')
    sys.exit(0)

def monitor(port):
    ser = serial.Serial(
        port=port,
        baudrate=115200,
        #parity=serial.PARITY_NONE,
        #stopbits=serial.STOPBITS_ONE,
        #bytesize=serial.EIGHTBITS,
        timeout=None,
    )
    print("Connected to: " + ser.portstr)
    print('Press Ctrl+C to exit')

    while True:
        cc = str(ser.readline())
        cc = cc.replace('\\r', '')
        cc = cc.replace('\\\\', '\\')
        if len(cc) < 200:
            line = cc[2:][:-3]
            print(line)

    ser.close()


if __name__ == '__main__':
    try:
        port = sys.argv[1]
    except:
        print(
           'Usage: minirobots-serial-monitor PORT',
           'Ports:',
           ' - Linux: /dev/ttyUSB0',
           ' - MacOS: /dev/cu.SLAB_USBtoUART',
           ' - Windows: COM3',
           sep='\n',
        )
    else:
        signal.signal(signal.SIGINT, signal_handler)
        monitor(port)
        signal.pause()

