Skip to content

Instantly share code, notes, and snippets.

@LunkwillAndFook
Created December 13, 2022 04:07
Show Gist options
  • Save LunkwillAndFook/105d73a213e1e2cba5d0ab4af932c2e2 to your computer and use it in GitHub Desktop.
Save LunkwillAndFook/105d73a213e1e2cba5d0ab4af932c2e2 to your computer and use it in GitHub Desktop.
AppDaemon SpeechManager for alexa_media
import adbase as ad
import hassapi as hass
import random
from datetime import datetime
from time import time
# Sample Speech Manager AppDaemon
# Created by LunkwillAndFook
# Copyright 2022 LunkwillAndFook
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
class SampleSpeechManager(hass.Hass):
delay = 0.092
async def HandleAnnouncePhrase(self, eventName, data, kwargs):
self.adapi = self.get_ad_api()
nearest_echo = await self.GetNearestEchoByOccupancy()
if nearest_echo != None:
echo = await self.adapi.get_state(nearest_echo,attribute='all')
last_volume = echo['attributes']['volume_level']
phrases = data['phrases']
phrase = random.choice(phrases)
self.log('HandleAnnouncePhrase called on ' + nearest_echo + ' with phrase ' + str(phrase))
await self.call_service('media_player/volume_set', volume_level=0.8, entity_id=nearest_echo)
await self.sleep(3)
await self.call_service('notify/alexa_media', message=phrase, data={'type': 'tts'}, target=nearest_echo)
delay = len(phrase) * self.delay
self.run_in(self.ResetVolume, delay, volume=last_volume, entity_id=nearest_echo)
async def HandleAnnouncePhraseToTarget(self, eventName, data, kwargs):
self.adapi = self.get_ad_api()
target_echo = data['target']
if target_echo != None:
self.log('HandleAnnouncePhraseToTarget called on ' + target_echo)
echo = await self.adapi.get_state(target_echo, attribute='all')
last_volume = echo['attributes']['volume_level']
phrases = data['phrases']
phrase = random.choice(phrases)
self.log('HandleAnnouncePhraseToTarget called on ' + target_echo + ' with phrase ' + str(phrase))
await self.call_service('media_player/volume_set', volume_level=0.8, entity_id=target_echo)
await self.sleep(2)
await self.call_service('notify/alexa_media', message=phrase, data={'type': 'tts'}, target=target_echo)
delay = len(phrase) * self.delay
self.run_in(self.ResetVolume, delay, volume=last_volume, entity_id=target_echo)
async def HandleAnnounceMessage(self, eventName, data, kwargs):
self.log('HandleAnnounceMessage', level='DEBUG')
self.adapi = self.get_ad_api()
nearest_echo = await self.GetNearestEchoByOccupancy()
if nearest_echo != None:
self.log('HandleAnnounceMessage called on ' + nearest_echo)
echo = await self.adapi.get_state(nearest_echo, attribute='all')
last_volume = echo['attributes']['volume_level']
message_content = data['message']
self.call_service("media_player/volume_set", volume_level=0.8, entity_id=nearest_echo)
await self.sleep(3)
self.call_service('notify/alexa_media', message=message_content, data={'type': 'tts'}, target=nearest_echo)
delay = len(message_content) * self.delay
self.run_in(self.ResetVolume, delay, volume=last_volume, entity_id=nearest_echo)
async def HandleAnnounceMessageToTarget(self, eventName, data, kwargs):
self.log('HandleAnnounceMessageToTarget', level='DEBUG')
self.adapi = self.get_ad_api()
target_echo = data['target']
if target_echo != None:
self.log('HandleAnnounceMessageToTarget called on ' + target_echo)
echo = await self.adapi.get_state(target_echo, attribute='all')
last_volume = echo['attributes']['volume_level']
message_content = data['message']
await self.call_service("media_player/volume_set", volume_level=0.8, entity_id=target_echo)
await self.sleep(3)
await self.call_service('notify/alexa_media', message=message_content, data={'type': 'tts'}, target=target_echo)
delay = len(message_content) * self.delay
self.run_in(self.ResetVolume, delay, volume=last_volume, entity_id=target_echo)
async def HandleResponseMessage(self, eventName, data, kwargs):
self.log('HandleResponseMessage', level='DEBUG')
self.adapi = self.get_ad_api()
try:
await self.call_service('alexa_media/update_last_called')
except Exception as e:
self.log(e, level='ERROR')
await self.sleep(3)
last_echo = await self.adapi.get_state('sensor.last_requesting_echo')
if last_echo != None:
self.log('HandleResponseMessage called on ' + last_echo)
echo = await self.adapi.get_state(last_echo, attribute='all')
last_volume = echo['attributes']['volume_level']
message_content = data['message']
await self.call_service("media_player/volume_set", entity_id=last_echo, volume_level=0.8)
await self.sleep(3)
await self.call_service('notify/alexa_media', message=message_content, data={'type': 'tts'}, target=last_echo)
delay = len(message_content) * self.delay
self.run_in(self.ResetVolume, delay, volume=last_volume, entity_id=last_echo)
async def HandleResponsePhrase(self, eventName, data, kwargs):
self.adapi = self.get_ad_api()
await self.call_service('alexa_media/update_last_called')
await self.sleep(3)
echo = await self.adapi.get_state(self.entities.sensor.last_requesting_echo.state,attribute='all')
self.log('HandleResponsePhrase called on ' + self.entities.sensor.last_requesting_echo)
last_volume = echo.volume_level
phrases = data['phrases']
last_called_text = str(echo['attributes']['last_called_timestamp'])
last_called_text_size = len(last_called_text)
last_called_text_fixed = last_called_text[:last_called_text_size - 3]
last_called_timestamp = int(last_called_text_fixed)
last_called_date = datetime.fromtimestamp(last_called_timestamp)
delta = datetime.now() - last_called_date
if delta.total_seconds() < 20:
phrase = random.choice(phrases)
await self.call_service('media_player/volume_set', data={'volume_level': 0.8}, entity_id=self.entities.sensor.last_requesting_echo.state)
await self.sleep(3)
await self.call_service('notify/alexa_media', message=phrase, data={'type': 'tts'}, target=self.entities.sensor.last_requesting_echo.state)
delay = len(phrase) * self.delay
await self.run_in(self.ResetVolume, delay, volume=last_volume, entity_id=self.entities.sensor.last_requesting_echo.state)
async def ResetVolume(self, kwargs):
await self.call_service('media_player/volume_set', entity_id=kwargs['entity_id'], volume_level=kwargs['volume'])
async def GetNearestEchoByOccupancy(self):
echo_mappings = self.args['motion_sensor_echo_mapping']
echo_mappings_list = list(echo_mappings)
for echo_mapping in echo_mappings_list:
if await self.adapi.get_state(echo_mapping) == 'on':
return self.args['motion_sensor_echo_mapping'][echo_mapping]
motion_ratios = await self.GetSortedMotionRatios()
# early out
if list(motion_ratios.values())[0] == 0:
return None
for key in list(motion_ratios.keys()):
if motion_ratios[key] > 0 and key in self.args['motion_ratio_echo_mapping']:
return self.args['motion_ratio_echo_mapping'][key]
def CheckLastTenMinuteSensor(self, sensor):
if 'last_10m' in sensor:
return True
return False
async def GetSortedMotionRatios(self):
states = await self.adapi.get_state()
states_iterator = filter(self.CheckLastTenMinuteSensor, states)
last_ten_sensor_names = list(states_iterator)
last_ten_sensors = {}
for sensor_name in last_ten_sensor_names:
last_ten_sensors[sensor_name] = float(self.get_state(sensor_name))
motion_ratios = dict(sorted(last_ten_sensors.items(), key=lambda item: item[1], reverse=True))
return motion_ratios
async def initialize(self):
self.adapi = self.get_ad_api()
self.listen_event(self.HandleResponsePhrase, 'speech_manager.respond_with_phrase')
self.listen_event(self.HandleAnnouncePhrase, 'speech_manager.announce_phrase')
self.listen_event(self.HandleAnnouncePhraseToTarget, 'speech_manager.announce_phrase_to_target')
self.listen_event(self.HandleResponseMessage, 'speech_manager.respond_with_message')
self.listen_event(self.HandleAnnounceMessageToTarget, 'speech_manager.announce_message_to_target')
self.listen_event(self.HandleAnnounceMessage, 'speech_manager.announce_message')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment