Example #1
0
def get_pdm_address():
    r = RileyLink()
    try:
        verify_auth(request)
        while True:
            timeout = 30000
            if request.args.get('timeout') is not None:
                timeout = int(request.args.get('timeout')) * 1000
                if timeout > 30000:
                    raise RestApiException(
                        "Timeout cannot be more than 30 seconds")

            data = r.get_packet(timeout)
            if data is None:
                p = None
                break

            if data is not None and len(data) > 2:
                calc = crc8(data[2:-1])
                if data[-1] == calc:
                    p = Packet.from_data(data[2:-1])
                    break
        if p is None:
            respond_error("No pdm packet detected")

        return respond_ok({"address": p.address})
    except RestApiException as rae:
        return respond_error(str(rae))
    except Exception:
        logger.exception("Error while trying to read address")
        return respond_error("Other error. Please check log files.")
    finally:
        r.disconnect(ignore_errors=True)
Example #2
0
 def __init__(self, msg_sequence=0, pkt_sequence=0):
     self.stopRadioEvent = threading.Event()
     self.messageSequence = msg_sequence
     self.packetSequence = pkt_sequence
     self.lastPacketReceived = None
     self.responseTimeout = 1000
     self.rileyLink = RileyLink()
Example #3
0
 def __init__(self, msg_sequence=0, pkt_sequence=0):
     self.stopRadioEvent = threading.Event()
     self.messageSequence = msg_sequence
     self.packetSequence = pkt_sequence
     self.lastPacketReceived = None
     self.logger = getLogger()
     self.rileyLink = RileyLink()
     self.last_packet_received = None
Example #4
0
def get_rl_info():
    try:
        verify_auth(request)

        r = RileyLink()
        info = r.get_info()
        return respond_ok(info)
    except RestApiException as rae:
        return respond_error(str(rae))
    except Exception:
        logger.error("Error during get RL info")
        return respond_error("Other error. Please check log files.")
Example #5
0
from podcomm.pod import Pod
from podcomm.pdm import Pdm
from podcomm.packet import Packet
from podcomm.rileylink import RileyLink
import logging
import sys
from podcomm.crc import crc8

logging.basicConfig(level=logging.DEBUG)

pod = Pod()
pod.lot = int(sys.argv[1])
pod.tid = int(sys.argv[2])
pod.lastNonce = None

r = RileyLink("88:6b:0f:44:fc:1b")
print("connecting to RL")
r.connect()
print("initializing")
r.init_radio()
print("ready to listen for pdm")

p = None
while True:
    data = r.get_packet(30000)
    if data is not None and len(data) > 2:
        calc = crc8(data[2:-1])
        if data[-1] == calc:
            p = Packet(0, data[2:-1])
            break
Example #6
0
class Radio:
    def __init__(self, msg_sequence=0, pkt_sequence=0):
        self.stopRadioEvent = threading.Event()
        self.messageSequence = msg_sequence
        self.packetSequence = pkt_sequence
        self.lastPacketReceived = None
        self.responseTimeout = 1000
        self.rileyLink = RileyLink()

    def __logPacket(self, p):
        logging.debug("Packet received: %s" % p)

    def __logMessage(self, msg):
        logging.debug("Message received: %s" % msg)

    def start(self):
        self.lastPacketReceived = None
        self.responseTimeout = 1000
        self.rileyLink.connect()
        self.rileyLink.init_radio()
        self.rileyLink.disconnect()

    def stop(self):
        pass

    def listenForAnyPacket(self, timeout):
        pass

    def sendRequestToPod(self, message, responseHandler=None):
        try:
            self.rileyLink.connect()
            self.rileyLink.init_radio()
            while True:
                time.sleep(3)
                message.sequence = self.messageSequence
                logging.debug("SENDING MSG: %s" % message)
                packets = message.getPackets()
                received = None

                for i in range(0, len(packets)):
                    packet = packets[i]
                    if i == len(packets) - 1:
                        exp = "POD"
                    else:
                        exp = "ACK"
                    received = self.__sendPacketAndGetPacketResponse(
                        packet, exp)
                    if received is None:
                        raise CommunicationError()

                podResponse = Message.fromPacket(received)
                if podResponse is None:
                    raise ProtocolError()

                while podResponse.state == MessageState.Incomplete:
                    ackPacket = Packet.Ack(message.address, False)
                    received = self.__sendPacketAndGetPacketResponse(
                        ackPacket, "CON")
                    podResponse.addConPacket(received)

                if podResponse.state == MessageState.Invalid:
                    raise ProtocolError()

                logging.debug("RECEIVED MSG: %s" % podResponse)
                respondResult = None
                if responseHandler is not None:
                    respondResult = responseHandler(message, podResponse)

                if respondResult is None:
                    ackPacket = Packet.Ack(message.address, True)
                    self.__sendPacketUntilQuiet(ackPacket)
                    self.messageSequence = (podResponse.sequence + 1) % 16
                    return podResponse
                else:
                    message = respondResult
        finally:
            self.rileyLink.disconnect()

    def __sendPacketUntilQuiet(self, packetToSend, trackSequencing=True):
        if trackSequencing:
            packetToSend.setSequence(self.packetSequence)
        logging.debug("SENDING PACKET expecting quiet: %s" % packetToSend)
        data = packetToSend.data
        data += bytes([crc.crc8(data)])

        while True:
            self.rileyLink.send_final_packet(data, 10, 25, 42)
            timed_out = False
            try:
                received = self.rileyLink.get_packet(300)
            except RileyLinkError as rle:
                if rle.response_code != Response.RX_TIMEOUT:
                    raise rle
                else:
                    timed_out = True

            if not timed_out:
                p = self.__getPacket(received)
                if p is not None:
                    continue

            if trackSequencing:
                self.packetSequence = (self.packetSequence + 1) % 32
            return

    def __sendPacketAndGetPacketResponse(self,
                                         packetToSend,
                                         expectedType,
                                         trackSequencing=True):
        expectedAddress = packetToSend.address
        while True:
            if trackSequencing:
                packetToSend.setSequence(self.packetSequence)
            logging.debug("SENDING PACKET expecting response: %s" %
                          packetToSend)
            data = packetToSend.data
            data += bytes([crc.crc8(data)])
            received = self.rileyLink.send_and_receive_packet(
                data, 0, 0, 300, 30, 127)
            p = self.__getPacket(received)
            if p is not None and p.address == expectedAddress:
                logging.debug("RECEIVED PACKET: %s" % p)
                packet_accepted = False
                if expectedType is None:
                    if self.lastPacketReceived is None:
                        packet_accepted = True
                    else:
                        if self.lastPacketReceived.data != p.data:
                            packet_accepted = True
                else:
                    if p.type == expectedType:
                        packet_accepted = True

                if packet_accepted:
                    logging.debug("received packet accepted. %s" % p)
                    if trackSequencing:
                        self.packetSequence = (p.sequence + 1) % 32
                    self.lastPacketReceived = p
                    return p
                else:
                    logging.debug(
                        "received packet does not match expected criteria. %s"
                        % p)
                    if trackSequencing:
                        self.packetSequence = (p.sequence + 1) % 32

    def __getPacket(self, data):
        if data is not None and len(data) > 2:
            calc = crc.crc8(data[2:-1])
            if data[-1] == calc:
                return Packet(0, data[2:-1])
        return None
Example #7
0
#!/usr/bin/python3
from podcomm.rileylink import RileyLink
from podcomm.definitions import *
import logging
import os

logging.basicConfig(level=logging.WARNING)

if os.path.exists(RILEYLINK_MAC_FILE):
    os.remove(RILEYLINK_MAC_FILE)

print("connecting to RL..")
r = RileyLink()
r.connect()
print("Connected. Verifying radio settings..")
r.init_radio(force_init=True)
info = r.get_info()
print(info)
print("All looks good.")
Example #8
0
class Radio:
    def __init__(self, msg_sequence=0, pkt_sequence=0):
        self.stopRadioEvent = threading.Event()
        self.messageSequence = msg_sequence
        self.packetSequence = pkt_sequence
        self.lastPacketReceived = None
        self.logger = getLogger()
        self.rileyLink = RileyLink()
        self.last_packet_received = None

    def send_request_get_response(self, message, stay_connected=True):
        try:
            return self._send_request_get_response(message, stay_connected)
        except TransmissionOutOfSyncError:
            raise
        except Exception:
            self.rileyLink.disconnect(ignore_errors=True)
            raise

    def disconnect(self):
        try:
            self.rileyLink.disconnect(ignore_errors=True)
        except Exception as e:
            self.logger.warning("Error while disconnecting %s" % str(e))

    def _send_request_get_response(self, message, stay_connected=True):
        try:
            return self._send_request(message)
        except TransmissionOutOfSyncError:
            self.logger.warning("Transmission out of sync, radio needs resyncing")
            raise
        finally:
            if not stay_connected:
                self.rileyLink.disconnect()

    def _send_request(self, message):
        message.setSequence(self.messageSequence)
        self.logger.debug("SENDING MSG: %s" % message)
        packets = message.getPackets()
        received = None
        packet_index = 1
        packet_count = len(packets)
        for packet in packets:
            if packet_index == packet_count:
                expected_type = "POD"
            else:
                expected_type = "ACK"
            received = self._exchange_packets(packet, expected_type)
            if received is None:
                raise ProtocolError("Timeout reached waiting for a response.")

            if received.type != expected_type:
                raise ProtocolError("Invalid response received. Expected type %s, received %s"
                                    % (expected_type, received.type))
            packet_index += 1

        pod_response = Message.fromPacket(received)

        while pod_response.state == MessageState.Incomplete:
            ack_packet = Packet.Ack(message.address, False)
            received = self._exchange_packets(ack_packet, "CON")
            if received is None:
                raise ProtocolError("Timeout reached waiting for a response.")
            if received.type != "CON":
                raise ProtocolError("Invalid response received. Expected type CON, received %s" % received.type)
            pod_response.addConPacket(received)

        if pod_response.state == MessageState.Invalid:
            raise ProtocolError("Received message is not valid")

        self.logger.debug("RECEIVED MSG: %s" % pod_response)

        self.logger.debug("Sending end of conversation")
        ack_packet = Packet.Ack(message.address, True)
        self._send_packet(ack_packet)
        self.logger.debug("Conversation ended")

        self.messageSequence = (pod_response.sequence + 1) % 16
        return pod_response

    def _exchange_packets(self, packet_to_send, expected_type):
        packet_to_send.setSequence(self.packetSequence)
        expected_sequence = (self.packetSequence + 1) % 32
        expected_address = packet_to_send.address
        send_retries = 3
        while send_retries > 0:
            try:
                self.logger.debug("SENDING PACKET EXP RESPONSE: %s" % packet_to_send)
                data = packet_to_send.data
                data += bytes([crc.crc8(data)])

                if packet_to_send.type == "PDM":
                    send_retries -= 1
                    received = self.rileyLink.send_and_receive_packet(data, 0, 300, 300, 10, 80)
                else:
                    received = self.rileyLink.send_and_receive_packet(data, 0, 20, 300, 10, 20)

                if received is None:
                    self.logger.debug("Received nothing")
                    continue
                p = self._get_packet(received)
                if p is None:
                    self.logger.debug("Received illegal packet")
                    continue
                if p.address != expected_address:
                    self.logger.debug("Received packet for a different address")
                    continue

                if p.type != expected_type or p.sequence != expected_sequence:
                    if self.last_packet_received is not None:
                        if p.type == self.last_packet_received.type and \
                                p.sequence == self.last_packet_received.sequence:
                            self.logger.debug("Received previous response")
                            continue

                    self.logger.debug("Resynchronization requested")
                    self.packetSequence = (p.sequence + 1) % 32
                    self.messageSequence = 0
                    raise TransmissionOutOfSyncError()

                self.packetSequence = (self.packetSequence + 2) % 32
                self.last_packet_received = p
                self.logger.debug("SEND AND RECEIVE complete")
                return p
            except RileyLinkError as rle:
                raise ProtocolError("Radio error during send and receive") from rle
        else:
            raise ProtocolError("Exceeded retry count while send and receive")

    def _send_packet(self, packetToSend):
        packetToSend.setSequence(self.packetSequence)
        try:
            data = packetToSend.data
            data += bytes([crc.crc8(data)])
            while True:
                self.logger.debug("SENDING FINAL PACKET: %s" % packetToSend)
                received = self.rileyLink.send_and_receive_packet(data, 0, 20, 1000, 2, 40)
                if received is None:
                    received = self.rileyLink.get_packet(2.5)
                    if received is None:
                        self.logger.debug("Silence has fallen")
                        break
                p = self._get_packet(received)
                if p is None:
                    self.logger.debug("Received illegal packet")
                    continue
                if p.address != packetToSend.address:
                    self.logger.debug("Received packet for a different address")
                    continue
                if self.last_packet_received is not None:
                    if p.type == self.last_packet_received.type and \
                            p.sequence == self.last_packet_received.sequence:
                        self.logger.debug("Received previous response")
                        continue
                self.logger.warning("Resynchronization requested")
                self.packetSequence = (self.packetSequence + 1) % 32
                self.messageSequence = 0
                raise TransmissionOutOfSyncError()

            self.packetSequence = (self.packetSequence + 1) % 32
            self.logger.debug("SEND FINAL complete")
        except RileyLinkError as rle:
            raise ProtocolError("Radio error during sending") from rle

    @staticmethod
    def _get_packet(data):
        p = None
        if data is not None and len(data) > 2:
            calc = crc.crc8(data[2:-1])
            if data[-1] == calc:
                try:
                    p = Packet.from_data(data[2:-1])
                    getLogger().debug("RECEIVED PACKET: %s" % p)
                except ProtocolError as pe:
                    getLogger().warning("Crc match on an invalid packet, error: %s" % pe)
        return p