Beispiel #1
0
        def _utf8(data):
            if isinstance(data, bytes):
                try:
                    data = codecs_decode(data, session.protocol_flags["ENCODING"])
                except LookupError:
                    # wrong encoding set on the session. Set it to a safe one
                    session.protocol_flags["ENCODING"] = "utf-8"
                    data = codecs_decode(data, "utf-8")
                except UnicodeDecodeError:
                    # incorrect unicode sequence
                    session.sendLine(_ERR_BAD_UTF8)
                    data = ""

            return data
Beispiel #2
0
def test_message(message):
    """
    Test, filter and verify that the incoming message is valid
    Return true if valid, False if not
    """

    # Remove any whitespaces and linebreaks
    message = message.replace(' ', '')
    message = message.replace("\r", "")
    message = message.replace("\n", "")

    # Remove all invalid characters
    message = stripped(message)

    # Test the string if it is hex format
    try:
        int(message, 16)
    except Exception:
        return False

    # Check that length is even
    if len(message) % 2:
        return False

    # Check that first byte is not 00
    if ByteToHex(codecs_decode(message, "hex")[0]) == "00":
        return False

    # Length more than one byte
    if not len(codecs_decode(message, "hex")) > 1:
        return False

    # Check if string is the length that it reports to be
    cmd_len = int(ByteToHex(codecs_decode(message, "hex")[0]), 16)
    if not len(codecs_decode(message, "hex")) == (cmd_len + 1):
        return False

    return True
Beispiel #3
0
def calculate(amount, itemcode):
    # calculate chat code
    # itemcode from base64 to hex
    hex_itemcode = b64decode(itemcode).hex()
    # amount to hex
    hex_amount = '{0:02x}'.format(int(amount))
    # calculate item + amount
    hexa = hex_itemcode[:2] + hex_amount + hex_itemcode[4:]
    # encode to base64
    b64 = codecs_encode(codecs_decode(hexa, 'hex'), 'base64').decode()
    # Next 2 lines to remove \n from b64
    strb64 = str(b64)
    strb64 = strb64[:-1]
    return "[&" + strb64 + "]"
def varbytehex_recv(data: bytes, idx: int, length: int) -> str:
    return codecs_decode(data[idx:idx + length],
                         "hex_codec").decode(_client_encoding)
Beispiel #5
0
def rfx_sendmsg(message=None):

    if message is None:
        LOGGER.debug("No message was specified")
        return False

    # Check that serial module is loaded
    try:
        LOGGER.debug("Serial extension version: " + serial.VERSION)
    except:
        LOGGER.error("Error: Serial extension for Python could not be loaded")
        return False

    # Check for serial device
    if SERIAL.port:
        LOGGER.debug("Device: " + SERIAL.port)
    else:
        LOGGER.error("Device name missing")
        return False

    # Open serial port
    LOGGER.debug("Open Serialport")
    try:
        SERIAL.device = serial.Serial(SERIAL.port, SERIAL.rate, timeout=SERIAL.timeout)
    except serial.SerialException as err:
        LOGGER.error("Error: Failed to connect on device, %s" % err)
        return False

    # Flush buffer
    LOGGER.debug("Serialport flush output")
    SERIAL.device.flushOutput()
    LOGGER.debug("Serialport flush input")
    SERIAL.device.flushInput()

    # Send RESET
    LOGGER.debug("Send RFX reset")
    SERIAL.device.write(codecs_decode(RFXCMD.reset, "hex"))
    time.sleep(1)

    # Flush buffer
    LOGGER.debug("Serialport flush output")
    SERIAL.device.flushOutput()
    LOGGER.debug("Serialport flush input")
    SERIAL.device.flushInput()

    LOGGER.debug("Send message")
    SERIAL.device.write(codecs_decode(message, "hex"))
    time.sleep(1)

    # Waiting reply
    result = None
    byte = None
    LOGGER.debug("Wait for the reply")
    try:
        while 1:
            time.sleep(0.01)
            try:
                try:
                    if SERIAL.device.inWaiting() != 0:
                        timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
                        LOGGER.debug("Timestamp: %s", timestamp)
                        LOGGER.debug("SerWaiting: %d", SERIAL.device.inWaiting())
                        byte = SERIAL.device.read()
                        LOGGER.debug("Byte: %s", ByteToHex(byte))
                except IOError as err:
                    LOGGER.error("Serial read error: %s", err)
                    break

                try:
                    if byte is not None:
                        if ord(byte) == 20 or ord(byte) == 13:
                            result = byte + readbytes(ord(byte))
                            LOGGER.debug("Message: %s", ByteToHex(result))
                            break
                        else:
                            result = byte + readbytes(ord(byte))
                            LOGGER.debug("Message: %s", ByteToHex(result))
                            LOGGER.error("Wrong or no response received")
                            sys.exit(1)

                except Exception as err:
                    LOGGER.error(err)
                    sys.exit(1)

            except OSError as err:
                LOGGER.error("Error in message: %s", ByteToHex(message))
                LOGGER.error(err)
                LOGGER.error("Traceback: %s", traceback.format_exc())
                LOGGER.error("Serial error (%s) ", ByteToHex(message))
                break

    except KeyboardInterrupt:
        LOGGER.debug("Received keyboard interrupt")
        pass

    LOGGER.debug("Close serial port")
    try:
        SERIAL.device.close()
        LOGGER.debug("Serial port closed")
    except:
        LOGGER.error("Error: Failed to close the serial port (%s)" % SERIAL.port)
        return False

    return result