Verisure python to domoticz
Moderator: leecollings
Verisure python to domoticz
Hi!
I dont have a clue, therfore my question.
Can someone tell me a way to implement this python to a switch in domoticz?
I have a lock connected to verisure that i want to control, or at least read status for locked or unlocked.
https://github.com/persandstrom/python-verisure
I dont have a clue, therfore my question.
Can someone tell me a way to implement this python to a switch in domoticz?
I have a lock connected to verisure that i want to control, or at least read status for locked or unlocked.
https://github.com/persandstrom/python-verisure
-
- Posts: 110
- Joined: Friday 20 September 2013 18:49
- Target OS: Raspberry Pi / ODroid
- Domoticz version: 2.3530
- Location: Finland
- Contact:
Re: Verisure python to domoticz
You could make python program that starts at boot and in this program you handle all events and status updates.
It is also possible to make separate scripts which you trigger from switches or time based, but then you should realize that every time you run script (like example from github...) You log in Verisure server and then log out again. If you do this 1440 times a day - once in a minute - it could cause a problems and that's why my advice is do one all the time running python code with login in begin and logout in the end. Then you could check if you are still logged in - if not, then you login again.
This is just example from Github
To update values in Domoticz with Python - here is one example: https://www.domoticz.com/wiki/Presence_detection
It is also possible to make separate scripts which you trigger from switches or time based, but then you should realize that every time you run script (like example from github...) You log in Verisure server and then log out again. If you do this 1440 times a day - once in a minute - it could cause a problems and that's why my advice is do one all the time running python code with login in begin and logout in the end. Then you could check if you are still logged in - if not, then you login again.
This is just example from Github
Code: Select all
import verisure
myPages = verisure.MyPages('[email protected]', 'password')
myPages.login()
overviews = myPages.get_overviews()
myPages.logout()
-
- Posts: 110
- Joined: Friday 20 September 2013 18:49
- Target OS: Raspberry Pi / ODroid
- Domoticz version: 2.3530
- Location: Finland
- Contact:
Re: Verisure python to domoticz
So first thing is load zip-file from Github: https://github.com/persandstrom/python-verisure -> Download ZIP - button
Then unpack. I suppose that you have Python installed?
In command line:
This way you are able to see what do you have and what info you could use.
I have for example something like:
alarm
. status: unarmed
. notAllowedReason:
. name: **************
. label: Disarmed
. date: Today 14:56
. type: ARM_STATE
. id: 1
. changeAllowed: True
climate
. plottable: True
. temperatureBelowMinAlertValue:
. humidityBelowMinAlertValue:
. temperatureAboveMaxAlertValue:
. monitorable: False
. humidityAboveMaxAlertValue:
. humidity:
. location: ********
. timestamp: Today 18:19
. type: Siren
. id: **** ****
. temperature: 22.7°
You probably can also see your lock and so on.
When you know what you need then install module for Python: and you can use verisure in your Python code with import verisure.
Then unpack. I suppose that you have Python installed?
In command line:
Code: Select all
python verisure.py <YOUR EMAIL> <YOUR PASSWORD> get all
I have for example something like:
alarm
. status: unarmed
. notAllowedReason:
. name: **************
. label: Disarmed
. date: Today 14:56
. type: ARM_STATE
. id: 1
. changeAllowed: True
climate
. plottable: True
. temperatureBelowMinAlertValue:
. humidityBelowMinAlertValue:
. temperatureAboveMaxAlertValue:
. monitorable: False
. humidityAboveMaxAlertValue:
. humidity:
. location: ********
. timestamp: Today 18:19
. type: Siren
. id: **** ****
. temperature: 22.7°
You probably can also see your lock and so on.
When you know what you need then install module for Python:
Code: Select all
pip install vsure
-
- Posts: 110
- Joined: Friday 20 September 2013 18:49
- Target OS: Raspberry Pi / ODroid
- Domoticz version: 2.3530
- Location: Finland
- Contact:
Re: Verisure python to domoticz
After you have installed module then you could write simple Pyhton script to get some data from your equipment:
verisure_getTemp.py
When you execute this from command line: python verisure_getTemp.py it will shortly print out temperature for you.
Same idea goes for your lock:
However I don't have a lock so I'm not sure about syntax, but here is part from Smartplug and Lock code:
Smartplug:
Lock:
Code: Select all
import verisure
myPages = verisure.MyPages('<YOUR EMAIL>', '<YOUR PASSWORD>')
myPages.login()
climate_overview = myPages.climate.get()
myPages.logout()
print(climate_overview[0].temperature)
When you execute this from command line: python verisure_getTemp.py it will shortly print out temperature for you.
Same idea goes for your lock:
Code: Select all
mport verisure
myPages = verisure.MyPages('<YOUR EMAIL>', '<YOUR PASSWORD>')
myPages.login()
myPages.lock.set('<YOUR ALARM CODE>', '<YOUR LOCK ID>', 'LOCKED')
myPages.logout()
However I don't have a lock so I'm not sure about syntax, but here is part from Smartplug and Lock code:
Smartplug:
Code: Select all
def set(self, device_id, value):
""" Set device status
Args:
device_id (str): Id of the smartplug
value (str): new status, 'on' or 'off'
"""
data = {
'targetDeviceLabel': device_id,
'targetOn': value
}
return not self._session.post(COMMAND_URL, data)
Code: Select all
def set(self, code, device_id, state):
""" set status of alarm component
Args:
code (str): Personal alarm code (four digits)
device_id (str): lock device id
state (str): 'LOCKED', or 'UNLOCKED'
"""
data = {
'code': code,
'deviceLabel': device_id,
'state': state
}
return not self._session.post(COMMAND_URL, data)
-
- Posts: 110
- Joined: Friday 20 September 2013 18:49
- Target OS: Raspberry Pi / ODroid
- Domoticz version: 2.3530
- Location: Finland
- Contact:
Re: Verisure python to domoticz
Ok. I continue my monologue.
Here is piece of Python:
I don't know too much about programming, but somehow this seems to work. This is script that is running in my Domoticz server. From Domoticz I can use Lua scripts to ask and set status of the Verisure system. I just want to find out how is it possible to visualize some data from my Verisure. Feel free to use and improve this code. I think that I'm not capable to give any support so basically it is what it is.
As you can see I haven't implement all functions, but it shouldn't be too hard to do.
Here is piece of Python:
Code: Select all
# Verisure alarm control script with verisure library
#
# In Domoticz Lua:
# reply = os.execute ("curl --data '{\"get_temperature\"}' http://<YOUR_IP:PORT>/&")
#
# Message types:
# {\"get_alarm\"}
# {\"get_lock\"}
# {\"get_temperature\"}
# {\"get_all\"}
# {\"set_alarm\":\"ARM_AWAY"}, {\"set_alarm\":\"ARM_HOME"}, {\"set_alarm\":\"DISARM"}
# {\"set_lock\":\"LOCK"}, {\"set_lock\":\"UNLOCK"}
import socket
import sys
import time
import verisure # https://github.com/persandstrom/python-verisure
import urllib
host = ''
port = 50001
backlog = 5
size = 1024
myPages = verisure.MyPages('<YOUR_EMAIL>', '<YOUR_PASSWORD>')
def loginVerisure():
try:
myPages.login()
except verisure.session.Error as e:
print (e)
sys.exit()
return
def logoutVerisure():
try:
myPages.logout()
sys.exit()
except verisure.session.Error:
sys.exit()
return
def setAlarm(msg):
if msg == "ARM_AWAY":
msg = "Verisure alarm armed away"
elif msg == "ARM_HOME":
msg = "Verisure alarm armed home"
elif msg == "DISARM":
msg = "Verisure alarm disarmed"
else:
msg = "Err."
return msg;
def setLock(msg):
if msg == "LOCK":
msg = "Verisure door locked"
elif msg == "UNLOCK":
msg = "Verisure door unlocked"
else:
msg = "Err."
return msg;
def getAlarm():
try:
alarm_overview = myPages.alarm.get()
msg = (alarm_overview[0].status).capitalize()
status = urllib.urlopen("http://<DOMOTICZ_IP:PORT>/json.htm?type=command¶m=udevice&idx=<YOUR_DEVICE_ID>&nvalue=0&svalue=" + msg)
except verisure.session.Error as e:
msg = ("Verisure connection broken")
#print (e)
#sys.exit()
return msg;
def getLock():
msg = "Verisure door status"
return msg;
def getTemperature():
try:
climate_overview = myPages.climate.get()
msg = (climate_overview[0].temperature)
msg = (msg[0:(len(msg)-2)])
status = urllib.urlopen("http://<DOMOTICZ_IP:PORT>/json.htm?type=command¶m=udevice&idx=<YOUR_DEVICE_ID>&nvalue=0&svalue=" + msg )
print ("Verisure temperature: " + msg)
except verisure.session.Error as e:
print ("Verisure connection broken")
#print (e)
#sys.exit()
return msg;
def getAll():
msg = "Verisure system status"
return msg;
def decodeMessage(msg):
msg = (msg[(msg.find("{\"")+2):msg.find("\"}")])
msg = msg.replace("\":\"",";")
#print (msg) # debug
tmpParam = msg.split(";")
return tmpParam;
# Create socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(backlog)
# Log in Verisure service
loginVerisure()
while 1:
client, address = s.accept()
data = client.recv(size)
if data:
# print (data) #debug
params = decodeMessage(data)
if len(params) >= 2:
if (params[0] == "set_alarm"):
data = setAlarm(params[1])
elif (params[0] == "set_lock"):
data = setLock(params[1])
else:
data = "Err."
elif len(params) >= 1:
if (params[0] == "get_alarm"):
data = getAlarm()
elif (params[0] == "get_lock"):
data = getLock()
elif (params[0] == "get_temperature"):
data = getTemperature()
elif (params[0] == "get_all"):
data = getAll()
else:
data = "Err."
else:
data = "Err."
client.send(data)
client.close()
As you can see I haven't implement all functions, but it shouldn't be too hard to do.
-
- Posts: 110
- Joined: Friday 20 September 2013 18:49
- Target OS: Raspberry Pi / ODroid
- Domoticz version: 2.3530
- Location: Finland
- Contact:
Re: Verisure python to domoticz
Here is my Lua script_time_verisure.lua:
And here screenshot from Domoticz.
Alarm status is Text device and Temperature is Temperature...
Code: Select all
print('Verisure Status Update')
commandArray = {}
reply = os.execute ("curl --data '{\"get_temperature\"}' http://<YOUR_IP:50001>/&")
reply = os.execute ("curl --data '{\"get_alarm\"}' http://<YOUR_IP:50001/&")
return commandArray
Alarm status is Text device and Temperature is Temperature...
- Attachments
-
- Verisure.png (34.7 KiB) Viewed 10196 times
Re: Verisure python to domoticz
Thank you very much for all your work!
i will give it a try this weekend
But you install python, then pip install vsure module
then you use only the last python script.
in wich folder do you put the python?
i will give it a try this weekend
But you install python, then pip install vsure module
then you use only the last python script.
in wich folder do you put the python?
Re: Verisure python to domoticz
When i run:
I´ll get:
Code: Select all
python verisure.py <YOUR EMAIL> <YOUR PASSWORD> get all
Code: Select all
lock
status: locked
notAllowedReason:
changeAllowed: True
secureMode: False
image: locked
operational: True
location: --------
date: Today 00:44
label: Locked
type: DOOR_LOCK
id: ------------
name: ------ ------------
vacationmode
scheduled: False
-
- Posts: 1
- Joined: Saturday 06 February 2016 18:54
- Target OS: Raspberry Pi / ODroid
- Domoticz version:
- Contact:
Re: Verisure python to domoticz
alfred_j_kwak wrote:Here is my Lua script_time_verisure.lua:And here screenshot from Domoticz.Code: Select all
print('Verisure Status Update') commandArray = {} reply = os.execute ("curl --data '{\"get_temperature\"}' http://<YOUR_IP:50001>/&") reply = os.execute ("curl --data '{\"get_alarm\"}' http://<YOUR_IP:50001/&") return commandArray
Alarm status is Text device and Temperature is Temperature...
alfred_j_kwak: Can you please point me in the right direction...I need information on how to "connect" the graphical boxes in Domoticx with the Verisure module made by "persandstrom". Currently I have Installed Domoticz on my Mac to make development convenient for myself, but my goal in to put it on a RaspberryPi. I´m not a "native" programmer, but I´m able to copy and reason if I get examples and documentation.
-
- Posts: 54
- Joined: Saturday 08 October 2016 12:15
- Target OS: Raspberry Pi / ODroid
- Domoticz version: 2022.1
- Location: The Netherlands
- Contact:
Re: Verisure python to domoticz
The scripts above work, but how did you guys get to run the scripts reliably to get the Verisure status updated?
I have tried to run the scripts several ways (CRON at reboot, init.d, from a .sh file) but every time the script which runs the webserver on port 50001 stops working and I have no clue why. It stops after just 10 minutes or after several hours. But I haven't been able to get it running steadily for 24 hours, which makes it nearly useless.
I already increased the time it checks from 1 to 10 to 30 seconds, as I noticed the Verisure site banned my IP when trying to often, but that hasn't solved the issue.
Any ideas?
Regards,
Martijn
I have tried to run the scripts several ways (CRON at reboot, init.d, from a .sh file) but every time the script which runs the webserver on port 50001 stops working and I have no clue why. It stops after just 10 minutes or after several hours. But I haven't been able to get it running steadily for 24 hours, which makes it nearly useless.
I already increased the time it checks from 1 to 10 to 30 seconds, as I noticed the Verisure site banned my IP when trying to often, but that hasn't solved the issue.
Any ideas?
Regards,
Martijn
-
- Posts: 4
- Joined: Thursday 02 February 2017 21:29
- Target OS: Linux
- Domoticz version: Beta
- Location: Stockholm, Sweden
- Contact:
Re: Verisure python to domoticz
My solution:
IDX 417 is a Dummy Alert - used for AlarmState
IFX 415 is a Dummy Switch - used for Yale Doorman Lock State
main.py
domoticz.py
start.sh
crontab -e
LUA - Device
IDX 417 is a Dummy Alert - used for AlarmState
IFX 415 is a Dummy Switch - used for Yale Doorman Lock State
main.py
Code: Select all
import domoticz
import verisure
import configparser
import time
config = configparser.ConfigParser()
config.read('.cache.cfg')
if not 'verisure' in config.sections():
config.add_section('verisure')
session = verisure.Session('LOGIN', 'PASSWORD')
session.login()
monkey = True
while monkey:
try:
overview = session.get_overview()
except:
monkey = False
armStatus = overview['armState']
if armStatus['statusType'] == 'ARMED_AWAY':
armState = 4
elif armStatus['statusType'] == 'ARMED_HOME':
armState = 3
else:
armState = 1
try:
old_armState = config.getint('verisure', 'armState')
except:
old_armState = None
if isinstance(armState, int) and armState != old_armState:
config.set('verisure', 'armState', str(armState))
domoticz.publish('{"command":"udevice","idx":417,"nvalue":%s,"svalue":"%s"}' % (armState, armStatus['statusType']))
doorStatus = overview['doorLockStatusList'][0]
doorState = doorStatus['currentLockState']
if doorState == 'LOCKED':
doorState = False
else:
doorState = True
try:
old_doorState = config.getboolean('verisure', 'doorState')
except:
old_doorState = None
if isinstance(doorState, bool) and doorState != old_doorState:
config.set('verisure', 'doorState', str(doorState))
if doorState:
domoticz.publish('{"idx":415,"command":"switchlight","switchcmd":"On"}')
else:
domoticz.publish('{"idx":415,"command":"switchlight","switchcmd":"Off"}')
with open('.cache.cfg', 'w') as configfile:
config.write(configfile)
time.sleep(60)
session.logout()
Code: Select all
# -*- coding: utf-8 -*-
import paho.mqtt.client as mqtt
mqttc = mqtt.Client('python_pub')
def publish(message):
mqttc.connect('127.0.0.1', 1883)
mqttc.publish("domoticz/in", message)
Code: Select all
#!/bin/bash
cd /home/domoticz/verisure
until python main.py; do
echo "main.py crashed with exit code $?. Respawning.." >&2
sleep 1
done
Code: Select all
@reboot /usr/bin/screen -dmS verisure /home/domoticz/verisure/start.sh
Code: Select all
alarmState = 'Verisure - Alarm State'
commandArray = {}
if (devicechanged[alarmState] == 'ARMED_AWAY') then
commandArray['Security Panel'] = 'Arm Away'
commandArray['Group:All Lamps'] = 'Off'
elseif (devicechanged[alarmState] == 'ARMED_HOME') then
commandArray['Security Panel'] = 'Arm Home'
commandArray['Group:Alarm Off'] = 'On'
elseif (devicechanged[alarmState] == 'DISARMED') then
commandArray['Security Panel'] = 'Disarm'
commandArray['Group:Alarm Off'] = 'On'
end
return commandArray
-
- Posts: 4
- Joined: Thursday 02 February 2017 21:29
- Target OS: Linux
- Domoticz version: Beta
- Location: Stockholm, Sweden
- Contact:
Re: Verisure python to domoticz
After spending a bit more time on it I came up with this solution. This solution do not poll, it just fetches statuses when it gets an email from Verisure via Sendgrid Inbound Email.
https://github.com/clearminds/verisure-inbound
https://github.com/clearminds/verisure-inbound
-
- Posts: 3
- Joined: Sunday 26 February 2017 0:25
- Target OS: Raspberry Pi / ODroid
- Domoticz version:
- Contact:
Re: Verisure python to domoticz
I'm working on using this idea:
https://github.com/DevvAndreas/VerisureOpenHabMQTT
to just run a pyhton script qnd publish to MQTT so the data is vissible in domoticz, but my knowledge at this point is to limited.
How do i get the date in the phyton script to MQTT?
And if i run the script i get an error on line 1 import : Command unknown
Thx for the advice
https://github.com/DevvAndreas/VerisureOpenHabMQTT
to just run a pyhton script qnd publish to MQTT so the data is vissible in domoticz, but my knowledge at this point is to limited.
How do i get the date in the phyton script to MQTT?
And if i run the script i get an error on line 1 import : Command unknown
Thx for the advice
-
- Posts: 1
- Joined: Thursday 23 March 2017 20:31
- Target OS: Raspberry Pi / ODroid
- Domoticz version: beta
- Location: Aalst, Belgium
- Contact:
Re: Verisure python to domoticz
I did something similar to clearminds' solution, I just run this script every 5 minutes (I've gotten warning emails from verisure when I update it too often):
(yes my code is ugly, I had to learn python just for this)
of course you have to create the virtual switches first and use the right ID's
(yes my code is ugly, I had to learn python just for this)
Code: Select all
#!/usr/bin/python3
import verisure
import urllib
myPages = verisure.Session('----username-----', '------pass-----')
myPages.login()
overview = myPages.get_overview()
climate_overview = overview['climateValues']
climate_kelder = climate_overview[0]
climate_living = climate_overview[2]
climate_gang = climate_overview[1]
climate_keuken = climate_overview[3]
alarm_overview = myPages.get_arm_state()
myPages.logout()
def updateTemp( idx, inTemp, inHum ):
temperature=str(inTemp)
humidity=str(inHum)
setValue=temperature + ";" + humidity + ";0"
params = urllib.parse.urlencode({'type': 'command','param': 'udevice', 'idx': idx, 'nvalue': 0, 'svalue': setValue})
get = urllib.request.urlopen("http://127.0.0.1:8080/json.htm?%s" % params)
return;
# kelder
updateTemp(26, climate_kelder['temperature'], climate_kelder['humidity'])
# living
updateTemp(24, climate_living['temperature'], climate_living['humidity'])
# gang
updateTemp(27, climate_gang['temperature'], climate_gang['humidity'])
# keuken
updateTemp(25, climate_keuken['temperature'], climate_living['humidity'])
alarmStatus = alarm_overview['statusType']
if alarmStatus == 'DISARMED':
aLevel = 10
elif alarmStatus == 'ARMED_HOME':
aLevel = 20
elif alarmStatus == 'ARMED_AWAY':
aLevel = 30
# update alarm status
params = urllib.parse.urlencode({'type': 'command', 'param': 'switchlight', 'idx': '31', 'switchcmd': 'Set Level', 'level': aLevel})
get = urllib.request.urlopen("http://127.0.0.1:8080/json.htm?%s" % params)
-
- Posts: 6
- Joined: Tuesday 11 April 2017 16:19
- Target OS: Raspberry Pi / ODroid
- Domoticz version:
- Contact:
Re: Verisure python to domoticz
I've also had a go at this, as I actually wanted to import the info and learn python at the same time.
This script is currently missing some error handling, so it's "beta" at best
I run this from cron every 10 minutes.
Run it for the first time, It'll create a file called vsure.ini, in which you have to fill in the necessary info:
where the identifiers in [sensorindex] are the serial numbers of the different verisure components.
Run the script, It'll push the updates straight into Domoticz. I have no smartplugs, so I haven't added any info for those yet.
This script is currently missing some error handling, so it's "beta" at best
I run this from cron every 10 minutes.
Code: Select all
#!/usr/bin/python3
import argparse
import arrow
import configparser
import logging
import json
import os.path
import urllib.request
import verisure
# Version 0.1
# Author: Jan De Luyck ([email protected])
#
# This script depends on the verisure module by Per Sandström, which you can find at https://github.com/persandstrom/python-verisure
#
# Notes: if you want additional sensors to be added, supply me with the output of
# vsure 'user' 'password' overview
#
#
################################
# Device config
# Create a dummy hardware device, and add per item you want in Domoticz a Virtual Sensor
# - Temperature + Humidity: smoke detectors
# - Temperature: Siren
# - Switch: door/window locks, ethernet status, arm state
# - Custom Sensor (X Axis: SMS count): SMS
#
# Add the Verisure identifiers _and_ the device ID's (which you can find on the devices view) to vsure.ini (or your own ini file)
# Please keep the identifiers 'sms count' and 'arm state' for the smscount and alarm state respectively
#################################
def parseArgs():
parser = argparse.ArgumentParser(description = 'Import Verisure information into Domoticz', prog='importVerisure.py')
parser.add_argument('-l', '--log', dest='logLevel',type=str, choices=['info', 'warning', 'error', 'debug'], help='Specifies the loglevel to be used')
parser.add_argument('-c', '--config', dest='configFile', default='vsure.ini', type=str, help='Name of the configuration file to use (default: %(default)s')
results = parser.parse_args()
return vars(results)
def parseConfig(configFile):
config = configparser.ConfigParser()
if not os.path.isfile(configFile):
logging.debug('Config file %s does not exist, creating dummy', configFile)
# create a 'new' config file and write it
config['domoticz'] = { 'protocol' : 'http', 'host':'localhost', 'port':'8080'}
config['verisure'] = { 'username':'', 'password':''}
config['global'] = { 'loglevel':'warning', 'timezone':'local'}
config['sensorindex'] = { 'sms count':'XX', 'arm state':'XX', 'AAAA BBBB':'XX'}
with open(configFile, 'w') as file:
config.write(file)
print ("A default (empty) config file was written as %s. Please review and re-run this script.", configFile)
exit (1)
else:
config.read(configFile)
return config
def callDomoticz(URL):
logging.debug ('** Entered CallDomoticz(%s) **', URL)
response = urllib.request.urlopen(URL)
httpOutput = response.read().decode('utf-8')
output = json.loads(httpOutput)
logging.debug ('Output: %s', output)
if output['status'] == 'OK':
if 'result' in output:
returnValue = output['result'][0]
else:
returnValue = output
else:
returnValue = -1
logging.error ('ERROR: error occurred querying Domoticz! Full output available in debug.')
return returnValue
def getLastDomoticzUpdatedTimestamp(deviceIndex):
logging.debug ('** Entered getLastDomoticzUpdatedTimestamp(%s) **', deviceIndex)
output = callDomoticz(domoticzUrl + 'type=devices&rid=' + str(deviceIndex))
if output != -1:
returnValue = arrow.get(arrow.get(output['LastUpdate']).naive, config['global']['timezone']).timestamp
else:
returnValue = output
logging.debug('Return value: %s', str(returnValue))
return returnValue
def getVerisureInfo(verisureUser, verisurePw):
logging.debug ('** Entered getVerisureInfo(username,password) **')
# Connect to Verisure and get all the data
verisureSession = verisure.Session(verisureUser, verisurePw);
verisureSession.login()
verisureOverview = verisureSession.get_overview()
verisureSession.logout()
logging.debug ('Verisure output:')
logging.debug ('************************')
logging.debug (verisureOverview)
logging.debug ('************************')
return verisureOverview
def processUpdates(deviceType, sensorIdx, deviceLastUpdated, device):
if 'deviceLabel' not in device:
device['deviceLabel'] = deviceType.upper()
logging.info ('Now processing device %s (sensorIdx %s)', device['deviceLabel'], sensorIdx)
# get last updated time in Domoticz
lastUpdatedDomoticz = getLastDomoticzUpdatedTimestamp(sensorIdx)
if lastUpdatedDomoticz != -1:
logging.info (' - Last Updated in Domoticz: %s', arrow.get(lastUpdatedDomoticz).naive)
# Last updated on Verisure
lastUpdatedVerisure = arrow.get(deviceLastUpdated).timestamp
logging.info (' - Last updated in Verisure: %s', arrow.get(lastUpdatedVerisure).naive)
if lastUpdatedVerisure > lastUpdatedDomoticz:
# Climate devices
if deviceType == 'climate':
logging.info (' - Updating temperature to %s', str(device['temperature']))
requestUrl = 'type=command¶m=udevice&idx=' + sensorIdx + '&nvalue=0&svalue=' + str(device['temperature'])
if 'humidity' in device:
logging.info (' - Updating humidity to %s', str(device['humidity']))
requestUrl += ';' + str(device['humidity']) + ';0'
elif deviceType == 'doorwindow':
# doorWindow locks
if device['state'] == 'CLOSE':
switchState = 'Off'
elif device['state'] == 'OPEN':
switchState = 'On'
logging.info (' - Updating switch status to %s', switchState)
requestUrl = 'type=command¶m=switchlight&idx=' + sensorIdx + '&switchcmd=' + switchState
elif deviceType == 'smscount':
# SMS Count
logging.info (' - Updating SMS count to %s', device['totalSmsCount'])
requestUrl = 'type=command¶m=udevice&idx=' + sensorIdx + '&nvalue=0&svalue=' + str(device['totalSmsCount'])
elif deviceType == 'armstate':
# Alarm Arm status
if device['statusType'] == "DISARMED":
alarmState = 'Off'
else:
alarmState = 'On'
logging.info (' - Updating alarm state to %s', alarmState)
requestUrl = 'type=command¶m=switchlight&idx=' + sensorIdx + '&switchcmd=' + alarmState
elif deviceType == 'ethstate':
# Ethernet status
if device['latestEthernetTestResult'] == True:
ethernetState = 'On'
else:
ethernetState = 'Off'
logging.info (' - Updating ethernet state to %s', ethernetState)
requestUrl = 'type=command¶m=switchlight&idx=' + sensorIdx + '&switchcmd=' + ethernetState
else:
logging.error ('ERROR: Unknown device type!')
requestUrl = None
if requestUrl != None:
output = callDomoticz(domoticzUrl + requestUrl)
if output == -1:
logging.error ('ERROR: Update not sent to Domoticz for device %s!', sensorIdx)
else:
logging.info (' - Update sent successfully to Domoticz')
else:
logging.info (' - Not updating Domoticz')
else:
logging.error ('ERROR: something went wrong querying Domoticz!')
# Execute script
if __name__ == '__main__':
# Parse command line
arguments = parseArgs()
# Read config
config = parseConfig(arguments["configFile"])
# Overwrite loglevel, it can be passed on command line
if arguments['logLevel'] != None:
config['global']['loglevel'] = str(arguments['logLevel'])
# Switch default log level
logging.basicConfig(format='%(asctime)s %(message)s', level=getattr(logging, config['global']['loglevel'].upper()))
# Construct Domoticz url
domoticzUrl = config['domoticz']['protocol'] + '://' + config['domoticz']['host'] + ':' + config['domoticz']['port'] + '/json.htm?'
verisureOverview = getVerisureInfo(config['verisure']['username'], config['verisure']['password'])
# Process climateValues
for device in verisureOverview['climateValues']:
if device['deviceLabel'] in config['sensorindex']:
processUpdates('climate', config['sensorindex'][device['deviceLabel']], device['time'], device)
# Process DoorWindowDevices
for device in verisureOverview['doorWindow']['doorWindowDevice']:
if device['deviceLabel'] in config['sensorindex']:
processUpdates('doorwindow', config['sensorindex'][device['deviceLabel']], device['reportTime'], device)
# Process SMS
processUpdates('smscount', config['sensorindex']['sms count'], arrow.now(), verisureOverview)
# Process Alarm State
processUpdates('armstate', config['sensorindex']['arm state'], verisureOverview['armState']['date'], verisureOverview['armState'])
# Process Ethernet State
processUpdates('ethstate', config['sensorindex'][verisureOverview['latestEthernetStatus']['deviceLabel']], verisureOverview['latestEthernetStatus']['testDate'], verisureOverview['latestEthernetStatus'])
Code: Select all
[domoticz]
protocol=http
host=localhost
port=8080
[global]
timezone=local
loglevel=warning
[verisure]
[email protected]
password=superfancypassword
[sensorindex]
AABB CCDD=22
EEFF GGHH=21
IIJJ KKLL=23
MMNN OOPP=28
QQRR SSTT=27
UUVV XXYY=26
ARM STATE=30
SMS COUNT=32
Run the script, It'll push the updates straight into Domoticz. I have no smartplugs, so I haven't added any info for those yet.
-
- Posts: 148
- Joined: Tuesday 01 October 2013 8:31
- Target OS: Raspberry Pi / ODroid
- Domoticz version: 2023.2
- Location: Sweden
- Contact:
Re: Verisure python to domoticz
Was looking at this thread to get verisure status indication when I stumpled over this thread and which looks interesting. What I'm wondering is how often you're able to poll the status from Verisure without them complaining; like every 5 minutes?
-
- Posts: 1
- Joined: Saturday 19 August 2017 11:25
- Target OS: Raspberry Pi / ODroid
- Domoticz version:
- Contact:
Re: Verisure python to domoticz
Does anyone have any suggestions what to do with this error message?
(My python script is called devilkin )
And any suggestion on how to make this a CRON-task?
Code: Select all
pi@RPI3HA1:~/domoticz/scripts $ python devilkin.py
Traceback (most recent call last):
File "devilkin.py", line 205, in <module>
verisureOverview = getVerisureInfo(config['verisure']['username'], config['verisure']['password'])
File "devilkin.py", line 97, in getVerisureInfo
verisureSession.login()
File "/usr/local/lib/python2.7/dist-packages/verisure/session.py", line 90, in login
self._vid = json.loads(response.text)['cookie']
KeyError: 'cookie'
And any suggestion on how to make this a CRON-task?
-
- Posts: 6
- Joined: Tuesday 11 April 2017 16:19
- Target OS: Raspberry Pi / ODroid
- Domoticz version:
- Contact:
Re: Verisure python to domoticz
No idea. Trial and error.
-
- Posts: 6
- Joined: Tuesday 11 April 2017 16:19
- Target OS: Raspberry Pi / ODroid
- Domoticz version:
- Contact:
Re: Verisure python to domoticz
Eh. The only thing I can say is that I programmed it for Python 3, not 2.7... so perhaps it's a syntax issue with python 2.7?lanc wrote: ↑Saturday 19 August 2017 11:29 Does anyone have any suggestions what to do with this error message?
(My python script is called devilkin )Code: Select all
pi@RPI3HA1:~/domoticz/scripts $ python devilkin.py Traceback (most recent call last): File "devilkin.py", line 205, in <module> verisureOverview = getVerisureInfo(config['verisure']['username'], config['verisure']['password']) File "devilkin.py", line 97, in getVerisureInfo verisureSession.login() File "/usr/local/lib/python2.7/dist-packages/verisure/session.py", line 90, in login self._vid = json.loads(response.text)['cookie'] KeyError: 'cookie'
And any suggestion on how to make this a CRON-task?
-
- Posts: 28
- Joined: Tuesday 24 October 2017 9:41
- Target OS: Raspberry Pi / ODroid
- Domoticz version:
- Contact:
Re: Verisure python to domoticz
How do you get Verisure to send an email on arm/disarm?clearminds wrote: ↑Saturday 04 February 2017 10:51 After spending a bit more time on it I came up with this solution. This solution do not poll, it just fetches statuses when it gets an email from Verisure via Sendgrid Inbound Email.
https://github.com/clearminds/verisure-inbound
Domoticz on Rpi, Z-wave, Hue with Philips and Ikea bulbs
Who is online
Users browsing this forum: No registered users and 1 guest