Grafana and myopenhab.com - FINAL solution

Tags: #<Tag:0x00007f7464895280> #<Tag:0x00007f74648951b8> #<Tag:0x00007f74648950c8>

I hope I will not rediscover a wheel here but obviously all the very nice tutorials about integrating InfluxDB and Grafana do miss one final step - integration with myopenhab.com
They do mention how to configure habpanel to use Grafana link. This means that openhabian:3000 has to be exposed. This is a solution for a home network, not for an Internet. Especially when you do not want to forward port 3000 behind your router and use the service like no-ip.com to update your dynamic IP. When you have an overprotective internet provider, you are not even allowed to do that as all incoming connections are going to be filtered anyway.
So, the desired solution is to have a png served by your OpenHAB and not Grafana, so it can be nicely presented on habpanel and seamlessly exposed to myopenhab.
While I was checking the community resources I’ve found that all proposal for solutions of similar problems are not a perfect fit.

  1. The ideal solution Have an Image item and using Http binding communicate with Grafana. Problem: It requires Base64 image, not a binary data. Ideal solution convert incoming binary to Base64 using JavaScript transformation. This does not work, at least I was not able to solve it. The problem is that JavaScript does get a string, not a byte array and conversion of that string to byte array does not give initial set of bytes which are on the wire. Maybe there is a way to do that, but it is hidden somewhere in the dark side of Internet. Someone is willing to implement Java, Groovy transformation?

  2. @bloodboy Usage of Image Item. hack. This one is not so bad but… opening yet another port just to have FTPUpload binding working as a gate for an Image item doesn’t sound too convincing.

  3. @rlkoshak Comprehensive Wunderground using HTTP Binding Example This is a great tutorial, but the proposal how to serve dynamic images is, at least to my taste, a way to abusive with the respect to violating the concept of serving static html resources. Downloading an image with wget is not so bad idea but storing them somewhere on the drive and then refreshing the screen with simple page refresh without nice possibility to even detect if an image has changed is not appealing at all. Yes, there is a hack for that in the tutorial as well.

  4. The wget + Image solution Now is what I have invented. It is simple and it is based on Image item. All nice Angular page refreshment is happening in the background and of course we do have checking if we do have the same image or we do have something which is new and should be rendered by the browser.
    a) Items Create Image item with nice name and define a channel

Image grafana_temperature_measure_salon_image "Salon" (grafana) {channel="ftpupload:imagereceiver:grafana_measure_salon:image"}

b) Rules Use cron (here every 15min and fetch tih image from Grafana using image share


Encode binary content of the file with Base64 and send it to the Image item. Downside of that is that you don’t have an Image content set for first 15min after restart but who cares? You can work this out with some rule which is intercepting OpenHAB startup or just accept this limitation.

import org.eclipse.xtext.xbase.lib.Functions
import java.nio.file.FileSystems;
import java.nio.file.Files;

val logName = "grafana.rules"
val Functions$Function1<String, String> getSnapshotImage = [url |
	val fileType = "png"; // url.substring(url.lastIndexOf('.') + 1);
	val tmpFile = "/tmp/grafana_snapshot." + fileType
    executeCommandLine("wget -O " + tmpFile + " \"" + url + "\"", 10000)
	val path = FileSystems.getDefault().getPath(tmpFile);
    val fileData = Files.readAllBytes(path);
	"data:image/" + fileType + ";base64," + java.util.Base64.encoder.encodeToString(fileData)
]

rule "Update Grafana snapshots"
when
    Time cron "0 0/15 * * * ? *" 
then
	logInfo(logName, "Refreshing Grafana")
	val imageSnapshotSalon = getSnapshotImage.apply("http://onepi:3000/render/d-solo/TsnclLmRz/salon?orgId=1&panelId=2&width=1000&height=500&tz=UTC%2B01%3A00")
    grafana_temperature_measure_salon_image.postUpdate(imageSnapshotSalon)
	logInfo(logName, "Refreshing Grafana completed")
end

c) Habpanel Create an image in habpanel and set Image item as a source of image

d) Enjoy the Grafana image on myopenhab.com with your mobile device while you are 1000km away from home.

Cheers,
Sebastian

5 Likes

Unlikely but you might be able to make it work with a Proxy Item and a Rule. Use the HTTP to populate a String Item then use the String Item to trigger a Rule that converts the String to bytes and then to Base64. Then update the Image Item with the Base64 String.

This approach was never really meant to apply to this sort of use case anyway and I’m not totally convinced it would work with Grafana anyway. I left it a little loose because Wunderground was known to change up their icon sets periodically (e.g. they’s use one set of icons for daytime and another set at night time but the actual weather conditions are the same).

This import is not necessary.

You should use the cleaner lambda definition syntax:

val getSnapshotImage = [ String url |

Does this solution depend on PhantomJS and Grafana’s static image URL? If so it should be noted that new versions of Grafana no longer come with PhantomJS and if you try to restore this library (lots of tutorials on the web) you might encounter significant performance problems with Grafana consuming a whole lot of resources rendering the charts. From what I’ve seen reported, an RPi can handle maybe one or two simultaneous renderings. Any more and it will cause your OH instance to be killed as the kernel desperately searches for more resources to give to PhantomJS.

Thanks for posting! It’s a great tutorial and I’m positive many will find it very useful. Particularly the loading and conversion of the image to Base64.

Thanks for the code review :wink: I’m not familiar with this syntax and therefore the code is more plain Java style. No, the code does not depends on PhantomJS at least to my knowledge. I have a fresh installation of everything and I was not installing any addons. I’m using Grafana v5.1.4

The cleaner lambda syntax is the old way of doing it that became broken at some point (probably around OH 2.0 release) and then was fixed and usable again around OH 2.3 release. So you will see lots of examples that use the overly verbose and ugly Functions$Function1<Type, Type… syntax because for a little over a year the cleaner syntax didn’t work.

OK, so I think you are using the version just before they removed PhantomJS. On Grafana 5.2.4 I think and definitely by the latest version 5.4.3 the solo links will no longer work unless you add PhantomJS back to your installation. And if you do that then you will see the performance issues already mentioned.

Ahh. I forgot to mention. I’m on RPI https://github.com/fg2it/grafana-on-raspberry

Thank you for this solution.
I am however not using the PNG image, I use a webview in my sitemap to have an interactive chart where I can do mouseovers or zooming. It of course only works locally because I don’t want to forward port 3000 to the internet.
Is there a similar solution to display the webview over myopenhab.org in the sitemap? For example a copy of the html file that is updated every 5 minutes?

This is exactly a workaround to have the graph exposed over the internet. I have pretty much similar solution for camera view. The point is, myopenhab.org does not provide interaction routing functionality. It does provide the view and this is your limitation. If you do not want to expose the port over services like serveo.com or similar then image is your only option. To be frank, I was pretty much curious about the possibility of making the screen shots instead of using PhantomJS plugin from Grafana (check the comment from @rlkoshak) but I was completely unsuccessful with available command line tools.

Hi @create1st,

First, thanks for this nice tutorial. :grinning:

Unfortunately, I am not successful in exposing it to openHAB cloud (running my own instance). I can access HABpanel via my openHAB cloud instance but the image is not shown (only the default image icon) - also not when accessing HABPanel locally. Tried different browsers as well. My setup (for testing I stayed as close to your original example as possible):

testgrafana.items

Image imgTempIndoor24H "Indoor Temperature" {channel="ftpupload:imagereceiver:grf_temp_indoor:image"}

testgrafana.rules

import org.eclipse.xtext.xbase.lib.Functions
import java.nio.file.FileSystems;
import java.nio.file.Files;

val logName = "grafana.rules"

val Functions$Function1<String, String> getSnapshotImage = [url |
	val fileType = "png"; // url.substring(url.lastIndexOf('.') + 1);
	val tmpFile = "/tmp/grafana_snapshot." + fileType
    executeCommandLine("wget -O " + tmpFile + " \"" + url + "\"", 10000)
	val path = FileSystems.getDefault().getPath(tmpFile);
    val fileData = Files.readAllBytes(path);
	"data:image/" + fileType + ";base64," + java.util.Base64.encoder.encodeToString(fileData)
]

rule "Update Grafana snapshots"
when
    Time cron "0 0/10 * * * ? *" 
then
	logInfo(logName, "Refreshing Grafana Indoor Temp Graph")
	val imageSnapshot = getSnapshotImage.apply("http://192.168.2.2:3000/d/DRmxtepWz/openhab2?orgId=1&fullscreen&panelId=2&from=now-24h&to=now")
    imgTempIndoor24H.postUpdate(imageSnapshot)
	logInfo(logName, "Refreshing Grafana Indoor Temp Graph completed")
end

The image item gets created:

openhab> smarthome:items list | grep img
imgTempIndoor24H (Type=ImageItem, State=raw type (image/png): 27087 bytes, Label=Indoor temp last 24H, Category=null)

And in HABPanel, the image is added like this (never mind the typo…):


The image is shown as the default image placeholder icon:

The image link in the browser for this image is: data:image/png;base64,PCFET0NUWVBFIGh0bWw+CjxodG1sIG......

What am I missing?

EDIT: From the official openHAB HABPanel documentation:
“The image widget can display an image, directly or via an openHAB String item, and can refresh it at regular intervals.”. No mention of the Image Item type…?

EDIT2: Probably not related, but I did notice an error in the browser console:

  ...
Service worker registered
openhab.service.js:35 Loaded 327 openHAB items
manifest.json:1 GET https://openhab.domain.ext/habpanel/manifest.json 401
manifest.json:1 Manifest: Line: 1, column: 1, Syntax error.

This turned out to be a ‘user error’: the URL to the Grafana image was wrong resulting in an HTML file to be stored as the PNG. The rest is history… :grin:

Next step: generalise this so I can support any number of graphs with a few simple rules.