sensor.unifigateway icon indicating copy to clipboard operation
sensor.unifigateway copied to clipboard

Update for sensor fails after a couple hours

Open myopenflixr opened this issue 1 year ago • 65 comments

I am having an error that seemed to start on Home Assistant 2023.11. After a couple hours of restarting Home Assistant, the sensors fail and stop updating. The only FIX is to restart Home Assistant to get the sensor data back. But, it stops working and throws errors again after a couple hours.

Here's two entries in the Logs showing the errors.

Any help would be greatly appreciated!

Logger: homeassistant.helpers.entity
Source: helpers/entity.py:696
First occurred: 12:38:35 PM (12 occurrences)
Last logged: 12:44:05 PM

Update for sensor.unifi_gateway_firmware_upgradable fails
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 696, in async_update_ha_state
    await self.async_device_update()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 959, in async_device_update
    await hass.async_add_executor_job(self.update)
  File "/usr/local/lib/python3.11/concurrent/futures/thread.py", line 58, in run
    result = self.fn(*self.args, **self.kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/util/__init__.py", line 190, in wrapper
    result = method(*args, **kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^
  File "/config/custom_components/unifigateway/sensor.py", line 166, in update
    if devices.get('upgradable'):
       ^^^^^^^^^^^
AttributeError: 'str' object has no attribute 'get'
Logger: homeassistant.helpers.entity
Source: helpers/entity.py:696
First occurred: 12:38:35 PM (60 occurrences)
Last logged: 12:44:05 PM

Update for sensor.unifi_gateway_www fails
Update for sensor.unifi_gateway_wan fails
Update for sensor.unifi_gateway_wlan fails
Update for sensor.unifi_gateway_lan fails
Update for sensor.unifi_gateway_vpn fails
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 696, in async_update_ha_state
    await self.async_device_update()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 959, in async_device_update
    await hass.async_add_executor_job(self.update)
  File "/usr/local/lib/python3.11/concurrent/futures/thread.py", line 58, in run
    result = self.fn(*self.args, **self.kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/util/__init__.py", line 190, in wrapper
    result = method(*args, **kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^
  File "/config/custom_components/unifigateway/sensor.py", line 178, in update
    if sub['subsystem'] == self._sensor:
       ~~~^^^^^^^^^^^^^
TypeError: string indices must be integers, not 'str'

myopenflixr avatar Dec 03 '23 17:12 myopenflixr

I'm having exactly the same issue as well.

SeeThisIsMe avatar Dec 16 '23 23:12 SeeThisIsMe

Same here! Works fine for a few hours and then starts failing until the next reboot.

ykuijs avatar Dec 22 '23 08:12 ykuijs

Experiencing the same issue. Seems to be connected to the latest UniFi OS 3.2. Started here after having upgraded the UniFi Cloud Key.

Logger: homeassistant.helpers.entity
Source: helpers/entity.py:698
First occurred: 20:06:37 (32 occurrences)
Last logged: 20:22:07
Update for sensor.unifi_gateway_firmware_upgradable fails

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 698, in async_update_ha_state
    await self.async_device_update()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 961, in async_device_update
    await hass.async_add_executor_job(self.update)
  File "/usr/local/lib/python3.11/concurrent/futures/thread.py", line 58, in run
    result = self.fn(*self.args, **self.kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/util/__init__.py", line 190, in wrapper
    result = method(*args, **kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^
  File "/config/custom_components/unifigateway/sensor.py", line 162, in update
    if devices.get('upgradable'):
       ^^^^^^^^^^^
AttributeError: 'str' object has no attribute 'get'
Logger: homeassistant.helpers.entity
Source: helpers/entity.py:698
First occurred: 20:06:37 (32 occurrences)
Last logged: 20:22:07

Update for sensor.unifi_gateway_alerts fails
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 698, in async_update_ha_state
    await self.async_device_update()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 961, in async_device_update
    await hass.async_add_executor_job(self.update)
  File "/usr/local/lib/python3.11/concurrent/futures/thread.py", line 58, in run
    result = self.fn(*self.args, **self.kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/util/__init__.py", line 190, in wrapper
    result = method(*args, **kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^
  File "/config/custom_components/unifigateway/sensor.py", line 145, in update
    if not alert['archived']:
           ~~~~~^^^^^^^^^^^^
TypeError: string indices must be integers, not 'str'
Logger: homeassistant.helpers.entity
Source: helpers/entity.py:698
First occurred: 20:06:37 (128 occurrences)
Last logged: 20:22:07

Update for sensor.unifi_gateway_www fails
Update for sensor.unifi_gateway_wan fails
Update for sensor.unifi_gateway_wlan fails
Update for sensor.unifi_gateway_lan fails
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 698, in async_update_ha_state
    await self.async_device_update()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 961, in async_device_update
    await hass.async_add_executor_job(self.update)
  File "/usr/local/lib/python3.11/concurrent/futures/thread.py", line 58, in run
    result = self.fn(*self.args, **self.kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/util/__init__.py", line 190, in wrapper
    result = method(*args, **kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^
  File "/config/custom_components/unifigateway/sensor.py", line 174, in update
    if sub['subsystem'] == self._sensor:
       ~~~^^^^^^^^^^^^^
TypeError: string indices must be integers, not 'str'

Tamsy avatar Dec 24 '23 13:12 Tamsy

I have the same issue, if anyone finds a fix please let me know

haroldboom avatar Dec 24 '23 20:12 haroldboom

Same here. Only option is to reload. Frustrating, given I have automation hung off this.

martinkwright avatar Jan 02 '24 14:01 martinkwright

Seem to work again as it should with HA 2024.1.1. In case it stops again I will report here.

Addendum: I wrote too soon. The issue started again :(

Tamsy avatar Jan 06 '24 00:01 Tamsy

Same here. After a reload it works for a couple of hours and then fails again.

DocEvel avatar Jan 07 '24 15:01 DocEvel

same here.

Logger: homeassistant.helpers.entity
Source: helpers/entity.py:894
First occurred: 08:51:25 (1 occurrences)
Last logged: 08:51:25

Update for sensor.unifi_gateway_firmware_upgradable fails
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 894, in async_update_ha_state
    await self.async_device_update()
  File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 1214, in async_device_update
    await hass.async_add_executor_job(self.update)
  File "/usr/local/lib/python3.11/concurrent/futures/thread.py", line 58, in run
    result = self.fn(*self.args, **self.kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/src/homeassistant/homeassistant/util/__init__.py", line 190, in wrapper
    result = method(*args, **kwargs)
             ^^^^^^^^^^^^^^^^^^^^^^^
  File "/config/custom_components/unifigateway/sensor.py", line 162, in update
    if devices.get('upgradable'):
       ^^^^^^^^^^^
AttributeError: 'str' object has no attribute 'get'

canedje avatar Jan 09 '24 07:01 canedje

I also have this issue

bobbinz avatar Jan 15 '24 20:01 bobbinz

last update was about 3 years. So I do not expect anything. A pitty

canedje avatar Jan 22 '24 20:01 canedje

I guess it’s time to remove it?

haroldboom avatar Jan 22 '24 22:01 haroldboom

I guess it’s time to remove it?

Sadly it pretty much looks like this useful tool has turned into abandonedware.

Tamsy avatar Jan 23 '24 01:01 Tamsy

Why is not anyone else taking over? Can't imagine some devs are not into this as ubiquiti is very popular! Same issue here. Only thing that helps is to reset the Template sensors or reboot HA

coldburn89 avatar Feb 07 '24 12:02 coldburn89

I guess it’s time to remove it?

Sadly it pretty much looks like this useful tool has turned into abandonedware.

What about this one? https://github.com/zvldz/unifi_status/tree/master/custom_components/unifi_status

Looks like someone took over but its also not updated for 2 years

coldburn89 avatar Feb 07 '24 12:02 coldburn89

Why is not anyone else taking over? Can't imagine some devs are not into this as ubiquiti is very popular! Same issue here. Only thing that helps is to reset the Template sensors or reboot HA

I tried resetting the template sensors but it instantly fails for me. Yeah I wish I had the skills to take it over, it works so well

haroldboom avatar Feb 07 '24 19:02 haroldboom

I guess it’s time to remove it?

Sadly it pretty much looks like this useful tool has turned into abandonedware.

What about this one? https://github.com/zvldz/unifi_status/tree/master/custom_components/unifi_status

Looks like someone took over but its also not updated for 2 years

Tried it and no good. I even tried removing code that I didn’t use like firmware and vpn but it still crashes.

Maybe @zvldz could fix it if anyone can get hold of them?

haroldboom avatar Feb 07 '24 19:02 haroldboom

I guess it’s time to remove it?

Sadly it pretty much looks like this useful tool has turned into abandonedware.

What about this one? https://github.com/zvldz/unifi_status/tree/master/custom_components/unifi_status Looks like someone took over but its also not updated for 2 years

Tried it and no good. I even tried removing code that I didn’t use like firmware and vpn but it still crashes.

Maybe @zvldz could fix it if anyone can get hold of them?

Since the new update today it's completely broken and the sensors doesn't work anymore. 😢

coldburn89 avatar Feb 09 '24 19:02 coldburn89

I managed to replace all the functionality I was using this for via other means quite easily. I get bits of information now for my dream machine SE instead using the official integration (status, uptime, external IP, and a few others) and a graph for bandwidth usage via SNMP.

Depending on what people used this for, you may be able to do the same without too much difficulty.

SeeThisIsMe avatar Feb 10 '24 00:02 SeeThisIsMe

I tried SNMP but I couldn’t get CPU usage and also when it updated it wiped off my SNMP install. This is on the UDM-Pro

On Sat, 10 Feb 2024 at 11:51, SeeThisIsMe @.***> wrote:

I managed to replace all the functionality I was using this for via other means quite easily. I get bits of information now for my dream machine SE instead using the official integration (status, uptime, external IP, and a few others) and a graph for bandwidth usage via SNMP.

Depending on what people used this for, you may be able to do the same without too much difficulty.

— Reply to this email directly, view it on GitHub https://github.com/custom-components/sensor.unifigateway/issues/59#issuecomment-1936779870, or unsubscribe https://github.com/notifications/unsubscribe-auth/AKH2FP66NCR2FFMEBTAS4PDYS2777AVCNFSM6AAAAABAE6EHR6VHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMYTSMZWG43TSOBXGA . You are receiving this because you are subscribed to this thread.Message ID: @.*** com>

haroldboom avatar Feb 10 '24 01:02 haroldboom

I managed to replace all the functionality I was using this for via other means quite easily. I get bits of information now for my dream machine SE instead using the official integration (status, uptime, external IP, and a few others) and a graph for bandwidth usage via SNMP.

Depending on what people used this for, you may be able to do the same without too much difficulty.

Do you mind sharing? I think alot of people will find that useful.

coldburn89 avatar Feb 10 '24 07:02 coldburn89

@SeeThisIsMe It would be really great if you could share the steps you took to get it to work. That will benefit many more of us.

ykuijs avatar Feb 12 '24 07:02 ykuijs

Here is my "fix"... please note that this script grew organically over time as I moved features from the other plugins to my unified script ( pun intended ) ...

** Disclosure: not once have I gone back over the code to refactor, clean up, or optimize**!!

#!/usr/local/bin/python

from datetime import timedelta
import json, yaml, requests
from datetime import datetime
import requests,time
from re import sub
import sys

resp={}
resp['data']={}


def parse_uptime(uptime):
  seconds = uptime
  days = seconds // 86400
  hours = (seconds - (days * 86400)) // 3600
  minutes = (seconds - (days * 86400) - (hours * 3600)) // 60
  uptime = str(days)+'d '+str(hours)+'h '+str(minutes)+'m'
  return uptime

controller_url = 'https://xxxxx.xxxxx.xxxxx'
username = 'xxxx'
password = 'xxxx'
site = 'default'  # The site ID, 'default' for most installations


login_url = f'{controller_url}/api/auth/login'
login_data = {
    'username': username,
    'password': password
}

session = requests.Session()
response = session.post(login_url, json=login_data, verify=True)
response.raise_for_status()

def snake_case(s):
  return '_'.join(
    sub('([A-Z][a-z]+)', r' \1',
    sub('([A-Z]+)', r' \1',
    s.replace('-', ' '))).split()).lower()


rules_url = 'https://xxxx.xxxx.xxxx/proxy/network/api/s/default/stat/device'

response = session.get(rules_url, verify=False)
response.raise_for_status()
rules = response.json()
sysinfo_url = 'https://xxxx.xxxx.xxxx/proxy/network/api/s/default/stat/sysinfo'

response = session.get(sysinfo_url, verify=False)
response.raise_for_status()
version = response.json()




health_url = 'https://xxxx.xxxx.xxx/proxy/network/api/s/default/stat/health'

response = session.get(health_url, verify=False)
response.raise_for_status()
health_data = response.json()

# keys = health_data['data'][0].keys()
# a = {k: set(d[k] for d in health_data['data']) for k in keys}
# print(json.dumps(health_data, indent = 1))
#
for h in health_data['data']:

  match h['subsystem']:
    case 'www':
      # print(json.dumps(h, indent = 1))
      resp['data'].update({
        "health_" + h['subsystem'] + ".status": h['status'],
        "health_" + h['subsystem'] + ".tx_bytes-r": h['tx_bytes-r'],
        "health_" + h['subsystem'] + ".rx_bytes-r": h['rx_bytes-r'],
        "health_" + h['subsystem'] + ".latency": h['latency'],
        "health_" + h['subsystem'] + ".uptime": h['uptime'],
        "health_" + h['subsystem'] + ".drops": h['drops'],
        "health_" + h['subsystem'] + ".xput_up": h['xput_up'],
        "health_" + h['subsystem'] + ".xput_down": h['xput_down'],
        "health_" + h['subsystem'] + ".speedtest_status": h['speedtest_status'],
        "health_" + h['subsystem'] + ".speedtest_lastrun": h['speedtest_lastrun'],
        "health_" + h['subsystem'] + ".speedtest_ping": h['speedtest_ping'],
        "health_" + h['subsystem'] + ".uptime": h['uptime']

      })

    case 'vpn':
      resp['data'].update({
        "health_" + h['subsystem'] + ".status": h['status'],
      })
      # test
    case 'wlan':
      resp['data'].update({
        "health_" + h['subsystem'] + ".num_user": h['num_user'],
        "health_" + h['subsystem'] + ".num_guest": h['num_guest'],
        "health_" + h['subsystem'] + ".num_iot": h['num_iot'],
        "health_" + h['subsystem'] + ".tx_bytes": h['tx_bytes-r'],
        "health_" + h['subsystem'] + ".rx_bytes": h['rx_bytes-r'],
        "health_" + h['subsystem'] + ".status": h['status'],
        "health_" + h['subsystem'] + ".num_ap": h['num_ap']
      })

    case 'lan':
      resp['data'].update({
        "health_" + h['subsystem'] + ".status": h['status'],
        "health_" + h['subsystem'] + ".num_user": h['num_user'],
        "health_" + h['subsystem'] + ".num_iot": h['num_iot'],
        "health_" + h['subsystem'] + ".num_sw": h['num_sw'],
        "health_" + h['subsystem'] + ".num_adopted": h['num_adopted']
      })

      # test
    case 'wan':
      # print(h['subsystem'])
      # print(json.dumps(h, indent = 1))
      resp['data'].update({
        "health_" + h['subsystem'] + ".status": h['status'],
        "health_" + h['subsystem'] + ".isp_organization": h['isp_organization'],
        "health_" + h['subsystem'] + ".isp_name": h['isp_name'],
        "health_" + h['subsystem'] + ".gw_version": h['gw_version'],
        "health_" + h['subsystem'] + ".num_sta": h['num_sta'],
        "health_" + h['subsystem'] + ".cpu": h['gw_system-stats']['cpu'],
        "health_" + h['subsystem'] + ".mem": h['gw_system-stats']['mem'],
        "health_" + h['subsystem'] + ".uptime": h['gw_system-stats']['uptime'],
        "health_" + h['subsystem'] + ".tx_bytes": h['tx_bytes-r'],
        "health_" + h['subsystem'] + ".rx_bytes": h['rx_bytes-r']
      })

    case _:
      print("else")


# uptime_stats = "https://xxxxx.xxx.xxxx/proxy/network/api/s/default/stat/stats"
#

# response_stats = session.get(uptime_stats, verify=False)
# response_stats.raise_for_status()
# data = response_stats.json()["data"][0]
# # # print(version)
# json.dumps(print(resp['data']))
# print(json.dumps(resp['data'], indent = 1))
# print(json.dumps({
#     "cpu": data["system-stats"]["cpu"],
#     "cpu_temp": round(data["temperatures"][1]["value"], 1),
#     "system_temp": round(data["temperatures"][0]["value"], 1),
#     "memory": data["system-stats"]["mem"],
#     "disk": round(data["storage"][1]["used"] / data["storage"][1]["size"] * 100, 1),
#     "internet": data["wan1"]["up"],
#     "uptime": datetime.fromtimestamp(data["startup_timestamp"]).isoformat(),
#     "availability": data["uptime_stats"]["WAN"]["availability"],
#     "average_latency": data["uptime_stats"]["WAN"]["latency_average"],
#     "down": data["uplink"]["rx_rate"] / 1000000,
#     "up": data["uplink"]["tx_rate"] / 1000000,
#     "version": data["displayable_version"],
#     "last_wan_ip": data["last_wan_ip"]
# }))
# sys.exit(2)


resp["version"]=version['data'][0]['version']
# # Find the rule to update
for client_data in rules['data']:

  ## If switch is offline ignore
  if client_data['state'] == 0:
    continue

  name=snake_case(client_data['name'])
  # print(client_data)
  # resp[name]={}

# # print(version)
  # json.dumps(print(client_data))

  internet = None
  speedtest_status = None
  # print("client_data['model'] %s",client_data['model'] )
  if client_data['model'] == "UDMPRO":
    speedtest_status = client_data['uplink']['speedtest_status'] == "Success"
    internet = client_data['uplink']['up']
    # if 'uplink' in client_data.keys():
    #   if client_data['uplink']['uplink_source'] == 'legacy':
    #     internet = client_data['uplink']['up']
    #   else:
    #     internet = client_data['internet']
    #     print("client_data['model'] %s",client_data['model'] )
    # elif 'internet' in client_data.keys():
    #   internet = client_data['internet']
    #   print("client_data['model'] %s",client_data['model'] )
  cpu=0
  ram=0
  try:
    if client_data['system-stats'] and client_data['system-stats'] != {} and len(client_data['system-stats'].keys()) != 0:
      try:
        cpu = float(client_data['system-stats']['cpu'])
      except:
        cpu = 0.0
      try:
        ram = float(client_data['system-stats']['mem'])
      except:
        ram = 0
  except:
    print("An exception occurred")
    print(json.dumps(client_data, indent = 1))
    print("------")



  activity = round(client_data['uplink']['rx_bytes-r']/125000 + client_data['uplink']['tx_bytes-r']/125000,1)
  uptime = parse_uptime(client_data['uptime'])
  update = int(client_data['upgradable'])
  model_type = client_data['model']




  # print(type)


  if client_data['is_access_point']:
      wifi0clients = client_data['radio_table_stats'][0]['user-num_sta']
      wifi1clients = client_data['radio_table_stats'][1]['user-num_sta']
      wifi0score = client_data['radio_table_stats'][0]['satisfaction']
      wifi1score = client_data['radio_table_stats'][1]['satisfaction']
      numclients = client_data['user-wlan-num_sta']
      numguests = client_data['guest-wlan-num_sta']
      score = client_data['satisfaction']

      # raise ValueError('Some error')
      resp['data'].update ({
          name+".Clients":numclients,
          name+".Guests":numguests,
          name+".Clients_wifi0":wifi0clients ,
          name+".Clients_wifi1":wifi1clients ,
          name+".Score":score,
          name+".CPU": cpu,
          name+".RAM":ram,
          name+".Uptime":uptime,
          name+".Score_wifi0":wifi0score ,
          name+".Score_wifi1":wifi1score ,
          name+".Activity":str(activity)+' Mbps',
          name+".Update":update,
      })

  else:
    cpu_temp = None
    board_temp = None
    wan_drops = None
    wan_latency = None
    if 'temperatures' in client_data.keys() and  client_data['temperatures']!={}:
      for t in client_data['temperatures']:
        if t['type'] == "cpu" : cpu_temp = t['value']
        if t['type'] == "board" : board_temp = t['value']



    # json.dumps(print(client_data))
    # print(json.dumps(client_data, indent = 1))


    storage_used = None
    storage_size = None
    if 'storage' in client_data.keys() and  client_data['storage']!=[]:
      for t in client_data['storage']:

        if t['mount_point'] == "/persistent":
          storage_size = t['size']
          storage_used = t['used']

    availability=None
    latency_average=None
    uplink_ip=None

    if 'uptime_stats' in client_data.keys() and  client_data['uptime_stats']!={}:
        for t in client_data['uptime_stats']['WAN']['alerting_monitors']:
          if t['target'] == "1.1.1.1":
            latency_average = t['latency_average']
            availability = t['availability']


    if 'uplink' in client_data.keys() and client_data['uplink']!={} and 'comment' in client_data['uplink'].keys():

        # json.dumps(print(client_data['uplink']))
        # print(json.dumps(client_data['uplink'], indent = 1))
        if client_data['uplink']['comment'] == "WAN":
          wan_latency = client_data['uplink']['latency']
          wan_drops = client_data['uplink']['drops']
          uplink_ip = client_data['uplink']['ip']


# uplink


        # print(t)
            # print(json.dumps(client_data, indent = 1))
    # if 'speedtest-status' in client_data.keys() and client_data['speedtest-status'] is not None:
    #   print("---")
    #   # print(client_data['speedtest-status'])
    #   # json.dumps(print(client_data))
    #   print(json.dumps(client_data['uplink'], indent = 1))

    #   print("---")
    # internet = client_data['internet']
    usedports = client_data['num_sta']
    userports = client_data['user-num_sta']
    guestports = client_data['guest-num_sta']


    resp['data'].update({
      name+".Activity":str(activity)+' Mbps',
      name+".CPU":cpu,
      name+".RAM":ram,
      name+".Uptime":uptime,
      name+".Ports_used":usedports,
      name+".Ports_user":userports,
      name+".Ports_guest":guestports,
      name+".Update":update,
      name+".Model": model_type
    })

    if 'speedtest_ping' in client_data['uplink'].keys() and client_data['uplink']['speedtest_ping'] is not None:

      resp['data'].update({
        name+".Speedtest_ping": client_data['uplink']['speedtest_ping'],
        name+".Speedtest_up":   client_data['uplink']['xput_up'],
        name+".Speedtest_down": client_data['uplink']['xput_down']
      })
    if storage_used is not None:
      resp['data'].update({
        name+".StorageUsed": storage_used,
        name+".StorageSize": storage_size
      })
    if internet is not None:
      resp['data'].update({
        name+".Internet": internet
      })
    if speedtest_status is not None:
      resp['data'].update({
        name+".SpeedTestPass": speedtest_status
      })
    if cpu_temp is not None:
      resp['data'].update({
        name+".CPUTemp":cpu_temp,
        name+".BoardTemp":board_temp
      })

    if wan_drops is not None:
      resp['data'].update({
        name+".WanDrops":wan_drops,
        name+".WanLatency":wan_latency
      })


    if latency_average is not None:
      resp['data'].update({
        name+".LatencyAvg":latency_average,
        name+".WanAvailability":availability
      })

    if uplink_ip is not None:
      resp['data'].update({
        name+".UplinkIP":uplink_ip
      })





# print(resp)
# formatted_json = json.dumps(resp, sort_keys=True, indent=4)
# colorful_json = highlight(formatted_json, lexers.JsonLexer(), formatters.TerminalFormatter())
# print(colorful_json)
json_formatted_str = json.dumps(resp, indent=2)
print(json_formatted_str)
# Log out of the UniFi Controller
logout_url = f'{controller_url}/api/auth/logout'
session.post(logout_url, verify=False)

sys.exit(0)

Here is my ha config

command_line:

  - sensor:
      name: udmpro_disk_usage
      command: !secret udmpro_disk_usage
      scan_interval: 3600

  - sensor:
      command: '/config/scripts/unifi_combined2.py'
      command_timeout: 180
      name: unifi_stats
      value_template: '{{value_json.version}}' 
      scan_interval: 300
      json_attributes:
        - data
     
template:
  binary_sensor:
    - name: Unifi UDM Pro Internet Up
      unique_id: unifi_udmpro_internet_up
      state: >
        {{ state_attr('sensor.unifi_stats','data')['udmpro.Internet'] }}

  sensor:
    ## Unifi AP Basement
    - name: Unifi AP Basement Guests
      unique_id: unifi_ap_basement_guests
      state: >
          {{ state_attr('sensor.unifi_stats','data')['basement_ap.Guests'] }}

    - name: Unifi AP Basement Activity
      unique_id: unifi_ap_basement_activity
      unit_of_measurement: 'Mbps'
      state: >
          {{ state_attr('sensor.unifi_stats','data')['basement_ap.Activity'].split(' ')[0] | float(0) }}

    - name: Unifi AP Basement RAM
      unique_id: unifi_ap_basement_ram
      unit_of_measurement: '%'
      state: >
        {{ state_attr('sensor.unifi_stats','data')['basement_ap.RAM'] | float(0) }}

    - name: Unifi AP Basement CPU
      unique_id: unifi_ap_basement_cpu
      unit_of_measurement: '%'
      state: >
        {{ state_attr('sensor.unifi_stats','data')['basement_ap.CPU'] | float(0) }}

    - name: Unifi AP Basement Score
      unique_id: unifi_ap_basement_score
      state: >
        {{ state_attr('sensor.unifi_stats','data')['basement_ap.Score'] }}

    - name: Unifi AP Basement 2.4gHz Score
      unique_id: unifi_ap_basement_2ghz_score
      state: >
        {{ state_attr('sensor.unifi_stats','data')['basement_ap.Score_wifi0'] | default(0) }}

    - name: Unifi AP Basement 5gHz Score
      unique_id: unifi_ap_basement_5ghz_score
      state: >
        {{ state_attr('sensor.unifi_stats','data')['basement_ap.Score_wifi1'] | default(0) }}

    - name: Unifi AP Basement 2.4gHz Clients
      unique_id: unifi_ap_basement_2ghz_wifi_devices
      state: >
        {{ state_attr('sensor.unifi_stats','data')['basement_ap.Clients_wifi0']  | default(0) }}

    - name: Unifi AP Basement 5gHz Clients
      unique_id: unifi_ap_basement_5ghz_wifi_devices
      state: >
        {{ state_attr('sensor.unifi_stats','data')['basement_ap.Clients_wifi1'] | default(0) }}

    - name: Unifi AP Basement Total Clients
      unique_id: unifi_ap_basement_total_clients
      state: >
        {{ state_attr('sensor.unifi_stats','data')['basement_ap.Clients_wifi0'] + state_attr('sensor.unifi_stats','data')['basement_ap.Clients_wifi1']  | default(0) }}

    - name: Unifi AP Basement Updates
      unique_id: unifi_ap_basement_update
      state: >
        {% if state_attr('sensor.unifi_stats', 'data')['basement_ap.Update'] == 0 %}
          No
        {% else %}
          Available
        {% endif %}

    ### Unifi AP Outside
    - name: Unifi AP Outside Guests
      unique_id: unifi_ap_outside_guests
      state: >
        {{ state_attr('sensor.unifi_stats','data')['outside_ap.Guests'] }}

    - name: Unifi AP Outside Activity
      unique_id: unifi_ap_outside_activity
      unit_of_measurement: 'Mbps'
      state: >
        {{ state_attr('sensor.unifi_stats','data')['outside_ap.Activity'].split(' ')[0] | float(0) }}

    - name: Unifi AP Outside RAM
      unique_id: unifi_ap_outside_ram
      unit_of_measurement: '%'
      state: >
        {{ state_attr('sensor.unifi_stats','data')['outside_ap.RAM'] | float(0) }}

    - name: Unifi AP Outside CPU
      unique_id: unifi_ap_outside_cpu
      unit_of_measurement: '%'
      state: >
        {{ state_attr('sensor.unifi_stats','data')['outside_ap.CPU'] | float(0) }}

    - name: Unifi AP Outside Score
      unique_id: unifi_ap_outside_score
      state: >
        {{ state_attr('sensor.unifi_stats','data')['outside_ap.Score'] }}

    - name: Unifi AP Outside 2.4gHz Score
      unique_id: unifi_ap_outside_2ghz_score
      state: >
        {{ state_attr('sensor.unifi_stats','data')['outside_ap.Score_wifi0'] | default(0) }}

    - name: Unifi AP Outside 5gHz Score
      unique_id: unifi_ap_outside_5ghz_score
      state: >
        {{ state_attr('sensor.unifi_stats','data')['outside_ap.Score_wifi1'] | default(0) }}

    - name: Unifi AP Outside 2.4gHz Clients
      unique_id: unifi_ap_outside_2ghz_wifi_devices
      state: >
        {{ state_attr('sensor.unifi_stats','data')['outside_ap.Clients_wifi0']  | default(0) }}

    - name: Unifi AP Outside 5gHz Clients
      unique_id: unifi_ap_outside_5ghz_wifi_devices
      state: >
        {{ state_attr('sensor.unifi_stats','data')['outside_ap.Clients_wifi1'] | default(0) }}

    - name: Unifi AP Outside total Clients
      unique_id: unifi_ap_outside_total_clients
      state: >
        {{ state_attr('sensor.unifi_stats','data')['outside_ap.Clients_wifi0'] + state_attr('sensor.unifi_stats','data')['outside_ap.Clients_wifi1']  | default(0) }}

    - name: Unifi AP Outside Updates
      unique_id: unifi_ap_outside_update
      state: >
        {% if state_attr('sensor.unifi_stats', 'data')['outside_ap.Update'] == 0 %}
          No
        {% else %}
          Available
        {% endif %}

    # Unifi AP Upstairs
    - name: Unifi AP Upstairs Guests
      unique_id: unifi_ap_upstairs_guests
      state: >
        {{ state_attr('sensor.unifi_stats','data')['upstairs_ap.Guests'] }}


    - name: Unifi AP Upstairs Activity
      unique_id: unifi_ap_upstairs_activity
      unit_of_measurement: 'Mbps'
      state: >
        {{ state_attr('sensor.unifi_stats','data')['upstairs_ap.Activity'].split(' ')[0] | float(0) }}


    - name: Unifi AP Upstairs RAM
      unique_id: unifi_ap_upstairs_ram
      unit_of_measurement: '%'
      state: >
        {{ state_attr('sensor.unifi_stats','data')['upstairs_ap.RAM'] | float(0) }}


    - name: Unifi AP Upstairs CPU
      unique_id: unifi_ap_upstairs_cpu
      unit_of_measurement: '%'
      state: >
        {{ state_attr('sensor.unifi_stats','data')['upstairs_ap.CPU'] | float(0) }}


    - name: Unifi AP Upstairs Score
      unique_id: unifi_ap_upstairs_score
      state: >
        {{ state_attr('sensor.unifi_stats','data')['upstairs_ap.Score'] }}


    - name: Unifi AP Upstairs 2.4gHz Score
      unique_id: unifi_ap_upstairs_2ghz_score
      state: >
        {{ state_attr('sensor.unifi_stats','data')['upstairs_ap.Score_wifi0'] | default(0) }}


    - name: Unifi AP Upstairs 5gHz Score
      unique_id: unifi_ap_upstairs_5ghz_score
      state: >
        {{ state_attr('sensor.unifi_stats','data')['upstairs_ap.Score_wifi1'] | default(0) }}


    - name: Unifi AP Upstairs 2.4gHz Clients
      unique_id: unifi_ap_upstairs_2ghz_wifi_devices
      state: >
        {{ state_attr('sensor.unifi_stats','data')['upstairs_ap.Clients_wifi0']  | default(0) }}


    - name: Unifi AP Upstairs 5gHz Clients
      unique_id: unifi_ap_upstairs_5ghz_wifi_devices
      state: >
        {{ state_attr('sensor.unifi_stats','data')['upstairs_ap.Clients_wifi1'] | default(0) }}


    - name: Unifi AP Upstairs total Clients
      unique_id: unifi_ap_upstairs_total_clients
      state: >
        {{ state_attr('sensor.unifi_stats','data')['upstairs_ap.Clients_wifi0'] + state_attr('sensor.unifi_stats','data')['upstairs_ap.Clients_wifi1']  | default(0) }}

    - name: Unifi AP Upstairs Updates
      unique_id: unifi_ap_upstairs_update
      state: >
        {% if state_attr('sensor.unifi_stats', 'data')['upstairs_ap.Update'] == 0 %}
          No
        {% else %}
          Available
        {% endif %}

    ### Unifi UDM Pro
    - name: Unifi UDM Pro Ports Used
      unique_id: unifi_udmpro_ports_used
      state: >
        {{ state_attr('sensor.unifi_stats','data')['udmpro.Ports_used'] }}

    - name: Unifi UDM Pro Ports User
      unique_id: unifi_udmpro_guests
      state: >
        {{ state_attr('sensor.unifi_stats','data')['udmpro.Ports_user'] }}

    - name: Unifi UDM Pro Ports Guest
      unique_id: unifi_udmpro_ports_guests
      state: >
        {{ state_attr('sensor.unifi_stats','data')['udmpro.Ports_guest'] | default(0)}}

    - name: Unifi UDM Pro Activity
      unique_id: unifi_udmpro_activity
      unit_of_measurement: 'Mbps'
      state: >
        {{ state_attr('sensor.unifi_stats','data')['udmpro.Activity'].split(' ')[0] | float(0) }}

    - name: Unifi UDM Pro RAM
      unique_id: unifi_udmpro_ram
      unit_of_measurement: '%'
      state: >
        {{ state_attr('sensor.unifi_stats','data')['udmpro.RAM'] | float(0) }}

    - name: Unifi UDM Pro CPU
      unique_id: unifi_udmpro_cpu
      unit_of_measurement: '%'
      state: >
        {{ state_attr('sensor.unifi_stats','data')['udmpro.CPU'] | float(0) }}

    - name: Unifi UDM Pro CPU Temp
      unique_id: unifi_udmpro_cpu_temp
      unit_of_measurement: 'c'
      state: >
        {{ state_attr('sensor.unifi_stats','data')['udmpro.CPUTemp'] | default(0) }}

    - name: Unifi UDM Pro Board Temp
      unique_id: unifi_udmpro_board_temp
      unit_of_measurement: 'c'
      state: >
        {{ state_attr('sensor.unifi_stats','data')['udmpro.BoardTemp'] | default(0) }}

    - name: Unifi UDM Pro Updates
      unique_id: unifi_udmpro_update
      state: >
        {% if state_attr('sensor.unifi_stats', 'data')['udmpro.Update'] == 0 %}
          No
        {% else %}
          Available
        {% endif %}

    - name: Unifi UDM Pro Speedtest Ping
      unique_id: unifi_udmpro_speed_test_ping
      state: >
        {{state_attr('sensor.unifi_stats','data')['udmpro.Speedtest_ping']}}


    - name: Unifi UDM Pro Speedtest up
      unique_id: unifi_udmpro_speed_test_up
      state: >
        {{state_attr('sensor.unifi_stats','data')['udmpro.Speedtest_up']}}


    - name: Unifi UDM Pro Speedtest Down
      unique_id: unifi_udmpro_speed_test_down
      state: >
        {{state_attr('sensor.unifi_stats','data')['udmpro.Speedtest_down']}}

    # Unifi AP Garage
    - name: Unifi AP Garage Guests
      unique_id: unifi_ap_garage_guests
      state: >
        {{ state_attr('sensor.unifi_stats','data')['garage_ap.Guests'] }}

    - name: Unifi AP Garage Activity
      unique_id: unifi_ap_garage_activity
      unit_of_measurement: 'Mbps'
      state: >
        {{ state_attr('sensor.unifi_stats','data')['garage_ap.Activity'].split(' ')[0] | float(0) }}

    - name: Unifi AP Garage RAM
      unique_id: unifi_ap_garage_ram
      unit_of_measurement: '%'
      state: >
        {{ state_attr('sensor.unifi_stats','data')['garage_ap.RAM'] | float(0) }}

    - name: Unifi AP Garage CPU
      unique_id: unifi_ap_garage_cpu
      unit_of_measurement: '%'
      state: >
        {{ state_attr('sensor.unifi_stats','data')['garage_ap.CPU'] | float(0) }}

    - name: Unifi AP Garage Score
      unique_id: unifi_ap_garage_score
      state: >
        {{ state_attr('sensor.unifi_stats','data')['garage_ap.Score'] }}

    - name: Unifi AP Garage 2.4gHz Score
      unique_id: unifi_ap_garage_2ghz_score
      state: >
        {{ state_attr('sensor.unifi_stats','data')['garage_ap.Score_wifi0'] | default(0) }}

    - name: Unifi AP Garage 5gHz Score
      unique_id: unifi_ap_garage_5ghz_score
      state: >
        {{ state_attr('sensor.unifi_stats','data')['garage_ap.Score_wifi1'] | default(0) }}

    - name: Unifi AP Garage 2.4gHz Clients
      unique_id: unifi_ap_garage_2ghz_wifi_devices
      state: >
        {{ state_attr('sensor.unifi_stats','data')['garage_ap.Clients_wifi0']  | default(0) }}

    - name: Unifi AP Garage 5gHz Clients
      unique_id: unifi_ap_garage_5ghz_wifi_devices
      state: >
        {{ state_attr('sensor.unifi_stats','data')['garage_ap.Clients_wifi1'] | default(0) }}

    - name: Unifi AP Garage total Clients
      unique_id: unifi_ap_garage_total_clients
      state: >
        {{ state_attr('sensor.unifi_stats','data')['garage_ap.Clients_wifi0'] + state_attr('sensor.unifi_stats','data')['garage_ap.Clients_wifi1']  | default(0) }}

    - name: Unifi AP Garage Updates
      unique_id: unifi_ap_garage_update
      state: >
        {% if state_attr('sensor.unifi_stats', 'data')['garage_ap.Update'] == 0 %}
          No
        {% else %}
          Available
        {% endif %}



    - name: "UDM CPU"
      unique_id: unifi_gateway_wan_cpu
      unit_of_measurement: "%"
      state: >
        {{ state_attr('sensor.unifi_stats','data')['health_wan.cpu'] }}

    - name: "UDM Memory"
      unique_id: unifi_gateway_wan_mem
      unit_of_measurement: "%"
      state: >
       {{ state_attr('sensor.unifi_stats','data')['health_wan.mem'] }}

    - name: "WAN IP"
      unique_id: unifi_gateway_wan_ip
      state: >
        {{ state_attr('sensor.unifi_stats','data')['udmpro.UplinkIP'] }}

    - name: "WAN Download"
      unique_id: unifi_gateway_wan_download
      unit_of_measurement: Kbps
      icon: "mdi:progress-download"
      state: >
        {{ (state_attr('sensor.unifi_stats','data')['health_wan.rx_bytes'] / 1024 )| int }}

    - name: "USG Uptime"
      unique_id: unifi_gateway_wan_uptime
      state: >-
        {%- set time = state_attr('sensor.unifi_stats','data')['health_wan.uptime'] | int %}
        {%- set minutes = ((time % 3600) // 60) %}
        {%- set minutes = '{}min'.format(minutes) if minutes > 0 else '' %}
        {%- set hours = ((time % 86400) // 3600) %}
        {%- set hours = '{}hr '.format(hours) if hours > 0 else '' %}
        {%- set days = (time // 86400) %}
        {%- set days = '{}d '.format(days) if days > 0 else '' %}
        {{ 'Less than 1 min' if time < 60 else days + hours + minutes }}

    - name: "USG Firmware Version"
      unique_id: unifi_gateway_firmware_version
      icon: "mdi:database-plus"
      state: >-
        {{ state_attr('sensor.unifi_stats','data')['health_wan.gw_version'] }}

    - name: "USG Speedtest Download"
      unique_id: unifi_gateway_www_xput_down
      unit_of_measurement: Mbps
      icon: "mdi:progress-download"
      state: >-
        {{ state_attr('sensor.unifi_stats','data')['health_www.xput_down'] }}

    - name: "USG Speedtest Upload"
      unique_id: unifi_gateway_www_xput_up
      unit_of_measurement: Mbps
      icon: "mdi:progress-upload"
      state: >-
        {{ state_attr('sensor.unifi_stats','data')['health_www.xput_up'] }}

    - name: "USG Speedtest Ping"
      unique_id: unifi_gateway_www_speedtest_ping
      unit_of_measurement: ms
      icon: "mdi:progress-clock"
      state: >-
        {{ state_attr('sensor.unifi_stats','data')['health_www.speedtest_ping'] }}


    - name: "Internet Uptime"
      unique_id: unifi_gateway_www_uptime
      state: >
        {%- set time = state_attr('sensor.unifi_stats','data')['health_www.uptime'] | int %}
        {%- set minutes = ((time % 3600) // 60) %}
        {%- set minutes = '{}min'.format(minutes) if minutes > 0 else '' %}
        {%- set hours = ((time % 86400) // 3600) %}
        {%- set hours = '{}hr '.format(hours) if hours > 0 else '' %}
        {%- set days = (time // 86400) %}
        {%- set days = '{}d '.format(days) if days > 0 else '' %}
        {{ 'Less than 1 min' if time < 60 else days + hours + minutes }}

    - name: "Unifi Wlan Users"
      unique_id: unifi_gateway_wlan_num_user
      icon: "mdi:account-multiple"
      state: >
        {{ state_attr('sensor.unifi_stats','data')['health_lan.num_user'] }}

    - name: "Unifi Users Lan"
      unique_id: unifi_gateway_lan_num_user
      icon: "mdi:account-multiple"
      state: >
        {{ state_attr('sensor.unifi_stats','data')['health_lan.num_user'] }}

    - name: "UDM-Firmware Version"
      unique_id: unifi_gateway_firmware
      state: >
        {{ state_attr('sensor.unifi_stats','version') }}
      icon: mdi:counter

hope its helpful to someone

johntdyer avatar Feb 12 '24 13:02 johntdyer

Thank you very much!! How did you implement this? The configuration.yaml part is clear, but the python script is not listed like:

  • command: '/config/scripts/unifi_combined2.py'
  • #!/usr/local/bin/python

On Mon, 12 Feb 2024 at 14:10, John Dyer @.***> wrote:

Here is my "fix"... please note that this script grew organically over time as I moved features from the other plugins to mine... not once have I gone back over the code to refactor, clean up, or optimize!!

#!/usr/local/bin/python from datetime import timedeltaimport json, yaml, requestsfrom datetime import datetimeimport requests,timefrom re import subimport sys resp={}resp['data']={}

def parse_uptime(uptime): seconds = uptime days = seconds // 86400 hours = (seconds - (days * 86400)) // 3600 minutes = (seconds - (days * 86400) - (hours * 3600)) // 60 uptime = str(days)+'d '+str(hours)+'h '+str(minutes)+'m' return uptime controller_url = 'https://xxxxx.xxxxx.xxxxx'username = 'xxxx'password = 'xxxx'site = 'default' # The site ID, 'default' for most installations

login_url = f'{controller_url}/api/auth/login'login_data = { 'username': username, 'password': password } session = requests.Session()response = session.post(login_url, json=login_data, verify=True)response.raise_for_status() def snake_case(s): return '_'.join( sub('([A-Z][a-z]+)', r' \1', sub('([A-Z]+)', r' \1', s.replace('-', ' '))).split()).lower()

rules_url = 'https://xxxx.xxxx.xxxx/proxy/network/api/s/default/stat/device' response = session.get(rules_url, verify=False)response.raise_for_status()rules = response.json()sysinfo_url = 'https://xxxx.xxxx.xxxx/proxy/network/api/s/default/stat/sysinfo' response = session.get(sysinfo_url, verify=False)response.raise_for_status()version = response.json()

health_url = 'https://xxxx.xxxx.xxx/proxy/network/api/s/default/stat/health' response = session.get(health_url, verify=False)response.raise_for_status()health_data = response.json()

keys = health_data['data'][0].keys()# a = {k: set(d[k] for d in health_data['data']) for k in keys}# print(json.dumps(health_data, indent = 1))#for h in health_data['data']:

match h['subsystem']: case 'www': # print(json.dumps(h, indent = 1)) resp['data'].update({ "health_" + h['subsystem'] + ".status": h['status'], "health_" + h['subsystem'] + ".tx_bytes-r": h['tx_bytes-r'], "health_" + h['subsystem'] + ".rx_bytes-r": h['rx_bytes-r'], "health_" + h['subsystem'] + ".latency": h['latency'], "health_" + h['subsystem'] + ".uptime": h['uptime'], "health_" + h['subsystem'] + ".drops": h['drops'], "health_" + h['subsystem'] + ".xput_up": h['xput_up'], "health_" + h['subsystem'] + ".xput_down": h['xput_down'], "health_" + h['subsystem'] + ".speedtest_status": h['speedtest_status'], "health_" + h['subsystem'] + ".speedtest_lastrun": h['speedtest_lastrun'], "health_" + h['subsystem'] + ".speedtest_ping": h['speedtest_ping'], "health_" + h['subsystem'] + ".uptime": h['uptime']

  })

case 'vpn':
  resp['data'].update({
    "health_" + h['subsystem'] + ".status": h['status'],
  })
  # test
case 'wlan':
  resp['data'].update({
    "health_" + h['subsystem'] + ".num_user": h['num_user'],
    "health_" + h['subsystem'] + ".num_guest": h['num_guest'],
    "health_" + h['subsystem'] + ".num_iot": h['num_iot'],
    "health_" + h['subsystem'] + ".tx_bytes": h['tx_bytes-r'],
    "health_" + h['subsystem'] + ".rx_bytes": h['rx_bytes-r'],
    "health_" + h['subsystem'] + ".status": h['status'],
    "health_" + h['subsystem'] + ".num_ap": h['num_ap']
  })

case 'lan':
  resp['data'].update({
    "health_" + h['subsystem'] + ".status": h['status'],
    "health_" + h['subsystem'] + ".num_user": h['num_user'],
    "health_" + h['subsystem'] + ".num_iot": h['num_iot'],
    "health_" + h['subsystem'] + ".num_sw": h['num_sw'],
    "health_" + h['subsystem'] + ".num_adopted": h['num_adopted']
  })

  # test
case 'wan':
  # print(h['subsystem'])
  # print(json.dumps(h, indent = 1))
  resp['data'].update({
    "health_" + h['subsystem'] + ".status": h['status'],
    "health_" + h['subsystem'] + ".isp_organization": h['isp_organization'],
    "health_" + h['subsystem'] + ".isp_name": h['isp_name'],
    "health_" + h['subsystem'] + ".gw_version": h['gw_version'],
    "health_" + h['subsystem'] + ".num_sta": h['num_sta'],
    "health_" + h['subsystem'] + ".cpu": h['gw_system-stats']['cpu'],
    "health_" + h['subsystem'] + ".mem": h['gw_system-stats']['mem'],
    "health_" + h['subsystem'] + ".uptime": h['gw_system-stats']['uptime'],
    "health_" + h['subsystem'] + ".tx_bytes": h['tx_bytes-r'],
    "health_" + h['subsystem'] + ".rx_bytes": h['rx_bytes-r']
  })

case _:
  print("else")

uptime_stats = "https://xxxxx.xxx.xxxx/proxy/network/api/s/default/stat/stats"#

response_stats = session.get(uptime_stats, verify=False)# response_stats.raise_for_status()# data = response_stats.json()["data"][0]# # # print(version)# json.dumps(print(resp['data']))# print(json.dumps(resp['data'], indent = 1))# print(json.dumps({# "cpu": data["system-stats"]["cpu"],# "cpu_temp": round(data["temperatures"][1]["value"], 1),# "system_temp": round(data["temperatures"][0]["value"], 1),# "memory": data["system-stats"]["mem"],# "disk": round(data["storage"][1]["used"] / data["storage"][1]["size"] * 100, 1),# "internet": data["wan1"]["up"],# "uptime": datetime.fromtimestamp(data["startup_timestamp"]).isoformat(),# "availability": data["uptime_stats"]["WAN"]["availability"],# "average_latency": data["uptime_stats"]["WAN"]["latency_average"],# "down": data["uplink"]["rx_rate"] / 1000000,# "up": data["uplink"]["tx_rate"] / 1000000,# "version": data["displayable_version"],# "last_wan_ip": data["last_wan_ip"]# }))# sys.exit(2)

resp["version"]=version['data'][0]['version']# # Find the rule to updatefor client_data in rules['data']:

If switch is offline ignore

if client_data['state'] == 0: continue

name=snake_case(client_data['name'])

print(client_data)

resp[name]={}

# print(version)

json.dumps(print(client_data))

internet = None speedtest_status = None

print("client_data['model'] %s",client_data['model'] )

if client_data['model'] == "UDMPRO": speedtest_status = client_data['uplink']['speedtest_status'] == "Success" internet = client_data['uplink']['up'] # if 'uplink' in client_data.keys(): # if client_data['uplink']['uplink_source'] == 'legacy': # internet = client_data['uplink']['up'] # else: # internet = client_data['internet'] # print("client_data['model'] %s",client_data['model'] ) # elif 'internet' in client_data.keys(): # internet = client_data['internet'] # print("client_data['model'] %s",client_data['model'] ) cpu=0 ram=0 try: if client_data['system-stats'] and client_data['system-stats'] != {} and len(client_data['system-stats'].keys()) != 0: try: cpu = float(client_data['system-stats']['cpu']) except: cpu = 0.0 try: ram = float(client_data['system-stats']['mem']) except: ram = 0 except: print("An exception occurred") print(json.dumps(client_data, indent = 1)) print("------")

activity = round(client_data['uplink']['rx_bytes-r']/125000 + client_data['uplink']['tx_bytes-r']/125000,1) uptime = parse_uptime(client_data['uptime']) update = int(client_data['upgradable']) model_type = client_data['model']

print(type)

if client_data['is_access_point']: wifi0clients = client_data['radio_table_stats'][0]['user-num_sta'] wifi1clients = client_data['radio_table_stats'][1]['user-num_sta'] wifi0score = client_data['radio_table_stats'][0]['satisfaction'] wifi1score = client_data['radio_table_stats'][1]['satisfaction'] numclients = client_data['user-wlan-num_sta'] numguests = client_data['guest-wlan-num_sta'] score = client_data['satisfaction']

  # raise ValueError('Some error')
  resp['data'].update ({
      name+".Clients":numclients,
      name+".Guests":numguests,
      name+".Clients_wifi0":wifi0clients ,
      name+".Clients_wifi1":wifi1clients ,
      name+".Score":score,
      name+".CPU": cpu,
      name+".RAM":ram,
      name+".Uptime":uptime,
      name+".Score_wifi0":wifi0score ,
      name+".Score_wifi1":wifi1score ,
      name+".Activity":str(activity)+' Mbps',
      name+".Update":update,
  })

else: cpu_temp = None board_temp = None wan_drops = None wan_latency = None if 'temperatures' in client_data.keys() and client_data['temperatures']!={}: for t in client_data['temperatures']: if t['type'] == "cpu" : cpu_temp = t['value'] if t['type'] == "board" : board_temp = t['value']

# json.dumps(print(client_data))
# print(json.dumps(client_data, indent = 1))


storage_used = None
storage_size = None
if 'storage' in client_data.keys() and  client_data['storage']!=[]:
  for t in client_data['storage']:

    if t['mount_point'] == "/persistent":
      storage_size = t['size']
      storage_used = t['used']

availability=None
latency_average=None
uplink_ip=None

if 'uptime_stats' in client_data.keys() and  client_data['uptime_stats']!={}:
    for t in client_data['uptime_stats']['WAN']['alerting_monitors']:
      if t['target'] == "1.1.1.1":
        latency_average = t['latency_average']
        availability = t['availability']


if 'uplink' in client_data.keys() and client_data['uplink']!={} and 'comment' in client_data['uplink'].keys():

    # json.dumps(print(client_data['uplink']))
    # print(json.dumps(client_data['uplink'], indent = 1))
    if client_data['uplink']['comment'] == "WAN":
      wan_latency = client_data['uplink']['latency']
      wan_drops = client_data['uplink']['drops']
      uplink_ip = client_data['uplink']['ip']

uplink

    # print(t)
        # print(json.dumps(client_data, indent = 1))
# if 'speedtest-status' in client_data.keys() and client_data['speedtest-status'] is not None:
#   print("---")
#   # print(client_data['speedtest-status'])
#   # json.dumps(print(client_data))
#   print(json.dumps(client_data['uplink'], indent = 1))

#   print("---")
# internet = client_data['internet']
usedports = client_data['num_sta']
userports = client_data['user-num_sta']
guestports = client_data['guest-num_sta']


resp['data'].update({
  name+".Activity":str(activity)+' Mbps',
  name+".CPU":cpu,
  name+".RAM":ram,
  name+".Uptime":uptime,
  name+".Ports_used":usedports,
  name+".Ports_user":userports,
  name+".Ports_guest":guestports,
  name+".Update":update,
  name+".Model": model_type
})

if 'speedtest_ping' in client_data['uplink'].keys() and client_data['uplink']['speedtest_ping'] is not None:

  resp['data'].update({
    name+".Speedtest_ping": client_data['uplink']['speedtest_ping'],
    name+".Speedtest_up":   client_data['uplink']['xput_up'],
    name+".Speedtest_down": client_data['uplink']['xput_down']
  })
if storage_used is not None:
  resp['data'].update({
    name+".StorageUsed": storage_used,
    name+".StorageSize": storage_size
  })
if internet is not None:
  resp['data'].update({
    name+".Internet": internet
  })
if speedtest_status is not None:
  resp['data'].update({
    name+".SpeedTestPass": speedtest_status
  })
if cpu_temp is not None:
  resp['data'].update({
    name+".CPUTemp":cpu_temp,
    name+".BoardTemp":board_temp
  })

if wan_drops is not None:
  resp['data'].update({
    name+".WanDrops":wan_drops,
    name+".WanLatency":wan_latency
  })


if latency_average is not None:
  resp['data'].update({
    name+".LatencyAvg":latency_average,
    name+".WanAvailability":availability
  })

if uplink_ip is not None:
  resp['data'].update({
    name+".UplinkIP":uplink_ip
  })

print(resp)# formatted_json = json.dumps(resp, sort_keys=True, indent=4)# colorful_json = highlight(formatted_json, lexers.JsonLexer(), formatters.TerminalFormatter())# print(colorful_json)json_formatted_str = json.dumps(resp, indent=2)print(json_formatted_str)# Log out of the UniFi Controllerlogout_url = f'{controller_url}/api/auth/logout'session.post(logout_url, verify=False)

sys.exit(0)

Here is my ha config

  • sensor: command: '/config/scripts/unifi_combined2.py' command_timeout: 180 name: unifi_stats value_template: '{{value_json.version}}' scan_interval: 300 json_attributes: - data

template: binary_sensor: - name: Unifi UDM Pro Internet Up unique_id: unifi_udmpro_internet_up state: > {{ state_attr('sensor.unifi_stats','data')['udmpro.Internet'] }}

sensor: ## Unifi AP Basement - name: Unifi AP Basement Guests unique_id: unifi_ap_basement_guests state: > {{ state_attr('sensor.unifi_stats','data')['basement_ap.Guests'] }}

- name: Unifi AP Basement Activity
  unique_id: unifi_ap_basement_activity
  unit_of_measurement: 'Mbps'
  state: >
      {{ state_attr('sensor.unifi_stats','data')['basement_ap.Activity'].split(' ')[0] | float(0) }}

- name: Unifi AP Basement RAM
  unique_id: unifi_ap_basement_ram
  unit_of_measurement: '%'
  state: >
    {{ state_attr('sensor.unifi_stats','data')['basement_ap.RAM'] | float(0) }}

- name: Unifi AP Basement CPU
  unique_id: unifi_ap_basement_cpu
  unit_of_measurement: '%'
  state: >
    {{ state_attr('sensor.unifi_stats','data')['basement_ap.CPU'] | float(0) }}

- name: Unifi AP Basement Score
  unique_id: unifi_ap_basement_score
  state: >
    {{ state_attr('sensor.unifi_stats','data')['basement_ap.Score'] }}

- name: Unifi AP Basement 2.4gHz Score
  unique_id: unifi_ap_basement_2ghz_score
  state: >
    {{ state_attr('sensor.unifi_stats','data')['basement_ap.Score_wifi0'] | default(0) }}

- name: Unifi AP Basement 5gHz Score
  unique_id: unifi_ap_basement_5ghz_score
  state: >
    {{ state_attr('sensor.unifi_stats','data')['basement_ap.Score_wifi1'] | default(0) }}

- name: Unifi AP Basement 2.4gHz Clients
  unique_id: unifi_ap_basement_2ghz_wifi_devices
  state: >
    {{ state_attr('sensor.unifi_stats','data')['basement_ap.Clients_wifi0']  | default(0) }}

- name: Unifi AP Basement 5gHz Clients
  unique_id: unifi_ap_basement_5ghz_wifi_devices
  state: >
    {{ state_attr('sensor.unifi_stats','data')['basement_ap.Clients_wifi1'] | default(0) }}

- name: Unifi AP Basement Total Clients
  unique_id: unifi_ap_basement_total_clients
  state: >
    {{ state_attr('sensor.unifi_stats','data')['basement_ap.Clients_wifi0'] + state_attr('sensor.unifi_stats','data')['basement_ap.Clients_wifi1']  | default(0) }}

- name: Unifi AP Basement Updates
  unique_id: unifi_ap_basement_update
  state: >
    {% if state_attr('sensor.unifi_stats', 'data')['basement_ap.Update'] == 0 %}
      No
    {% else %}
      Available
    {% endif %}

### Unifi AP Outside
- name: Unifi AP Outside Guests
  unique_id: unifi_ap_outside_guests
  state: >
    {{ state_attr('sensor.unifi_stats','data')['outside_ap.Guests'] }}

- name: Unifi AP Outside Activity
  unique_id: unifi_ap_outside_activity
  unit_of_measurement: 'Mbps'
  state: >
    {{ state_attr('sensor.unifi_stats','data')['outside_ap.Activity'].split(' ')[0] | float(0) }}

- name: Unifi AP Outside RAM
  unique_id: unifi_ap_outside_ram
  unit_of_measurement: '%'
  state: >
    {{ state_attr('sensor.unifi_stats','data')['outside_ap.RAM'] | float(0) }}

- name: Unifi AP Outside CPU
  unique_id: unifi_ap_outside_cpu
  unit_of_measurement: '%'
  state: >
    {{ state_attr('sensor.unifi_stats','data')['outside_ap.CPU'] | float(0) }}

- name: Unifi AP Outside Score
  unique_id: unifi_ap_outside_score
  state: >
    {{ state_attr('sensor.unifi_stats','data')['outside_ap.Score'] }}

- name: Unifi AP Outside 2.4gHz Score
  unique_id: unifi_ap_outside_2ghz_score
  state: >
    {{ state_attr('sensor.unifi_stats','data')['outside_ap.Score_wifi0'] | default(0) }}

- name: Unifi AP Outside 5gHz Score
  unique_id: unifi_ap_outside_5ghz_score
  state: >
    {{ state_attr('sensor.unifi_stats','data')['outside_ap.Score_wifi1'] | default(0) }}

- name: Unifi AP Outside 2.4gHz Clients
  unique_id: unifi_ap_outside_2ghz_wifi_devices
  state: >
    {{ state_attr('sensor.unifi_stats','data')['outside_ap.Clients_wifi0']  | default(0) }}

- name: Unifi AP Outside 5gHz Clients
  unique_id: unifi_ap_outside_5ghz_wifi_devices
  state: >
    {{ state_attr('sensor.unifi_stats','data')['outside_ap.Clients_wifi1'] | default(0) }}

- name: Unifi AP Outside total Clients
  unique_id: unifi_ap_outside_total_clients
  state: >
    {{ state_attr('sensor.unifi_stats','data')['outside_ap.Clients_wifi0'] + state_attr('sensor.unifi_stats','data')['outside_ap.Clients_wifi1']  | default(0) }}

- name: Unifi AP Outside Updates
  unique_id: unifi_ap_outside_update
  state: >
    {% if state_attr('sensor.unifi_stats', 'data')['outside_ap.Update'] == 0 %}
      No
    {% else %}
      Available
    {% endif %}

# Unifi AP Upstairs
- name: Unifi AP Upstairs Guests
  unique_id: unifi_ap_upstairs_guests
  state: >
    {{ state_attr('sensor.unifi_stats','data')['upstairs_ap.Guests'] }}


- name: Unifi AP Upstairs Activity
  unique_id: unifi_ap_upstairs_activity
  unit_of_measurement: 'Mbps'
  state: >
    {{ state_attr('sensor.unifi_stats','data')['upstairs_ap.Activity'].split(' ')[0] | float(0) }}


- name: Unifi AP Upstairs RAM
  unique_id: unifi_ap_upstairs_ram
  unit_of_measurement: '%'
  state: >
    {{ state_attr('sensor.unifi_stats','data')['upstairs_ap.RAM'] | float(0) }}


- name: Unifi AP Upstairs CPU
  unique_id: unifi_ap_upstairs_cpu
  unit_of_measurement: '%'
  state: >
    {{ state_attr('sensor.unifi_stats','data')['upstairs_ap.CPU'] | float(0) }}


- name: Unifi AP Upstairs Score
  unique_id: unifi_ap_upstairs_score
  state: >
    {{ state_attr('sensor.unifi_stats','data')['upstairs_ap.Score'] }}


- name: Unifi AP Upstairs 2.4gHz Score
  unique_id: unifi_ap_upstairs_2ghz_score
  state: >
    {{ state_attr('sensor.unifi_stats','data')['upstairs_ap.Score_wifi0'] | default(0) }}


- name: Unifi AP Upstairs 5gHz Score
  unique_id: unifi_ap_upstairs_5ghz_score
  state: >
    {{ state_attr('sensor.unifi_stats','data')['upstairs_ap.Score_wifi1'] | default(0) }}


- name: Unifi AP Upstairs 2.4gHz Clients
  unique_id: unifi_ap_upstairs_2ghz_wifi_devices
  state: >
    {{ state_attr('sensor.unifi_stats','data')['upstairs_ap.Clients_wifi0']  | default(0) }}


- name: Unifi AP Upstairs 5gHz Clients
  unique_id: unifi_ap_upstairs_5ghz_wifi_devices
  state: >
    {{ state_attr('sensor.unifi_stats','data')['upstairs_ap.Clients_wifi1'] | default(0) }}


- name: Unifi AP Upstairs total Clients
  unique_id: unifi_ap_upstairs_total_clients
  state: >
    {{ state_attr('sensor.unifi_stats','data')['upstairs_ap.Clients_wifi0'] + state_attr('sensor.unifi_stats','data')['upstairs_ap.Clients_wifi1']  | default(0) }}

- name: Unifi AP Upstairs Updates
  unique_id: unifi_ap_upstairs_update
  state: >
    {% if state_attr('sensor.unifi_stats', 'data')['upstairs_ap.Update'] == 0 %}
      No
    {% else %}
      Available
    {% endif %}

### Unifi UDM Pro
- name: Unifi UDM Pro Ports Used
  unique_id: unifi_udmpro_ports_used
  state: >
    {{ state_attr('sensor.unifi_stats','data')['udmpro.Ports_used'] }}

- name: Unifi UDM Pro Ports User
  unique_id: unifi_udmpro_guests
  state: >
    {{ state_attr('sensor.unifi_stats','data')['udmpro.Ports_user'] }}

- name: Unifi UDM Pro Ports Guest
  unique_id: unifi_udmpro_ports_guests
  state: >
    {{ state_attr('sensor.unifi_stats','data')['udmpro.Ports_guest'] | default(0)}}

- name: Unifi UDM Pro Activity
  unique_id: unifi_udmpro_activity
  unit_of_measurement: 'Mbps'
  state: >
    {{ state_attr('sensor.unifi_stats','data')['udmpro.Activity'].split(' ')[0] | float(0) }}

- name: Unifi UDM Pro RAM
  unique_id: unifi_udmpro_ram
  unit_of_measurement: '%'
  state: >
    {{ state_attr('sensor.unifi_stats','data')['udmpro.RAM'] | float(0) }}

- name: Unifi UDM Pro CPU
  unique_id: unifi_udmpro_cpu
  unit_of_measurement: '%'
  state: >
    {{ state_attr('sensor.unifi_stats','data')['udmpro.CPU'] | float(0) }}

- name: Unifi UDM Pro CPU Temp
  unique_id: unifi_udmpro_cpu_temp
  unit_of_measurement: 'c'
  state: >
    {{ state_attr('sensor.unifi_stats','data')['udmpro.CPUTemp'] | default(0) }}

- name: Unifi UDM Pro Board Temp
  unique_id: unifi_udmpro_board_temp
  unit_of_measurement: 'c'
  state: >
    {{ state_attr('sensor.unifi_stats','data')['udmpro.BoardTemp'] | default(0) }}

- name: Unifi UDM Pro Updates
  unique_id: unifi_udmpro_update
  state: >
    {% if state_attr('sensor.unifi_stats', 'data')['udmpro.Update'] == 0 %}
      No
    {% else %}
      Available
    {% endif %}

- name: Unifi UDM Pro Speedtest Ping
  unique_id: unifi_udmpro_speed_test_ping
  state: >
    {{state_attr('sensor.unifi_stats','data')['udmpro.Speedtest_ping']}}


- name: Unifi UDM Pro Speedtest up
  unique_id: unifi_udmpro_speed_test_up
  state: >
    {{state_attr('sensor.unifi_stats','data')['udmpro.Speedtest_up']}}


- name: Unifi UDM Pro Speedtest Down
  unique_id: unifi_udmpro_speed_test_down
  state: >
    {{state_attr('sensor.unifi_stats','data')['udmpro.Speedtest_down']}}

# Unifi AP Garage
- name: Unifi AP Garage Guests
  unique_id: unifi_ap_garage_guests
  state: >
    {{ state_attr('sensor.unifi_stats','data')['garage_ap.Guests'] }}

- name: Unifi AP Garage Activity
  unique_id: unifi_ap_garage_activity
  unit_of_measurement: 'Mbps'
  state: >
    {{ state_attr('sensor.unifi_stats','data')['garage_ap.Activity'].split(' ')[0] | float(0) }}

- name: Unifi AP Garage RAM
  unique_id: unifi_ap_garage_ram
  unit_of_measurement: '%'
  state: >
    {{ state_attr('sensor.unifi_stats','data')['garage_ap.RAM'] | float(0) }}

- name: Unifi AP Garage CPU
  unique_id: unifi_ap_garage_cpu
  unit_of_measurement: '%'
  state: >
    {{ state_attr('sensor.unifi_stats','data')['garage_ap.CPU'] | float(0) }}

- name: Unifi AP Garage Score
  unique_id: unifi_ap_garage_score
  state: >
    {{ state_attr('sensor.unifi_stats','data')['garage_ap.Score'] }}

- name: Unifi AP Garage 2.4gHz Score
  unique_id: unifi_ap_garage_2ghz_score
  state: >
    {{ state_attr('sensor.unifi_stats','data')['garage_ap.Score_wifi0'] | default(0) }}

- name: Unifi AP Garage 5gHz Score
  unique_id: unifi_ap_garage_5ghz_score
  state: >
    {{ state_attr('sensor.unifi_stats','data')['garage_ap.Score_wifi1'] | default(0) }}

- name: Unifi AP Garage 2.4gHz Clients
  unique_id: unifi_ap_garage_2ghz_wifi_devices
  state: >
    {{ state_attr('sensor.unifi_stats','data')['garage_ap.Clients_wifi0']  | default(0) }}

- name: Unifi AP Garage 5gHz Clients
  unique_id: unifi_ap_garage_5ghz_wifi_devices
  state: >
    {{ state_attr('sensor.unifi_stats','data')['garage_ap.Clients_wifi1'] | default(0) }}

- name: Unifi AP Garage total Clients
  unique_id: unifi_ap_garage_total_clients
  state: >
    {{ state_attr('sensor.unifi_stats','data')['garage_ap.Clients_wifi0'] + state_attr('sensor.unifi_stats','data')['garage_ap.Clients_wifi1']  | default(0) }}

- name: Unifi AP Garage Updates
  unique_id: unifi_ap_garage_update
  state: >
    {% if state_attr('sensor.unifi_stats', 'data')['garage_ap.Update'] == 0 %}
      No
    {% else %}
      Available
    {% endif %}



- name: "UDM CPU"
  unique_id: unifi_gateway_wan_cpu
  unit_of_measurement: "%"
  state: >
    {{ state_attr('sensor.unifi_stats','data')['health_wan.cpu'] }}

- name: "UDM Memory"
  unique_id: unifi_gateway_wan_mem
  unit_of_measurement: "%"
  state: >
   {{ state_attr('sensor.unifi_stats','data')['health_wan.mem'] }}

- name: "WAN IP"
  unique_id: unifi_gateway_wan_ip
  state: >
    {{ state_attr('sensor.unifi_stats','data')['udmpro.UplinkIP'] }}

- name: "WAN Download"
  unique_id: unifi_gateway_wan_download
  unit_of_measurement: Kbps
  icon: "mdi:progress-download"
  state: >
    {{ (state_attr('sensor.unifi_stats','data')['health_wan.rx_bytes'] / 1024 )| int }}

- name: "USG Uptime"
  unique_id: unifi_gateway_wan_uptime
  state: >-
    {%- set time = state_attr('sensor.unifi_stats','data')['health_wan.uptime'] | int %}
    {%- set minutes = ((time % 3600) // 60) %}
    {%- set minutes = '{}min'.format(minutes) if minutes > 0 else '' %}
    {%- set hours = ((time % 86400) // 3600) %}
    {%- set hours = '{}hr '.format(hours) if hours > 0 else '' %}
    {%- set days = (time // 86400) %}
    {%- set days = '{}d '.format(days) if days > 0 else '' %}
    {{ 'Less than 1 min' if time < 60 else days + hours + minutes }}

- name: "USG Firmware Version"
  unique_id: unifi_gateway_firmware_version
  icon: "mdi:database-plus"
  state: >-
    {{ state_attr('sensor.unifi_stats','data')['health_wan.gw_version'] }}

- name: "USG Speedtest Download"
  unique_id: unifi_gateway_www_xput_down
  unit_of_measurement: Mbps
  icon: "mdi:progress-download"
  state: >-
    {{ state_attr('sensor.unifi_stats','data')['health_www.xput_down'] }}

- name: "USG Speedtest Upload"
  unique_id: unifi_gateway_www_xput_up
  unit_of_measurement: Mbps
  icon: "mdi:progress-upload"
  state: >-
    {{ state_attr('sensor.unifi_stats','data')['health_www.xput_up'] }}

- name: "USG Speedtest Ping"
  unique_id: unifi_gateway_www_speedtest_ping
  unit_of_measurement: ms
  icon: "mdi:progress-clock"
  state: >-
    {{ state_attr('sensor.unifi_stats','data')['health_www.speedtest_ping'] }}


- name: "Internet Uptime"
  unique_id: unifi_gateway_www_uptime
  state: >
    {%- set time = state_attr('sensor.unifi_stats','data')['health_www.uptime'] | int %}
    {%- set minutes = ((time % 3600) // 60) %}
    {%- set minutes = '{}min'.format(minutes) if minutes > 0 else '' %}
    {%- set hours = ((time % 86400) // 3600) %}
    {%- set hours = '{}hr '.format(hours) if hours > 0 else '' %}
    {%- set days = (time // 86400) %}
    {%- set days = '{}d '.format(days) if days > 0 else '' %}
    {{ 'Less than 1 min' if time < 60 else days + hours + minutes }}

- name: "Unifi Wlan Users"
  unique_id: unifi_gateway_wlan_num_user
  icon: "mdi:account-multiple"
  state: >
    {{ state_attr('sensor.unifi_stats','data')['health_lan.num_user'] }}

- name: "Unifi Users Lan"
  unique_id: unifi_gateway_lan_num_user
  icon: "mdi:account-multiple"
  state: >
    {{ state_attr('sensor.unifi_stats','data')['health_lan.num_user'] }}

- name: "UDM-Firmware Version"
  unique_id: unifi_gateway_firmware
  state: >
    {{ state_attr('sensor.unifi_stats','version') }}
  icon: mdi:counter

hope its helpful to someone

— Reply to this email directly, view it on GitHub https://github.com/custom-components/sensor.unifigateway/issues/59#issuecomment-1938652085, or unsubscribe https://github.com/notifications/unsubscribe-auth/AYS5HXJRTOXGLDJYPXDIOQLYTIIDHAVCNFSM6AAAAABAE6EHR6VHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMYTSMZYGY2TEMBYGU . You are receiving this because you commented.Message ID: @.***>

coldburn89 avatar Feb 12 '24 14:02 coldburn89

I dont really like inline python so I put my scripts into a script folder and execute them from the command_line sensor w/ the full path

johntdyer avatar Feb 12 '24 16:02 johntdyer

I dont really like inline python so I put my scripts into a script folder and execute them from the command_line sensor w/ the full path

Do you mind sharing that part of the command_line?

coldburn89 avatar Feb 12 '24 17:02 coldburn89

I did.... So try these steps

  1. Take the python code and paste that into /config/scripts/unifi_combined.py
  2. chmod +x /config/scripts/unifi_combined.py
  3. Add the following to your configuration.yaml
command_line:

  - sensor:
      command: '/config/scripts/unifi_combined.py'
      command_timeout: 180
      name: unifi_stats
      value_template: '{{value_json.version}}' 
      scan_interval: 300
      json_attributes:
        - data
  1. run the command_line.reload service from developer tools
  2. Goto entities and look for sensor.unifi_stats

Hope that helps

johntdyer avatar Feb 12 '24 17:02 johntdyer

is the "chmod +x /config/scripts/unifi_combined.py" really needed? And also how do I do this? via SSH?

On Mon, 12 Feb 2024 at 18:28, John Dyer @.***> wrote:

I did.... So try these steps

  1. Take the python code and paste that into /config/scripts/unifi_combined.py
  2. chmod +x /config/scripts/unifi_combined.py
  3. Add the following to your configuration.yaml

command_line:

  • sensor: command: '/config/scripts/unifi_combined.py' command_timeout: 180 name: unifi_stats value_template: '{{value_json.version}}' scan_interval: 300 json_attributes: - data
    
    

— Reply to this email directly, view it on GitHub https://github.com/custom-components/sensor.unifigateway/issues/59#issuecomment-1939200163, or unsubscribe https://github.com/notifications/unsubscribe-auth/AYS5HXIDJM3D34CEW6PDFYTYTJGLPAVCNFSM6AAAAABAE6EHR6VHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMYTSMZZGIYDAMJWGM . You are receiving this because you commented.Message ID: @.***>

coldburn89 avatar Feb 12 '24 17:02 coldburn89

oh yea, its all via SSH... sorry, guess I assumed you were using ssh

johntdyer avatar Feb 12 '24 17:02 johntdyer

when loading the command_line (i copied your script) i get the following error. Do you know what happend? Do i need to install python or something?

Logger: homeassistant.components.command_line.utils Source: components/command_line/utils.py:54 Integration: Command Line (documentation, issues) First occurred: 19:19:58 (3 occurrences) Last logged: 19:21:58

Command failed (with return code 1): /config/scripts/unifi_combined.py Command failed (with return code 1): python3 /config/scripts/unifi_ap.py

On Mon, 12 Feb 2024 at 18:43, John Dyer @.***> wrote:

oh yea, its all via SSH... sorry, guess I assumed you were using ssh

— Reply to this email directly, view it on GitHub https://github.com/custom-components/sensor.unifigateway/issues/59#issuecomment-1939224956, or unsubscribe https://github.com/notifications/unsubscribe-auth/AYS5HXPQ4BI6PTQA6HEIYLTYTJIEXAVCNFSM6AAAAABAE6EHR6VHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMYTSMZZGIZDIOJVGY . You are receiving this because you commented.Message ID: @.***>

coldburn89 avatar Feb 12 '24 18:02 coldburn89

Can you drop to ssh shell and run

python3 /config/scripts/unifi_ap.py
python3 /config/scripts/unifi_combined.py

I would like to see the error

johntdyer avatar Feb 12 '24 18:02 johntdyer