I have created a Python script to change volume on a media player entity or a group of media players with a “transition” by repeatedly calling the volume_set service. To achieve this I am creating a dictionary consisting of the entity id’s as key and a boolean as value:
dict_of_speaker_bools = dict([(speaker_id, False) for speaker_id in entity_id_list])
However, the execution of the code line above returns the following error message:
Traceback (most recent call last):
File “/usr/src/homeassistant/homeassistant/components/python_script/init.py”, line 205, in execute
exec(compiled.code, restricted_globals)
File “media_player_volume_set.py”, line 12, in
NameError: name ‘dict’ is not defined
The Python script as a whole:
entity_id = data.get('entity_id')
group_volume = bool(data.get('group_volume'))
target_volume = float(data.get('volume_level'))
if group_volume:
entity_id_list = hass.states.get(entity_id).attributes['sonos_group']
else:
entity_id_list = entity_id
logger.warning(entity_id_list) # For debugging purposes
dict_of_speaker_bools = dict([(speaker_id, False) for speaker_id in entity_id_list])
volume_increment = 0.015
while not all(dict_of_speaker_bools.values()):
for speaker_id in entity_id_list:
current_volume = hass.states.get(speaker_id).attributes['volume_level']
volume_diff = target_volume - current_volume
if abs(volume_diff) <= volume_increment:
dict_of_speaker_bools[speaker_id] = True
service_data = {"entity_id": speaker_id, "volume_level": target_volume}
hass.services.call("media_player", "volume_set", service_data)
continue
volume_diff_sign = volume_diff/abs(volume_diff)
volume_delta = volume_increment * volume_diff_sign
new_volume = current_volume + volume_delta
service_data = {"entity_id": speaker_id, "volume_level": new_volume}
hass.services.call("media_player", "volume_set", service_data)
time.sleep(.1)
The code is available on Github.
Thank you for any assistance!