question

offgridtas avatar image
offgridtas asked

Help with API

Hi.


I'm trying to extract some SoC information from the Cerbo using a Raspberry Pi running Python. I'm able to get a token but when I try and use the token it is returning "errors":"Login required","error_code":"invalid_credentials"


Surely if it's giving me a token, the credentials aren't invalid.


Any help greatly appreciated.


import requests





USERNAME = 'my username'

PASSWORD = 'my password'



# VRM API endpoints

LOGIN_URL = 'https://vrmapi.victronenergy.com/v2/auth/login'

DATA_URL_TEMPLATE = 'https://vrmapi.victronenergy.com/v2/installations/{installation_id}/stats/latest'



def get_auth_token(username, password):

    # Authenticate and obtain an authorization token

    headers = {'Content-Type': 'application/json'}

    payload = {'username': username, 'password': password}

    response = requests.post(LOGIN_URL, headers=headers, json=payload)



    if response.status_code == 200:

        token = response.json().get('token')

        return token

    else:

        print(f'Failed to authenticate: {response.status_code} - {response.text}')

        return None



def get_current_soc(token, installation_id):

    # Get current State of Charge (SoC) using the obtained token

    headers = {

        'Authorization':f'Bearer {token}',

        'Content-Type':'application/json'

    }

    url = DATA_URL_TEMPLATE.format(installation_id=installation_id)

    response = requests.get(url, headers=headers)



    if response.status_code == 200:

        data = response.json()

        soc = data.get('battery', {}).get('stateOfCharge')

        if soc is not None:

            return soc

        else:

            print('State of Charge (SoC) not found in response.')

            return None

    else:

        print(f'Failed to fetch SoC: {response.status_code} - {response.text}')

        return None



if __name__ == '__main__':

    

    installation_id = 'my installation ID'



    # Authenticate and get token

    token = get_auth_token(USERNAME, PASSWORD)

    if token:

        # Get current SoC

        print(token)

        soc = get_current_soc(token, installation_id)

        if soc is not None:

            print(f'Current State of Charge (SoC): {soc}%')

        else:

            print('Failed to fetch State of Charge (SoC)..')

    else:

        print('Authentication failed.')



api
1 comment
2 |3000

Up to 8 attachments (including images) can be used with a maximum of 190.8 MiB each and 286.6 MiB total.

0 Answers

Related Resources

Additional resources still need to be added for this topic