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)
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
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
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
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
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)
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])
def test_group(self): self.mocklib.tdAddDevice = lambda: 1 self.mocklib.tdGetDeviceType = lambda id: TELLSTICK_TYPE_GROUP device = {} device['parameters'] = {} def tdSetName(id, name): device['name'] = self.decode_string(name) return id == 1 self.mocklib.tdSetName = tdSetName def tdSetProtocol(id, protocol): device['protocol'] = self.decode_string(protocol) return id == 1 self.mocklib.tdSetProtocol = tdSetProtocol def tdSetDeviceParameter(id, name, value): name = self.decode_string(name) if value: device['parameters'][name] = self.decode_string(value) elif name in device['parameters']: del device['parameters'][name] return id == 1 self.mocklib.tdSetDeviceParameter = tdSetDeviceParameter def tdGetDeviceParameter(id, name, default): name = self.decode_string(name) try: return c_char_p(self.encode_string(device['parameters'][name])) except KeyError: return c_char_p(default) self.mocklib.tdGetDeviceParameter = tdGetDeviceParameter core = TelldusCore() dev = core.add_group("test", [1, Device(2), 3, 4]) self.assertEqual("test", device['name']) self.assertEqual("group", device['protocol']) self.assertDictEqual({'devices': '1,2,3,4'}, device['parameters']) dev.add_to_group(5) self.assertDictEqual({'devices': '1,2,3,4,5'}, device['parameters']) dev.remove_from_group([3, 2, 6, Device(2), Device(1)]) self.assertDictEqual({'devices': '4,5'}, device['parameters']) self.assertListEqual([4, 5], [d.id for d in dev.devices_in_group()]) dev.remove_from_group(4) self.assertDictEqual({'devices': '5'}, device['parameters']) self.assertIsInstance(dev.devices_in_group()[0], DeviceGroup) dev.remove_from_group([5]) self.assertDictEqual({}, device['parameters'])
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
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
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])
def run(self): core = TelldusCore() sensorDb = SensorDB(database = 'ha', user = '******', password = '******') while True: listOfSensors = core.sensors() timestamp = 0 for sensor in listOfSensors: if debug: sys.stdout.write("Found sensor: " + str(sensor.id) + "\n") if sensor.has_temperature(): if debug: sys.stdout.write("... sensor supports temperature\n") sensorTemperature = sensor.temperature() timestamp = sensorTemperature.timestamp else: if debug: sys.stdout.write(".. sensor does not support temperature\n") sensorTemperature = SensorValue(const.TELLSTICK_TEMPERATURE, -100.0, 0) if sensor.has_humidity(): if debug: sys.stdout.write("... sensor supports humidity\n") sensorHumidity = sensor.humidity() timestamp = sensorHumidity.timestamp else: if debug: sys.stdout.write(".. sensor does not support humidity\n") sensorHumidity = SensorValue(const.TELLSTICK_HUMIDITY, 0, 0) if timestamp > 0: if sensor.id > 0: sensorDb.insertSensorData(sensor.id, sensorTemperature.value, sensorHumidity.value, timestamp) else: if debug: sys.stdout.write("E: sensor id is not in allowed range\n") else: if debug: sys.stdout.write("Not able to setup timestamp for sensor values\n") if debug: sys.stdout.flush() time.sleep(300)
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)
def test_device_event(self): core = TelldusCore() self.event_tester(core, core.register_device_event, self.mockdispatcher.trigger_device_event, (c_int(1), c_int(2), c_char_p(b"foo")))
# -*- 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)
def _getSensors(): tdc = TelldusCore() return tdc.sensors()
blinks = 0 blinks_total = 0 max_temp = 0 min_temp = 0 sensors = {11: Sensor("ute"), 12: Sensor("pumpe"), 21: Sensor("gang"), 22: Sensor("soverom"), 23: Sensor("stue")} app = firebase.FirebaseApplication("https://hytta.firebaseio.com/", None) GPIO.setmode(GPIO.BOARD) GPIO.setup(7, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) GPIO.add_event_detect(7, GPIO.RISING, callback=on_blink, bouncetime=500) td_core = TelldusCore() td_core.register_sensor_event(on_sensor_event) run_daily(update_energy) run_minutely(update_power) run_minutely(td_core.callback_dispatcher.process_pending_callbacks) # def switch2_changed(response): # print(response) # if response == TELLSTICK_TURNON: # camera_switch.turn_on() # print('Switch 2: On') # elif response == TELLSTICK_TURNOFF: # print('Switch 2: Off') # camera_switch.turn_off()
def test_device_change_event(self): core = TelldusCore(callback_dispatcher=QueuedCallbackDispatcher()) self.event_tester(core, core.register_device_change_event, self.mockdispatcher.trigger_device_change_event, (c_int(3), c_int(4), c_int(5)))
from tellcore.telldus import TelldusCore core = TelldusCore() lamp = core.add_device("lamp", "arctech", "selflearning-switch", house=12345, unit=1) lamp.turn_on() for device in core.devices(): device.turn_off()
def activateFan(): core = TelldusCore() for device in core.devices(): if "Fan control device" == device.name: device.turn_on()
def test_raw_device_event(self): core = TelldusCore() self.event_tester(core, core.register_raw_device_event, self.mockdispatcher.trigger_raw_device_event, (c_char_p(b"bar"), c_int(6)))
import time from tellcore.telldus import TelldusCore core = TelldusCore() #Configure reporters from Reporters import EmonCMS_Reporter, Console_Reporter reporter1 = EmonCMS_Reporter("https://emoncms.org", apikey="YOUR_API_KEY", node="MY_NODE_NAME", only_mapped=True) #reporter2 = EmonCMS_Reporter("http://yourserver.me:8080",apikey="YOUR_API_KEY2",node="MY_NODE_NAME2",only_mapped=True) reporter3 = Console_Reporter(only_mapped=False) reporters = [reporter1, reporter3] #How frequently to pull sensor data from Telldus Core (in seconds) reporting_interval = 60 from Sensor_record import Sensor_record stop_time = time.time() while True: start_time = stop_time Sensor_records = map(Sensor_record, core.sensors()) for reporter in reporters: #By first buffering all the sensors and flushing at the end, we will only get one timeout in case the server #is not available. map(reporter.report_async, Sensor_records) reporter.flush_buffer()
print "}" 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
def test_sensor_event(self): core = TelldusCore() self.event_tester(core, core.register_sensor_event, self.mockdispatcher.trigger_sensor_event, (c_char_p(b"proto"), c_char_p(b"model"), c_int(7), c_int(8), c_char_p(b"value"), c_int(9)))
def test_controller_event(self): core = TelldusCore() self.event_tester(core, core.register_controller_event, self.mockdispatcher.trigger_controller_event, (c_int(10), c_int(11), c_int(12), c_char_p(b"new")))
try: import asyncio loop = asyncio.get_event_loop() dispatcher = td.AsyncioCallbackDispatcher(loop) except ImportError: loop = None dispatcher = td.QueuedCallbackDispatcher() ip_queue = Queue() ip_queue.put('10.0.0.73') work_queue = Queue() # core = TelldusCore() core = TelldusCore(callback_dispatcher=dispatcher) callbacks = [core.register_raw_device_event(raw_event)] web_thread = threading.Thread(target=run, kwargs={ 'host': '0.0.0.0', 'port': 8888 }) web_thread.daemon = True worker_thread = threading.Thread(target=queue_worker) worker_thread.daemon = True # run(host='0.0.0.0', port=8888) try: web_thread.start()
def test_sensors(self): self.sensor_index = 0 def tdSensor(protocol, p_len, model, m_len, id, datatypes): sensors = [{'protocol': b"proto_1", 'model': b"model_1", 'id': 1, 'datatypes': TELLSTICK_TEMPERATURE}, {'protocol': b"proto_2", 'model': b"model_2", 'id': 2, 'datatypes': TELLSTICK_HUMIDITY}, {'protocol': b"proto_3", 'model': b"model_3", 'id': 3, 'datatypes': TELLSTICK_RAINRATE}, {'protocol': b"proto_4", 'model': b"model_4", 'id': 4, 'datatypes': TELLSTICK_RAINTOTAL}, {'protocol': b"proto_5", 'model': b"model_5", 'id': 5, 'datatypes': TELLSTICK_WINDDIRECTION}, {'protocol': b"proto_6", 'model': b"model_6", 'id': 6, 'datatypes': TELLSTICK_WINDAVERAGE}, {'protocol': b"proto_7", 'model': b"model_7", 'id': 7, 'datatypes': TELLSTICK_WINDGUST}] if self.sensor_index < len(sensors): sensor = sensors[self.sensor_index] self.sensor_index += 1 protocol.value = sensor['protocol'] model.value = sensor['model'] try: id._obj.value = sensor['id'] datatypes._obj.value = sensor['datatypes'] except AttributeError: # With pypy we must use contents instead of _obj id.contents.value = sensor['id'] datatypes.contents.value = sensor['datatypes'] return TELLSTICK_SUCCESS else: self.sensor_index = 0 return TELLSTICK_ERROR_DEVICE_NOT_FOUND self.mocklib.tdSensor = tdSensor def tdSensorValue(protocol, model, id, datatype, value, v_len, times): if datatype == 1 << (id - 1): value.value = self.encode_string("%d" % (id * 100 + datatype)) return TELLSTICK_SUCCESS else: return TELLSTICK_ERROR_METHOD_NOT_SUPPORTED self.mocklib.tdSensorValue = tdSensorValue core = TelldusCore() sensors = core.sensors() self.assertEqual(7, len(sensors)) self.assertEqual(["proto_%d" % i for i in range(1, 8)], [s.protocol for s in sensors]) self.assertEqual(["model_%d" % i for i in range(1, 8)], [s.model for s in sensors]) self.assertEqual(list(range(1, 8)), [s.id for s in sensors]) self.assertEqual([TELLSTICK_TEMPERATURE, TELLSTICK_HUMIDITY, TELLSTICK_RAINRATE, TELLSTICK_RAINTOTAL, TELLSTICK_WINDDIRECTION, TELLSTICK_WINDAVERAGE, TELLSTICK_WINDGUST], [s.datatypes for s in sensors]) self.assertEqual([False] * 0 + [True] + [False] * 6, [s.has_temperature() for s in sensors]) self.assertEqual([False] * 1 + [True] + [False] * 5, [s.has_humidity() for s in sensors]) self.assertEqual([False] * 2 + [True] + [False] * 4, [s.has_rainrate() for s in sensors]) self.assertEqual([False] * 3 + [True] + [False] * 3, [s.has_raintotal() for s in sensors]) self.assertEqual([False] * 4 + [True] + [False] * 2, [s.has_winddirection() for s in sensors]) self.assertEqual([False] * 5 + [True] + [False] * 1, [s.has_windaverage() for s in sensors]) self.assertEqual([False] * 6 + [True] + [False] * 0, [s.has_windgust() for s in sensors]) self.assertEqual("%d" % (100 + TELLSTICK_TEMPERATURE), sensors[0].temperature().value) self.assertEqual("%d" % (200 + TELLSTICK_HUMIDITY), sensors[1].humidity().value) self.assertEqual("%d" % (300 + TELLSTICK_RAINRATE), sensors[2].rainrate().value) self.assertEqual("%d" % (400 + TELLSTICK_RAINTOTAL), sensors[3].raintotal().value) self.assertEqual("%d" % (500 + TELLSTICK_WINDDIRECTION), sensors[4].winddirection().value) self.assertEqual("%d" % (600 + TELLSTICK_WINDAVERAGE), sensors[5].windaverage().value) self.assertEqual("%d" % (700 + TELLSTICK_WINDGUST), sensors[6].windgust().value)
try: import asyncio loop = asyncio.get_event_loop() dispatcher = td.AsyncioCallbackDispatcher(loop) except ImportError: loop = None dispatcher = td.QueuedCallbackDispatcher() ip_queue = Queue() ip_queue.put('10.0.0.73') work_queue = Queue() # core = TelldusCore() core = TelldusCore(callback_dispatcher=dispatcher) callbacks = [core.register_raw_device_event(raw_event)] web_thread = threading.Thread(target=run, kwargs={'host': '0.0.0.0', 'port': 8888}) web_thread.daemon = True worker_thread = threading.Thread(target=queue_worker) worker_thread.daemon = True # run(host='0.0.0.0', port=8888) try: web_thread.start() worker_thread.start() # web_thread.join() # worker_thread.join()
def test_device_change_event(self): core = TelldusCore() self.event_tester(core, core.register_device_change_event, self.mockdispatcher.trigger_device_change_event, (c_int(3), c_int(4), c_int(5)))
elif action == "on": return onaction else: raise IllegalArgumentException() def getshutdown(): def shutdown(): if messagebox.askyesno("Really shut down?", "Are you sure you want to shut down the remote?"): call(["sudo", "poweroff"]) 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)
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, }
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))
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
# Getting the token from command-line is better than embedding it in code, # because tokens are supposed to be kept secret. TOKEN = sys.argv[1] user_ids = [] user_state = [] for index in range(2, len(sys.argv)): user_ids.append(long(sys.argv[index])) user_state.append(DF_DEFAULT) localtime = time.asctime( time.localtime(time.time()) ) print "Local current time :", localtime print 'Init telldus core' lightcore = TelldusCore() light_list = [] names = [] groups = [] # Parse from XML xml_config = untangle.parse('config.xml') for switch in xml_config.control.devices.switch: names.append(switch['name']) light_list.append(lightcore.add_device( switch['name'], switch['protocol'], switch['model'], house=switch['house'], unit=switch['unit'], code=switch['code']))
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
import sqlite3 import datetime import time from tellcore.telldus import TelldusCore from enum import Enum BEDROOM = 151 BALCONY = 135 KTICHEN = 167 offset_bedroom = 0.5 core = TelldusCore() conn = sqlite3.connect( '/home/pi/projects/sensor_webbapp/sensor_reading/sensordata.db') curs = conn.cursor() while (True): try: list_sensors = core.sensors() print(len(list_sensors)) if list_sensors is not None: for sens in list_sensors: dev_id = sens.id temp = sens.value(1).value hum = sens.value(2).value if dev_id == BEDROOM: curs.execute( "INSERT INTO sensor_data VALUES (datetime('now'), ?, ?,?)", (float(temp) + offset_bedroom, hum, dev_id)) print( "Added reading for bedroom, dev_id: {} temp: {}, hum: {}"