Exemplo n.º 1
0
    def command(command, device_id):
        tlock.acquire(True)
        core = TelldusCore()
        if device_id < len(core.devices()):
            d = core.devices()[device_id]
        else:
            return "Unknow id " + str(device_id)

        if ((command == "E") or (command == "0") or (command == 0)
                or (command == "OFF") or (command == False)):
            command = False
        elif (command == "!") or (command == -1) or (command == "-1"):
            if d.last_sent_command(tellcore.constants.TELLSTICK_TURNON
                                   | tellcore.constants.TELLSTICK_TURNOFF
                                   ) == tellcore.constants.TELLSTICK_TURNON:
                command = False
            else:
                command = True
        else:
            command = True

        if (not command):
            d.turn_off()
        elif (command):
            d.turn_on()
        tlock.release()
        return d.name + " is now " + str(command)
Exemplo n.º 2
0
def setup(hass, config):
    """Setup the Tellstick component."""
    from tellcore.constants import TELLSTICK_DIM
    from tellcore.library import DirectCallbackDispatcher
    from tellcore.telldus import TelldusCore

    global TELLCORE_REGISTRY

    try:
        tellcore_lib = TelldusCore(
            callback_dispatcher=DirectCallbackDispatcher())
    except OSError:
        _LOGGER.exception('Could not initialize Tellstick')
        return False

    # Get all devices, switches and lights alike
    all_tellcore_devices = tellcore_lib.devices()

    # Register devices
    TELLCORE_REGISTRY = TellstickRegistry(hass, tellcore_lib)
    TELLCORE_REGISTRY.register_tellcore_devices(all_tellcore_devices)

    # Discover the switches
    _discover(hass, config, 'switch',
              [tellcore_device.id for tellcore_device in all_tellcore_devices
               if not tellcore_device.methods(TELLSTICK_DIM)])

    # Discover the lights
    _discover(hass, config, 'light',
              [tellcore_device.id for tellcore_device in all_tellcore_devices
               if tellcore_device.methods(TELLSTICK_DIM)])

    return True
Exemplo n.º 3
0
def main():
    core = TelldusCore()
    d = core.devices()[int(sys.argv[1])]
    if d.last_sent_command(tellcore.constants.TELLSTICK_TURNON | tellcore.constants.TELLSTICK_TURNOFF)==tellcore.constants.TELLSTICK_TURNON:
        print 1
    else:
        print 0
Exemplo n.º 4
0
    def test_devices(self):
        devs = {
            0: {
                'protocol': b"proto_1",
                'model': b"model_1"
            },
            3: {
                'protocol': b"proto_2",
                'model': b"model_2"
            },
            6: {
                'protocol': b"proto_3",
                'model': b"model_3"
            }
        }

        self.mocklib.tdGetNumberOfDevices = lambda: len(devs)
        self.mocklib.tdGetDeviceId = lambda index: index * 3
        self.mocklib.tdGetDeviceType = lambda id: TELLSTICK_TYPE_DEVICE
        self.mocklib.tdGetProtocol = lambda id: \
            c_char_p(devs[id]['protocol'])
        self.mocklib.tdGetModel = lambda id: \
            c_char_p(devs[id]['model'])

        core = TelldusCore()
        devices = core.devices()

        self.assertEqual(3, len(devices))
        self.assertEqual(['proto_1', 'proto_2', 'proto_3'],
                         [d.protocol for d in devices])
        self.assertEqual(['model_1', 'model_2', 'model_3'],
                         [d.model for d in devices])
Exemplo n.º 5
0
def setup(hass, config):
    """Setup the Tellstick component."""
    from tellcore.constants import TELLSTICK_DIM
    from tellcore.telldus import AsyncioCallbackDispatcher
    from tellcore.telldus import TelldusCore

    try:
        tellcore_lib = TelldusCore(
            callback_dispatcher=AsyncioCallbackDispatcher(hass.loop))
    except OSError:
        _LOGGER.exception('Could not initialize Tellstick')
        return False

    # Get all devices, switches and lights alike
    all_tellcore_devices = tellcore_lib.devices()

    # Register devices
    tellcore_registry = TellstickRegistry(hass, tellcore_lib)
    tellcore_registry.register_tellcore_devices(all_tellcore_devices)
    hass.data['tellcore_registry'] = tellcore_registry

    # Discover the switches
    _discover(hass, config, 'switch',
              [tellcore_device.id for tellcore_device in all_tellcore_devices
               if not tellcore_device.methods(TELLSTICK_DIM)])

    # Discover the lights
    _discover(hass, config, 'light',
              [tellcore_device.id for tellcore_device in all_tellcore_devices
               if tellcore_device.methods(TELLSTICK_DIM)])

    return True
Exemplo n.º 6
0
def setup(hass, config):
    """Setup the Tellstick component."""
    from tellcore.constants import TELLSTICK_DIM
    from tellcore.telldus import AsyncioCallbackDispatcher
    from tellcore.telldus import TelldusCore

    try:
        tellcore_lib = TelldusCore(
            callback_dispatcher=AsyncioCallbackDispatcher(hass.loop))
    except OSError:
        _LOGGER.exception('Could not initialize Tellstick')
        return False

    # Get all devices, switches and lights alike
    all_tellcore_devices = tellcore_lib.devices()

    # Register devices
    tellcore_registry = TellstickRegistry(hass, tellcore_lib)
    tellcore_registry.register_tellcore_devices(all_tellcore_devices)
    hass.data['tellcore_registry'] = tellcore_registry

    # Discover the switches
    _discover(hass, config, 'switch', [
        tellcore_device.id for tellcore_device in all_tellcore_devices
        if not tellcore_device.methods(TELLSTICK_DIM)
    ])

    # Discover the lights
    _discover(hass, config, 'light', [
        tellcore_device.id for tellcore_device in all_tellcore_devices
        if tellcore_device.methods(TELLSTICK_DIM)
    ])

    return True
Exemplo n.º 7
0
def main():
    core = TelldusCore()
    d = core.devices()[int(sys.argv[1])]
    if d.last_sent_command(tellcore.constants.TELLSTICK_TURNON
                           | tellcore.constants.TELLSTICK_TURNOFF
                           ) == tellcore.constants.TELLSTICK_TURNON:
        print 1
    else:
        print 0
Exemplo n.º 8
0
    def command(command,device_id):
	tlock.acquire(True)
        core = TelldusCore()
        if device_id < len(core.devices()):
            d = core.devices()[device_id]
        else:
            return "Unknow id "+str(device_id)

        if ((command == "E") or (command == "0") or (command == 0) or (command == "OFF") or (command == False)):
            command = False
        elif (command == "!") or (command == -1) or (command == "-1"):
            if d.last_sent_command(tellcore.constants.TELLSTICK_TURNON | tellcore.constants.TELLSTICK_TURNOFF)==tellcore.constants.TELLSTICK_TURNON:
                command = False
            else:
                command = True
        else:
            command = True

        if (not command):
            d.turn_off()
        elif (command):
            d.turn_on()
	tlock.release()
        return d.name + " is now " + str(command)
Exemplo n.º 9
0
def setup(hass, config):
    """Set up the Tellstick component."""
    from tellcore.constants import TELLSTICK_DIM
    from tellcore.telldus import QueuedCallbackDispatcher
    from tellcore.telldus import TelldusCore
    from tellcorenet import TellCoreClient

    conf = config.get(DOMAIN, {})
    net_host = conf.get(CONF_HOST)
    net_port = conf.get(CONF_PORT)

    # Initialize remote tellcore client
    if net_host and net_port:
        net_client = TellCoreClient(net_host, net_port)
        net_client.start()

        def stop_tellcore_net(event):
            """Event handler to stop the client."""
            net_client.stop()

        hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_tellcore_net)

    try:
        tellcore_lib = TelldusCore(
            callback_dispatcher=QueuedCallbackDispatcher())
    except OSError:
        _LOGGER.exception("Could not initialize Tellstick")
        return False

    # Get all devices, switches and lights alike
    all_tellcore_devices = tellcore_lib.devices()

    # Register devices
    tellcore_registry = TellstickRegistry(hass, tellcore_lib)
    tellcore_registry.register_tellcore_devices(all_tellcore_devices)
    hass.data['tellcore_registry'] = tellcore_registry

    # Discover the switches
    _discover(hass, config, 'switch',
              [tellcore_device.id for tellcore_device in all_tellcore_devices
               if not tellcore_device.methods(TELLSTICK_DIM)])

    # Discover the lights
    _discover(hass, config, 'light',
              [tellcore_device.id for tellcore_device in all_tellcore_devices
               if tellcore_device.methods(TELLSTICK_DIM)])

    return True
Exemplo n.º 10
0
    def test_devices(self):
        devs = {0: {'protocol': b"proto_1", 'model': b"model_1"},
                3: {'protocol': b"proto_2", 'model': b"model_2"},
                6: {'protocol': b"proto_3", 'model': b"model_3"}}

        self.mocklib.tdGetNumberOfDevices = lambda: len(devs)
        self.mocklib.tdGetDeviceId = lambda index: index * 3
        self.mocklib.tdGetDeviceType = lambda id: TELLSTICK_TYPE_DEVICE
        self.mocklib.tdGetProtocol = lambda id: \
            c_char_p(devs[id]['protocol'])
        self.mocklib.tdGetModel = lambda id: \
            c_char_p(devs[id]['model'])

        core = TelldusCore()
        devices = core.devices()

        self.assertEqual(3, len(devices))
        self.assertEqual(['proto_1', 'proto_2', 'proto_3'],
                         [d.protocol for d in devices])
        self.assertEqual(['model_1', 'model_2', 'model_3'],
                         [d.model for d in devices])
Exemplo n.º 11
0
def setup(opp, config):
    """Set up the Tellstick component."""

    conf = config.get(DOMAIN, {})
    net_host = conf.get(CONF_HOST)
    net_ports = conf.get(CONF_PORT)

    # Initialize remote tellcore client
    if net_host:
        net_client = TellCoreClient(host=net_host,
                                    port_client=net_ports[0],
                                    port_events=net_ports[1])
        net_client.start()

        def stop_tellcore_net(event):
            """Event handler to stop the client."""
            net_client.stop()

        opp.bus.listen_once(EVENT_OPENPEERPOWER_STOP, stop_tellcore_net)

    try:
        tellcore_lib = TelldusCore(
            callback_dispatcher=AsyncioCallbackDispatcher(opp.loop))
    except OSError:
        _LOGGER.exception("Could not initialize Tellstick")
        return False

    # Get all devices, switches and lights alike
    tellcore_devices = tellcore_lib.devices()

    # Register devices
    opp.data[DATA_TELLSTICK] = {
        device.id: device
        for device in tellcore_devices
    }

    # Discover the lights
    _discover(
        opp,
        config,
        "light",
        [
            device.id
            for device in tellcore_devices if device.methods(TELLSTICK_DIM)
        ],
    )

    # Discover the cover
    _discover(
        opp,
        config,
        "cover",
        [
            device.id
            for device in tellcore_devices if device.methods(TELLSTICK_UP)
        ],
    )

    # Discover the switches
    _discover(
        opp,
        config,
        "switch",
        [
            device.id for device in tellcore_devices
            if (not device.methods(TELLSTICK_UP)
                and not device.methods(TELLSTICK_DIM))
        ],
    )

    @callback
    def async_handle_callback(tellcore_id, tellcore_command, tellcore_data,
                              cid):
        """Handle the actual callback from Tellcore."""
        opp.helpers.dispatcher.async_dispatcher_send(SIGNAL_TELLCORE_CALLBACK,
                                                     tellcore_id,
                                                     tellcore_command,
                                                     tellcore_data)

    # Register callback
    callback_id = tellcore_lib.register_device_event(async_handle_callback)

    def clean_up_callback(event):
        """Unregister the callback bindings."""
        if callback_id is not None:
            tellcore_lib.unregister_callback(callback_id)

    opp.bus.listen_once(EVENT_OPENPEERPOWER_STOP, clean_up_callback)

    return True
Exemplo n.º 12
0
def setup(hass, config):
    """Set up the Tellstick component."""
    from tellcore.constants import TELLSTICK_DIM
    from tellcore.telldus import AsyncioCallbackDispatcher
    from tellcore.telldus import TelldusCore
    from tellcorenet import TellCoreClient

    conf = config.get(DOMAIN, {})
    net_host = conf.get(CONF_HOST)
    net_port = conf.get(CONF_PORT)

    # Initialize remote tellcore client
    if net_host and net_port:
        net_client = TellCoreClient(net_host, net_port)
        net_client.start()

        def stop_tellcore_net(event):
            """Event handler to stop the client."""
            net_client.stop()

        hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_tellcore_net)

    try:
        tellcore_lib = TelldusCore(
            callback_dispatcher=AsyncioCallbackDispatcher(hass.loop))
    except OSError:
        _LOGGER.exception("Could not initialize Tellstick")
        return False

    # Get all devices, switches and lights alike
    tellcore_devices = tellcore_lib.devices()

    # Register devices
    hass.data[DATA_TELLSTICK] = {device.id: device for
                                 device in tellcore_devices}

    # Discover the switches
    _discover(hass, config, 'switch',
              [device.id for device in tellcore_devices
               if not device.methods(TELLSTICK_DIM)])

    # Discover the lights
    _discover(hass, config, 'light',
              [device.id for device in tellcore_devices
               if device.methods(TELLSTICK_DIM)])

    @callback
    def async_handle_callback(tellcore_id, tellcore_command,
                              tellcore_data, cid):
        """Handle the actual callback from Tellcore."""
        hass.helpers.dispatcher.async_dispatcher_send(
            SIGNAL_TELLCORE_CALLBACK, tellcore_id,
            tellcore_command, tellcore_data)

    # Register callback
    callback_id = tellcore_lib.register_device_event(
        async_handle_callback)

    def clean_up_callback(event):
        """Unregister the callback bindings."""
        if callback_id is not None:
            tellcore_lib.unregister_callback(callback_id)

    hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, clean_up_callback)

    return True
Exemplo n.º 13
0
    print "</script>"
    print "<body>"
    print """<button onclick="goBack()">Go Back</button>"""
    print "</body>"
    exit()  #end here if errors

device_id, power, powerOnTime = int(
    form['device'].value), form['power'].value, int(form['time'].value)

if not ('pass' in form and form['pass'].value == "p@ssw0rd"):
    print "<p class=errr> Password is incorrect."
    exit()

from tellcore.telldus import TelldusCore
core = TelldusCore()
devices = core.devices()

if not (power in ['off', 'on', 'time'] and device_id <= len(devices)):
    print "<p class=err> Incorrect values for the params have been provided."
    print "<script>"
    print "function goBack()"
    print "{"
    print "window.history.back()"
    print "}"
    print "</script>"
    print "<body>"
    print """<button onclick="goBack()">Go Back</button>"""
    print "</body>"
    exit()  #end here if errors

device = devices[device_id]
Exemplo n.º 14
0
import time
import os
import math
import webbrowser
from urllib.parse import urlparse

import pyautogui as pag
from tellcore.telldus import TelldusCore
from ctypes import cast, POINTER
from comtypes import CLSCTX_ALL
from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume

from wit_recognition import recognize_cmd

core = TelldusCore()
lights = core.devices()[1]

numbers = {
    'zero': 0,
    'one': 1,
    'two': 2,
    'three': 3,
    'four': 4,
    'five': 5,
    'six': 6,
    'seven': 7,
    'eight': 8,
    'nine': 9,
    'ten': 10,
    #    'eleven': 11,
}
Exemplo n.º 15
0
class TellstickActor(AbstractActor):
    # Setup
    def setup(self):
        # Callback dispatcher
        # --------------------
        # Dispatcher for use with the event loop available in Python 3.4+.
        # Callbacks will be dispatched on the thread running the event loop.
        # The loop argument should be a BaseEventLoop instance, e.g. the one
        # returned from asyncio.get_event_loop().
        dispatcher = AsyncioCallbackDispatcher(self.context.loop)

        # Telldus core
        # --------------------
        # 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.
        self.telldus = TelldusCore(callback_dispatcher=dispatcher)

        # Devices
        # --------------------
        # List of configured devices in /etc/tellstick.conf
        self.devices = self.get_devices()
        # self.last_seen = {}
        self.state.devices = {did: d.name for did, d in self.devices.items()}

        # Register event callback handlers
        self.telldus.register_device_event(self.callbacks.device_event)
        self.telldus.register_device_change_event(
            self.callbacks.device_change_event)
        self.telldus.register_raw_device_event(self.callbacks.raw_event)
        # self.telldus.register_sensor_event(self.sensor_event)
        # self.telldus.register_controller_event(self.controller_event)

    # Get devices
    def get_devices(self):
        ''' Return all known devices. '''

        logger.debug('Fetching list of known devices')

        devices = self.telldus.devices()

        for d in devices:
            logger.debug('> Device: {0}, {1}, {2}, {3}, {4}'.format(
                d.id, d.name, d.protocol, d.type, d.model))

        return {device.id: device for device in devices}

    # Class: Callbacks
    class Callbacks(AbstractActor.Callbacks):
        # Device event
        def device_event(self, device_id, method, data, cid):
            ''' Device event callback handler. '''

            logger.debug(
                'Device event, id={}, method={}, data={}, cid={}'.format(
                    device_id, method, data, cid))

            method_string = METHODS.get(method)

            if not method_string:
                logger.warning('Unknown method %s' % (method))
                return

            # self.actor.last_seen[device_id] = method_string
            # self.actor.state.last_seen = self.actor.last_seen

            self.actor.create_event(
                name='%s.%s' %
                (method_string, self.actor.devices[device_id].name),
                payload={
                    'method': method_string,
                    'id': device_id,
                    'name': self.actor.devices[device_id].name,
                })

        # Device change event
        def device_change_event(self, id, event, type, cid):
            ''' Device change event callback handler. '''

            event_string = EVENTS.get(event, "UNKNOWN EVENT {0}".format(event))
            string = "[DEVICE_CHANGE] {0} {1}".format(event_string, id)
            if event == const.TELLSTICK_DEVICE_CHANGED:
                type_string = CHANGES.get(type,
                                          "UNKNOWN CHANGE {0}".format(type))
                string += " [{0}]".format(type_string)
            logger.debug(string)
            print(string)

        # Raw event
        def raw_event(self, data, controller_id, cid):
            ''' Raw device event callback handler. '''

            logger.debug('Raw[%s]:%s' % (str(controller_id), data))

        '''
        def sensor_event(self, protocol, model, id_, dataType, value, timestamp, cid):
            logger.debug('Sensor event: [SENSOR] {0} [{1}/{2}] ({3}) @ {4} <- {5}'.format(
                id_, protocol, model, dataType, timestamp, value
            ))


        def controller_event(self, id_, event, type_, new_value, cid):
            event_string = EVENTS.get(event, "UNKNOWN EVENT {0}".format(event))
            string = "[CONTROLLER] {0} {1}".format(event_string, id_)
            if event == const.TELLSTICK_DEVICE_ADDED:
                type_string = TYPES.get(type_, "UNKNOWN TYPE {0}".format(type_))
                string += " {0}".format(type_string)
            elif (event == const.TELLSTICK_DEVICE_CHANGED
                  or event == const.TELLSTICK_DEVICE_STATE_CHANGED):
                type_string = CHANGES.get(type_, "UNKNOWN CHANGE {0}".format(type_))
                string += " [{0}] -> {1}".format(type_string, new_value)
            print(string)
        '''

    # Class: Actions
    class Actions(AbstractActor.Actions):
        def on(self, device_id):
            device = self.actor.devices.get(device_id)
            if not device:
                return False, 'Unknown device'
            device.turn_on()
            return True, 'Device "%s" turned on' % (device.name)

        def off(self, device_id):
            device = self.actor.devices.get(device_id)
            if not device:
                return False, 'Unknown device'
            device.turn_off()
            return True, 'Device "%s" turned off' % (device.name)

        def dim(self, device_id, level=50):
            if level < 0 or level > 255:
                return False, 'Invalid dim level (%s)' % (str(level))
            device = self.actor.devices.get(device_id)
            if not device:
                return False, 'Unknown device'
            device.dim(level)
            return True, 'Device "%s" dimmed to level %d' % (device.name,
                                                             level)

        def all_on(self, exclude=[]):
            for device in self.actor.devices.values():
                if device.id not in exclude:
                    device.turn_on()
            return True, 'All devices (%d) turned on' % (len(
                self.actor.devices))

        def all_off(self, exclude=[]):
            for device in self.actor.devices.values():
                if device.id not in exclude:
                    device.turn_on()
            return True, 'All devices (%d) turned off' % (len(
                self.actor.devices))
Exemplo n.º 16
0
    return shutdown


tk = Tk()
tell = TelldusCore()

font = Font(size=16)

root = ScrolledWindow(tk, scrollbar=Y)
root.vsb.config(width=28)

col = 0
row = 0

devices = tell.devices()
devices.sort(key=(lambda device: device.name))
for device in devices:

    container = Frame(root.window)
    label = Label(container, text=device.name, font=font)
    label.pack(side=TOP)

    buttonframe = Frame(container)

    onbutton = Button(
        buttonframe, text="ON", command=makeaction(device, "on"), font=font, activebackground="#00FF00", bg="#00AA00"
    )
    onbutton.pack(side=LEFT)

    offbutton = Button(
Exemplo n.º 17
0
def activateFan():
    core = TelldusCore()
    for device in core.devices():
        if "Fan control device" == device.name:
            device.turn_on()
Exemplo n.º 18
0
# -*- coding: utf-8 -*-
import sys, os, signal, datetime, threading, logging, time, uuid
from flask import Flask, render_template, jsonify, request, url_for
from tellcore.telldus import TelldusCore
from wit import Wit
from os import system
sys.path.insert(0, "./modules/")
from get_data import RemoteData
from audio_handler import AudioHandler
from nlg import NLG
from cal import Calendar

core = TelldusCore()

devices = {}
for device in core.devices():
    devices[device.name] = device

devices_in_room = {
    "bedroom": ["sovrum"],
    "living room": ["skrivbord"],
    "office": ["skrivbord"],
}

device_translation = {"desk lamp": "skrivbord", "bed lamp": "sovrum"}

app = Flask(__name__)

log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)