summaryrefslogtreecommitdiff
path: root/trunk/users/metalab/python/metahost/SerialFactory.py
blob: 55273229b244166441576d9deb0ae868d2c1b860 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#!/usr/bin/env python

import sys
import os
import serial
import time
import glob

# Creates a pyserial Serial instance
def createSerialPort(port=None, baudrate=115200, verbose=False):
    if port == None:
        ports = scan()
        if verbose:
            print(ports)
        if len(ports) > 0: port = ports[0]

    if port == None:
        if verbose:
            print("No serial ports found")
        return None

    if verbose:
        print("Opening serial port: " + port)

    #Timeout value 10" max travel, 1RPM, 20 threads/in = 200 seconds
    serialport = serial.Serial(port, baudrate, timeout=200)
                
    if verbose:
        print("Serial Open?: " + str(serialport.isOpen()))
        print("Baud Rate: " + str(serialport.baudrate))

    return serialport

def scan():
    """scans for available ports. returns a list filenames"""
    available = []
    for i in range(256):
        try:
            s = serial.Serial(i)
            available.append(s.portstr)
            s.close()
        except serial.SerialException, err:
            pass
    if sys.platform.lower() == 'darwin':
            macports = glob.glob("/dev/tty.usbserial-*")
            available.extend(macports);
    return available