All my hue lights randomly becoming unavailable

I keep getting an error saying “Unable to reach bridge 192.168.29.166”. This just started happening a couple days ago and seems to be getting worse. Someone on reddit was having a similar issue. Anyone here? The hue app is still communicating with my hub just fine so it seems like it’s hassio that’s having the connection issues.

start simple. Is the hue bridge on a static IP? Has something else on the network received it’s IP?

I’ve been having the same issue since .72.0

Randomly unavailable.

Static IP
No changes to hue config for quite a while.
Just going unavailable and then back to available

No issues with hue app or Alexa control either.

1 Like

I’m also seeing this the last version or 2.
My logbook is filled with lights becoming unavailable then switching back to normal.

Hey, also been running into this issue. For the moment I am testing if the issue might be due to issues with the hue groups / rooms. I found out that i also had a room that also existed as group in HASSIO. I have removed all the rooms that i had in hue app, and turned the setting for HUE in config; allow_unreachable: false and allow_hue_groups: false. I just changed things so will see in the coming days if it makes a definite change.

Additional point that I found was that an additional raspberry pi zero that i use for presence detection was causing significant interference… Resulting in a not reachable bridge, random lights unavailable so you might also need to look for possible equipment that could cause interference.

search for flapping on the home-assistant github issues and find many related experiences. Happening since the Hue integration was changed to asyncio, and seems to have uncovered yet to be resolved issues along the way.

made a small summary of earlier issues here before:

2 Likes

Hi Marius, thanks for replying. It looks like it is solved. Another point that made me look further in interference issue, was that also my sonos and samsung tv became unavailable every now and then, also on wifi. I had my wifi set on auto and have now chosen a channel that does not interfere with the current channel of my Hue bridge.

this is an interesting point you make. Don’t you have your Hue hub on Lan? I believed the channel on the hub to be for the zigbee connection, not for the wifi connection. So how could changing the Wifi channel for Sonos have anything to do with that?

Hi Marius, correct my bridge is on LAN indeed, however Wifi 2.4 GHz and Zigbee can overlap, see for example metageek on zigbee wifi coexistence, this might cause general wifi turmoil and instability :wink: also affecting other equipment that might be on the wifi network.

thanks, thats a fine source.
So you chose to change the wifi channel, not the zigbee channel of the Hue Hub?

I wonder if z- wave has influence here too, since thats what i suspected before, when several Z-wave switches weren’t connected robustly and seemed to interfere when in each others line, or in proximity of the Tradfri hub for example. Although the dev told me that it would be impossible, since they use different channels and frequencies, experienced learned otherwise…

Will start experimenting…

back to the unavailable of the lights: still there, or really gone (solved as you say) after changing channels, or have you taken accompanying measures?

Hi Marius,

Well in the end I had the choice to change either zigbee either wifi channel. As the zigbee is operating for a while on 11, and my wifi for 2.4 GHz was still on ’ auto ’ I needed to set this one anyway.

I will monitor the lights logbook for the coming days for a final conclusion… :slight_smile:

I hope that i can after that get back to presence detection from andrew. Mmmm out of curiosity I just plugged it in and immediately get unavailable lights again… this is already a common issue of the BT interference that has been reported to him… https://github.com/andrewjfreyer/. Also for this I could test on other wifi channels (BT and wifi both are in 2.4 GHz) but first things first, first I want to be sure that the unavailable issue with Hue has been cleared.

For a moment I thought of disabling my 2.4 Ghz wifi completely, only using 5 Ghz, but this will be problematic for some of the wifi equipment in my house (Esp’s etc). I’ll keep you posted.

After same days now the flapping is 99% eliminated, have had only 1 light going to unavailable mode. So for sure it is Either wifi of my neighbours versus my Zigbee, either my own wifi versus zigbee.

Hi @timkeizer,

glad your making progress, hope to learn when you make the final 1% :wink:
the thing is, the ‘flapping’ only started after the move to Asyncio for Hue in Hassio. So I fear something else is going on to make the Hue hub disconnect.
There are other reasons to suspect that, because several other sensors i have to see whether lights are ‘reachable’ stay online, even when the Hue Lights show unavailable. So is the Hub, online that is.

Since there’s no direct connection to the lights, other than over the Hub, this must indicate another issue. Scanning the logs only shows timing issues, unfortunately I havent found the source yet.

do you have this in the logs too:

2018-07-04 19:11:35 ERROR (MainThread) [homeassistant.components.light.hue] Unable to reach bridge 192.168.1.212
2018-07-04 19:11:40 ERROR (MainThread) [homeassistant.core] Timer got out of sync. Resetting
2018-07-04 19:11:46 ERROR (MainThread) [homeassistant.core] Timer got out of sync. Resetting
2018-07-04 19:11:48 ERROR (MainThread) [homeassistant.core] Timer got out of sync. Resetting
2018-07-04 19:11:55 ERROR (MainThread) [homeassistant.core] Timer got out of sync. Resetting
2018-07-04 19:11:57 ERROR (MainThread) [homeassistant.core] Timer got out of sync. Resetting
2018-07-04 19:12:01 ERROR (MainThread) [homeassistant.core] Timer got out of sync. Resetting
2018-07-04 19:12:14 INFO (MainThread) [homeassistant.components.light.hue] Reconnected to bridge 192.168.1.212
2018-07-04 19:12:15 ERROR (MainThread) [homeassistant.core] Timer got out of sync. Resetting
2018-07-04 19:12:18 ERROR (MainThread) [homeassistant.core] Timer got out of sync. Resetting
2018-07-04 19:12:27 ERROR (MainThread) [homeassistant.core] Timer got out of sync. Resetting
2018-07-04 19:12:30 ERROR (MainThread) [homeassistant.core] Timer got out of sync. Resetting
2018-07-04 19:27:34 ERROR (SyncWorker_6) [homeassistant.core] Error doing job: Task was destroyed but it is pending!
2018-07-04 19:35:41 ERROR (SyncWorker_18) [homeassistant.core] Error doing job: Task was destroyed but it is pending!
2018-07-04 19:52:52 ERROR (MainThread) [homeassistant.core] Timer got out of sync. Resetting
2018-07-04 19:52:55 ERROR (MainThread) [homeassistant.core] Timer got out of sync. Resetting
2018-07-04 19:53:02 ERROR (MainThread) [homeassistant.components.light.hue] Unable to reach bridge 192.168.1.212
2018-07-04 19:53:08 ERROR (MainThread) [homeassistant.core] Timer got out of sync. Resetting
2018-07-04 19:53:11 ERROR (MainThread) [homeassistant.core] Timer got out of sync. Resetting
2018-07-04 19:53:24 ERROR (MainThread) [homeassistant.core] Timer got out of sync. Resetting
2018-07-04 19:53:36 INFO (MainThread) [homeassistant.components.light.hue] Reconnected to bridge 192.168.1.212
2018-07-04 19:53:41 ERROR (MainThread) [homeassistant.core] Timer got out of sync. Resetting
2018-07-04 19:53:54 ERROR (MainThread) [homeassistant.components.light.hue] Unable to reach bridge 192.168.1.212
2018-07-04 19:53:57 ERROR (MainThread) [homeassistant.core] Timer got out of sync. Resetting
2018-07-04 19:54:01 ERROR (MainThread) [homeassistant.core] Timer got out of sync. Resetting
2018-07-04 19:54:09 ERROR (MainThread) [homeassistant.core] Timer got out of sync. Resetting
2018-07-04 19:54:18 INFO (MainThread) [homeassistant.components.light.hue] Reconnected to bridge 192.168.1.212
2018-07-04 19:54:24 ERROR (MainThread) [homeassistant.core] Timer got out of sync. Resetting
2018-07-04 19:54:31 ERROR (MainThread) [homeassistant.core] Timer got out of sync. Resetting
2018-07-04 19:54:33 ERROR (MainThread) [homeassistant.core] Timer got out of sync. Resetting

Hi Marius,

It looks a bit different, i strongly believe your issue has a different nature as you conclude. Now again I turned on my pizero with presence detection (bluetooth scanning). Directly I have the issue below.

2018-07-04 21:43:25 ERROR (MainThread) [homeassistant.components.light.hue] Unable to reach bridge 10.0.1.3
2018-07-04 21:43:25 INFO (MainThread) [homeassistant.core] Bus:Handling <Event state_changed[L]: entity_id=light.hue_ambiance_spot_4, old_state=<state light.hue_ambiance_spot_4=off; min_mireds=153, max_mireds=500, friendly_name=Hue ambiance spot 4, supported_features=43 @ 2018-07-04T21:38:37.857220+02:00>, new_state=<state light.hue_ambiance_spot_4=unavailable; friendly_name=Hue ambiance spot 4, supported_features=43 @ 2018-07-04T21:43:25.853328+02:00>>
2018-07-04 21:43:25 INFO (MainThread) [homeassistant.core] Bus:Handling <Event state_changed[L]: entity_id=light.hue_ambiance_spot_5, old_state=<state light.hue_ambiance_spot_5=off; min_mireds=153, max_mireds=500, friendly_name=Hue ambiance spot 5, supported_features=43 @ 2018-07-04T21:38:37.844316+02:00>, new_state=<state light.hue_ambiance_spot_5=unavailable; friendly_name=Hue ambiance spot 5, supported_features=43 @ 2018-07-04T21:43:25.860572+02:00>>
2018-07-04 21:43:25 INFO (MainThread) [homeassistant.core] Bus:Handling <Event state_changed[L]: entity_id=light.hue_white_lamp_2, old_state=<state light.hue_white_lamp_2=off; friendly_name=Hue white lamp 2, supported_features=41 @ 2018-07-04T21:38:37.881026+02:00>, new_state=<state light.hue_white_lamp_2=unavailable; friendly_name=Hue white lamp 2, supported_features=41 @ 2018-07-04T21:43:25.867617+02:00>>
2018-07-04 21:43:25 INFO (MainThread) [homeassistant.core] Bus:Handling <Event state_changed[L]: entity_id=light.hue_ambiance_spot_1, old_state=<state light.hue_ambiance_spot_1=off; min_mireds=153, max_mireds=500, friendly_name=Hue ambiance spot 1, supported_features=43 @ 2018-07-04T21:38:37.887188+02:00>, new_state=<state light.hue_ambiance_spot_1=unavailable; friendly_name=Hue ambiance spot 1, supported_features=43 @ 2018-07-04T21:43:25.874279+02:00>>
2018-07-04 21:43:25 INFO (MainThread) [homeassistant.core] Bus:Handling <Event state_changed[L]: entity_id=light.hue_white_lamp_3, old_state=<state light.hue_white_lamp_3=off; friendly_name=Hue white lamp 3, supported_features=41 @ 2018-07-04T21:38:37.892953+02:00>, new_state=<state light.hue_white_lamp_3=unavailable; friendly_name=Hue white lamp 3, supported_features=41 @ 2018-07-04T21:43:25.882457+02:00>>
2018-07-04 21:43:25 INFO (MainThread) [homeassistant.core] Bus:Handling <Event state_changed[L]: entity_id=light.hue_ambiance_lamp_1, old_state=<state light.hue_ambiance_lamp_1=off; min_mireds=153, max_mireds=500, friendly_name=Hue ambiance lamp 1, supported_features=43 @ 2018-07-04T21:38:37.862976+02:00>, new_state=<state light.hue_ambiance_lamp_1=unavailable; friendly_name=Hue ambiance lamp 1, supported_features=43 @ 2018-07-04T21:43:25.890735+02:00>>
2018-07-04 21:43:25 INFO (MainThread) [homeassistant.core] Bus:Handling <Event state_changed[L]: entity_id=light.hue_ambiance_spot_3, old_state=<state light.hue_ambiance_spot_3=off; min_mireds=153, max_mireds=500, friendly_name=Hue ambiance spot 3, supported_features=43 @ 2018-07-04T21:38:37.874820+02:00>, new_state=<state light.hue_ambiance_spot_3=unavailable; friendly_name=Hue ambiance spot 3, supported_features=43 @ 2018-07-04T21:43:25.901226+02:00>>
2018-07-04 21:43:25 INFO (MainThread) [homeassistant.core] Bus:Handling <Event state_changed[L]: entity_id=light.hue_ambiance_spot_6, old_state=<state light.hue_ambiance_spot_6=off; min_mireds=153, max_mireds=500, friendly_name=Hue ambiance spot 6, supported_features=43 @ 2018-07-04T21:38:37.868975+02:00>, new_state=<state light.hue_ambiance_spot_6=unavailable; friendly_name=Hue ambiance spot 6, supported_features=43 @ 2018-07-04T21:43:25.914141+02:00>>
2018-07-04 21:43:25 INFO (MainThread) [homeassistant.core] Bus:Handling <Event state_changed[L]: entity_id=light.hue_ambiance_spot_2, old_state=<state light.hue_ambiance_spot_2=off; min_mireds=153, max_mireds=500, friendly_name=Hue ambiance spot 2, supported_features=43 @ 2018-07-04T21:38:37.851177+02:00>, new_state=<state light.hue_ambiance_spot_2=unavailable; friendly_name=Hue ambiance spot 2, supported_features=43 @ 2018-07-04T21:43:25.924260+02:00>>
2018-07-04 21:43:28 INFO (MainThread) [homeassistant.components.light.hue] Reconnected to bridge 10.0.1.3

ok, but thats another possible interfering protocol: bluetooth scanning, as reported by others indeed. Thats why I have already disabled the bluetooth add-on…

no conclusions yet, Im still trying to figure out if the Hub causes the timing issues, or if the timing issues cause the Hub to make the lights unavailable …

ok, with regards to the log, which log did you dump in you previous post? as the layout looked quite smooth and organised, or is that the way you posted it?

Maybe it would be nice to know the logs from the other people look like, just to get a better understanding of the issue in general.

simply the home-assistant.log…

this is the current debug setting for it:

# https://home-assistant.io/components/logger/
# Possible log severities: critical, fatal, error, warning, warn, info, debug, notset
default: error
logs:
  homeassistant.components.device_tracker: warn
  homeassistant.components.mqtt: warn
#  homeassistant.components.device_tracker.mqtt: info
  homeassistant.components.logbook: warn
  homeassistant.components.logger: warn
  homeassistant.components.hassio: debug
  homeassistant.components.weather: warn
  homeassistant.components.recorder: info
#  homeassistant.components.python_script: debug
#  homeassistant.components.script: debug
#  homeassistant.components.scripts: debug
#    homeassistant.components.nmap_tracker: error
#    homeassistant.helpers.entity: critical
  homeassistant.setup: debug
  homeassistant.core: warn
#    homeassistant.helpers.condition: critical
#  homeassistant.config.automation: debug
#  homeassistant.components.websocket_api: warn
#  homeassistant.components.switch: info
#  homeassistant.components.binary_sensor.mqtt: debug
#  py.warnings: critical
  homeassistant.components.light.hue: debug
1 Like

other than identifying wifi/zigbee issues, i’ve been hard cutting in some scripts and automations, as @balloob told me to…

I am able to report rather significant progress on this, that is to say I can identify a big decrease in disconnections/unavailabilty of Hue lights, when I turn-off 1 automation. This automation sense_lights_change checks the states of the lights, and if changed runs 2 python scripts, simply counting these lights and showing their names.

I really like to use it, cause it is part of a monitoring system showing whats happening when. Taking it out makes me need to rely on a time based automation running these python scripts, which takes away much of the elegance.

I was most prominently forced to check this during Party mode… An automation that randomly turns 4 Hue lights on , with random colors. The Hue lights were kicked out almost immediately, and hardly ever came back, even so bad I couldn’t stop the Partymode, since the lights were unavailable to the system.

Right now, ive adapted the Partymode to first switch off the sense_lights_change automation, which is a huge improvement.

Not sure why this only started after moving to Asyncio, (had it al working before without issues), and the many Ikea lights don’t suffer this behavior.

This is in no way an effort of mine to deny your wifi/Zigbee issues. Simply an effort to disclose issues experienced here, so you could take advantage of that.

Can you share your Python script ? Becauseif more people are having performance issues with their python scripts with just normal commands, we might need to evaluate that component and see where things go wrong.

sure, id be glad to.

What im trying to figure out is which causes what: the automation is triggered by changes in the lights, which also happens when the hue lights become unavailable and back again. so a possible loop of events.

Only happening on the Hue lights. Half of the lights are Tradfri, and there is zero issue there. They are checked by the same 2 scripts and same automations.
Hope this helps.

please see below:

whats_on.py:

##########################################################################################
# Whats_on.py, previously known as Anything_on...
#
# interrelated with the Summary.py, which doesn't show the entities per badge (yet)
# modified and customized by https://community.home-assistant.io/u/Mariusthvdb/summary
# big hand in Python by https://community.home-assistant.io/u/petro/summary
# tbd: timezone correction a bit of a challenge, solved with a little hack (=2)
##########################################################################################

familyEntities = 'group.family'
switchEntities = 'group.iungo_switch_switches_template'
lightEntities = 'group.all_lights_only'
applianceEntities = 'group.iungo_switch_appliances_template'

filteredLightEntities = [ entity_id for entity_id in lightEntities if ' ' not in entity_id ]

def CountMyEntities(hass, entity_list, entity_state):
    cnt = 0

#  using a full list:  for entity_id in entity_list:
#  using groups in a [list] :  for group_entity in entity_list:
#   for entity_id in hass.states.get(group_entity).attributes['entity_id']:
    for entity_id in hass.states.get(entity_list).attributes['entity_id']:
        state = hass.states.get(entity_id)
        if state.state == entity_state:
            cnt = cnt + 1
    return cnt

familyHome = CountMyEntities(hass, familyEntities, 'home')
switchesOn = CountMyEntities(hass, switchEntities, 'on')
appliancesOn = CountMyEntities(hass, applianceEntities, 'on')
lightsOn = CountMyEntities(hass, lightEntities, 'on') #if needed, use filteredLightEntities

totalOn = switchesOn + lightsOn + appliancesOn
whichIcon = 'mdi:lightbulb-on-outline' if totalOn else 'mdi:lightbulb-outline' 
status = 'on' if totalOn else 'off' # will evaluate "off" if totalOn == 0.

hass.states.set('input_boolean.whats_on', status, { 
    'friendly_name': "What's On?",
    'icon': whichIcon,
    'family_home': familyHome,
    'lights_on': lightsOn,
    'switches_on': switchesOn,
    'appliances_on': appliancesOn,
    'total_on': totalOn,
    'extra_data_template':'{total_on} on'
})

##########################################################################################
# Lights:
# Badges images: /config/www/lights
##########################################################################################

lights_on = []
#show only lights, not light groups
#excluded = ['light.custom_group_for_group','light.custom_group_for_lights_2']

#total_lights_on = hass.states.get('input_boolean.whats_on').attributes.get('lights_on')
state = hass.states.get('automation.sense_lights_change')

if state:
    total_on = hass.states.get('input_boolean.whats_on').attributes.get('lights_on')
    for entity_id in hass.states.get(lightEntities).attributes['entity_id']:
        dt = state.last_updated + datetime.timedelta(hours=2)
        time = '%02d:%02d' % (dt.hour, dt.minute)

        if hass.states.get(entity_id).state is 'on': #and entity_id not in excluded
            lights_on.append(hass.states.get(entity_id).attributes['friendly_name'])

    if len(lights_on) > 0:
        picture = '/local/lights/hue_pl.png'
        message = ', '.join(lights_on)
        sensor_message = 'Lights on: ' + message
        lights_desc = '=- Lights on: {} -- {} since {}'.format(total_on, message,time)
        uom = 'Lights'

        if len(lights_on) == 1:
            uom = 'Light'
    else:
        picture = '/local/lights/bulboff.png'
        message= ''
        sensor_message= 'No lights on'
        uom = 'Lights'

    sensor_lights_desc = '{}'.format(sensor_message)

    hass.states.set('sensor.lights_badge', total_on, {
#        'custom_ui_state_card': 'state-card-value_only',
        'text': sensor_message,
        'unit_of_measurement': uom,
        'friendly_name': time,
        'entity_picture': picture
         })

##########################################################################################
# Switches:
# Badges images: /config/www/buttons
##########################################################################################

switches_on = []

#total_switches_on = hass.states.get('input_boolean.whats_on').attributes.get('switches_on')
state = hass.states.get('automation.sense_switches_change')

if state:
    total_on = hass.states.get('input_boolean.whats_on').attributes.get('switches_on')
    for entity_id in hass.states.get(switchEntities).attributes['entity_id']:
        dt = state.last_updated + datetime.timedelta(hours=2)
        time = '%02d:%02d' % (dt.hour, dt.minute)

        if hass.states.get(entity_id).state is 'on':
            switches_on.append(hass.states.get(entity_id).attributes['friendly_name'])

    if len(switches_on) > 0:
        picture = '/local/buttons/button_power_on.png'
        message = ', '.join(switches_on)
        sensor_message = 'Switches on: ' + message
        switches_desc = '#- Switches on: {} -- {} since {}'.format(total_on, message,time)
        uom = 'Switches'

        if len(switches_on) == 1:
           uom = 'Switch'
    else:
        picture = '/local/buttons/button_power_off.png'
        message= ''
        sensor_message= 'No switches on'
        uom = 'Switches'

    sensor_switches_desc = '{}'.format(sensor_message)

    hass.states.set('sensor.switches_badge', total_on, {
#        'custom_ui_state_card': 'state-card-value_only',
            'text': sensor_message,
            'unit_of_measurement': uom,
            'friendly_name': time,
            'entity_picture': picture
         })

##########################################################################################
# Appliances:
# Badges images: /config/www/buttons
##########################################################################################
#appliancesGroup = 'group.iungo_switch_appliances_template'
appliances_on = []

#total_appliances_on = hass.states.get('input_boolean.whats_on').attributes.get('appliances_on')
state = hass.states.get('automation.sense_appliances_change')

if state:
    total_on = hass.states.get('input_boolean.whats_on').attributes.get('appliances_on')
    for entity_id in hass.states.get(applianceEntities).attributes['entity_id']:
        dt = state.last_updated + datetime.timedelta(hours=2)
        time = '%02d:%02d' % (dt.hour, dt.minute)

        if hass.states.get(entity_id).state is 'on':
            appliances_on.append(hass.states.get(entity_id).attributes['friendly_name'])

    if len(appliances_on) > 0:
        picture = '/local/buttons/button_power_on.png'
        message = ', '.join(appliances_on)
        sensor_message = 'Appliances on: ' + message
        uom = 'Appliances'

        if len(appliances_on) == 1:
            uom = 'Appliance'
    else:
        picture = '/local/buttons/button_power_off.png'
        message= ''
        sensor_message= 'No appliances on'
        appliances_desc = '!|-> No appliances on since {}'.format(time)
        uom = 'Appliances'

    sensor_appliances_desc = '{}'.format(sensor_message)

    hass.states.set('sensor.appliances_badge', total_on, {
    #        'custom_ui_state_card': 'state-card-value_only',
            'text': sensor_message,
            'unit_of_measurement': uom,
            'friendly_name': time,
            'entity_picture': picture
         })

summary.py (slightly bigger):

##########################################################################################
# Resources:
# https://github.com/maattdiy/home-assistant-config @Mviezzer
# https://home-assistant.io/components/python_script/
# https://home-assistant.io/docs/configuration/state_object/
# modified and customized by https://community.home-assistant.io/u/Mariusthvdb/summary
# big hand in Python by https://community.home-assistant.io/u/petro/summary
##########################################################################################

debug = False

if debug:
    event = data.get('event')
    logger.error("\n\nSUMMARY: " + str(event))

show_badges = True
show_card = True

##########################################################################################
# Group count
# Groups config:
# Entities summary by group name 
# groups = need to have same max member_count
# groups_format = # Message prefix
# groups_filter = # Filter to list
# groups_badge = # Badge 'belt' (unit_of_measurement)
# groups_badge_pic = # none, one, or a list of pictures (picture position = match the count)
# groups_min_show = # Mininum count to show
# groups_theme =  # Theme template
# groups_desc = # Can set the default description, for use in case count = 0
# themes build up or down according to counted value
##########################################################################################
group_count = 0
group_desc = ''
summary = ''
idx = 0
dt_prevstate = None

on ='black_badge|red_badge|yellow_badge|grey_badge|blue_badge|orange_badge|brown_badge|purple_badge|green_badge'

off ='green_badge|purple_badge|brown_badge|orange_badge|blue_badge|grey_badge|yellow_badge|red_badge|black_badge'

groups = ['group.family',
          'group.hubs_binary_pinged',
          'group.critical_devices_state',
          'group.media_player_media',
          'group.device_tracker_media',
          'group.all_lights_only',
          'group.iungo_switch_switches_template',
          'group.iungo_switch_appliances_template',
          'group.binary_sensors_active_template']

groups_format = ['+- Home: {} -- {}',
                 '!|-> Offline: {} -- {}',
                 '!|-> Status - Critical device offline: {} -- {}',
                 '#- Playing: {} -- {}',
                 '#- Tracked: {} -- {}',
                 '=- Lights on: {} -- {}',
                 '#- Switches on: {} -- {}',
                 '#- Appliances on: {} -- {}',
                 '+- Active: {} -- {}']

groups_filter = ['home',
                 'off|idle|not_home', 
                 'off|idle|unknown|not_home',
                 'home|playing|on',
                 'home|playing|on',
                 'on',
                 'on',
                 'on',
                 'on'] # was: 'home|playing|on'

groups_badge = ['Home','Hubs','Status','Play','Track','Lamps','Switch','Appli','Active']

groups_badge_pic = ['','ok|bug|critical','ok|bug|critical','','','','','','']

groups_min_show = [0,0,0,0,0,0,0,0,0]

groups_theme = [on,off,off,on,on,on,on,on,on]

groups_desc = ['!|-> Nobody home since ',
               '+- Hubs: all online',
               '+- Status: all online',
               '%|-> Nothing playing',
               '%|-> Nothing tracked',
               '!|-> No lights on since ',
               '!|-> No switches on since ',
               '!|-> No appliances on since ',
               '%|-> No Appliances active since ']

groups_count = [0, 0, 0, 0, 0, 0, 0, 0, 0]

for group in groups:
    group_count = 0
    group_desc = ''

    for entity_id in hass.states.get(group).attributes['entity_id']:
        state = hass.states.get(entity_id)
        filter = groups_filter[idx]

        if (state.state in filter.split('|') or debug):
            dt = state.last_updated + datetime.timedelta(hours= 2)
            time = '%02d:%02d' % (dt.hour, dt.minute)
            ch = state.last_changed + datetime.timedelta(hours= 2)
            ch_time = '%02d:%02d' % (dt.hour, dt.minute)
          # If state changed in the past days show the date too
            if dt.date() < datetime.datetime.now().date():
                time = '{} {}'.format('%02d/%02d' % (dt.day, dt.month), time)

            group_count = group_count + 1
            group_desc = '{} {} ({}), '.format( group_desc, state.name, time)

        else:
            if (dt_prevstate is None):
                dt_prevstate = state.last_changed
            else:
                if (not state.last_changed is None):
                    if (state.last_changed > dt_prevstate):
                        dt_prevstate = state.last_changed

    # Final format for this group
    if (group_count >= groups_min_show[idx]):
        if (group_count == 0):
            group_desc = groups_desc[idx]
           # If there is none 'On/Home' state in group, show since
            if (group_desc.find(' since ') > 0): #if (group_desc != ''):
                dt = dt_prevstate + datetime.timedelta(hours= 2)
                group_desc = '{} {}'.format(group_desc, '%02d:%02d' % (dt.hour, dt.minute))

        else:
            group_desc = groups_format[idx].format(group_count, group_desc[:-2])

        groups_desc[idx] = group_desc
        groups_count[idx] = group_count

    idx = idx + 1

##########################################################################################
# Badges updates
##########################################################################################

idx = 0

if show_badges:
    for badge in groups_badge:
        if (badge != ''):
            entity_id = 'sensor.{}_badge'.format(badge.replace(' ', '').lower());
            hidden = False if (groups_count[idx] >= groups_min_show[idx] or debug) else True
            fname = groups_desc[idx] if debug else ' '
            picture = groups_badge_pic[idx].replace(' ', '').lower()

            themelist = groups_theme[idx].split('|')
            if len(themelist) > 1:
                try:
                    theme = themelist[groups_count[idx]]
                except IndexError:
                    theme = 'green_badge' # Oops, error badge.1 ;-))
            else:
                theme = 'black_badge' # this will be the default theme

            # Check for picture X index/count
            if (picture != ''):
                picturelist = picture.split('|')
                if (len(picturelist) in [1, groups_count[idx]]):
                    picture = picturelist[-1] #was mylist[len(mylist)-1]
                else:
                    picture = picturelist[groups_count[idx]]

                if (picture != ''):
                    picture = '/local/badges/{}.png'.format(picture)

            hass.states.set(entity_id, groups_count[idx], {
              'friendly_name': fname,
              'unit_of_measurement': badge,
              'entity_picture': picture,
              'templates': { 'theme': theme }
            })

        idx = idx + 1

##########################################################################################
# Alarm clock
# https://github.com/maattdiy/home-assistant-config/blob/master/config/packages/alarmclock.yaml
##########################################################################################

alarms_prefix = ['alarmclock_wd', 'alarmclock_we']
alarms_wfilter = [range(1,6), range(6,8)]
alarms_desc = ''
mydict = {'hidden':hidden}

for entity_id, filter in zip(alarms_prefix, alarms_wfilter):
    state = hass.states.get('input_boolean.{}_enabled'.format(entity_id))
    if state:
        if state.state is 'on' and datetime.datetime.now().isoweekday() in filter:
            state = hass.states.get('sensor.{}_time_template'.format(entity_id))
            alarms_desc = '{}{}, '.format(alarms_desc, state.state)

if (alarms_desc == ''):
    mydict['entity_picture'] = '/local/badges/alarm_off.png'
    mydict['friendly_name'] =  'Relax'
    mydict['unit_of_measurement'] = 'Off'
    mydict['theme'] = 'grey_badge'
    alarms_desc = '%- Alarm clock is not set, relax'
else:
    mydict['entity_picture'] = '/local/badges/alarm.png'
    mydict['friendly_name'] = alarms_desc[:-2]
    mydict['unit_of_measurement'] = 'On'
    mydict['theme'] = 'orange_badge'
    alarms_desc = '/- Alarm clock set at ' + alarms_desc[:-2]

hass.states.set('sensor.alarms_badge', '', mydict)

##########################################################################################
# Mode:
# Inspired by: https://github.com/maattdiy/home-assistant-config/blob/master/config/packages/profiles.yaml
#              https://github.com/maattdiy/home-assistant-config/blob/master/config/packages/developer.yaml
# Badges images: /config/www/modes
##########################################################################################

mode_desc = ''
## Get Mode description
state = hass.states.get('input_select.mode')

if state:
    dt = state.last_changed + datetime.timedelta(hours= 2)
    time = "%02d:%02d" % (dt.hour, dt.minute)

    mode_desc = '{}*- {} mode selected at: {}\n'.format(summary, state.state, time)

    hass.states.set('sensor.mode_badge',state.state, {
         'entity_picture': '/local/modes/{''}.png'.format(state.state.replace(' ','').lower()),
         'friendly_name': time,
         'unit_of_measurement': 'Mode'
          })

##########################################################################################
# Activity:
# Badges images: /config/www/activities
##########################################################################################

activity_desc = ''
## Get Activity description
state = hass.states.get('input_select.activity')

if state:
    dt = state.last_changed + datetime.timedelta(hours= 2)
    time = "%02d:%02d" % (dt.hour, dt.minute)

    activity_desc = '{}$- {} activity selected at: {}\n'.format(summary, state.state, time)

    hass.states.set('sensor.activity_badge', state.state, {
            'friendly_name': time,
            'entity_picture': '/local/activities/{' '}.png'.format(state.state.replace(' ','').lower()),
            'unit_of_measurement': 'Act'
            })

##########################################################################################
# Summary update
# Custom card: /custom_ui/state-card-value_only.html
##########################################################################################

for group_desc in groups_desc:
    if group_desc != '' and not group_desc.endswith(': '):
        summary = '{}{}\n'.format(summary, group_desc)

# Add to final summary
summary = '*============== Status ============\n' \
          '{}\n' \
          '*============= Settings ===========\n' \
          '{}\n' \
          '*============== Modes =============\n' \
          '{}\n' \
          '{}' \
          .format(summary, 
                  alarms_desc, 
                  activity_desc, 
                  mode_desc)

if show_card:
    hass.states.set('sensor.summary', '', {
        'custom_ui_state_card': 'state-card-value_only',
        'text': summary
    })

##########################################################################################
# Codes for text_colors declared in 
# Custom card: /custom_ui/state-card-value_only.html
# changed to use below customizing options:
##########################################################################################

#      case "*": return "bold";
#      case "/": return "italic";
#      case "!": return "red";
#      case "+": return "green";
#      case "=": return "yellow";
#      case "%": return "grey";
#      case "$": return "brown";
#      case "#": return "blue";
#      default:  return "normal";