Ejemplo n.º 1
0
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.getConfigOption("agoscheduler", "all", "[]")
    schedules = json.loads(schedules)
    #and store them in sorted collection
    for schedule in schedules:
        addSchedule(schedule)
    logging.info('Loaded %d schedules' % len(allSchedules))
Ejemplo n.º 2
0
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.getConfigOption("agoscheduler", "all", "[]")
    schedules = json.loads(schedules)
    #and store them in sorted collection
    for schedule in schedules:
        addSchedule(schedule)
    logging.info('Loaded %d schedules' % len(allSchedules))
Ejemplo n.º 3
0
# 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.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
Ejemplo n.º 4
0
					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.addHandler(messageHandler)
devicelist=agoclient.getConfigOption("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.addDevice(device, "onvifnvt")
		else:
			client.addDevice(device, "camera")

client.run()
Ejemplo n.º 5
0
# 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 getConfigOption 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.getConfigOption("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"])
Ejemplo n.º 6
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.getConfigOption("raspi1wGPIO", "interval", "600")
interval = int(readInterval)

change = float(agoclient.getConfigOption("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 = {}
Ejemplo n.º 7
0
            client.emitEvent(internalid, "event.device.statechanged", "255",
                             "")

        if content["command"] == "off":
            print "switching off: " + internalid
            client.emitEvent(internalid, "event.device.statechanged", "0", "")


# specify our message handler method
client.addHandler(messageHandler)

# if you need to fetch any settings from config.ini, use the getConfigOption 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

print agoclient.getConfigOption("example", "parameter", "0")

# of course you need to tell the client library about the devices you provide. The addDevice 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 /etc/opt/agocontrol/uuidmap/<instance name>.json
# you don't need to worry at all about this, when the messageHandler is called, you'll be passed the internalid for the device that you did specifiy when using addDevice()

# we add a switch and a dimmer
client.addDevice("123", "dimmer")
client.addDevice("124", "switch")
# for our threading example in the next section we also add a binary sensor:
client.addDevice("125", "binarysensor")

# then we add a background thread. This is not required and just shows how to send events from a separate thread. This might be handy when you have to poll something
# 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.
Ejemplo n.º 8
0
#
# 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

import time

readID = agoclient.getConfigOption("weather","locations_ID","90210")
readTempUnits = agoclient.getConfigOption("weather","tempunits","f")
readWaitTime = int(agoclient.getConfigOption("weather","waittime","300"))
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)
Ejemplo n.º 9
0
    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...')
    library = pylmslibrary.LMSLibrary(host, port, login, passwd)
    playlist = pylmsplaylist.LMSPlaylist(library, host, port, login, passwd)
    #play, pause, stop, on, off, add, del, move, reload
Ejemplo n.º 10
0
        #     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:
    if 'SensorPollDelay' in config['tellstick']:
        SensorPollDelay = config['tellstick']['SensorPollDelay']
except KeyError:
Ejemplo n.º 11
0
    client.emitEvent(internalid, "event.mediaplayer.statechanged", "pause", "")
    client.emitEvent(internalid, "event.device.mediastatechanged", str(STATE_PAUSE), "")
def emit_on(internalid):
    client.emitEvent(internalid, "event.device.statechanged", str(STATE_ON), "")
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...')
    library = pylmslibrary.LMSLibrary(host, port, login, passwd)
    playlist = pylmsplaylist.LMSPlaylist(library, host, port, login, passwd)
    #play, pause, stop, on, off, add, del, move, reload
Ejemplo n.º 12
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 = {}

for adcCh in inputs:
    deviceconfig[(adcCh, 'value')] = 0
Ejemplo n.º 13
0
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 = ""
                if "templow" in content:
                    print "templow on " + internalid + " set to " + content[
Ejemplo n.º 14
0
# 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 = {}

for adcCh in inputs:
    deviceconfig[(adcCh, 'value')] = 0 
    deviceconfig[(adcCh, 'lastreporttime')] = time.time()
Ejemplo n.º 15
0
                            if tempC <> self.lastTempC:
                                self.lastTempC = tempC
                                if (TempUnits == 'f' or TempUnits == 'F'):
                                        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"))

if readWaitTime < 300: #Used to guarantie minumum 5 minutes between API calls
    readWaitTime  = 300
Ejemplo n.º 16
0
        #     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:
    if 'SensorPollDelay' in config['tellstick']:
        SensorPollDelay = config['tellstick']['SensorPollDelay']
except KeyError:
Ejemplo n.º 17
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.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")


# 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)
Ejemplo n.º 18
0
#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)

Ejemplo n.º 19
0
                try:
                    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.addHandler(messageHandler)

# get config parameters
host = agoclient.getConfigOption("mPower", "host", "127.0.0.1")
username = agoclient.getConfigOption("mPower", "username", "ubnt")
password = agoclient.getConfigOption("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.addDevice(str(i), "switch")
        i = i + 1

Ejemplo n.º 20
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.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")

# 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()


Ejemplo n.º 21
0
#!/usr/bin/python

import agoclient
import threading
import time
import logging

readInterface = agoclient.getConfigOption("x10","interface","CM11")
readPort = agoclient.getConfigOption("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'}
Ejemplo n.º 22
0
                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")
    computers[config["Computers"][y]["name"]] = config["Computers"][y]["mac"]
Ejemplo n.º 23
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"))

if readWaitTime < 300:  #Used to guarantie minumum 5 minutes between API calls
Ejemplo n.º 24
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.getConfigOption("raspi1wGPIO", "interval", "600")
interval = int(readInterval)

change = float(agoclient.getConfigOption("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 = {}

for device in readDevices:
Ejemplo n.º 25
0
                            try:   
				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.addHandler(messageHandler)


# get config parameters
host =  agoclient.getConfigOption("mPower", "host", "127.0.0.1")
username =  agoclient.getConfigOption("mPower", "username", "ubnt")
password = agoclient.getConfigOption("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.addDevice(str(i), "switch")
                i = i + 1

class mPowerEvent(threading.Thread):
Ejemplo n.º 26
0
				t.setCoolPoint(float(content["temperature"]))
				client.emitEvent(internalid, "event.environment.temperaturechanged", content["temperature"], "")
	      	if content["command"] == "setthermostatmode":
	                print "set thermostat mode: " + internalid
	                #client.emitEvent(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.addHandler(messageHandler)

ipAddress =  agoclient.getConfigOption("radiothermostat", "ipaddress", "0.0.0.0")
tempUnit = agoclient.getConfigOption("system", "units", "SI")
#print "IP: ", ipAddress
#print "UNIT: ", tempUnit
t = TStat(ipAddress)
t.setCacheExpiry(15)

client.addDevice(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
Ejemplo n.º 27
0
    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')
    configPushbulletDevices = agoclient.getConfigOption('pushbullet', 'devices', '', 'alert')
    configPushoverUserid = agoclient.getConfigOption('pushover', 'userid', '', 'alert')
    configNotifymyandroidApikeys = agoclient.getConfigOption('notifymyandroid', 'apikeys', '', 'alert')
Ejemplo n.º 28
0
#

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.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 = ""
				if "templow" in content:
					print "templow on " + internalid + " set to " + content["templow"]
					s0.write('{"content": { "variable":"AirTemperature.low", "value": "%s"}}' % int(content["templow"]))
Ejemplo n.º 29
0
import socket
import traceback
import syslog

remote  = 'python remote'
app     = 'agocontrol'
tvmodel = "LE32C650"

client = agoclient.AgoConnection("TvSamsung")

def log_exception(exc):
    for line in exc.split('\n'):
        if len(line):
            syslog.syslog(syslog.LOG_ERR, line)

hostsconfig = agoclient.getConfigOption("tvsamsung", "hosts", "192.168.14.50")
tvs={}
hosts=[]
try:
    hosts = map(str, hostsconfig.split(','))
except:
    syslog.syslog(syslog.LOG_ERR, 'Error when reading hosts TVs')
else:
    for host in hosts:
        try :
            if os.system('ping -c 2 ' + host):
                syslog.syslog(syslog.LOG_WARNING, 'No response to ping from %s'%host)
            else :
                pid = Popen(["/usr/sbin/arp", "-n", host], stdout=PIPE)
                s = pid.communicate()[0]
                macaddress = re.search(r"(([a-f\d]{1,2}\:){5}[a-f\d]{1,2})", s).groups()[0]
Ejemplo n.º 30
0
#!/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

def getstatus(host, port):
Ejemplo n.º 31
0
    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')
    configPushbulletDevices = agoclient.getConfigOption('pushbullet', 'devices', '', 'alert')
    configPushoverUserid = agoclient.getConfigOption('pushover', 'userid', '', 'alert')
    configNotifymyandroidApikeys = agoclient.getConfigOption('notifymyandroid', 'apikeys', '', 'alert')
Ejemplo n.º 32
0
# ago Weather device
# Copyright (c) 2013 by rages
#
# 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.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, ):
Ejemplo n.º 33
0
#!/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 ,
Ejemplo n.º 34
0
#/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
		GPIO.setup(pin, GPIO.IN)
		client.addDevice(pin, "binarysensor")
Ejemplo n.º 35
0
                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.addHandler(messageHandler)
devicelist = agoclient.getConfigOption("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.addDevice(device, "onvifnvt")
        else:
            client.addDevice(device, "camera")

client.run()
Ejemplo n.º 36
0
# 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 getConfigOption 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.getConfigOption("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"])
Ejemplo n.º 37
0

# 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")


def mycallback(name, host, port):
    if "dm500hd" in name or "dm600pvr" in name:
        # print "callback %s %s %s\n" % (name, host, port)
Ejemplo n.º 38
0
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")

def mycallback(name, host, port):
	if "dm500hd" in name or "dm600pvr" in name:
		# print "callback %s %s %s\n" % (name, host, port)
		try:
Ejemplo n.º 39
0
        '''
        self._tdlib.tdStop(c_int(deviceid))

    def methods(self, deviceid, methods):
        '''
        Stop the shutter.
        Test if the device support the up command
        If not try to manage it supporting the on command
        @param deviceid : id of the module
        '''
        #int methods = tdMethods(id, TELLSTICK_TURNON | \
        #    TELLSTICK_TURNOFF | TELLSTICK_BELL);
        return self._tdlib.tdMethods(c_int(deviceid), methods)

client = agoclient.AgoConnection("tellstick")
device = agoclient.getConfigOption("tellstick", "device", "/dev/tellstick")
delay_rf = float(agoclient.getConfigOption("tellstick", "delay_rf", "400"))

lib = Telldusd()
sensor_func = SENSORFUNC(sensor_callback)
device_func = DEVICEFUNC(device_callback)
raw_func = RAWFUNC(raw_callback)

lib.register_sensor_event(sensor_func)
lib.register_device_event(device_func)
lib.register_device_change_event(raw_func)

devices=lib.get_devices()
for dev in devices.keys() :
    if lib.is_dimmer(dev) :
        client.addDevice(lib.make_device_id(dev), "dimmer")
Ejemplo n.º 40
0
#! /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)
Ejemplo n.º 41
0
                client.emitEvent(internalid,
                                 "event.environment.temperaturechanged",
                                 content["temperature"], "")
        if content["command"] == "setthermostatmode":
            print "set thermostat mode: " + internalid
            #client.emitEvent(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.addHandler(messageHandler)

ipAddress = agoclient.getConfigOption("radiothermostat", "ipaddress",
                                      "0.0.0.0")
tempUnit = agoclient.getConfigOption("system", "units", "SI")
#print "IP: ", ipAddress
#print "UNIT: ", tempUnit
t = TStat(ipAddress)
t.setCacheExpiry(15)

client.addDevice(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)
Ejemplo n.º 42
0
ex_humidity = "%s-humidity-%s"
ex_pressure = "%s-pressure-%s"
ex_windspeed = "%s-windspeed-%s"
ex_windangle = "%s-windangle-%s"
ex_rain3h = "%s-rain3h-%s"
ex_cloud = "%s-cloud-%s"
ex_snow3h = "%s-snow3h-%s"

def log_exception(exc):
    for line in exc.split('\n'):
        if len(line):
            syslog.syslog(syslog.LOG_ERR, line)

client = agoclient.AgoConnection("Weather")

weatherconfig = agoclient.getConfigOption("weather","locations","Dijon,France")
locations=[]
fails={}
try:
    locations = map(str, weatherconfig.split(','))
except:
    syslog.syslog(syslog.LOG_ERR, 'Error when reading weather locations')
else:
    if '' in locations :
        locations.remove('')
    for loc in locations:
        try :
            client.addDevice(ex_rain%(loc,0), "binarysensor")
            client.addDevice(ex_temp%(loc,0), "temperaturesensor")
            client.addDevice(ex_humidity%(loc,0), "multilevelsensor")
            client.addDevice(ex_pressure%(loc,0), "multilevelsensor")
Ejemplo n.º 43
0
                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")
    computers[config['Computers'][y]['name']] = config['Computers'][y]['mac']
Ejemplo n.º 44
0
import agoclient
import time
import traceback
import bluetooth
import threading
from threading import Timer
import syslog

client = agoclient.AgoConnection("Bluescan")

def log_exception(exc):
    for line in exc.split('\n'):
        if len(line):
            syslog.syslog(syslog.LOG_ERR, line)

method = agoclient.getConfigOption("bluescan","method","lookup")
scan_delay = int(agoclient.getConfigOption("bluescan","delay-scan","30"))
error_delay = int(agoclient.getConfigOption("bluescan","delay-error","450"))
hysteresis = int(agoclient.getConfigOption("bluescan","hysteresis","3"))
phoneconfig = agoclient.getConfigOption("bluescan","phones","D0:B3:3F:BC:0E:21")
sphones=[]
phones={}
ex_bluescan="bluescan-%s"

try:
    sphones = map(str, phoneconfig.split(','))
except:
    syslog.syslog(syslog.LOG_NOTICE, 'no phone defined')
else:
    for phon in sphones:
        try :
Ejemplo n.º 45
0
#!/usr/bin/python

import agoclient
import threading
import time
import logging

readInterface = agoclient.getConfigOption("x10", "interface", "CM11")
readPort = agoclient.getConfigOption("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',
Ejemplo n.º 46
0
#/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
        GPIO.setup(pin, GPIO.IN)
        client.addDevice(pin, "binarysensor")
Ejemplo n.º 47
0
#!/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