Add Annotations to Grafana Automatically from OpenHAB

Hey everyone! I recently discovered a neat way to add annotations to Grafana automatically using rules from OpenHAB. I thought it might be helpful to share my experience in case others are interested or facing similar challenges. Here’s how I did it:

What You Can Achieve

With this method, you can add annotations to your Grafana dashboards automatically. For example, you might want to log when your heating system turns on or when a device goes offline. This can be incredibly useful for monitoring and troubleshooting.

What You Need

  1. A running OpenHAB instance
  2. A running Grafana instance (can be on the same host as OpenHAB)

Step-by-Step Guide

  1. Create an API Key in Grafana:

    • Navigate to Grafana’s settings and go to the API Keys section.
    • Generate a new API key with no expiration date. The name is just for reference, so feel free to name it something descriptive.
  2. Set Up the Rule in OpenHAB:

    • Here’s a sample rule that adds an annotation when a specific lamp goes offline:

    val String url = “http://api_key:YOUR_API_KEY@YOUR_IP:3000/api/annotations”
    val String DashboardID = “2”
    rule “Add annotation to Grafana if Bettlampe goes offline”
    when Item Netzwerk_Bettlampe_Online changed to OFF
    then
    logInfo(“Rule triggered”, “Rule “test.rules: Testrule” started”)
    var String json = ‘{ “panelId”:10, “dashboardId”:’ + DashboardID + ‘, “time”:’ + Long::toString(now.millis) + ‘, “tags”:“[Online]”, “text”:“Bettlampe offline” }’
    sendHttpPostRequest(url, “application/json”, json)
    end

    • Replace YOUR_API_KEY with your actual Grafana API key and YOUR_IP with your Grafana server’s IP address.
  3. Find Dashboard and Panel IDs:

    • Dashboard ID: Go to your desired dashboard, click on the settings (gear icon), and select “JSON Model”. The ID is listed under “id”.
    • Panel ID: Click on “Share” on the panel you want to annotate. The panel ID is in the URL parameter “viewPanel=”.
  4. Test and Adjust:

    • After setting up the rule, test it by triggering the event (e.g., turning off the lamp). Check Grafana to ensure the annotation appears.
    • If you encounter issues, check your logs. A common error is related to authentication, so make sure your API key and URL are correctly formatted.

Troubleshooting

If you see this error in your logs:

Fatal transport error: java.util.concurrent.ExecutionException: org.eclipse.jetty.client.HttpResponseException: HTTP protocol violation: Authentication challenge without WWW-Authenticate header

It means there’s an issue with the authentication. Double-check your API key and URL settings.

Conclusion

This method has been a great addition to my setup, providing clear and automatic annotations that help me monitor my home automation system more effectively. I hope this guide helps you achieve similar results!

Feel free to ask questions or share your experiences below. Happy automating! :rocket: