init_serial.py 2.63 KB
Newer Older
1
import serial
2
import sys
3
import time
4
from datetime import datetime
5

6
def get_serial(baudrate=9600, read_timeout=1.5, board_reset_timeout=2,
Nelso Jost's avatar
Nelso Jost committed
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
               find_port_timeout=0.5):
    ports = []
    for i in range(5):
        ports.append('/dev/ttyACM{}'.format(i))
        ports.append('/dev/ttyUSB{}'.format(i))
    i = 0
    while True:
        serial_port = ports[i]
        try:
            ser = serial.Serial(port=serial_port,
                                baudrate=baudrate,
                                timeout=read_timeout,
                                xonxoff=True)
            time.sleep(board_reset_timeout)
            return ser
        except Exception as e:
            print("Exception: {}".format(e))

            if i < len(ports) - 1:
                i += 1
            else:
                i = 0
            time.sleep(find_port_timeout)
30

31
def send(command_str, response_wait=0):
32
33
34
    '''
    Send the string 'command_str' to the serial port and return the response.
    '''
35
    ser.write(bytes(command_str, encoding='utf-8'))
36
    # time.sleep(response_wait)
37
    try:
38
        raw = ser.readall()
39
40
        return raw.decode('ascii').strip()
    except:
41
        print("Unable to decode raw response to ASCII:\n{}".format(raw))
42

43

44
45
46
47
48
def sync_rtc():
    '''
    Synchronizes the board clock with the system's.
    '''
    dt = datetime.now()
49
50
51
52
53
54
55
56
57
58
59
60
61
    print('\nCurrent system time:', dt.isoformat().replace('T', ' '))
    print("\nAttempting serial connection ...", end='')
    ser = get_serial()
    print('got it!')
    print(ser)
    ser.flush()

    command = 'setrtc,{Y},{m},{d},{H},{M},{S}'.format(
        Y=dt.year, m=dt.month, d=dt.day, H=dt.hour, M=dt.minute, S=dt.second)

    print('\nSending serial command:\n    "{}"\n'.format(command))

    ser.write(bytes(command, encoding='utf-8'))
62
63
64
65
66
67
    try:
        raw = ser.readall()
        return raw.decode('ascii').strip()
    except:
        print("Unable to decode raw response to ASCII:\n{}".format(raw))

Nelso Jost's avatar
Nelso Jost committed
68

69
70
71
72
73
74
75
76
77
if '-c' in sys.argv and len(sys.argv) == 3:
    print(send(input('> ')))
elif '--syncrtc' in sys.argv:
    print(sync_rtc())
else:
    print("\nAttempting serial connection ...\n")
    ser = get_serial()
    print(ser)
    ser.flush()
78

79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
    print("\nSent 'help'... waiting for board response ...")
    response = send('help')
    print("\nBoard commands:\n" + '-'*40 + '\n' + response + '\n' + '-'*40)
    print(
    """\
    Examples:

        > read,t,l                      # for reading temp. and lum.
        > setrtc,2015,7,15,17,45,0      # for setting RTC datetime

    Hit Ctrl+C to exit!""")
    print('-'*40 + '\n')
    try:
        while True:
            print(send(input('> ')))
    except:
        pass
Nelso Jost's avatar
Nelso Jost committed
96