Unifi Access API

Hello
I don’t know if someone is working on this. But unifi released a new API to control doors get events etc.

For the moment I had some success in this little python script for testing:


import requests
import json
import time

def fetch_system_logs(host, token, topic, page_num=1, page_size=25, since=None, until=None, actor_id=None):
    url = f"{host}/api/v1/developer/system/logs"
    headers = {
        "Authorization": f"Bearer {token}",
        "accept": "application/json",
        "content-type": "application/json"
    }
    query_params = {
        "page_num": page_num,
        "page_size": page_size
    }
    if since:
        query_params["since"] = since
    if until:
        query_params["until"] = until
    body = {
        "topic": topic
    }
    if actor_id:
        body["actor_id"] = actor_id
    try:
        response = requests.post(url, headers=headers, params=query_params, json=body, verify=False)
        if response.status_code == 200:
            return response.json()
        else:
            return {"error": f"Failed to fetch logs, HTTP Status Code: {response.status_code}"}
    except requests.exceptions.RequestException as e:
        return {"error": f"An error occurred: {e}"}

def extract_user_info_from_logs(logs):
    user_activity = []
    if 'data' in logs and 'hits' in logs['data']:
        for log_entry in logs['data']['hits']:
            source = log_entry.get('_source', {})
            timestamp = log_entry.get('@timestamp', 'N/A')
            actor = source.get('actor', {})
            event = source.get('event', {})
            actor_name = actor.get('display_name', 'N/A')
            event_type = event.get('type', 'N/A')
            event_result = event.get('result', 'N/A')
            user_activity.append({
                'Timestamp': timestamp,
                'Name': actor_name,
                'Event': event_type,
                'Result': event_result
            })
    return user_activity

if __name__ == "__main__":
    host = "https://192.168.1.1:12445"  # IP most likely the same
    token = "token_here"  # here your actual token from the security tab of unifi Access webinterface
    topic = "door_openings" 

    while True: 
        logs = fetch_system_logs(host, token, topic)
        user_activity = extract_user_info_from_logs(logs)
        for activity in user_activity:
            print(f"Timestamp: {activity['Timestamp']}, Name: {activity['Name']}, Event: {activity['Event']}, Result: {activity['Result']}")
        
        time.sleep(10)


Still reading on what is the best way to use openhab to poll this API to get almost real time events seeing I don’t find any webhooks references in this document:
api_reference.pdf (580.8 KB)

Is the http binding the right tool for this job ?

You’re not going to get near realtime through polling from OH. The only way you’ll get near realtime is if Unifi can push the status to OH. I see no mechanism for it to do that from this API.

Given that you have this working in Python already, the easiest would be to use the Exec binding to call this script. Another approach would be to update this script to run as a service and push state updates to OH either through OH’s REST API or MQTT.

If you want to implement this as a native OH rule, you’ll want to use the HTTP binding and/or the sendHttpXRequest actions.

Thank you rlkoshak
I already posted on the unifi forums the lack of webhooks maybe in two years we will get another update.
For now I already did the same for wallbox pulsar API to integrate it openhab using an python library used also by homeassistant so maybe I will stick with this test grow it and add mqtt. As for the real time update I have a cunning plan because I have knx connected to the doorbel output and also the lock I can poll the api only then so hey presto real time update(I think). I will work on a proof of concept this would be nice with my alarm diy projects if I can poll the pin code entered. I don’t need to worry about ssl for the moment because it’s all local.
But would be cool to have an example of someone doing API using openhab without having to deal with java binding and someone developing one for simple task like this.

I do something similar with my router. I use the http actions in a (JSScripting) rule instead of the http binding. I chose this method for one primary reason: for dynamic header information such as a bearer token that changes the http binding isn’t great; it’s much easier to handle the authentication in the script. There’s a secondary reason about how I process the data I get from the polling but that’s specific to my system.

How do you deal with ssl because I cannot find anything to ignore it in the JavaScript docs ?

The HTTP binding supports HTTPS but the rule actions do not. Also, the usual JavaScript HTTP stuff like XMLHttpRequest are not available. You’ll have to use the raw Java Objects. See Honeywell Home API with openHAB using just rules for an example though be forewarned it’s pretty hackey and never did work well.

I need time to process that. Just for fun what are the consequences if I modify /etc/openhab/runtime.cfg with this

-Dcom.sun.net.ssl.checkRevocation=false
-Djava.security.egd=file:/dev/./urandom

It looks like it may make it ignore bad certificates but it’s not going to suddenly convert HTTPS to HTTP. You’ll still have to do the handshake and set up an encrypted SSL/TLS channel, it just wont refuse to do so when the certificate is revoked, self signed, or otherwise untrusted.

Unifi has an event driven api based on websockets. It has been reversed engineered. I utilize this api for events in the unifi protect binding for detecting motions in cameras and when you push the doorbell button. Feel free to look at the code for inspiration and how to decode the websocket frames.

As far as i know, the same api is used with the other unifi products as well, it’s not only limited to unifi protect.

Best regards, s

Well I am not an developer and I do use your binding to get events from some unifi cameras that I have. I am still trying to grasp the ropes of scripting languages. But probably in the end I will have to start something and see what happens.
Keep in mind I am just a simple electrician :slight_smile:

Hi!
Yes, then I understand. If you want to start develop some java-binding yourself (given if you have interest) then I can recommend to take a look at all the current bindings, it is not that hard and you don’t have to come up with everything yourself.

/S

Hello
Well I asked on the unifi forums for webhooks and actually they said they are working on it


Hi @stamate,

Webhook functionality will be available at a later stage as it's still under development.

So I don’t think it’s available the same way as unifi protect. For the moment I tried setting up eclipse took a whole day for it to startup and I got millions of errors and don’t know what to do next also the bloody thing is heavy takes 70 percent of the memory of the computer.

Hi!

Yes, might still be a websocket API you can use. Webhooks is something else.
https://hookdeck.com/webhooks/guides/when-to-use-webhooks

/S