Exemple #1
0
def main():
    global args

    pilight_client = None

    try:
        parser = argparse.ArgumentParser(description='Test for 433Mhz sensors')
        parser.add_argument('--raw',
                            help='show raw sensor readings',
                            action="store_true")
        parser.add_argument('-S',
                            '--server',
                            help='Server to connect with pilight daemon',
                            default='127.0.0.1')
        parser.add_argument('-P',
                            '--port',
                            help='Port to connect with pilight daemon',
                            default=5000)
        parser.add_argument(
            '-p',
            '--protocol',
            help='show only sensor readings with this protocol')
        parser.add_argument(
            '-m',
            '--message-key',
            help='show only sensor readings containing this key in the message'
        )
        parser.add_argument('-v',
                            '--verbose',
                            help='show verbose output',
                            action="store_true")
        parser.add_argument('--blink',
                            help='say anything on receiving',
                            action="store_true")

        args = parser.parse_args()

        server433 = args.server
        port433 = args.port

        print "\n*** gw 433Mhz Testprogramm zum Sensorempfang ***"
        print "Verbinde zu pilight-daemon an {0} über Port {1}\n".format(
            server433, port433)
        # Create new pilight connection
        pilight_client = pilight.Client(host=server433, port=port433)

        # Set a data handle that is called on received data
        pilight_client.set_callback(handle_code)
        pilight_client.start()  # Start the receiver
        print "Beginne Überwachung..\n"
        if args.raw:
            print "Zeige Rohdaten..\n"

        while True:
            time.sleep(5)

    except KeyboardInterrupt:
        print "\nAbbruch durch Benutzer Ctrl+C\n"
    except RuntimeError, e:
        print "RuntimeError {0}".format(e)
Exemple #2
0
    def test_invalid_identification(self):
        """Send an invalid identification and check for connection failure."""
        recv_ident = {"action": "invalid"}

        with self.assertRaises(IOError):
            with pilight_daemon.PilightDaemon(send_codes=True):
                pilight.Client(host=pilight_daemon.HOST,
                               port=pilight_daemon.PORT,
                               recv_ident=recv_ident)
Exemple #3
0
    def test_send_code(self):
        """Test for successfull code send."""
        with pilight_daemon.PilightDaemon() as my_daemon:
            pilight_client = pilight.Client(host=pilight_daemon.HOST,
                                            port=pilight_daemon.PORT)
            pilight_client.send_code(data={'protocol': 'daycom'})
            time.sleep(1)

        self.assertEqual(my_daemon.get_data()['code'], {'protocol': 'daycom'})
Exemple #4
0
    def test_no_callback(self):
        """Test for no callback defined."""
        with pilight_daemon.PilightDaemon(send_codes=True):
            pilight_client = pilight.Client(host=pilight_daemon.HOST,
                                            port=pilight_daemon.PORT)
            pilight_client.start()
            time.sleep(1)  # Give time to set thread status

        self.assertFalse(pilight_client.isAlive())
        pilight_client.stop()
Exemple #5
0
    def __init__(self):
        super(PilightCKSkill, self).__init__(name="PilightCKSkill")

        # Initialize working variables used within the skill.
        self.data = {
            "protocol": ["intertechno_old"],
            "id": 1,
            "unit": 0,
            "off": 1
        }
        pilight_client = pilight.Client(host='pick', port=5000)
Exemple #6
0
    def test_receive_code(self, mock):
        """Test for successfull code received."""

        with pilight_daemon.PilightDaemon(send_codes=True):
            pilight_client = pilight.Client(host=pilight_daemon.HOST,
                                            port=pilight_daemon.PORT)
            pilight_client.set_callback(_callback)
            pilight_client.start()
            time.sleep(2)
        pilight_client.stop()

        # Check if callback was called several times with expected data
        mock.assert_has_calls([call(pilight_daemon.FAKE_DATA)] * 10)
Exemple #7
0
    def test_send_code_fail(self):
        """Tests for failed code send."""
        with pilight_daemon.PilightDaemon():
            pilight_client = pilight.Client(host=pilight_daemon.HOST,
                                            port=pilight_daemon.PORT)

            # Test 1: Use unknows protocol
            with self.assertRaises(IOError):
                pilight_client.send_code(data={'protocol': 'unknown'})

            # Test 2: Do not send protocoll info, thus Value Error expected
            with self.assertRaises(ValueError):
                pilight_client.send_code(data={'no_protocol': 'test'})
Exemple #8
0
 def test_api(self):
     """Tests connection with different receiver filter and identification."""
     recv_ident = {
         "action": "identify",
         "options": {
             "core": 1,  # To get CPU load and RAM of pilight daemon
             "receiver": 1  # To receive the RF data received by pilight
         }
     }
     with pilight_daemon.PilightDaemon(send_codes=True):
         pilight_client = pilight.Client(host=pilight_daemon.HOST,
                                         port=pilight_daemon.PORT,
                                         recv_ident=recv_ident,
                                         recv_codes_only=False)
         pilight_client.set_callback(_callback)
         pilight_client.start()
         time.sleep(1)
     pilight_client.stop()
Exemple #9
0
    def test_no_receive_filter(self, mock):
        """Test for successfull code received."""
        with pilight_daemon.PilightDaemon(send_codes=True):
            pilight_client = pilight.Client(host=pilight_daemon.HOST,
                                            port=pilight_daemon.PORT,
                                            veto_repeats=False)
            pilight_client.set_callback(_callback)
            pilight_client.start()
            time.sleep(2)
        pilight_client.stop()

        # Check if calls with repeats != 1 have been made
        calls = []
        for i in range(10):
            fake_data = pilight_daemon.FAKE_DATA.copy()
            fake_data['repeats'] = i + 1
            calls.append(call(fake_data))

        mock.assert_has_calls(calls)
Exemple #10
0
        # Post data to REST API
        post_temperature_data({
            'sensor_id': sensor_id,
            'binary_state': binary_state,
            'source': 'raspberry'
        })

        last_binary_sensor_message = code['message']
    elif 'arctech' in code['protocol']:
        # ignore all other arctech entries (they are the same as artec_contact)
        pass
    else:
        print("--- !!!! Unknown protocl --- ")
        print(datetime.now(), code['protocol'], code)


# pylint: disable=C0103
if __name__ == '__main__':
    # Create new pilight connection that runs on localhost with port 5000
    pilight_client = pilight.Client(host='127.0.0.1',
                                    port=5000,
                                    veto_repeats=False)

    # Set a data handle that is called on received data
    pilight_client.set_callback(handle_code)
    pilight_client.start()  # Start the receiver

    # You have 10 seconds to print all the data the pilight-daemon receives
    time.sleep(100000000)
    pilight_client.stop()  # Stop the receiver
Exemple #11
0
def setup(hass, config):
    """Setup the pilight component."""
    from pilight import pilight

    try:
        pilight_client = pilight.Client(host=config[DOMAIN][CONF_HOST],
                                        port=config[DOMAIN][CONF_PORT])
    except (socket.error, socket.timeout) as err:
        _LOGGER.error("Unable to connect to %s on port %s: %s",
                      config[CONF_HOST], config[CONF_PORT], err)
        return False

    # Start / stop pilight-daemon connection with HA start/stop
    def start_pilight_client(_):
        """Called once when home assistant starts."""
        pilight_client.start()

    hass.bus.listen_once(EVENT_HOMEASSISTANT_START, start_pilight_client)

    def stop_pilight_client(_):
        """Called once when home assistant stops."""
        pilight_client.stop()

    hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_pilight_client)

    def send_code(call):
        """Send RF code to the pilight-daemon."""
        message_data = call.data

        # Patch data because of bug:
        # https://github.com/pilight/pilight/issues/296
        # Protocol has to be in a list otherwise segfault in pilight-daemon
        message_data["protocol"] = ensure_list(message_data["protocol"])

        try:
            pilight_client.send_code(message_data)
        except IOError:
            _LOGGER.error('Pilight send failed for %s', str(message_data))

    hass.services.register(DOMAIN,
                           SERVICE_NAME,
                           send_code,
                           schema=RF_CODE_SCHEMA)

    # Publish received codes on the HA event bus
    # A whitelist of codes to be published in the event bus
    whitelist = config[DOMAIN].get('whitelist', False)

    def handle_received_code(data):
        """Called when RF codes are received."""
        # Unravel dict of dicts to make event_data cut in automation rule
        # possible
        data = dict({
            'protocol': data['protocol'],
            'uuid': data['uuid']
        }, **data['message'])

        # No whitelist defined, put data on event bus
        if not whitelist:
            hass.bus.fire(EVENT, data)
        # Check if data matches the defined whitelist
        elif all(data[key] in whitelist[key] for key in whitelist):
            hass.bus.fire(EVENT, data)

    pilight_client.set_callback(handle_received_code)

    return True
Exemple #12
0
"""Example how to to simply send RF commands.

A running pilight-daemon is needed.
"""

from pilight import pilight

# pylint: disable=C0103
if __name__ == '__main__':
    # Create new pilight connection that runs on localhost with port 5000
    pilight_client = pilight.Client(host='127.0.0.1', port=5000)

    # Send a good code. It is checked to be acknoledged by the piligt-daemon.
    # Data from https://manual.pilight.org/en/api
    pilight_client.send_code(data={
        "protocol": ["kaku_switch"],
        "id": 1,
        "unit": 0,
        "off": 1
    })

    # Send a wrong code that lead to an IO error since the pilight-daemon
    # rejects it. Data from https://manual.pilight.org/en/api
    pilight_client.send_code(
        data={
            "protocol": ["kaku_switch"],
            "id": 0,  # ID has to be > 0
            "unit": 0,
            "off": 1
        })
Exemple #13
0
 def test_client_connection_fail(self):
     """Test for failing pilight daemon connection."""
     with pilight_daemon.PilightDaemon():
         with self.assertRaises(IOError):
             pilight.Client(host='8.8.8.8', port=0)
Exemple #14
0
 def test_client_connection(self):
     """Test for successfull pilight daemon connection."""
     with pilight_daemon.PilightDaemon():
         pilight.Client(host=pilight_daemon.HOST, port=pilight_daemon.PORT)
    values = {}
    for key, value in config["devices"].items():
        if "id" in value and "id" in value["id"][0]:
            value["id"] = value["id"][0]["id"]
            if key in config["gui"]:
                name = config["gui"][key]["name"].replace(" und ", "&")
            else:
                name = key
            value["name"] = (name + 10 * " ")[:10]
            value["unit"] = "c"
            values[value["id"]] = value
    lcd_config = None
    for path in ("/etc/pilight", os.path.dirname("__file__")):
        if os.path.exists(os.path.join(path, "lcd-config.json")):
            lcd_config = os.path.join(path, "lcd-config.json")

    while True:
        connector = PilightConnector(values, lcd_config)
        print(values)

        # Create new pilight connection that runs on localhost with port 5000
        pilight_client = pilight.Client(host='127.0.0.1', port=config.get("settings", {}).get("port", 5000))

        # Set a data handle that is called on received data
        pilight_client.set_callback(connector.handle_code)
        pilight_client.start()  # Start the receiver

        # restart every hour becuase sometimes the lcd connection breaks
        time.sleep(3600)
        pilight_client.stop()  # Stop the receiver
Exemple #16
0
if __name__ == '__main__':
    # Suscribe receiver to core info to have something to receive
    # asynchrounosly. With std. settings the receiver calls the
    # data handle only on received codes!
    recv_ident = {
        "action": "identify",
        "options": {
            "core": 1,  # To get CPU load and RAM of pilight daemon
            "receiver": 1  # To receive the RF data received by pilight
        }
    }

    # Create new pilight connection that runs on localhost with port 5000
    # Turn off to print core info and send info of the pilight-daemon
    pilight_client = pilight.Client(host='127.0.0.1',
                                    port=5000,
                                    recv_ident=recv_ident,
                                    recv_codes_only=False)

    # Set a data handle that is called on received data
    pilight_client.set_callback(handle_code)
    pilight_client.start()  # Start the receiver

    # While the received data is handled you can also send commands
    # Data from https://manual.pilight.org/en/api
    data = {"protocol": ["kaku_switch"],
            "id": 1,
            "unit": 0,
            "off": 1}

    for i in range(5):
        data['id'] = i + 1  # ID > 0 for the kaku_switch protocoll
Exemple #17
0
def setup(hass, config):
    """Set up the Pilight component."""
    from pilight import pilight

    host = config[DOMAIN][CONF_HOST]
    port = config[DOMAIN][CONF_PORT]
    send_throttler = CallRateDelayThrottle(hass,
                                           config[DOMAIN][CONF_SEND_DELAY])

    try:
        pilight_client = pilight.Client(host=host, port=port)
    except (socket.error, socket.timeout) as err:
        _LOGGER.error("Unable to connect to %s on port %s: %s", host, port,
                      err)
        return False

    def start_pilight_client(_):
        """Run when Home Assistant starts."""
        pilight_client.start()

    hass.bus.listen_once(EVENT_HOMEASSISTANT_START, start_pilight_client)

    def stop_pilight_client(_):
        """Run once when Home Assistant stops."""
        pilight_client.stop()

    hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_pilight_client)

    @send_throttler.limited
    def send_code(call):
        """Send RF code to the pilight-daemon."""
        # Change type to dict from mappingproxy since data has to be JSON
        # serializable
        message_data = dict(call.data)

        try:
            pilight_client.send_code(message_data)
        except OSError:
            _LOGGER.error("Pilight send failed for %s", str(message_data))

    hass.services.register(DOMAIN,
                           SERVICE_NAME,
                           send_code,
                           schema=RF_CODE_SCHEMA)

    # Publish received codes on the HA event bus
    # A whitelist of codes to be published in the event bus
    whitelist = config[DOMAIN].get(CONF_WHITELIST)

    def handle_received_code(data):
        """Run when RF codes are received."""
        # Unravel dict of dicts to make event_data cut in automation rule
        # possible
        data = dict({
            "protocol": data["protocol"],
            "uuid": data["uuid"]
        }, **data["message"])

        # No whitelist defined, put data on event bus
        if not whitelist:
            hass.bus.fire(EVENT, data)
        # Check if data matches the defined whitelist
        elif all(str(data[key]) in whitelist[key] for key in whitelist):
            hass.bus.fire(EVENT, data)

    pilight_client.set_callback(handle_received_code)

    return True
Exemple #18
0
def pilight_send(command):
    pilight_connection = pilight.Client(host=PILIGHT_HOST)
    print('Send command {}'.format(command))
    return pilight_connection.send_code(data=command)