Presenting SMA converter values

#Challenge:
Hey all. A few months ago, we had a few solar panels installed. I was doubting between the brands of the inverter, but went with the SMA. I knew that they didn’t have an API for getting the data, but I knew I could probably retrieve it one way or the other. So my challenge was to get the values from the inverter into HA.

#Setup:
I want to run everything on a Raspberry Pi, even though the description below was only tested on a laptop running Linux. So still need to test it on the Rasp. Also, I was doing this on the train, with bad wi-fi, so I did not actually test the complete code yet.

In regards to the inverter: there are two ways that I can pursue to solve this challenge. I can either collect the data from the inverter directly, or through the Sunny Portal. In both cases I webscrape. I believe there are some SMA inverters and extensions that allow direct polling for values. If so, you can change your project accordingly.

#How I tackled it:

Part 1: Webscraping

My first step was to tackle to get the values like generated power. Since there is no API, I decided to go with webscraping. For that, the easiest way that I could find was CasperJS, as that had an intuitive way of logging in and getting the HTML of the page. You can find more about CasperJS here. Below you can find the code, but the steps that I follow on a high level are:

  • Go to the Sunny Portal (or, connect to the wi-fi signal in your inverter)
  • Sign in
  • Get the value and print it

var casper = require(‘casper’).create({
pageSettings: {
loadImages: false,// Don’t load images, as it makes the script quicker
loadPlugins: false,// Don’t load plugins, as it makes the script quicker
userAgent: ‘Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36’,
},
waitTimeout: 10000,// A longer wait timeout
});

// Start the script
casper.start();

// Open Sunny Portal
casper.then(function(){
    this.open('https://www.sunnyportal.com/', {
        method: 'get'
    });
});

// Fill in the credentials
casper.waitForSelector("#txtUserName", function() {
    this.evaluate(function(username, password) {
        document.querySelector('#txtUserName').value = username;
        document.querySelector('#txtPassword').value = password;
    }, USERNAME, PASSWORD); // Replace USERNAME and PASSWORD with your Sunny Portal credentials
});

// Click button to login
casper.then(function(){
    this.evaluate(function() {
        document.querySelector('#ctl00_ContentPlaceHolder1_Logincontrol1_LoginBtn').click();
    });
});

// Get the current value
casper.waitForSelector(".mainValueAmount", function(){
    var value = this.evaluate(function(){
        return document.querySelector(".mainValueAmount").innerHTML;
    });
    // Get the value and parse it to float
    value = parseFloat(value);
    console.log(value);
});

// Run the script
casper.run(function(){
    this.exit();
});

The above script only outputs the current power that is being generated, but of course you can output other values too.

Part 2: Adding value to HA

This part was interesting, as I was considering different options:

  1. Create a REST API using NodeJS, which performs a shell command and have HA poll the API in intervals
  2. Use NodeJS and the shell command option to create an MQTT client and have it send the information to the MQTT broker embedded in the HA (or another broker of course)
  3. Use NodeJS and the shell command option to send information to the REST API from HA, in combination with a template sensor
  4. Use the command line sensor option from HA

I started with implementing the first option and the third option. Both worked, but I thought it was a bit weird that I would need to implement NodeJS and have that running continuously to being able to have the value. This then also applied for the second option. So I found the possibility for the fourth option, and decided to go for that. And actually succeeding.

The only thing I needed to do was to add the command line sensor, and make sure it runs the casperjs shell command. That’s actually just it. It is important to note that the path has to be absolute. If not, it won’t find it and it won’t work.

// sensors.yaml
- platform: command_line
  command: "casperjs ~/.homeassistant/sensors/scrape_current_data.js"
  name: current solar power
  unit_of_measurement: w

Add the sensor to anywhere you want, and it will update at regular intervals with the necessary information.

Things to still do and possible additions:

I do have some adjustments that I want to make:

  • I want to test this in a Raspberry Pi in combination with a good internet connection. I have now tested it with fake data, but I am not sure if HA polling will wait for the value to be retrieved (as CasperJS takes some time to collect the information)
  • I want to change the scanning interval, as Sunny Portal is updated about every 5-7 seconds. I have tried to change it, but it doesn’t seem to change. I’ll do some researching though
  • I am considering to also send this information to InfluxDB and Grafana, tackling two things at once. To do this, it should be quite easy to create a bash script in which you perform the CasperJS script as well as sending the information to InfluxDB

#In conclusion
It is not the most elegant way of collecting data, and it is subject to change of the Sunny Portal website or the inverter website, but it is the easiest way I found to actually do this. If somebody has a better/cleaner/nice way of doing this, please let me know! Also, if somebody has an idea why one of the other options of getting the information into HA (with NodeJS and/or MQTT), I am curious about your thoughts.

2 Likes

There’s a web scraper being integrated into HA in 0.31. Might simplify this even more for you.

Wow, that is a great feature, thanks for sharing! But would it work with logging in though? For that, you would need several steps. It might be possible, but I have not delved into the link that you shared, as I was already thinking on different possibilities. The reasons:

  • It seemed like scan_interval did not allow for quick polling (in my case, 5s; not sure if this is a bug though…)
  • Even if scan_interval would work, using CasperJS was not quick enough to actually get through all the steps in 5s and timeouts were a common occurence

So I had to look for different possibilities. I have found the node osmosis webscraper, which is a lot quicker than CasperJS, but also a bit less intuitive. Also, because of some less than expert programming on the side of SMA, it was not possible to actually get into the Sunny Portal. Banging my head against the Sunny Portal, I decided to take a look at the inverter to see if that was any easier.

And indeed it seems like the good people at SMA are better at making their inverter webserver that that of their website. Turns out that you only need two server calls for getting the necessary data. Be aware, this works for me as I have a new Sunny Boy 2.5. If you try this, I think you have to have Webconnect from SMA on your inverter.

The first call is to get a session ID:

curl -X POST -H "Connection: keep-alive" -H "Content-Length: 37" -H "Accept: application/json" -H "Accept-Encoding: gzip, deflate" -H "Content-Type: application/json" -H "Cache-Control: no-cache" -H  '{"right":"usr","pass":"[[YOUR_PASSWORD]]"}' "http://[[INVERTER_IP]]/dyn/login.json"

You will receive the follow response containing a session id:

{
  "result": {
    "sid": "_-s_pfe_sQO_5ce5"
  }
}

With the session ID, you can retrieve data:

curl -X POST -H "Connection: Keep-alive" -H "Content-Length: 37" -H "Accept: application/json" -H "Accept-Encoding: gzip, deflate" -H "Content-Type: application/json" -H "Cache-Control: no-cache" -H '{"destDev":[],"keys":["6100_40263F00"]}' "http://[[INVERTER_IP]]/dyn/getValues.json?sid=_-s_pfe_sQO_5ce5"

In this example, I only request the current power with the key “6100_40263F00”. If you want different values, you can just add these to the keys. To see which key is which value, you can check the id in the HTML code when you login to your inverter with your browser.

Using these requests, I have created a NodeJS application which runs the second request every 5 seconds. It also does some error handling, as sometimes a request does not successfully receive a session id. When it gets a value, it uses the Restful API from HA to write the value to a template sensor.

There are several reasons why I have decided to create a separate system for collecting the information:

  • I want data to be written to InfluxDB at a certain point. Now that I have the current power being sent to HA, it is a matter of creating a new request that also sends it to InfluxDB.
  • I want to collect more data from the inverter, but at different time intervals (I don’t need to check every 5 seconds how much we collected yesterday :slight_smile:).
  • I am still considering sending the data through a MQTT broker (because I want to learn how it works, and throwing data directly to the Restful API which forcefully changes the value just feels dirty…).
  • I am considering requesting different sources of data (for example getting the amount of money that I am saving, for which I need to get the price per kW from my energy provider).

An image on two different states which were changed by the NodeJS script:

Any views on this are highly appreciated! And if you need more information on my work, let me know, I am more than happy to help. I am curious if this also works for other people.

1 Like

I’m also looking for a solution to bring SMA data into HA. I started to look at SBFSpot which seems like it brings the data into a database using the bluetooth connection and/or the speedwire module. Haven’t looked into it in detail, but might help you.

Hi!
I’m also looking for a solution to bring SMA data into Hass.
I try it with the scrape Sensor on my public website- so I don’t have to Login:

platform: scrape
    resource: "https://www.sunnyportal.com/Templates/PublicPage.aspx?page=7431e23c-a310-4fdf-99ec-e31db735d65f"
    name: pv
    select: '.mainValue'
    unit_of_measurement: 'KW/h'

But I only get a “-” as result :frowning:

1 Like

Hi @Ivor, thanks for sharing!

I also recently installed a SunnyBoy (1.5 with Webconnect) and playing around with getting the data into HASS. Step 1 is done, with a pysma library that will query Webconnect from HASS. Will complete the HASS sensor platform soon, and hopefully you have some pointers on what properties you use.

Initial docs PR available here

What SMA models do you all have?

Hey!
I have the Sunny Mini Central 6000TL and Sunny Mini Central 7000HV.
And I use the SMA WebBox.

Hi @Marius82, thanks!

Not sure if it will work, but you can try the sensor, it is available on https://github.com/home-assistant/home-assistant/pull/5118

The easiest way to try might be to add the sma.py file to your custom_components folder (e.g. ~/.homeassistant/custom_components/sensor/sma.py)

I’ve written some node.js to grab historical data from my inverter. Others might find it useful for that purpose, or just as a reference. If you’re interested, check it out:

Be aware that I’ve only tried this on one inverter, my own! If you try it, and see any problems, please file an issue on github. Thanks!

At our old house, I had an SMA with web connect. I wrote a python module to convert everything to MQTT messages. You can customize the frequency (it’s a polling system) and it can report instantaneous, daily, etc. The code is here: https://github.com/TD22057/T-Home. I don’t have the inverter anymore (we moved) but you’re welcome to fork and do whatever you want. If you just want Home Assistant integration, why not use: https://home-assistant.io/components/sensor.sma/

1 Like

Would it be possible to make something like this in HA ?

  1. actual W ( that’s already ok). Is it possible to make a meter like this ?
  2. total W of today
  3. Weather : already ok
  4. graph : with graphana i think ? how can I chance between days and month’s ?
  5. Table ( Table on front-end I think)

Hey @marius82,
How do you get your inverters to publish a pblic page like this?

Hi,

Thanks a lot for this. I also noticed the different codes used. As you already have a nodeJS application built, would you mind sharing it with me? It would be highly appreciated.
Once again a big thank you for this!

Maxime

log into sunnyportal and on first page in the bottom there is a configuration option. within that you can find a custom link for your system.

BUT in my Experience its really bad on updating comparing to the data you get when you logged in.

since i want to use the data for current consumption right now it does not work for me

1 Like

Anyone have a working integration to newer SMA Inverters right now? The SMA sensor does not work on my inverter, think they skipped the the service on tcp/ip in later firmwares/devices.
Or iam doing something wrong since i cant connect to it locally at all via ip.

Hey @nsim, thanks for sharing the tip on making the info public.

On newer SMA Sunny Boy inverters (with -40 at the end of the model number), you should see the Sunny Boy on your local network by using an app like Fing. If not, then it is not using your Wifi and probably does not connect to the Internet.
In that case, you should be able to connect directly to the inverter’s Wifi SSID. With an installer account you can change the Wifi settings. While you are there, enable ModBus TCP and WebConnect connections. These are the two ways you can read the sensors from the inverter in the most easy fashion. Neither are perfect:

  1. WebConnect allows many sensors to be read, including daily consumption. It’s a pain to find the sensor keys: connect to the inverter with Google Chrome, click the Instantaneous values tab, right click the value you want and click the Inspect feature, then write down the sensor key. It does not work, if, like me, you have a Home Manager, as WebConnect connections are reset to off within minutes.
  2. ModBus is fairly easy to use. Issue is you can only read sensors from one ModBus device with the current Home Assistant integration. I had to make a special instance of Home Assistance just to read a second device… You also need to get register keys from SMA’s clumsy Excel sheets.

If you need pre-written code for Sunny Boy and/or Sunny Island, I’ve shared my config elsewhere here:
https://community.home-assistant.io/t/sma-energy-meter-in-home-assistant/47482/42?u=monkey-house

Thanks for taking the time. Iam currently stuck trying to connect to the SMA inverter. I see it on the network. But it does not respond. I should have written this before that I have a SMA tripower and not a sunny boy.

Should exist a BT connection to it for configuration so will try to see if I have better luck that way of communicating the over IP.

Thanks for the link and description. Will try to analyze this more

Yup, no experience with TriPower so no idea. However the Home Manager I use is no help and you cannot connect to it via LAN at all… Unfortunately, SMA does not seem very Home Automation friendly. I even got an email from their Germany-based international services saying their inverters were not allowing for local integration: “A extended integration in your house system is not possible.”!
Makes me wish I’d chosen another brand.

2 Likes

@nsim, OK I found the custom link, but need to log in to access data. Do you need to enable this option?

Approval to use data via the online tool Sonnenertrag.eu:

all i done is just to use the link that is below.
Can use the link from link from othere devices when not loged in