Writing to a text file

OK, thanks. I know that I could use mqtt and Homeseer also supports it. I’ll try to keep OH intallation as clean as possible so the text file method is easier for me. And it is just a temporary solution until I install influxDB+Grafana.

I have to say that I’m extremely happy about the support I have received in this forum. I’m still on my learning curve but all the efforts I have spent are going to right direction. OH is extremely powerful and I have realized that I can do lot more things in a much better way than in Homeseer.

1 Like

I just solved writing to a file in a relatively generic way.

  1. Create /etc/openhab/scripts/write-file.sh
#simple append
#echo "$1,$2,foo" >> /etc/openhab/html/test.txt;

# prepend
# requires the $1.txt file to be seeded first or...just run this script twice
printf '%s\n%s\n' "$2" "$(cat /etc/openhab/html/$1.txt)" >/etc/openhab/html/$1.txt
  1. Set permissions on the shell script
  • sudo dos2unix write-file.sh # windows crlf will cause problems if edited with drive mapping from Windows
  • sudo chmod +x write-file.sh
  • sudo chown openhab write-file.sh
  1. Test OH3 can write to it
  • sudo -u openhab /etc/openhab/scripts/write-file.sh "kodi-usage" "mydata"
  • If above errors, try sudo chown openhab /etc/openhab/html/kodi-usage.txt
  • If it worked cat /etc/openhab/html/kodi-usage.txt should print mydata
  1. Use in Rules DSL
val String currentTime = String::format( "%tF %<tT", new java.util.Date )
val String logMessage = String::format("%s", kodi_show.state)
    
var String fullMessage = currentTime + " " + logMessage
val String result = executeCommandLine("/etc/openhab/scripts/write-file.sh", "kodi-usage", fullMessage);

Notice that the kodi-usage filename isn’t hard coded, so I can also write out interesting things to different files and view them in my *.sitemap

Frame label="Log" {
        Webview icon=none url="/static/kodi-usage.txt" height=14
}

which with any luck will contain something like

2022-04-08 20:55:17 Rick & Morty
3 Likes