Esempio n. 1
0
class TelldusCore(object):
    """The main class for tellcore-py.

    Has methods for adding devices and for enumerating controllers, devices and
    sensors. Also handles callbacks; both registration and making sure the
    callbacks are processed in the main thread instead of the callback thread.
    """

    def __init__(self, library_path=None, callback_dispatcher=None):
        """Create a new TelldusCore instance.

        Only one instance should be used per program.

        :param str library_path: Passed to the :class:`.library.Library`
            constructor.

        :param str callback_dispatcher: An instance implementing the
            :class:`.library.BaseCallbackDispatcher` interface (
            e.g. :class:`QueuedCallbackDispatcher` or
            :class:`AsyncioCallbackDispatcher`) A callback dispatcher must be
            provided if callbacks are to be used.

        """
        super(TelldusCore, self).__init__()
        self.lib = Library(library_path, callback_dispatcher)

    def __getattr__(self, name):
        if name == 'callback_dispatcher':
            return self.lib.callback_dispatcher
        raise AttributeError(name)

    def register_device_event(self, callback):
        """Register a new device event callback handler.

        See :ref:`event-example` for more information.

        :return: the callback id
        """
        return self.lib.tdRegisterDeviceEvent(callback)

    def register_device_change_event(self, callback):
        """Register a new device change event callback handler.

        See :ref:`event-example` for more information.

        :return: the callback id
        """
        return self.lib.tdRegisterDeviceChangeEvent(callback)

    def register_raw_device_event(self, callback):
        """Register a new raw device event callback handler.

        See :ref:`event-example` for more information.

        :return: the callback id
        """
        return self.lib.tdRegisterRawDeviceEvent(callback)

    def register_sensor_event(self, callback):
        """Register a new sensor event callback handler.

        See :ref:`event-example` for more information.

        :return: the callback id
        """
        return self.lib.tdRegisterSensorEvent(callback)

    def register_controller_event(self, callback):
        """Register a new controller event callback handler.

        See :ref:`event-example` for more information.

        :return: the callback id
        """
        return self.lib.tdRegisterControllerEvent(callback)

    def unregister_callback(self, cid):
        """Unregister a callback handler.

        :param int id: the callback id as returned from one of the
            register_*_event methods.
        """
        self.lib.tdUnregisterCallback(cid)

    def devices(self):
        """Return all known devices.

        :return: list of :class:`Device` or :class:`DeviceGroup` instances.
        """
        devices = []
        count = self.lib.tdGetNumberOfDevices()
        for i in range(count):
            device = DeviceFactory(self.lib.tdGetDeviceId(i), lib=self.lib)
            devices.append(device)
        return devices

    def sensors(self):
        """Return all known sensors.

        :return: list of :class:`Sensor` instances.
        """
        sensors = []
        try:
            while True:
                sensor = self.lib.tdSensor()
                sensors.append(Sensor(lib=self.lib, **sensor))
        except TelldusError as e:
            if e.error != const.TELLSTICK_ERROR_DEVICE_NOT_FOUND:
                raise
        return sensors

    def controllers(self):
        """Return all known controllers.

        Requires Telldus core library version >= 2.1.2.

        :return: list of :class:`Controller` instances.
        """
        controllers = []
        try:
            while True:
                controller = self.lib.tdController()
                del controller["name"]
                del controller["available"]
                controllers.append(Controller(lib=self.lib, **controller))
        except TelldusError as e:
            if e.error != const.TELLSTICK_ERROR_NOT_FOUND:
                raise
        return controllers

    def add_device(self, name, protocol, model=None, **parameters):
        """Add a new device.

        :return: a :class:`Device` or :class:`DeviceGroup` instance.
        """
        device = Device(self.lib.tdAddDevice(), lib=self.lib)
        try:
            device.name = name
            device.protocol = protocol
            if model:
                device.model = model
            for key, value in parameters.items():
                device.set_parameter(key, value)

            # Return correct type
            return DeviceFactory(device.id, lib=self.lib)
        except Exception:
            import sys
            exc_info = sys.exc_info()
            try:
                device.remove()
            except:
                pass

            if "with_traceback" in dir(Exception):
                raise exc_info[0].with_traceback(exc_info[1], exc_info[2])
            else:
                exec("raise exc_info[0], exc_info[1], exc_info[2]")

    def add_group(self, name, devices):
        """Add a new device group.

        :return: a :class:`DeviceGroup` instance.
        """
        device = self.add_device(name, "group")
        device.add_to_group(devices)
        return device

    def send_raw_command(self, command, reserved=0):
        """Send a raw command."""
        return self.lib.tdSendRawCommand(command, reserved)

    def connect_controller(self, vid, pid, serial):
        """Connect a controller."""
        self.lib.tdConnectTellStickController(vid, pid, serial)

    def disconnect_controller(self, vid, pid, serial):
        """Disconnect a controller."""
        self.lib.tdDisconnectTellStickController(vid, pid, serial)