#!/usr/bin/env python3
"""
Created on 19 Mar 2019

@author: Bruno Beloff ([email protected])

https://www.raspberrypi.org/documentation/configuration/uart.md
"""

from scs_host.sys.host_serial import HostSerial

# --------------------------------------------------------------------------------------------------------------------

serial = None

try:
    serial = HostSerial(0, 9600, False)
    serial.open(4, 2)
    print(serial)

    for line in serial.read_lines(timeout=10):
        print(line)

except KeyboardInterrupt:
    print()

finally:
    if serial:
        serial.close()
예제 #2
0
class SAMM8Q(object):
    """
    u-blox SAM M8Q GPS Antenna Module
    """

    SOURCE = "SAM8Q"

    START_MESSAGE_IDS = GPRMC.MESSAGE_IDS

    __BAUD_RATE = 9600

    __BOOT_DELAY = 0.500  # seconds

    __SERIAL_LOCK_TIMEOUT = 3.0
    __SERIAL_COMMS_TIMEOUT = 1.0

    # ----------------------------------------------------------------------------------------------------------------

    def __init__(self, uart):
        self.__io = IO()
        self.__serial = HostSerial(uart, self.__BAUD_RATE, False)

    # ----------------------------------------------------------------------------------------------------------------

    def power_on(self):
        self.__io.gps_power = IO.LOW
        time.sleep(self.__BOOT_DELAY)

    def power_off(self):
        self.__io.gps_power = IO.HIGH

    # ----------------------------------------------------------------------------------------------------------------

    def open(self):
        self.__serial.open(self.__SERIAL_LOCK_TIMEOUT,
                           self.__SERIAL_COMMS_TIMEOUT)

    def close(self):
        self.__serial.close()

    # ----------------------------------------------------------------------------------------------------------------

    def report(self, message_class):
        for i in range(11):
            try:
                line = self.__serial.read_line("\r\n",
                                               self.__SERIAL_COMMS_TIMEOUT)
                r = NMEAReport.construct(line)

                if r.str(0) in message_class.MESSAGE_IDS:
                    return message_class.construct(r)

            except (IndexError, UnicodeDecodeError, ValueError):
                continue

        return None

    # noinspection PyListCreation
    def report_all(self):
        # reports...
        reports = []
        for i in range(20):
            try:
                r = NMEAReport.construct(
                    self.__serial.read_line("\r\n",
                                            self.__SERIAL_COMMS_TIMEOUT))
                reports.append(r)

            except (UnicodeDecodeError, ValueError):
                continue

        # start...
        start = None
        for start in range(len(reports)):
            if reports[start].str(0) in SAMM8Q.START_MESSAGE_IDS:
                break

        if start is None:
            return []

        # sentences...
        sentences = []

        # GPRMC...
        sentences.append(GPRMC.construct(reports[start]))

        # GPVTG...
        sentences.append(GPVTG.construct(reports[start + 1]))

        # GPGGA...
        sentences.append(GPGGA.construct(reports[start + 2]))

        # GPGSA...
        sentences.append(GPGSA.construct(reports[start + 3]))

        report = None  # prevents post-loop warning

        # GPGSVs...
        for report in reports[start + 4:]:
            if report.str(0) in GPGSV.MESSAGE_IDS:
                break

        sentences.append(GPGSV.construct(report))

        # GPGLL...
        for report in reports[start + 5:]:
            if report.str(0) in GPGLL.MESSAGE_IDS:
                break

        sentences.append(GPGLL.construct(report))

        return sentences

    def line(self):
        return self.__serial.read_line("\r\n", self.__SERIAL_COMMS_TIMEOUT)

    # ----------------------------------------------------------------------------------------------------------------

    def __str__(self, *args, **kwargs):
        return "SAMM8Q:{io:%s, serial:%s}" % (self.__io, self.__serial)
예제 #3
0
 def __init__(self, uart):
     self.__io = IO()
     self.__serial = HostSerial(uart, self.__BAUD_RATE, False)
예제 #4
0
 def setup_serial(self):
     self.__serial = HostSerial(GE910.__UART, GE910.__BAUD_RATE, True)
예제 #5
0
#!/usr/bin/env python3
"""
Created on 26 Dec 2016

@author: Bruno Beloff ([email protected])
"""

from scs_host.sys.host_serial import HostSerial

# --------------------------------------------------------------------------------------------------------------------

serial = HostSerial(4, 115200, True)
print(serial)

try:
    serial.open(1.0, 1.0)
    print(serial)

    serial.write_line("hello world!")
    serial.write_line("goodbye world!")

finally:
    serial.close()
    print(serial)
예제 #6
0
 def __init__(self, uart):
     """
     Constructor
     """
     self._serial = HostSerial(uart, self.__BAUD_RATE, False)
예제 #7
0
class GE910(object):
    """
    Telit GE910 GSM modem
    """

    __LOCK_TX = "TX"
    __LOCK_TIMEOUT = 60.0

    __UART = 4
    __BAUD_RATE = 115200

    __SERIAL_TIMEOUT = 60.0

    # ----------------------------------------------------------------------------------------------------------------

    @classmethod
    def __lock_name(cls, func):
        return cls.__name__ + "-" + func

    # ----------------------------------------------------------------------------------------------------------------

    def __init__(self):
        self.__serial = None

    # ----------------------------------------------------------------------------------------------------------------

    def setup_serial(self):
        self.__serial = HostSerial(GE910.__UART, GE910.__BAUD_RATE, True)

    # ----------------------------------------------------------------------------------------------------------------

    def start_tx(self):
        Lock.acquire(self.__lock_name(GE910.__LOCK_TX), GE910.__LOCK_TIMEOUT)

    def end_tx(self):
        Lock.release(self.__lock_name(GE910.__LOCK_TX))

    # ----------------------------------------------------------------------------------------------------------------

    def execute(self, command):
        # print("executing: %s" % command)

        try:
            self.__serial.open(GE910.__SERIAL_TIMEOUT, GE910.__SERIAL_TIMEOUT)

            response = None
            time.sleep(0.3)

            for i in range(command.attempts):
                if i > 0:
                    time.sleep(command.timeout)

                if command.cmd.startswith("UR"):
                    terminators = [command.cmd[2:]]
                else:
                    terminators = ATResponse.RESULT_CODES
                    self.__serial.write_line(command.cmd)
                    time.sleep(0.1)

                lines = self.__read_text(terminators, command.timeout)
                print("lines:%s" % lines)

                response = ATResponse.construct(lines)

                if len(terminators) == 1 or response.code == "OK":
                    break

            return response

        finally:
            self.__serial.close()

    # ----------------------------------------------------------------------------------------------------------------

    def __read_text(self, terminators, timeout):
        end_time = time.time() + timeout

        text = []
        while True:
            if time.time() > end_time:
                break

            line = self.__serial.read_line(HostSerial.EOL, timeout)

            if len(line) == 0:
                continue

            text.append(line)

            for terminator in terminators:
                if line == terminator or (terminator.startswith("#")
                                          and line.startswith(terminator)):
                    return text

        return text

    # ----------------------------------------------------------------------------------------------------------------

    def __str__(self, *args, **kwargs):
        return "GE910:{serial:%s}" % self.__serial
예제 #8
0
class PSU(object):
    """
    South Coast Science PSU via UART
    """

    __BAUD_RATE =               1200

    __EOL =                     "\n"

    __SERIAL_LOCK_TIMEOUT =     6.0         # seconds
    __SERIAL_COMMS_TIMEOUT =    4.0         # seconds


    # ----------------------------------------------------------------------------------------------------------------

    def __init__(self, uart):
        """
        Constructor
        """
        self._serial = HostSerial(uart, self.__BAUD_RATE, False)


    # ----------------------------------------------------------------------------------------------------------------

    @abstractmethod
    def status(self):
        pass


    # ----------------------------------------------------------------------------------------------------------------

    def version(self):
        response = self.communicate("version")

        try:
            jdict = json.loads(response, object_pairs_hook=OrderedDict)
            return PSUVersion.construct_from_jdict(jdict)

        except ValueError:
            return None


    def uptime(self):
        response = self.communicate("uptime")

        try:
            jdict = json.loads(response, object_pairs_hook=OrderedDict)
            return PSUUptime.construct_from_jdict(jdict)

        except ValueError:
            return None


    def watchdog_start(self, interval):
        response = self.communicate("w-start % d" % interval)

        return response


    def watchdog_stop(self):
        response = self.communicate("w-stop")

        return response


    def watchdog_touch(self):
        response = self.communicate("w-touch")

        return response


    def charge_pause(self, on):
        state = 1 if bool(on) else 0
        response = self.communicate("c-pause % d" % state)

        return response


    def charge_dead(self, on):
        state = 1 if bool(on) else 0
        response = self.communicate("c-dead % d" % state)

        return response


    # ----------------------------------------------------------------------------------------------------------------

    def communicate(self, command):
        print("PSU.communicate - command:%s" % command, file=sys.stderr)

        try:
            self._serial.open(self.__SERIAL_LOCK_TIMEOUT, self.__SERIAL_COMMS_TIMEOUT)

            length = self._serial.write_line(command.strip(), self.__EOL)
            response = self._serial.read_line(self.__EOL, self.__SERIAL_COMMS_TIMEOUT)

            print("PSU.communicate - sent:%d response:%s" % (length, response), file=sys.stderr)

            return response

        finally:
            self._serial.close()
예제 #9
0
#!/usr/bin/env python3
"""
Created on 26 Dec 2016

@author: Bruno Beloff ([email protected])
"""

from scs_host.sys.host_serial import HostSerial

# --------------------------------------------------------------------------------------------------------------------

serial = HostSerial(1, 9600)  # the PAM7 GPS receiver
print(serial)

try:
    serial.open(2.0, 2.0)
    print(serial)

    while True:
        text = serial.read_line(eol="\r\n", timeout=4.0)
        print("text:[%s]" % text)

except KeyboardInterrupt:
    print("host_serial_read_test: KeyboardInterrupt")

finally:
    serial.close()
    print(serial)
예제 #10
0
class PAM7Q(object):
    """
    u-blox 7 GPS Antenna Module
    """

    START_MESSAGE_ID = GPRMC.MESSAGE_ID

    __BAUD_RATE =               9600

    __SERIAL_LOCK_TIMEOUT =     3.0
    __SERIAL_COMMS_TIMEOUT =    1.0


    # ----------------------------------------------------------------------------------------------------------------

    def __init__(self, uart):
        self.__io = IO()
        self.__serial = HostSerial(uart, self.__BAUD_RATE, False)


    # ----------------------------------------------------------------------------------------------------------------

    def power_on(self):
        self.__io.gps_power = IO.LOW


    def power_off(self):
        self.__io.gps_power = IO.HIGH


    # ----------------------------------------------------------------------------------------------------------------

    def open(self):
        self.__serial.open(self.__SERIAL_LOCK_TIMEOUT, self.__SERIAL_COMMS_TIMEOUT)


    def close(self):
        self.__serial.close()


    # ----------------------------------------------------------------------------------------------------------------

    def report(self, message_class):
        for i in range(11):
            try:
                line = self.__serial.read_line("\r\n", self.__SERIAL_COMMS_TIMEOUT)
                s = NMEASentence.construct(line)

                if s.str(0) == message_class.MESSAGE_ID:
                    return message_class.construct(s)

            except (UnicodeDecodeError, ValueError):
                continue

        return None


    # noinspection PyListCreation
    def report_all(self):
        # text...
        sentences = []
        for i in range(20):
            try:
                s = NMEASentence.construct(self.__serial.read_line("\r\n", self.__SERIAL_COMMS_TIMEOUT))
                sentences.append(s)

            except (UnicodeDecodeError, ValueError):
                continue

        # start...
        start = None
        for start in range(len(sentences)):
            if sentences[start].str(0) == PAM7Q.START_MESSAGE_ID:
                break

        if start is None:
            return []

        # messages...
        messages = []

        # GPRMC...
        messages.append(GPRMC.construct(sentences[start]))

        # GPVTG...
        messages.append(GPVTG.construct(sentences[start + 1]))

        # GPGGA...
        messages.append(GPGGA.construct(sentences[start + 2]))

        # GPGSA...
        messages.append(GPGSA.construct(sentences[start + 3]))

        sentence = None         # prevents post-loop warning

        # GPGSVs...
        for sentence in sentences[start + 4:]:
            if sentence.str(0) != GPGSV.MESSAGE_ID:
                break

            messages.append(GPGSV.construct(sentence))

        # GPGLL...
        messages.append(GPGLL.construct(sentence))

        return messages


    # ----------------------------------------------------------------------------------------------------------------

    def __str__(self, *args, **kwargs):
        return "PAM7Q:{io:%s, serial:%s}" % (self.__io, self.__serial)
예제 #11
0
 def __init__(self, uart):
     """
     Constructor
     """
     self._serial = HostSerial(uart, self.baud_rate())
예제 #12
0
class SerialPSU(PSU):
    """
    South Coast Science PSU via UART
    """

    __EOL = "\n"

    __SERIAL_LOCK_TIMEOUT = 3.0  # seconds
    __SERIAL_COMMS_TIMEOUT = 2.0  # seconds

    # ----------------------------------------------------------------------------------------------------------------

    @classmethod
    def requires_interface(cls):
        return False

    @classmethod
    def uses_batt_pack(cls):
        return False

    # ----------------------------------------------------------------------------------------------------------------

    def __init__(self, uart):
        """
        Constructor
        """
        self._serial = HostSerial(uart, self.baud_rate())

    # ----------------------------------------------------------------------------------------------------------------

    @abstractmethod
    def baud_rate(self):
        pass

    # ----------------------------------------------------------------------------------------------------------------

    def open(self):
        self._serial.open(self.__SERIAL_LOCK_TIMEOUT,
                          self.__SERIAL_COMMS_TIMEOUT)

    def close(self):
        self._serial.close()

    # ----------------------------------------------------------------------------------------------------------------

    def communicate(self, command):
        try:
            self._serial.write_line(command.strip(), self.__EOL)
        except AttributeError:
            return None

        try:
            response = self._serial.read_line(self.__EOL,
                                              self.__SERIAL_COMMS_TIMEOUT)
        except TimeoutError:
            return None

        return response

    # ----------------------------------------------------------------------------------------------------------------

    def version(self):
        response = self.communicate("version")

        try:
            jdict = json.loads(response)
            return PSUVersion.construct_from_jdict(jdict)

        except (TypeError, ValueError):
            return None

    def uptime(self):
        response = self.communicate("uptime")

        try:
            jdict = json.loads(response)
            return PSUUptime.construct_from_jdict(jdict)

        except (TypeError, ValueError):
            return None

    def host_shutdown_initiated(self):
        response = self.communicate("dnr %d" % 1)

        return response

    def do_not_resuscitate(self, on):
        param = 1 if bool(on) else 0
        response = self.communicate("dnr %d" % param)

        return response

    def watchdog_start(self, interval):
        response = self.communicate("w-start % d" % interval)

        return response

    def watchdog_stop(self):
        response = self.communicate("w-stop")

        return response

    def watchdog_touch(self):
        response = self.communicate("w-touch")

        return response

    def charge_pause(self, on):
        state = 1 if bool(on) else 0
        response = self.communicate("c-pause % d" % state)

        return response

    def charge_dead(self, on):
        state = 1 if bool(on) else 0
        response = self.communicate("c-dead % d" % state)

        return response

    def power_peripherals(self, on):
        pass