import agoclient client = agoclient.AgoConnection("test") def messageHandler(internalid, content): if "command" in content: if content["command"] == "test": retval = {} retval["hallo"] = "blah" return retval return {} client.addHandler(messageHandler) client.addDevice("123", "test") client.run()
#! /usr/bin/env python import sys import syslog import ow import time import threading import agoclient client = agoclient.AgoConnection("owfs") device = agoclient.getConfigOption("owfs", "device", "/dev/usbowfs") # route stderr to syslog class LogErr: def write(self, data): syslog.syslog(syslog.LOG_ERR, data) syslog.openlog(sys.argv[0], syslog.LOG_PID, syslog.LOG_DAEMON) # sys.stderr = LogErr() sensors = {} syslog.syslog(syslog.LOG_NOTICE, "agoowfs.py startup") try: ow.init( device ) except ow.exNoController: syslog.syslog(syslog.LOG_ERROR, "can't open one wire device, aborting") time.sleep(5) exit(-1)
#! /usr/bin/env python import random import sys import syslog import socket import threading import time import agoclient client = agoclient.AgoConnection("simulator") def messageHandler(internalid, content): if "command" in content: if content["command"] == "on": print "switching on: " + internalid client.emitEvent(internalid, "event.device.statechanged", "255", "") if content["command"] == "off": print "switching off: " + internalid client.emitEvent(internalid, "event.device.statechanged", "0", "") if content["command"] == "push": print "push button: " + internalid if content['command'] == 'setlevel': if 'level' in content: print "device level changed", content["level"] client.emitEvent(internalid, "event.device.statechanged", content["level"], "")
import threading import time import agoclient import socket import re import json import requests CLIENT = agoclient.AgoConnection("tomato") MIN_RSSI = -80 def message_handler(internal_id, content): print(internal_id, content) CLIENT.add_handler(message_handler) SERVER = agoclient.get_config_option("tomato", "server", "192.168.1.1") USERNAME = agoclient.get_config_option("tomato", "username", "admin") PASSWORD = agoclient.get_config_option("tomato", "password", "") TOKEN = agoclient.get_config_option("tomato", "token", "") def get_tomato_info(host, username, password, http_id): req = requests.post('http://{}/update.cgi'.format(host), data={
#[INIM] #terminal=10 #outputs=0 # # Interface for security panels from INIM: http://www.inim.biz # # the terminals connected to the control unit can be up to 100 # the base unit without expansion has 10 # import agoclient import time import threading import serial client = agoclient.AgoConnection("INIM") port = agoclient.getConfigOption("INIM", "port", "/dev/ttyS0") terminal = int(agoclient.getConfigOption("INIM", "terminal", "10")) outputs = agoclient.getConfigOption("INIM", "outputs", "3") # add devices for terminals for i in range(terminal): id = i + 1 client.addDevice("%d" % (id), "binarysensor") ser = serial.Serial(port, 57600, parity=serial.PARITY_EVEN, stopbits=1, timeout=1)
None, { 'uuid': scenarioControllerUuid, 'command': 'run', 'internalid': schedule['scenario'] }) except: logging.exception('Exception on timechanged event:') #================================= #main #================================= #init try: #connect agoclient client = agoclient.AgoConnection('agoscheduler') #members loadSchedules() #add client handlers client.addHandler(commandHandler) client.addEventHandler(eventHandler) #add controller client.addDevice('agoscheduler', 'agoscheduler') #get scenariocontroller uuid (don't catch exceptions because no uuid no scenario execution) inventory = client.getInventory() for uuid in inventory.content['devices']: if inventory.content['devices'][uuid][
# waittime = 30 # import agoclient import time import threading import pywapi import string readID = agoclient.getConfigOption("weather", "locations_ID", "00000") readTempUnits = agoclient.getConfigOption("weather", "tempunits", "f") readWaitTime = int(agoclient.getConfigOption("weather", "waittime", "30")) rain = "rain" ex_temp = "ex_temp" ex_umidity = "ex_umidity" client = agoclient.AgoConnection("Weather") client.addDevice(rain, "binarysensor") client.addDevice(ex_temp, "temperaturesensor") client.addDevice(ex_umidity, "multilevelsensor") class testEvent(threading.Thread): def __init__(self, ): threading.Thread.__init__(self) def run(self): while (True): weather_com_result = pywapi.get_weather_from_weather_com(readID) condizioni = weather_com_result['current_conditions']['text'] temperatura = float(
#! /usr/bin/env python # APC Switched Rack PDU Device import sys import syslog import socket from pysnmp.entity.rfc3413.oneliner import cmdgen from pysnmp.proto import rfc1902 import threading import time import agoclient client = agoclient.AgoConnection("apc") OIDOutletCount = "1,3,6,1,4,1,318,1,1,4,5,1,0" # sPDUOutletConfigTableSize OIDStatus = "1,3,6,1,4,1,318,1,1,4,4,2,1,3" # sPDUOutletCtl OIDName = "1,3,6,1,4,1,318,1,1,4,5,2,1,3" # sPDUOutletName OIDLoad = "1,3,6,1,4,1,318,1,1,12,2,3,1,1,2,1" # rPDULoadStatusLoad loadOID = (1, 3, 6, 1, 4, 1, 318, 1, 1, 12, 2, 3, 1, 1, 2, 1) apchost = agoclient.getConfigOption("apc", "host", "192.168.1.13") apcport = int(agoclient.getConfigOption("apc", "port", "161")) apcvoltage = int(agoclient.getConfigOption("apc", "voltage", "220")) apccommunityro = agoclient.getConfigOption("apc", "community_readonly", "public") apccommunityrw = agoclient.getConfigOption("apc", "community_readwrite", "private")
# # ago control - UBNT mPower device # # copyright (c) 2013 Christoph Jaeger <*****@*****.**> # import agoclient import threading import time import pyubnt from urllib2 import URLError client = agoclient.AgoConnection("mPower") needs_connection = False def messageHandler(internalid, content): global needs_connection if "command" in content: try: if content["command"] == "on": print "switching on port" + internalid try: mPowerDevice.SetDevice(internalid, 1) except ValueError as e: needs_connection = True if content["command"] == "off": print "switching off port: " + internalid
# tempC = value # if TempUnits == 'F': # tempF = 9.0/5.0 * tempC + 32.0 # client.emitEvent(str(devId), "event.environment.temperaturechanged", tempF, "degF") # else: # client.emitEvent(str(devId), "event.environment.temperaturechanged", tempC, "degC") if "humidity" in model and dataType & t.TELLSTICK_HUMIDITY == t.TELLSTICK_HUMIDITY: emitHumidityChanged(devId, float(value)) #client.emitEvent(str(devId), "event.environment.humiditychanged", float(value), "%") info("+------------------------------------------------------------") info("+ Tellstick.py startup. Version=" + AGO_TELLSTICK_VERSION) info("+------------------------------------------------------------") client = agoclient.AgoConnection("tellstick") #device = (agoclient.getConfigOption("tellstick", "device", "/dev/usbxxxx") if (agoclient.getConfigOption("tellstick", "debug", "false").lower() == "true"): debug = True config = ConfigObj("/etc/opt/agocontrol/conf.d/tellstick.conf") #config = ConfigObj("./tellstick.conf") try: general_delay = float(config['EventDevices']['Delay']) / 1000 except: general_delay = 0.5 #section = config['EventDevices'] SensorPollDelay = 300.0 # 5 minutes try:
def emit_off(internalid): client.emitEvent(internalid, "event.device.statechanged", str(STATE_OFF), "") def emit_stream(internalid): client.emitEvent(internalid, "event.device.mediastatechanged", str(STATE_STREAM), "") #init try: #connect agoclient client = agoclient.AgoConnection("squeezebox") #read configuration host = agoclient.getConfigOption("squeezebox", "host", "127.0.0.1") port = int(agoclient.getConfigOption("squeezebox", "port", "9090")) login = agoclient.getConfigOption("squeezebox", "login", "") passwd = agoclient.getConfigOption("squeezebox", "password", "") logging.info("Config: %s@%s:%d" % (login, host, port)) #connect to squeezebox server logging.info('Creating LMSServer...') server = pylmsserver.LMSServer(host, port, login, passwd) server.connect() #connect to notifications server logging.info('Creating LMSPlaylist...')
#! /usr/bin/env python import syslog import agoclient from WSDiscovery import * client = agoclient.AgoConnection("onvif") def messageHandler(internalid, content): if "command" in content: if content["command"] == "getvideoframe": print "nada" client.addHandler(messageHandler) # do a web service discovery to search for ONVIF NVTs wsd = WSDiscovery() wsd.start() typeNVT = QName("http://www.onvif.org/ver10/network/wsdl","NetworkVideoTransmitter"); #ret = wsd.searchServices(scopes=[scope1], timeout=10) ret = wsd.searchServices(types=[typeNVT]) for service in ret: print "Device: " + service.getEPR() + ":" print "Address information: " + str(service.getXAddrs()) print "Scopes: " + str(service.getScopes()) client.addDevice(service.getXAddrs()[0],"camera")
# voltage_divider = 1 # inputs = 0 # interval=600 # change=0.1 # import agoclient import threading import time import subprocess import re import string from time import gmtime, strftime import RPi.GPIO as GPIO client = agoclient.AgoConnection("raspiMCP3xxxGPIO") SPIMOSI = int(agoclient.getConfigOption("raspiMCP3xxxGPIO", "SPIMOSI", "10")) SPIMISO = int(agoclient.getConfigOption("raspiMCP3xxxGPIO", "SPIMISO", "9")) SPICLK = int(agoclient.getConfigOption("raspiMCP3xxxGPIO", "SPICLK", "11")) SPICS = int(agoclient.getConfigOption("raspiMCP3xxxGPIO", "SPICS", "8")) vDiv = float( agoclient.getConfigOption("raspiMCP3xxxGPIO", "voltage_divider", "1")) readInputs = agoclient.getConfigOption("raspiMCP3xxxGPIO", "inputs", "0,1") interval = int(agoclient.getConfigOption("raspiMCP3xxxGPIO", "interval", "60")) change = float(agoclient.getConfigOption("raspiMCP3xxxGPIO", "change", "0.1")) inputs = map(int, readInputs.split(',')) deviceconfig = {}
import threading import time import serial import json state = {"state": "", "AirTemperature": "", "AirHumidity": ""} variables = { "AirHumidity.low": "", "AirHumidity.high": "", "AirTemperature.low": "", "AirTemperature.high": "", "AirCircInterval": "" } sensors = {"AirTemperature": "", "AirHumidity": ""} client = agoclient.AgoConnection("MushroomControl") myport = agoclient.getConfigOption("MushroomControl", "device", "0") s0 = serial.Serial(myport, 9600) def inventory(): s0.write('{"content": {"command":"inventory"}}') def messageHandler(internalid, content): if "command" in content: if content["command"] == "setvariable": try: myvalue = ""
info ("pinging x=" + hosts[x]) if hosts[x] != '': res = ping (hosts[x]) if res==True: client.emitEvent(x, "event.device.statechanged", "255", "") else: client.emitEvent(x, "event.device.statechanged", "0", "") time.sleep (float(self.sleep)) info( "+------------------------------------------------------------") info( "+ wake_on_lan.py startup. Version=" + AGO_WOL_VERSION) info( "+------------------------------------------------------------") debug=False client = agoclient.AgoConnection("wake_on_lan") if (agoclient.getConfigOption("wake_on_lan", "debug", "false").lower() == "true"): debug = True config = ConfigObj("/etc/opt/agocontrol/conf.d/wake_on_lan.conf") try: pingsleep = config['wake_on_lan']['polltime'] except: pingsleep = 300 section = config['Computers'] computers={} hosts={} for y in section: client.addDevice(config['Computers'][y]['name'], "computer")
tempF = 9.0 / 5.0 * tempC + 32.0 client.emitEvent( devId, "event.environment.temperaturechanged", tempF, "degF") else: client.emitEvent( devId, "event.environment.temperaturechanged", tempC, "degC") time.sleep(readWaitTime) info("+------------------------------------------------------------") info("+ temperaturnu.py startup. Version=" + AGO_TEMPERATURNU_VERSION) info("+------------------------------------------------------------") client = agoclient.AgoConnection("temperaturnu") if (agoclient.getConfigOption("temperaturnu", "debug", "false").lower() == "true"): debug = True lat = agoclient.getConfigOption("system", "lat", "0") lon = agoclient.getConfigOption("system", "lon", "0") mailadress = agoclient.getConfigOption("system", "mailadress", "none") units = agoclient.getConfigOption("system", "units", "SI") TempUnits = "C" if units.lower() == "us": TempUnits = "F" readWaitTime = int(agoclient.getConfigOption("temperaturnu", "waittime", "300"))
'1': '5', '9': '6', '5': '7', 'd': '8', '7': '9', 'f': '10', '3': '11', 'b': '12', '0': '13', '8': '14', '4': '15', 'c': '16' } x10_funct = {'2': '255', '3': '0'} client = agoclient.AgoConnection("X10") # This section handles sending X10 devices over the CM11A using Python-X10 # this class will be instantiated and spawned into background to not block the messageHandler x10lock = threading.Lock() class x10send(threading.Thread): def __init__(self, id, functioncommand, level): threading.Thread.__init__(self) self.id = id self.functioncommand = functioncommand self.level = level def run(self):
import threading import time import agoclient import socket CLIENT = agoclient.AgoConnection("hunterdouglas") SOCKET = socket.socket(socket.AF_INET, socket.SOCK_STREAM) HD_GATEWAY_ADDR = (agoclient.get_config_option("hunterdouglas", "server", ""), agoclient.get_config_option("hunterdouglas", "port", "522")) TIMEOUT = 10 def verify_socket(): global SOCKET try: SOCKET.sendall("$dmy") print repr(recv_until("ack\n\r")) except socket.error as e: SOCKET.close() print "recreating socket" SOCKET = socket.create_connection(HD_GATEWAY_ADDR) SOCKET.settimeout(TIMEOUT) def set_shade(internal_id, hd_value): verify_socket() SOCKET.sendall("$pss%s-04-%03d" % (internal_id, hd_value)) recv_until("done") SOCKET.sendall("$rls") recv_until("act00-00-")
# check_time is the time (seconds) between each check import agoclient import threading import time import os import sys readPhoneaddress = agoclient.getConfigOption("wifi_device_detect","phoneaddress","00:00:00:00:00:00, FF:FF:FF:FF:FF:FF") phoneaddress = map(str, readPhoneaddress.split(',')) readDevicename = agoclient.getConfigOption("wifi_device_detect","devicename","androidphone, iphone") devicename = map(str, readDevicename.split(',')) client = agoclient.AgoConnection("Wifi_Device_Detect") for name in devicename: client.addDevice(name, "binarysensor") wifidevices = dict(zip(phoneaddress, devicename)) last_seen = {} for address in phoneaddress: last_seen[address] = 0 wait_time = float(agoclient.getConfigOption("wifi_device_detect","wait_time","15")) check_time = float(agoclient.getConfigOption("wifi_device_detect","check_time","15")) def checkForDevice(deviceaddress): # See if the device has connected to the network
uuid = content['uuid'] internalid = client.uuidToInternalId(uuid) if uuid and uuid in client.uuids: #uuid belongs to this handler #TODO manage events here pass #================================= #main #================================= #init try: #connect agoclient client = agoclient.AgoConnection('alert') #load config configMailSmtp = agoclient.getConfigOption("mail", "smtp", "", 'alert') configMailSender = agoclient.getConfigOption("mail", "sender", "", 'alert') configMailLogin = agoclient.getConfigOption("mail", "login", "", 'alert') configMailPassword = agoclient.getConfigOption("mail", "password", "", 'alert') configMailTls = agoclient.getConfigOption("mail", "tls", "", 'alert') configTwitterKey = agoclient.getConfigOption("twitter", "key", "", 'alert') configTwitterSecret = agoclient.getConfigOption("twitter", "secret", "", 'alert') configGTalkUsername = agoclient.getConfigOption("gtalk", "username", "", 'alert') configGTalkPassword = agoclient.getConfigOption("gtalk", "password", "", 'alert') configSmsUsername = agoclient.getConfigOption("12voip", "username", "", 'alert') configSmsPassword = agoclient.getConfigOption("12voip", "password", "", 'alert') configPushProvider = agoclient.getConfigOption('push', 'provider', '', 'alert') configPushbulletApikey = agoclient.getConfigOption('pushbullet', 'apikey', '', 'alert')
# raspiCamera device # # enabling camera suport on raspi http://www.raspberrypi.org/camera # # apt-get install python-picamera # import agoclient import urllib2 import base64 import picamera import io import time client = agoclient.AgoConnection("raspiCamera") def messageHandler(internalid, content): result = {} result["result"] = -1 if "command" in content: if content['command'] == 'getvideoframe': print "raspiCamera getting video frame" stream = io.BytesIO() with picamera.PiCamera() as camera: camera.resolution = (256, 188) camera.quality = (20) camera.start_preview() time.sleep(0.1) camera.capture(stream, format='jpeg')
#!/usr/bin/python # copyright (c) 2013 Harald Klein <*****@*****.**> # import agoclient import smtplib import string client = agoclient.AgoConnection("smtp") smtpserver = agoclient.getConfigOption("smtp", "server", "mx.mail.com") smtpport = agoclient.getConfigOption("smtp", "port", "25") smtpfrom = agoclient.getConfigOption("smtp", "from", "*****@*****.**") smtpauthrequired = agoclient.getConfigOption("smtp", "authrequired", "0") smtpuser = agoclient.getConfigOption("smtp", "user", "") smtppassword = agoclient.getConfigOption("smtp", "password", "") def messageHandler(internalid, content): if "command" in content: if content["command"] == "sendmail" and "to" in content: print "sending email" subject = "mail from agoman" if "subject" in content: subject = content["subject"] body = "no text" if "body" in content: body = content["body"] body = string.join(( "From: %s" % smtpfrom, "To: %s" % content["to"], "Subject: %s" % subject ,
import time import threading import socket import struct import re import agoclient GC100_ANNOUNCE_MCAST_IP = "239.255.250.250" GC100_ANNOUNCE_PORT = 9131 GC100_COMM_PORT = 4998 BUFFER_SIZE = 8192 client = agoclient.AgoConnection("gc100") devices = {} def sendcommand(host, port, command): # print "connecting to", host, "port", port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) s.send(command) data = s.recv(BUFFER_SIZE) s.close() return data def getdevices(host, port):
#!/usr/bin/python # ago client webcam device # # copyright (c) 2013 Harald Klein <*****@*****.**> # import agoclient import urllib2 import base64 client = agoclient.AgoConnection("webcam") def messageHandler(internalid, content): result = {} result["result"] = -1 if "command" in content: if content['command'] == 'getvideoframe': print "getting video frame" try: protocol, urldata = internalid.split("://") if "@" in urldata: logindata, urlpart = urldata.split("@") username, password = logindata.split(":") else: urlpart = urldata username = '' password = ''
# to use the client library we have to import it import agoclient # we'll also use a background thread in this example import threading import time # then we create an AgoConnection object. You need to specify an instance name as parameter. # This will be used to uniquely name the mappings file for internal id to uuid mapping and to identify the client devices ("handled-by" parameter) # Examples for the instance name would be "zwave" for our z-wave device, "knx" for KNX, "owfs" for the one wire device, and so on. # Just chose a name that is unique and speaks for itself. It is best practice to also use that instance name as section name in the config file # if you need any config parameters. client = agoclient.AgoConnection("example") # the messageHandler method will be called by the client library when a message comes in that is destined for one of the child devices you're handling # the first parameter is your internal id (all the mapping from ago control uuids to the internal ids is handled transparently for you) # the second parameter is a dict with the message content def messageHandler(internalid, content): if "command" in content: if content["command"] == "on": print "switching on: " + internalid # TODO: insert real stuff here, this is where you would do action and switch on your child device # depending on if the operation was successful, you want to report state back to ago control. We just send 255 in this case # so that ago control changes the device state in the inventory to on
import urllib import urllib2 import agoclient # route stderr to syslog class LogErr: def write(self, data): syslog.syslog(syslog.LOG_ERR, data) syslog.openlog(sys.argv[0], syslog.LOG_PID, syslog.LOG_DAEMON) # sys.stderr = LogErr() client = agoclient.AgoConnection("enigma2") syslog.syslog(syslog.LOG_NOTICE, "agoenigma2.py startup") hostsconfig = agoclient.getConfigOption("enigma2", "hosts", "") try: hosts = map(str, hostsconfig.split(',')) except: syslog.syslog(syslog.LOG_NOTICE, 'no static hosts defined') else: for host in hosts: client.addDevice(host, "settopbox") syslog.syslog(syslog.LOG_NOTICE, "discovering devices")
from core import eISCP import commands import agoclient # route stderr to syslog class LogErr: def write(self, data): syslog.syslog(syslog.LOG_ERR, data) syslog.openlog(sys.argv[0], syslog.LOG_PID, syslog.LOG_DAEMON) # sys.stderr = LogErr() client = agoclient.AgoConnection("iscp") devices = {} def discovery(timeout=3): avrs = eISCP.discover(timeout) for avr in avrs: client.addDevice("%s:%s" % (avr.host, avr.port), "avreceiver") # reportdevice("%s:%s" % (avr.host, avr.port), product=avr.info['model_name']); syslog.syslog(syslog.LOG_NOTICE, "agoiscp.py startup") syslog.syslog(syslog.LOG_NOTICE, "discovering devices") discovery()
# Device wrapper for Python-TStat # copyright (c) 2013 Michael Dingman <*****@*****.**> import agoclient import threading import time from TStat import * client = agoclient.AgoConnection("radiothermostat") #currentTemp = float(t.getCurrentTemp()) #tstatMode = t.getTstatMode() #fanMode = t.getFanMode() #holdState = bool(t.getHoldState()) #fanState = t.getFanState() #heatPoint = float(t.getHeatPoint()) #coolPoint = float(t.getCoolPoint()) def messageHandler(internalid, content): tstatMode = t.getTstatMode() if "command" in content: if content["command"] == "settemperature": print "setting temp: " + internalid + " Current mode: " + tstatMode if tstatMode == "Heat": print "set heat pont: " + content["temperature"] t.setHeatPoint(float(content["temperature"])) client.emitEvent(internalid, "event.environment.temperaturechanged", content["temperature"], "")
# ago raspberry pi GPIO device # #/etc/opt/agocontrol/config.ini # #[raspiGPIO] #inputs=18,23 #outputs=22,24,25 # import agoclient import threading import time import RPi.GPIO as GPIO import syslog client = agoclient.AgoConnection("raspiGPIO") readInputs = agoclient.getConfigOption("raspiGPIO", "inputs", "") readOutputs = agoclient.getConfigOption("raspiGPIO", "outputs", "") reverse = agoclient.getConfigOption("raspiGPIO", "reverse", "0") GPIO.setmode(GPIO.BCM) try: inputs = map(int, readInputs.split(',')) except: syslog.syslog(syslog.LOG_ERR, 'no valid inputs') inputs = None else: for pin in inputs: #print pin
#!/usr/bin/env python import socket import agoclient client = agoclient.AgoConnection("wifi370") COMMAND_ON = "\xcc\x23\x33" COMMAND_OFF = "\xcc\x24\x33" # COMMAND_RGB="\x56\xRR\xGG\xBB\xaa" COMMAND_STATUS = "\xef\x01\x77" try: deviceconfig = agoclient.getConfigOption("wifi370", "devices", "192.168.80.44:5577") devices = map(str, deviceconfig.split(',')) except e: devices = None print "Error, no devices:" + e else: for device in devices: client.addDevice(device, "dimmerrgb") def sendcmd(host, port, command): try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) s.send(command) s.close() except socket.error as msg: print "Socket error: ", msg