APSystem Solar Energy Integration

I just finished the config to collect daily energy production from APSystems API using a python script running under AppDaemon and PVoutputs integration.

The result is a sensor showing “live” energy production in kWh every day

Tutorial Steps:

  1. Identifying your ECU. Does it have web interface?
    ECU is that modem like device that receives signals from microinverters, which are connected with the solar panels.
    There are some ECU types, depending the world region you are.
    If your ECU has a web interface when accessing its ip address from any browser, you can make the integration localy, just scraping its web interface and get the value from “today” section.
    If your ECU does not offer a web interface, you’ll need to use PVOUTPUT integration.

  2. ECU with web interface:
    Use scrape sensor:

sensor:
   platform: scrape
   resource: http://192.168.0.26/ # your ecu ip address
   select: " tr:nth-child(2) > td" # where is the value you want to show here*
   name : Lifetime_generation
   value_template: ‘{{ ((value.split(" ")[0]) | replace (“KW”, “”)) }}’ # you will need to test the result from scrape select and template it to show just the numbers
   unit_of_measurement: “kWh”
   scan_interval: 300

How do you write the select part:
Open your ecu web interface on google chrome, select the value you want and right click and select “inspect”. It will open the chrome inspector.
Inside inspector, find the value, right click, “copy selector”
Paste it with " "

  1. ECU without web interface:
    Use PVOUTPUT integration:
    3.1) Take note your ECU number id.
    3.2) Access your EMA setup web interface
    https://www.apsema.com/ema/security/optmainmenu/intoManagementCustomer.action
    And check the box “Allow visitors to access to this system” and copy the “Authorized ID”
    3.3) Create an account on https://pvoutput.org/ and fill with yout solar system data.
    Enable API Settings, generate API Key and take note.
    Take note System Id from PVoutput as well.

Now you have all data you need to config home assistant integration.
This works this way:
You need to feed PVOutput system with your power generation and Home Assistant will download data from PVOutput system showing as a sensor.

There is a script from willemstoker https://github.com/willemstoker/aps-to-pvoutput that feed PVOutput with APSystems API and I turned it into a AppDaemon APP.

So, install AppDaemon Add-On if you use HASS.IO
Remend to install Requests package in configuration Add-On before start it:

system_packages: []
python_packages:
  - Requests
init_commands: []

Create a file called apstopvoutput.py inside ˜/appdaemon/apps folder with the code bellow and change by the numbers you noted:

import hassapi as hass
import requests
import json
from datetime import date
from datetime import datetime
import os.path

class APStoPVOUTPUT(hass.Hass):
  #initialize() function which will be called at startup and reload
  def initialize(self):
    # Schedule to run every 10 minutes
    self.run_every(self.apstopv, "now", 600)

   # Our callback function will be called by the scheduler
  def apstopv(self, kwargs):
    ECU_ID = 'YOUR ECU ID'
    PV_OUTPUT_SYSTEMID = 'YOUR PVOUTPUT SYSTEM ID'
    PV_OUTPUT_APIKEY = 'YOUT API KEY FROM PVOUTPUT'

    LAST_UPDATE_FILE = "/config/appdaemon/apps/lastupdate" # remember to change this folder if you need"

    MAX_NUMBER_HISTORY = 20
    APSYSTEMS_URL = 'http://api.apsystemsema.com:8073/apsema/v1/ecu/getPowerInfo'
    PVOUTPUT_URL = 'http://pvoutput.org/service/r2/addstatus.jsp'
    
    def readLastUpdate():
        f = open(LAST_UPDATE_FILE,"r")
        datestring = f.read()
        f.close()
        return datetime.strptime(datestring, "%Y%m%d %H:%M")

    def writeLastUpdate(timestringminutes):
        f = open(LAST_UPDATE_FILE,"w+")
        f.write(getDateStringOfToday()+ ' ' +timestringminutes)
        f.close()

    def getDateStringOfToday():
        return date.today().strftime("%Y%m%d");

    def getDataFromAPS():
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
        }

        data = {
          'ecuId': ECU_ID,
          'filter': 'power',
          'date': getDateStringOfToday()
        }

        response = requests.post(APSYSTEMS_URL, headers=headers, data=data)
        return response.json();

    def sendUpdateToPVOutput(timestringminutes, powerstring):
        pvoutputdata = {
          'd': getDateStringOfToday(),
          't': timestringminutes,
          'v2': powerstring
        }

        headerspv = {
            'X-Pvoutput-SystemId': PV_OUTPUT_SYSTEMID,
            'X-Pvoutput-Apikey': PV_OUTPUT_APIKEY
        }

        responsepv = requests.post(PVOUTPUT_URL, headers=headerspv, data=pvoutputdata)

        print ("Response: " + responsepv.text + " updated: " + timestringminutes + " power: " + powerstring)

    if not os.path.isfile(LAST_UPDATE_FILE):
        writeLastUpdate('00:00') #create file for the first time

    rootdict = getDataFromAPS()
    timesstring = rootdict.get("data").get("time")
    powersstring = rootdict.get("data").get("power")

    timelist = json.loads(timesstring)
    powerlist = json.loads(powersstring)
    latestUpdate = readLastUpdate()
    print("Found latest update: ")
    print(latestUpdate)

    i = len(timelist) - 1
    count = 0;
    while i >= 0 and count < MAX_NUMBER_HISTORY:
        timestringminutes = timelist[i][:-3] #get time and strip the seconds
        powerstring = powerlist[i] #get power

        currentUpdate = datetime.strptime(getDateStringOfToday()+ ' ' +timestringminutes, "%Y%m%d %H:%M")

        if currentUpdate > latestUpdate:
            sendUpdateToPVOutput(timestringminutes, powerstring)
        else:
            print("No update needed for: " + timestringminutes)

        if count == 0:
            writeLastUpdate(timestringminutes)
        
        i -= 1
        count += 1
    

This app runs every 10 minutes, and upload apsema data to pvoutputs
now, edit the apps.yaml to run the app only during solar generation time with this:

---
apstopvoutput:
  module: apstopvoutput
  class: APStoPVOUTPUT
  constrain_start_time: sunrise # your panels start generating before sunrise, but the app import last 20 entries, which means something like last hour
  constrain_end_time: sunset + 00:45:00 # change this if your panels generate after 45 min after sunset

and finaly, home assistant sensors in configuration.yaml:

sensor:
  - platform: pvoutput
    system_id: 99999 #change with your system Id again from pvoutputs
    api_key: 9999999 #change with your api key from pvoutputs
    scan_interval: 600

optionally you can create a template sensor to show in kWh unit:

sensor:
  - platform: template
    sensors:
      energia_solar:
        friendly_name: 'Today Solar Energy'
        value_template: "{{(states('sensor.pvoutput')|float / 1000)|round(1)}}"
        unit_of_measurement: "kWh"

Note that pvoutput allows only 60 interactions per hour, including uploading and downloading data.

1 Like

Hello. Where can i find my PV_OUTPUT_SYSTEMID ?

Hi there…
From the PV_OUTPUT website…
Click on Settings menu on the top and look at the bottom of the settings page.

Registered Systems
System Name - System Id - Status

NOTE: APS changed the api url, this script currently does not work anymore.

I’m looking for the fix…

This seems to be another way to get data from ECU-R
I did not try yet!

and here is the new user manual. I think someone could just change the script based on these new informations:

Apsystems EMA API operation manual.pdf

I have already tested just changing the url but did not work:
http://api.apsystemsema.com:8073/apsema/v1/apisystem/getSystemPowerInfo

Home Assistant custom component for local querying of APSystems ECU-R Solar System

If you own a ECU-C, we are looking for testers :slight_smile: It’s best to get the data where it is produced. APsystem is going to ask for an annual subscription fee - once you depend on the API. That would be weird, paying for data over which you have ownership and you’re the producer of that data, but it’s all in the FAQ.

I will certainly be happy to help, but I am still under construction and currently my HASS entity is not located on the same network as my photovoltaic system.

But as soon as I’m living in the new house, I can test everything you need.

I will probably be ready in 2 months.

Hi guys,

Due the problem with the old apsystems API that is not working anymore, I create a new HTTP APsystems Sensor. It is in HACS structure. So if you are using HACS, just add this repository:

It uses the https://apsystemsema.com web site to get the information. So it works with any APsystems inverter / ECU model.

Please, help me to test. If you like, just give me a beer :slight_smile:

I can’t find the repositorie in HACS

It seems that HACS only imports around 700 repositories (there are more than 1000 available) and then quits because the GitHub APi won’t let you pull more repositories. I updated HACS today but now HACS doesn’t work at all so I deinstalled hoping for better times.

If you are taking about my message, you have to add an custom repository pointing to GitHub - bgbraga/homeassistant-apsystems: An APsystems Sensor for Home Assistant

It should be done using the 3 dots in top / right of HACS / Integrations page.

Hi Bruno, did not work here…

I got all installed but all sensors show unavailable.

I have two entries on Log:

Setup of sensor platform apsystems is taking over 10 seconds.
16:13:16 – (WARNING) Sensor - a mensagem ocorreu pela primeira às 16:13:14 e apareceu 3 vezes

and

Logger: homeassistant.loader
Source: loader.py:783
First occurred: 16:13:01 (1 occurrences)
Last logged: 16:13:01

You are using a custom integration apsystems which has not been tested by Home Assistant. This component might cause stability problems, be sure to disable it if you experience issues with Home Assistant

Ok, so, is it broken?
No solution yet!!!

Hi @oliverdog and guys,

Unfortunately APSystems portal changed the way they handle cookies and it broken the integration.
I had to spend some time to figured out how to fix it.

Now I’m using another component (a browser like) to login and get apsystems cookies. Please try version 1.0.3 or above.

Hi Bruno,

thank you for your contribution. Finding a good integration for APSystem is something I am looking into already for a while. But my knowledge about setting this up is limited. I read from Github:

Configuration

Use your apsystemsema.com user to configure the configuration.yaml.

# Minimal configuration.yaml entry:
sensor:
  - platform: apsystems
    username: apsystemsema_user
    password: !secret apsystems
    systemId: apsystemsema_system_id
    ecuId: apsystemsema_ecu_id
    sunset: off

Does this mean where it says apsystemsema_user, I remove this and fill my login for APSystem? If yes, is this also applicable for systemID and password? I read something about Get the system id inside the managementClickCustomer(). and I was confused.

So I know by know. That in the configuration.yaml I just needed to fill in all my data.
I have done this. I also managed to find my systemic from the apsystemsema.com website.
So it’s active in HA.But I do not see any devices or entities popping up. So there must be something I missed.

Never mind. Restarting HA solved it. Now new entities are showing up! It works!

Bruno, Im using you HACS integration. But it seems not updating by the 5min update interval. Do you have any idea? Is there also a possibility to get the detailed module info? Even with contribution?

Great!!! It is working fine with the last version!!! Thanks @bgbraga

I got this setup and working…Thank you for making this integration.
image

But i do not seem to be able to add any of the sensors to “Energy/Solar Panels”, it seems the " Energy Management" in Home Assistant was added after the integration was made so i guess it has not be tested before and maybe something smal to fix?