def loadSchedules(): """load schedules from config file""" global allSchedules, timeSchedules #create members allSchedules = SortedCollection([], itemgetter(0)) timeSchedules = SortedCollection([], itemgetter(0)) #get schedules from confif file schedules = agoclient.get_config_option("agoscheduler", "all", "[]") schedules = json.loads(schedules) #and store them in sorted collection for schedule in schedules: addSchedule(schedule, False, False) logging.info('Loaded %d schedules' % len(allSchedules))
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-") return True
infos = get_media_infos(internalid, None) logging.info(infos) return infos #unhandled device command logging.warn('Unhandled device command') return False #init try: #connect agoclient client = agoclient.AgoConnection("squeezebox") #read configuration host = agoclient.get_config_option("squeezebox", "host", "127.0.0.1") cli_port = int(agoclient.get_config_option("squeezebox", "cliport", "9090")) html_port = int(agoclient.get_config_option("squeezebox", "htmlport", "9000")) login = agoclient.get_config_option("squeezebox", "login", "") passwd = agoclient.get_config_option("squeezebox", "password", "") logging.info("Config: %s@%s:%d" % (login, host, cli_port)) #connect to squeezebox server logging.info('Connecting to LMSServer...') server = pylmsserver.LMSServer(host, cli_port, login, passwd) server.connect() #connect to notifications server logging.info('Connecting to notification server...') library = pylmslibrary.LMSLibrary(host, cli_port, html_port, login, passwd) playlist = pylmsplaylist.LMSPlaylist(library, host, cli_port, login, passwd)
urllib2.install_opener(opener) u = urllib2.urlopen(url) else: u = urllib2.urlopen(url) buffer = u.read() result["image"] = base64.b64encode(buffer) result["result"] = 0; except urllib2.URLError, e: print ('Error opening URL %s' % (url) + ' - Reason: ' + e.reason) return result client.add_handler(messageHandler) devicelist=agoclient.get_config_option("webcam", "devices", "") try: devices = map(str, devicelist.split(',')) except: print "error reading device list" else: for device in devices: print "announcing device", device if "rtsp://" in device: client.add_device(device, "onvifnvt") else: client.add_device(device, "camera") client.run()
if hosts[x] != '': res = ping (hosts[x]) if res==True: client.emit_event(x, "event.device.statechanged", "255", "") else: client.emit_event(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.get_config_option("wake_on_lan", "debug", "false").lower() == "true"): debug = True config = ConfigObj(agoclient.CONFDIR + "/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.add_device(config['Computers'][y]['name'], "computer") computers[config['Computers'][y]['name']] = config['Computers'][y]['mac']
mPowerDevice.SetDevice(internalid, 0) except ValueError as e: needs_connection = True except URLError as e: print "Device could not be reached due to %s" % (e.reason) print "Needs reconnect ..." needs_connection = True # specify our message handler method client.add_handler(messageHandler) # get config parameters host = agoclient.get_config_option("mPower", "host", "127.0.0.1") username = agoclient.get_config_option("mPower", "username", "ubnt") password = agoclient.get_config_option("mPower", "password", "ubnt") # initial call to mPower device mPowerDevice = pyubnt.Device(host, username, password) # add the devices of the mPower content = mPowerDevice.GetDevices() i = 1 for item in content["value"]: if "relay" in item: client.add_device(str(i), "switch") i = i + 1
# v.3 Calculation code shamelessly taken from http://pydoc.net/Python/weather/0.9.1/weather.units.temp/ # # # Create /etc/opt/agocontrol/conf.d/weather.conf # [weather] # locations_ID=ITLM2916 # tempunits = f # waittime = 30 # import agoclient import time import threading import pywapi import string readID = agoclient.get_config_option("weather","locations_ID","90210") readTempUnits = agoclient.get_config_option("weather","tempunits","f") readWaitTime = int(agoclient.get_config_option("weather","waittime","300")) rain = "rain" temp = "temp" humidity = "humidity" dewpoint = "dewpoint" client = agoclient.AgoConnection("Weather") client.add_device(rain, "binarysensor") client.add_device(temp, "temperaturesensor") client.add_device(humidity, "multilevelsensor") client.add_device(dewpoint, "multilevelsensor") def celsius_to_fahrenheit(c):
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.get_config_option("mail", "smtp", "", 'alert') configMailSender = agoclient.get_config_option("mail", "sender", "", 'alert') configMailLogin = agoclient.get_config_option("mail", "login", "", 'alert') configMailPassword = agoclient.get_config_option("mail", "password", "", 'alert') configMailTls = agoclient.get_config_option("mail", "tls", "", 'alert') configTwitterKey = agoclient.get_config_option("twitter", "key", "", 'alert') configTwitterSecret = agoclient.get_config_option("twitter", "secret", "", 'alert') configGTalkUsername = agoclient.get_config_option("gtalk", "username", "", 'alert') configGTalkPassword = agoclient.get_config_option("gtalk", "password", "", 'alert') configSmsUsername = agoclient.get_config_option("12voip", "username", "", 'alert') configSmsPassword = agoclient.get_config_option("12voip", "password", "", 'alert') configPushProvider = agoclient.get_config_option('push', 'provider', '', 'alert') configPushbulletApikey = agoclient.get_config_option('pushbullet', 'apikey', '', 'alert') configPushbulletDevices = agoclient.get_config_option('pushbullet', 'devices', '', 'alert') configPushoverUserid = agoclient.get_config_option('pushover', 'userid', '', 'alert') configNotifymyandroidApikeys = agoclient.get_config_option('notifymyandroid', 'apikeys', '', 'alert')
#!/usr/bin/python # copyright (c) 2013 Harald Klein <*****@*****.**> # import agoclient import smtplib import string client = agoclient.AgoConnection("smtp") smtpserver = agoclient.get_config_option("smtp", "server", "mx.mail.com") smtpport = agoclient.get_config_option("smtp", "port", "25") smtpfrom = agoclient.get_config_option("smtp", "from", "*****@*****.**") smtpauthrequired = agoclient.get_config_option("smtp", "authrequired", "0") smtpuser = agoclient.get_config_option("smtp", "user", "") smtppassword = agoclient.get_config_option("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 ,
#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.get_config_option("INIM", "port", "/dev/ttyS0") terminal = int(agoclient.get_config_option("INIM", "terminal", "10")) outputs = agoclient.get_config_option("INIM", "outputs", "3") # add devices for terminals for i in range(terminal): id = i+1 client.add_device("%d" % (id), "binarysensor") ser = serial.Serial(port, 57600, parity=serial.PARITY_EVEN, stopbits=1, timeout=1) class requestZoneStatus(threading.Thread): def __init__(self,): threading.Thread.__init__(self) def run(self):
# devicename=androidphone,iphone # wait_time=15 # check_time=15 # # *NOTE* First phone address (MAC Address) matches first devicename, second matches second, etc # wait_time is the maximum time (minutes) a device can be inactive before being marked as away # check_time is the time (seconds) between each check import agoclient import threading import time import os import sys readPhoneaddress = agoclient.get_config_option("wifi_device_detect","phoneaddress","00:00:00:00:00:00, FF:FF:FF:FF:FF:FF") phoneaddress = map(str, readPhoneaddress.split(',')) readDevicename = agoclient.get_config_option("wifi_device_detect","devicename","androidphone, iphone") devicename = map(str, readDevicename.split(',')) client = agoclient.AgoConnection("Wifi_Device_Detect") for name in devicename: client.add_device(name, "binarysensor") wifidevices = dict(zip(phoneaddress, devicename)) last_seen = {} for address in phoneaddress: last_seen[address] = 0
# change=0.2 # temperature change between reports # import agoclient import threading import time import os import sys import syslog os.system('modprobe w1-gpio') os.system('modprobe w1-therm') client = agoclient.AgoConnection("raspi1wGPIO") readInterval = agoclient.get_config_option("raspi1wGPIO", "interval", "600") interval = int(readInterval) change = float(agoclient.get_config_option("raspi1wGPIO", "change", "0.2")) try: readDevices = (line.rstrip('\n') for line in open('/sys/bus/w1/devices/w1_bus_master1/w1_master_slaves')) except IOError: syslog.syslog(syslog.LOG_ERR, 'No devices exiting') sys.exit() devices = [] sensordata = {}
t.setCoolPoint(float(content["temperature"])) client.emit_event(internalid, "event.environment.temperaturechanged", content["temperature"], "") if content["command"] == "setthermostatmode": print "set thermostat mode: " + internalid #client.emit_event(internalid, "event.device.statechanged", "0", "") if content["command"] == "setthermostatfanmode": print "set radio thermostat fan mode: " + internalid if content["command"] == "setthermostathold": print "set radio thermostat hold: " + internalid # specify our message handler method client.add_handler(messageHandler) ipAddress = agoclient.get_config_option("radiothermostat", "ipaddress", "0.0.0.0") tempUnit = agoclient.get_config_option("system", "units", "SI") #print "IP: ", ipAddress #print "UNIT: ", tempUnit t = TStat(ipAddress) t.setCacheExpiry(15) client.add_device(ipAddress, "thermostat") #TODO implement thread here for polling # in the background or need to handle some other communication. If you don't need one or if you want to keep things simple at the moment just skip this section. class readThermostat(threading.Thread): #def cToF(tempC): #retval = float((float(tempC) * (9.0/5/0)) + 32) #return retval
except: #bad rrd file pass logging.info('Found rrd files:') for rrd in rrds.values(): logging.info(' - %s' % rrd) #add client handlers client.add_handler(commandHandler) client.add_event_handler(eventHandler) #add controller client.add_device('rrdtoolcontroller', 'rrdtoolcontroller') try: multi_nb = int(agoclient.get_config_option("multi", "nb_multi", "", "rrd")) except ValueError: multi_nb = 0 for i in range(multi_nb): key = "multi%d" % i uuids = agoclient.get_config_option("multi", key, "", "rrd") if uuids != "": uuids_list = uuids.split(",") client.add_device(key, 'multisensor') uuid = client.internal_id_to_uuid(key) multi[uuid] = {} multi[uuid]['internalid'] = key multi[uuid]['uuids'] = uuids_list except Exception as e: #init failed
# tempF = 9.0/5.0 * tempC + 32.0 # client.emit_event(str(devId), "event.environment.temperaturechanged", tempF, "degF") # else: # client.emit_event(str(devId), "event.environment.temperaturechanged", tempC, "degC") if "humidity" in model and dataType & t.TELLSTICK_HUMIDITY == t.TELLSTICK_HUMIDITY: emitHumidityChanged(devId, float(value)) # client.emit_event(str(devId), "event.environment.humiditychanged", float(value), "%") info("+------------------------------------------------------------") info("+ Tellstick.py startup. Version=" + AGO_TELLSTICK_VERSION) info("+------------------------------------------------------------") client = agoclient.AgoConnection("tellstick") # device = (agoclient.get_config_option("tellstick", "device", "/dev/usbxxxx") if agoclient.get_config_option("tellstick", "debug", "false").lower() == "true": debug = True config = ConfigObj(agoclient.CONFDIR + "/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: if "SensorPollDelay" in config["tellstick"]: SensorPollDelay = config["tellstick"]["SensorPollDelay"] except KeyError:
import agoclient import threading import time import subprocess import re import string from time import gmtime, strftime import spidev spi = spidev.SpiDev() spi.open(0, 0) client = agoclient.AgoConnection("MCP3x0x") vDiv = float(agoclient.get_config_option("MCP3x0x", "voltage_divider", "1")) readInputs = agoclient.get_config_option("MCP3x0x", "inputs", "0,1") interval = int(agoclient.get_config_option("MCP3x0x", "interval", "60")) change = float(agoclient.get_config_option("MCP3x0x", "change", "0.1")) inputs = map(int, readInputs.split(',')) deviceconfig = {} for adcCh in inputs: deviceconfig[(adcCh, 'value')] = 0 deviceconfig[(adcCh, 'lastreporttime')] = time.time() client.add_device(adcCh, "energysensor") def readadc(adcnum): read = spi.xfer2([1, 8 + adcnum << 4, 0])
# [agoping] # hostaddress=8.8.8.8,192.168.1.1 # devicename=Google,router # check_time=15 # # *NOTE* First host address matches first devicename, second matches # second, etc check_time is the time (seconds) between each check import agoclient import threading import time import os import sys readHostaddress = agoclient.get_config_option( "agoping", "hostaddress", "8.8.8.8,192.168.1.1") hostaddress = map(str, readHostaddress.split(',')) readDevicename = agoclient.get_config_option( "agoping", "devicename", "Google,Router") devicename = map(str, readDevicename.split(',')) client = agoclient.AgoConnection("agoping") for name in devicename: client.add_device(name, "binarysensor") hostdevices = dict(zip(hostaddress, devicename)) last_seen = {}
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-")
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={ '_http_id': http_id, 'exec': 'devlist' }, auth=requests.auth.HTTPBasicAuth(username, password)) tomato = { param: json.loads(value.replace("\'", '\"'))
# import agoclient 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.get_config_option("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 = "" if "templow" in content: print "templow on " + internalid + " set to " + content["templow"] s0.write('{"content": { "variable":"AirTemperature.low", "value": "%s"}}' % int(content["templow"]))
#! /usr/bin/env python import sys import syslog import ow import time import threading import agoclient CLIENT = agoclient.AgoConnection("owfs") DEVICE = agoclient.get_config_option("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(str(DEVICE)) except ow.exNoController: syslog.syslog(syslog.LOG_ERROR, "can't open one wire device, aborting") time.sleep(5)
import time import logging import json import base64 from qpid.datatypes import uuid4 client = None server = None units = {} devices = {} rooms = {} EVENT_BLACKLIST = ['event.environment.timechanged'] from socket import socket CARBON_SERVER = agoclient.get_config_option("graphite", "carbon_server", "127.0.0.1") CARBON_PORT = agoclient.get_config_option("graphite", "carbon_port", "2003") PATH_PREFIX = agoclient.get_config_option("graphite", "path_prefix", "home") sock = socket() try: sock.connect( (CARBON_SERVER,CARBON_PORT) ) except: print "Couldn't connect to %(server)s on port %(port)d, is carbon-agent.py running?" % { 'server':CARBON_SERVER, 'port':CARBON_PORT } sys.exit(1) #logging.basicConfig(filename='/opt/agocontrol/agoscheduler.log', level=logging.INFO, format="%(asctime)s %(levelname)s : %(message)s") logging.basicConfig(level=logging.INFO, format="%(asctime)s %(name)s %(levelname)s : %(message)s") #================================= #classes #=================================
if tempC <> self.lastTempC: self.lastTempC = tempC if (TempUnits == 'f' or TempUnits == 'F'): tempF = 9.0/5.0 * tempC + 32.0 client.emit_event(devId, "event.environment.temperaturechanged", tempF, "degF") else: client.emit_event(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.get_config_option("temperaturnu", "debug", "false").lower() == "true"): debug = True lat = agoclient.get_config_option("system","lat","0") lon = agoclient.get_config_option("system","lon","0") mailadress = agoclient.get_config_option("system","mailadress","none") units = agoclient.get_config_option("system","units","SI") TempUnits = "C" if units.lower() == "us": TempUnits = "F" readWaitTime = int(agoclient.get_config_option("temperaturnu","waittime","300")) if readWaitTime < 300: #Used to guarantie minumum 5 minutes between API calls readWaitTime = 300
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.get_config_option("enigma2", "hosts", "") try: hosts = map(str, hostsconfig.split(',')) except: syslog.syslog(syslog.LOG_NOTICE, 'no static hosts defined') else: for host in hosts: client.add_device(host, "settopbox") syslog.syslog(syslog.LOG_NOTICE, "discovering devices") def mycallback(name, host, port): if "dm500hd" in name or "dm600pvr" in name: # print "callback %s %s %s\n" % (name, host, port) try:
#!/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.get_config_option("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.add_device(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 def getstatus(host, port):
#!/usr/bin/python import agoclient import threading import time import logging readInterface = agoclient.get_config_option("x10","interface","CM11") readPort = agoclient.get_config_option("x10", "device", "/dev/ttyUSB1") if (readInterface == "CM11"): from x10.controllers.cm11 import CM11 dev = CM11(readPort) elif (readInterface == "CM15"): from x10.controllers.cm15 import CM15 dev = CM15(readPort) elif (readInterface == "CM17a"): from x10.controllers.cm17a import CM17a dev = CM17A(readPort) dev.open() # Dictionaries to decrypt hex values sent from CM11A to house/device codes as well as function on/off # Other functions exist but on/off are the only ones handled. All other functions are ignored # Functions are displayed as decimal values ON = 255 and OFF = 0 # See http://www.smarthome.com/manuals/protocol.txt for details x10_house = {'6': 'A', 'e': 'B', '2': 'C', 'a': 'D', '1': 'E', '9': 'F', '5': 'G', 'd': 'H', '7': 'I', 'f': 'J', '3': 'K', 'b': 'L', '0': 'M', '8': 'N', '4': 'O', 'c': 'P'} x10_device = {'6': '1', 'e': '2', '2': '3', 'a': '4', '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'}
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.get_config_option("apc", "host", "127.0.0.1") APCPORT = int(agoclient.get_config_option("apc", "port", "161")) APCVOLTAGE = int(agoclient.get_config_option("apc", "voltage", "220")) APCCOMMUNITYRO = agoclient.get_config_option("apc", "community_readonly", "public") APCCOMMUNITYRW = agoclient.get_config_option("apc", "community_readwrite", "private") # route stderr to syslog class LogErr: """Log errors.""" def write(self, data): """Log errors.""" syslog.syslog(syslog.LOG_ERR, data)
# CONFDIR/conf.d/raspiGPIO.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.get_config_option("raspiGPIO", "inputs", "") readOutputs = agoclient.get_config_option("raspiGPIO", "outputs", "") reverse = agoclient.get_config_option("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 GPIO.setup(pin, GPIO.IN) client.add_device(pin, "binarysensor")
import agoclient import threading import time import gps import math client = agoclient.AgoConnection("gps") device = "gps-1" client.add_device(device, "gpssensor") #Init vars core_lat = float(agoclient.get_config_option("system", "lat", "")) core_long = float(agoclient.get_config_option("system", "lon", "")) lastreporttime = time.time() def calculateDistance(lat1, long1, lat2, long2): # Convert latitude and longitude to # spherical coordinates in radians. try: degrees_to_radians = math.pi/180.0 phi1 = (90.0 - lat1)*degrees_to_radians phi2 = (90.0 - lat2)*degrees_to_radians
# 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.get_config_option("raspiMCP3xxxGPIO", "SPIMOSI", "10")) SPIMISO = int(agoclient.get_config_option("raspiMCP3xxxGPIO", "SPIMISO", "9")) SPICLK = int(agoclient.get_config_option("raspiMCP3xxxGPIO", "SPICLK", "11")) SPICS = int(agoclient.get_config_option("raspiMCP3xxxGPIO", "SPICS", "8")) vDiv = float(agoclient.get_config_option("raspiMCP3xxxGPIO", "voltage_divider", "1")) readInputs = agoclient.get_config_option("raspiMCP3xxxGPIO", "inputs", "0,1") interval = int(agoclient.get_config_option("raspiMCP3xxxGPIO", "interval", "60")) change = float(agoclient.get_config_option("raspiMCP3xxxGPIO", "change", "0.1")) inputs = map(int, readInputs.split(',')) deviceconfig = {} for adcCh in inputs: deviceconfig[(adcCh, 'value')] = 0 deviceconfig[(adcCh, 'lastreporttime')] = time.time()
if content["command"] == "off": print "switching off: " + internalid CLIENT.emit_event(internalid, "event.device.statechanged", "0", "") # specify our message handler method CLIENT.add_handler(message_handler) # if you need to fetch any settings from config.ini, # use the get_config_option call. The first parameter # is the section name in the file (should be your instance name) # the second one is the parameter name, and the third one # is the default value for the case when nothing is set in the config.ini print agoclient.get_config_option("example", "parameter", "0") # of course you need to tell the CLIENT library about the # devices you provide. The add_device call expects a internal id # and a device type (you can find all valid types in the # schema.yaml configuration file). The internal id is whatever # you're using in your code to distinct your devices. # Or the pin number of some GPIO output. Or the IP of a # networked device. Whatever fits your device specific stuff. # The persistent translation to a ago control uuid will be # done by the CLIENT library. The mapping is stored as a json # file in CONFDIR/uuidmap/<instance name>.json # you don't need to worry at all about this, when the # message_handler is called, you'll be passed the internalid # for the device that you did specifiy when using add_device()
# Squeezebox client # # copyright (c) 2013 James Roberts <*****@*****.**> # Using agoclient sample code as guidance! import agoclient import squeezeboxserver import threading import time client = agoclient.AgoConnection("squeezebox") # if you need to fetch any settings from config.ini, use the get_config_option call. The first parameter is the section name in the file (should be yor instance name) # the second one is the parameter name, and the third one is the default value for the case when nothing is set in the config.ini server = agoclient.get_config_option("squeezebox", "server", "127.0.0.1:9000") print "Server: " + server squeezebox = squeezeboxserver.SqueezeboxServer(server) # 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 squeezebox.power(internalid, content["command"])