### Device Actions Python

Domoticz supports executing of Device On / Of Actions using Lua, Bash, Python.
Below are two examples:
The first is the basic on how to define a python script for a device,
The second is logging the device on/off state with time stamp.
Raspberry Pi Example 1
Running a Python Device Action for an On/Off Switch.
Domoticz Create a Device from type On/Off Switch.
Set the On Action to: script:///home/pi/domoticz/scripts/python/testscript.py
Create in folder /home/pi/domoticz/scripts/python the file testscript.py.
Example content which appends some text to a file.
#!/usr/bin/python
## Domoticz Python Test Script
##
mylogfile = '/home/pi/domoticz/scripts/python/testscript.log'
f = open(mylogfile, 'a')
f.write('Writing Example')
f.close()
Make the script executable:
sudo chmod +x testscript.py
Set the script owner to user Pi:
sudo chown pi testscript.py
When switching the device on, the text is appended.
Note:
Prior using as Device Action, test the Python script by executing following steps, i.e.
Create/Edit the script, make the script executable, run the script using Python, log the content of the logfile
edit testscript.py
sudo chmod +x testscript.py
python3 testscript.py
cat testscript.log
Raspberry Pi Example 2
As previous, but instead writing some text, the switched state timestamp is written.
The script expects the parameter ON or OFF.
Switch Device On Action
script:///home/pi/domoticz/scripts/python/espledswitch.py ON
Switch Device Off Action
script:///home/pi/domoticz/scripts/python/espledswitch.py OFF
#!/usr/bin/python
##@brief Logging timestamp for switch device named ESP LED Switch
##@author Robert W.B. Linn
##@version 20170605
import sys
from datetime import datetime
state = "unknown"
if len(sys.argv) == 2:
state = sys.argv[1]
logfile = '/home/pi/domoticz/scripts/python/espledswitch.log'
with open(logfile , mode='a') as file:
now = datetime.now();
file.write('LED switched to %s at %s.\n' %
(state, now.strftime("%d-%m-%Y %H:%M:%S")))
file.close()
Output Example:
LED switched to ON at 05-06-2017 13:45:44.
LED switched to OFF at 05-06-2017 13:45:47.
Quick Ref DateTime Placeholder
Current year = %Y
Month of year = %B
Week number of the year = %W
Weekday of the week = %w
Day of year = %j
Day of the month = %d
Day of week = %A
Hour = %H
Minute = %M
Second = %S

Changed: 2018-06-07 09:10, Category: Domoticz Home Automation, File: T6C186M1345.htm, ID: 1345