Smappee Charger with Postman

Hello, I try to give a Smappee charger a limit of 10 amps while charging. This with a URL.
I have the correct acces_token and for the Serialnumber I used the deviceSerialNumber. The charger has 1 connector so for position I used 1.

When I sent the URL I get an error.
See link for more details: Set the charging mode of one of the connectors of a charging station - Smappee API - Confluence (atlassian.net)


Any tips?
Thanks

The serialnumber of the device wasn’t the same as in the Smappee App, when I used the number of the app it worked!

Hi Matisse,
I would like to do the same, however, i m not a programmer,
Could you please share how you set up this in Home assistant ?

Highly appreciated!

1 Like

Hi @SnokxStefan - What do you want to do with the Smappee Charger? As in what are you trying to control from HA and what will drive the automation?

I control my Smappee charger via an appdaemon “app” (to put only solar surplus in to the car and a few other modes of operation). I use OCPP to control sessions and just needed this for adjusting current as Smappee have not implemented current control in OCPP.

I have stripped it back a lot here for you to see just the smappee token and charger operation. However, this is defintely getting in to python programming to make it do something useful.

I tried to make the token generation and the use of token work via REST commands but in the end they were just too problematic (getting and saving and then using the bearer token) so I went the appdaemon path.

apps.yaml

smappee_charger_control:
  module: smappee_charger_control
  class: ChargerControl
  #Secrets......
  username: "UUUUUUUU"
  password: "PPPPPPPP"
  client_id: "IIIIIIII"
  client_secret: "SSSSSSS"

smappee_charger_control.py

import appdaemon.plugins.hass.hassapi as hass

import requests
import datetime as dt
from functools import wraps

#
# Smappee Smart Charging
# An AppDaemon App for controlling a smappee charger (via API)
#
# This was very customised to my house and emissions goals....
# Stripped back here

class ChargerControl(hass.Hass):

   def initialize(self):
      self.log("ChargerControl initialisation begins")

      self.access_token = None
      self.refresh_token = None
      self.token_expiration_time = None

      self.run_in( self.fetch_token, 0 ) #Get straight away and ever day (implement refresh one day.....)
      self.run_every(self.fetch_token, self.datetime(), 23*60*60)

      self.run_in(self.adjust_charger, 2)
      self.run_every(self.adjust_charger, self.datetime(), 60) #Update current every minute
      
      self.log("ChargerControl initialisation completes")


   def fetch_token(self, kwargs):
      login_url = "https://farm1pub.smappee.net/dev/v3/oauth2/token"

      data = {
            "grant_type": "password",
            "client_id": self.args["client_id"],
            "client_secret": self.args["client_secret"],
            "username": self.args["username"],
            "password": self.args["password"]
      }
      r = requests.post(login_url, data=data)
      r.raise_for_status()
      j = r.json()
      self.access_token = j['access_token']
      self.refresh_token = j['refresh_token']
      self._set_token_expiration_time(expires_in=j['expires_in'])

      self.log("sensor.smappee_token: {}".format( self.access_token ))

      self.log("sensor.smappee_refresh_token: {}".format( self.refresh_token ))

      return r

   def adjust_charger(self, kwargs):
      self.log("adjust_charger begin")

      headers = {
                  'Authorization': "Bearer {}".format( self.access_token),
                  'Content-Type': 'application/json'
               }
      current_amps = 6 #minimum
      #I have a lot more logic to control what the current should be based on solar, battery and load

      json_dict = {
                     'mode':"NORMAL",
                     'limit':{"unit": "AMPERE","value": current_amps},
                  }

      r = requests.put('https://app1pub.smappee.net/dev/v3/chargingstations/MY_CHARGER_ID/connectors/1/mode', json = json_dict, headers = headers)
      
      if r.status_code != 200:
         self.log("Not OK status code: {}".format(r.status_code))
      self.log("Charger current set to {} amps".format(current_amps) )

      return r


   def _set_token_expiration_time(self, expires_in):
      """
      Saves the token expiration time by adding the 'expires in' parameter
      to the current datetime (in utc).
      """
      self.token_expiration_time = dt.datetime.utcnow() + \
         dt.timedelta(0, expires_in)  # timedelta(days, seconds)

Let me know your thoughts/plans. I am happy to give some guidance and to tidy up my appdaemon app if it is useful.

Cheers,
Brody

1 Like

Thanks, saved me some hassle!

Hi Brody,
Thanks for answering my question, hihly appreciated !
i did get the API working for some time, but now it stopped. I assume because of token being expired.
I did set the power limit of my EV loader to low when my heat pump starts, and set back to high when the heat pump stops. This as a “peak shaving” solution.

I used this code :

Smappee Laadpaal set Limit

rest_command:
laadpaal_set_limit_high:
url: “https://app1pub.smappee.net/dev/v3/chargingstations/6521000106/connectors/1/mode
method: “put”
headers:
Content-Type: “application/json”
Authorization: “Bearer 1ef2b39d-684e-3abb-bc06-c83e9bfbcd16”
payload: ‘{“mode”: “NORMAL”,“limit”: {“unit”: “PERCENTAGE”,“value”: 100}}’
laadpaal_set_limit_low:
url: “https://app1pub.smappee.net/dev/v3/chargingstations/6521000106/connectors/1/mode
method: “put”
headers:
Content-Type: “application/json”
Authorization: “Bearer 1ef2b39d-684e-3abb-bc06-c83e9bfbcd16”
payload: ‘{“mode”: “NORMAL”,“limit”: {“unit”: “PERCENTAGE”,“value”: 5}}’

Worked fine as long as my heat pump switched on/off within the token expiracy time.
Now i was trying to create an automation to get a refresh token every 10 hours as per this post

i’ll try to get your solution working, however, i m not a programmer, so no idea what appdeamon is, will do some researh…
Thanks again !!

1 Like

I tried to make the API work without AppDaemon or Pyscript (just pure automation and sensors) but the token refresh was the kicker.

If you want to do something very basic w/ AppDaemon you can just get it to refresh a token and make that available as a sensor. Then your other setup should work (assuming that bearer header can be set using a template to get a token variable).

I find AppDaemon to be handy to do lots of my more complex automation needs (car charging and climate based on solar, battery levels and dynamic grid price).

I script various options for my charging because it is very powerful/flexible as it is python. It isn’t that difficult though (mainly just scripting with some asynchronous callbacks to trigger actions).

Let me know if/when you have the AppDaemon installed and I can give you a few more pointers.

1 Like

Hi Brody,
First of all thank you very much for your swift support !
Highly appreciated.
Quick question, i have Pyscript installed, as far as i understand, it has the same function as AppDaemon.
So, i’ll test your script using Pyscript as a first attempt
BR,
Stefan

1 Like

No probs.

Cool on Pyscript. You will need to rework the parts of the AppDaemon code that talk to the AppDaemon API to get/create sensors.

It should be a straightforward to port the code (especially for the tokens) BUT there will be a little “programming” know how to make those changes.

The refresh token snippet should be very easy to copy across though.

Let me know how you get on and if you get stuck.

1 Like

Cool, pyscript is set up, jupyter works,i’ll give it a try.
Thanks for your assistance !!

1 Like

Hi Brody,
Got it working in Pyscript !
Thank you for the inspiration, helped me a lot !
BR,
Stefan

1 Like

Excellent.

It seems like you might be a programmer after all!

Oh, after you are happy with the code it would be good to share it. Using Pyscript is something lots of people will prefer over AppDaemon so that will be a great example to share.

Hi, I want to try this in pyscript as well. Do you mind to share your code?
Thx

1 Like

@brodykenrick how u run this “apps.yaml” & “smappee_charger_control.py” in home assistant?
I’m still pretty new to home assistant, so only worked with integrations so far. This seems something different? :slight_smile:

Kind regards,

It is different. It is an add-on that allows you to program your own python scripts.

See AppDaemon Tutorial for HASS Users — AppDaemon 4.4.3 documentation

You need to add the AppDaemon add-on then copy in the “module” python file and modify the apps.yaml.

If there are enough Smappee users using HA with a Smappee charger we might want to raise that with Smappee to support it in the integration.

I raised a feature request nearly two years back at Smappee Charger Feature? · Issue #9 · smappee/pysmappee · GitHub

If people go and vote on that and send a message to Smappee support it might get some traction.

Yes, i seen the github issue, but noticed all issues & PR’s on they’re github are old, so not active maintained.

Alternative is making a custom integration for charger only if enough people interested? I guess for most people the “main” feature is putting the charger on pause or charge and limit the charge rate?

Smappee will potentially do something if more people ask. Their support said that to me.

They think it is just me out here in HA with a charger wanting more support. I suggest you (and anyone else keen) putting a +1 on the GitHub issue and ping smappee customer support directly.

I contemplated doing a custom component or extending the current component but the lack of features made it feel less useful. Especially that lack of power info.

I am happy with my AppDaemon setup currently as it allows me to more easily cover for the smappee deficiencies.

I was looking at the pysmappee code to see how API was implemented and what is required to make the required changes. Make some changes there and

Seems the implementation is mainly based on the service locations only, while it would require getting the service location, then the smart devices to get the serial for the EV charger(s) in case u want to enum them instead of hardcode / config the serial.

According to they’re release notes, they removed smart devices after 0.2.17 release, but even there it seems not fully implemented.

So i’m not sure if we should rely on Smappee to get a EV charger integration in HA