Skip to content

Instantly share code, notes, and snippets.

@glennschler
Last active December 25, 2023 06:34
Show Gist options
  • Save glennschler/f311edb2da6e9828e69f50d1a3896131 to your computer and use it in GitHub Desktop.
Save glennschler/f311edb2da6e9828e69f50d1a3896131 to your computer and use it in GitHub Desktop.
Tasmota, Sonoff, and OpenHab
Add rules

vim $OPENHAB_CONF/rules/default.rules

  1. rule "email Backyard Temperature every morning and every night"
  • OU_Backyard_Temperature must be defined in an .items file
import org.eclipse.smarthome.core.library.types.QuantityType
import org.eclipse.smarthome.core.library.unit.SIUnits

rule "email Backyard Temperature every morning and every night"

when
  Time cron "00 40 06 ? * MON-FRI *" or
  Time cron "00 15 08 ? * SAT,SUN *" or
  Time cron "0 0 21 1/1 * ? *"
then
  val QuantityType<Temperature> myCelsius = new QuantityType<Temperature>(OU_Backyard_Temperature.state, SIUnits.CELSIUS)

  // convert a quantity state into a different unit:
  val myFahrenheit = myCelsius.toUnit("°F")

  val msg = "Temperature = " + myCelsius + " (" + myFahrenheit + ")" +
     "\nHumidty = " + OU_Backyard_Humidity.state + "%" +
     "\nWifi = " + OU_Backyard_Wifi.state + "%"

  val dateStr = String::format( "%1$tl:%1$tM%1$tp %1$tB %1$te", new java.util.Date)
  logInfo("Temperature Notification", msg)
  sendMail("{MyOpenHABUserEmail}@email.com", "Temperatura afuera " + dateStr, msg)
end
  1. rule "Rule update light status on openhab startup"
rule "Rule update light status on openhab startup"
when
  System started
then
  logInfo("RuleParsed", ruleFilename)

  val actions = getActions("mqtt","mqtt:broker:ee9988bb")
  actions.publishMQTT("tasmota/cmnd/sonoff-basic-999/POWER", "")
end
All Tasmota devices
# SetOption65 1 will turn off fast power cycle detection device recovery. This will avoid reset to default
# firmware settings if there are several reboots or brownouts. Warning: there will be no way to reset
# settings without physical access to the device
BACKLOG poweronstate 0; Longitude -68.059105; Latitude -38.951607; Timezone -3; SetOption65 1
Backlog SaveData 600; WifiConfig 4
Sonoff Basic R1

A slight modification of the Tamosta rule cookbook #14

"Using Timers, you can be set to turn on and off a light for iluminate a street/patio by night. But if the Sonoff Device has no power at the trigger time, then, when it powers up, the light will be off all night. So, as a failsafe, can be implemented a conditional control to be checked at Sonoff Startup with rules."

Also as an ehancment to the existing rule, after a 10 second delay, check the current power state, so that MQTT message is published. This is better than a retained MQTT message, so that OpenHAB gets the latest POWER state after a reboot of the ESP8266 Sonoff device.

# Handle case when mains power was cut off and then turned back on
# If before midnight and after sunset, or if before sunrise and after midnight, then turn on the light
# If daytime then turn off the light
Rule1 ON Time#Initialized DO backlog event checksunrise=%time%; event checksunset=%time% ENDON
ON event#checksunset>%sunset% DO power1 1 ENDON
ON event#checksunrise<%sunrise% DO power1 1 ENDON
# reboot everyday at 10am. It was unreachbale via Wifi once, so see if this does anything
Rule2 on Time#Minute==600 do restart 1 endon

Turn on those rules

backlog Rule1 1; Rule2 1
# Set saving of paramters if there are "changes" every 600 seconds
SaveData 600
Sonoff TX T3

Still an open issue with Ghost switching because of capacitor hardware problem with the Sonoff TX switch. NOT the more talked about MQTT ghost switching problem when retain is on. This is attempt to resolve that issue, making the touch screen less sensitive

# - this buttondebounce is still debatable 2020-July
# - poweronstate power OFF after reboot
# - Stop detecting input change on the button GPIO. Solves #5449
# - SetOption40 Active only when SetOption1 1 and SetOption13 0. This disables all long press functionality. 
#     Must reverse to configure the IR remote
Backlog poweronstate 0; SetOption1 1; SetOption13 0; SetOption40 10; buttondebounce 175

# If given the power = blink command, then blink 10 times, every half second
Backlog BlinkCount 10; BlinkTime 5

Lights on and off everyday

BACKLOG Timer1 {"Enable":1,"Mode":2,"Time":"02:05","Window":5,"Days":"1111111","Repeat":1,"Output":2,"Action":0};
Timer2 {"Enable":1,"Mode":1,"Time":"00:00","Window":10,"Days":"1111111","Repeat":1,"Output":2,"Action":1};
Timer3 {"Enable":1, "Arm":1,"Mode":2,"Time":"00:15","Window":10,"Days":"1111111","Repeat":1,"Output":2,"Action":1};
Timer4 {"Enable":1, "Arm":1,"Mode":1,"Time":"01:30","Window":10,"Days":"1111111","Repeat":1,"Output":2,"Action":0};
Timer5 {"Enable":1, "Arm":1,"Mode":2,"Time":"00:05","Window":10,"Days":"1111111","Repeat":1,"Output":3,"Action":1};
Timer6 {"Enable":1, "Arm":1,"Mode":1,"Time":"-00:15","Window":10,"Days":"1111111","Repeat":1,"Output":3,"Action":0};
Timer7 {"Enable":0, "Arm":0,"Mode":0,"Time":"00:00","Window":10,"Days":"1111111","Repeat":0,"Output":1,"Action":0};
Timers 1
# If was rebooted and
# If before midnight and after sunset, or if before sunrise and after midnight, then turn on the light
# For SWITCH #3 only!
Rule1 
  ON Time#Initialized DO backlog event checksunrise=%time%; event checksunset=%time% ENDON
  ON event#checksunset>%sunset% DO power3 1 ENDON 
  ON event#checksunrise<%sunrise% DO power3 1 ENDON

Rule1 1
# Send MQTT msg to another device when 1st button (of 3) is pressed
Rule2 ON button1#state DO publish tasmota/cmnd/sonff-NNN-01/POWER1 toggle ENDON
Backlog Rule1 1; Rule2 1
sonoff-02
# example turn on 6am for one hour, su/tu/th/fr
Timer1 {"Arm":1,"Mode":0,"Time":"06:00","Window":0,"Days":"1010110","Repeat":1,"Output":1,"Action":1}
Timer2 {"Arm":1,"Mode":0,"Time":"07:00","Window":0,"Days":"1010110","Repeat":1,"Output":1,"Action":0}
sonoff-RF
# Modify multi-press actions. React as a single press
# Also send a mqtt topic message when RF button is pressed
#Backlog SetOption1 1; SetOption13 1; ButtonTopic 1

# If the RF is triggered, then tell another switch to blink
Rule1 ON button1#state DO backlog publish tasmota/cmnd/sonff-NN-01/POWER2 blink; publish openhab/cmnd/doorbell-01 pressed; ENDON
Rule1 1
shelly-1pm
# SetOption65 1 will turn off fast power cycle detection device recovery. This will avoid reset to default
# firmware settings if there are several reboots or brownouts. Warning: there will be no way to reset
# settings without physical access to the device
# PowerOnState == 4 == always turn on if rebooted, and do not let it be changed
# PowerOnState == 0 == reboot to be set to off
BACKLOG poweronstate 0; Longitude -68.059105; Latitude -38.951607; Timezone -3; SetOption65 1; NtpServer1 10.12.14.40; NtpServer2 ar.pool.tnp.org

# Now if Power command is give it will turn on for 30 seconds.
Rule1 ON clock#Timer=1 DO Power on ENDON
Timer1 {"Arm":1,"Mode":0,"Time":"04:45","Window":0,"Days":"0100100","Repeat":1,"Output":1,"Action":3}
#NOT WORKING Backlog BlinkCount 1;  BlinkTime 300; Rule1 1
# Pulse time 130 = 130 - 100 = 30 seconds
Backlog PulseTime 130; Rule1 1
# These are the calibration numbers recieved from a factory Sonoff POW R2 when monitoring a 53W incandescent light bulb
BACKLOG WattRes 2; EnergyRes 3; VoltRes 2
PowerSet 54.86
CurrentSet 0.25
VoltageSet 227.48
# I know ~55 watts and ~67 watts and < ~3 watts are repeatable important power states to monitor for my usage case.
# Though still watch for other wattage changes
# Set to report every time the Watts change by 2
PowerDelta 102

paste this text using visudo command

Allow openhab user to execute reboot and poweroff commands
Cmnd_Alias MYSERVICE = \
        /usr/local/bin/oh_stop.sh, \
        /usr/local/bin/oh_restart.sh, \
        /usr/local/bin/oh_restartAT.sh
openhab   ALL=(ALL) NOPASSWD: /sbin/reboot,MYSERVICE
```
#!/bin/bash
/usr/local/bin/oh_stop.sh
systemctl stop mosquitto.service
logger message stopping openhab2 2
systemctl start mosquitto.service
logger message stopping openhab2 3
systemctl start openhab2.service
```
```
#!/bin/bash
at now +1 minutes -f /usr/local/bin/oh_restart.sh
```
```
#!/bin/bash
/usr/local/bin/oh_stop.sh
systemctl stop mosquitto.service
logger message stopping openhab2 2
systemctl start mosquitto.service
logger message stopping openhab2 3
systemctl start openhab2.service
```
```
#!/bin/bash
logger stopping openhab
systemctl stop openhab2.service
logger stopped openhab
```
Install Openhab
xzcat ./openhabian-pi-raspbian-201908050414-gitca0976f-crc6a66b5a1.img.xz | sudo dd bs=4m of=/dev/diskN
  • Open the file openhabian.conf in a text editor
  • Uncomment and fill in wifi_ssid="My Wi-Fi SSID" and wifi_psk="password123"
Configuration and maintenance
# Confict between ntp.service and systemd-timesyncd.service. Just remove NPTD
sudo apt remove ntp ntpdate sntp chrony
sudo systemctl enable --now systemd-timesyncd.service

# make time-sync.target wait until the clock is synchronized
sudo systemctl enable --now systemd-time-wait-sync.service

# edit openhab service
sudo systemctl edit openhab.service
  • Add to openhab service config
[Unit]
After=time-sync.target
Wants=time-sync.target
# verify after reboot
sudo journalctl -b -u systemd-timesyncd.service -u systemd-time-wait-sync.service -u time-sync.target -u openhab.service

maintenance

  • Openhab log files tail -f /var/log/openhab2/events.log -f /var/log/openhab2/openhab.log

  • Mosquitto conf

log_dest syslog

# Tag as LOCAL0 for rsyslog
log_facility 0
log_timestamp false
  • Append to /etc/rsyslog.conf
# append to /etc/rsyslog.conf
local0.* -/var/log/mosquitto.log
  • MQTT logs

    • rsyslogd is the SYSLOG server process logging to /var/log/user.log. All the remote MQTT clients are remote logging to this SYSLOG server
    • The Mosquitto server is configured to log to syslog and the rsyslog conf is sending LOCAL0 to the mosquitto.log file
    tail -f /var/log/user.log -f /var/log/mosquitto.log
    
  • backup

sudo systemctl stop openhab2.service
sudo systemctl stop mosquitto
sudo openhab-cli backup
  • sync backup file to a local machine
rsync -avz -P openhab-machine.local:/var/lib/openhab2/backups/openhab2-backup-19_06_18-17_08_54.zip .
Logging
  • Karaf console change logging example
ssh -p 8101 openhab@localhost
log:list | grep -i mqtt

log:set DEBUG org.eclipse.smarthome.binding.mqtt
log:set DEBUG org.eclipse.smarthome.binding.mqtt.action
log:set DEBUG org.eclipse.smarthome.io.transport.mqtt
log:set DEBUG org.openhab.binding.mqtt

logout
  • Directly edit debug config file
vim $OPENHAB_USERDATA/etc/org.ops4j.pax.logging.cfg

UPS NUT setup

# user 'admin'
upscmd device@server beeper.toggle

NTP server

sudo apt install ntp ntpstat -y

#set the ntp servers
sudo vim /etc/ntp.conf
# AT queue commands for later execution. Allowing openhab to restart itself
apt-get install at
  • influxdb
wget -qO- https://repos.influxdata.com/influxdb.key | sudo apt-key add -
source /etc/os-release
test $VERSION_ID = "9" && echo "deb https://repos.influxdata.com/debian stretch stable" | sudo tee /etc/apt/sources.list.d/influxdb.list

sudo apt-get update 
sudo apt-get install influxdb
sudo service influxdb start
sudo systemctl enable influxdb.service

INFLUXDB_CONFIG_PATH=/etc/influxdb/influxdb.conf
influxd
> CREATE DATABASE openhab_db
> CREATE USER admin WITH PASSWORD 'SuperSecretPassword123+' WITH ALL PRIVILEGES
> CREATE USER openhab WITH PASSWORD 'AnotherSuperbPassword456-'
> CREATE USER grafana WITH PASSWORD 'PleaseLetMeRead789?'
> GRANT ALL ON openhab_db TO openhab
> GRANT READ ON openhab_db TO grafana
> exit
  • Edit /etc/influxdb/influxdb.conf
[http]  
enabled = true  
bind-address = ":8086"      # change to a specific interface if needed 
auth-enabled = true         # will enforce authentication
...

* Influx cli login

influx -username admin -password SuperSecretPassword123+ -host localhost


* Grafana

``` bash
wget https://dl.grafana.com/oss/release/grafana_6.3.2_armhf.deb 
sudo dpkg -i grafana_6.3.2_armhf.deb
sudo apt-get update
sudo apt-get install grafana

sudo service grafana-server start
sudo systemctl enable grafana-server.service

see 010_ac-reboot, oh_stop.sh, oh_start.sh, and oh_restart.sh

sudo visudo -f /etc/sudoers.d/010_ac-reboot
# paste this text into visudo editor
# Allow openhab user to execute reboot and poweroff commands
Cmnd_Alias MYSERVICE = \
        /usr/local/bin/oh_stop.sh, \
        /usr/local/bin/oh_restart.sh, \
        /usr/local/bin/oh_restartAT.sh
openhab   ALL=(ALL) NOPASSWD: /sbin/reboot,MYSERVICE
# allow openhab executeCommandLine() to execute with sudo 
sudo adduser openhab sudo

cat /usr/local/bin/oh_stop.sh
cat /usr/local/bin/oh_restartAT.sh
cat /usr/local/bin/oh_restart.sh

#
sudo chmod u+x /usr/local/bin/oh_stop.sh
sudo chmod u+x /usr/local/bin/oh_restartAT.sh
sudo chmod u+x /usr/local/bin/oh_restart.sh

#
sudo chgrp openhabian /usr/local/bin/oh_stop.sh
sudo chgrp openhabian /usr/local/bin/oh_restartAT.sh
sudo chgrp openhabian /usr/local/bin/oh_restart.sh
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment