def _time_polling(self):
     try:
         sleep(120)
         while True:
             hour = datetime.now().hour
             minute = datetime.now().minute
             if (self._alarm_info == None):
                 # if alarm infos were not received via mqtt, try get it via http
                 self._initiateApiGet()
                 # if no infos received wake me up at 6:00 am
                 if (hour == 6 and minute == 0):
                     self._alarmClockWakeup()
             elif (self._alarm_info["state"] == "on"):
                 if (hour == self._alarm_info["hour"]
                         and minute == self._alarm_info["minute"]):
                     self._alarmClockWakeup()
             # Polling rate
             sleep(45)
     except:
         get_logger(__name__).error(f'Error while time polling')
         logging.exception("error info: ")
     finally:
         # if any error occurs try to wake me up
         # has to wait 10 sec, cuz the alarm_sound has to be initialized
         sleep(10)
         self._alarmClockWakeup()
예제 #2
0
 def _triggered(self):
     get_logger(__name__).info(f'alarm-button-info fired!')
     if not(self.alarm_info_received):
         self._broker.publish('alarm-request-info')
         timestamp = time()
         while(not self.alarm_info_received and time() - timestamp < 30):
             sleep(0.250)
예제 #3
0
 def _initiate_request_callback(self):
     if (self._threadActive):
         self._thread_flag.set()
         get_logger(__name__).info(f'Initiate thread active')
     else:
         self._thread_flag = threading.Event()
         self._thread = threading.Thread(target=self._http_polling,
                                         name='REST-API-Thread',
                                         daemon=True)
         self._thread.start()
         self._threadActive = True
         get_logger(__name__).info(f'Initiate thread inactive')
예제 #4
0
 def _broker_notify_alarm_info(self, mosq, obj, msg):
     response = json.loads(msg.payload.decode("utf-8"))
     alarm_info = {}
     alarm_info["hour"], alarm_info["minute"], alarm_info["second"] = map(
         int, response["time"].split(':'))
     alarm_info["state"] = response["state"]
     alarm_song = response["song"]
     # Send the alarm_info to all subscribers
     self._broker.publish('alarm-info', alarm_info)
     # Send the alarm_song to all subscribers
     self._broker.publish('alarm-song-selected', alarm_song)
     get_logger(__name__).info(
         f'received & published the following alarm_infos={alarm_info}, alarm_song={alarm_song}'
     )
예제 #5
0
    def _make_sound(self):
        # First try for the not so important song
        try:
            # construct to set stop flag
            self._active_buzzer_beep = ActiveAlarmBeep(self._PIN_BEEP)
            # quiet song
            self._passive_buzzer_melody = BuzzerSong(self._PIN_SONG)
            self._passive_buzzer_melody.setup()
            # start the selected song
            self._passive_buzzer_melody.select_song(self._selected_song)
            get_logger(__name__).info(f'Passive Buzzer alarm was successful')
        except:
            get_logger(__name__).error(
                f'Critical error in _melody @ passiv buzzer')
            logging.exception('Critical error in _melody @ passiv buzzer')
        finally:
            gpio.setDigital(self._PIN_SONG, 'OFF')

        # Second try in case the passive buzzer fails
        try:
            self._active_buzzer_beep.play(1, 90)
            get_logger(__name__).info(
                f'Active Buzzer BEEP LOUD alarm was successful')
        except:
            get_logger(__name__).error(
                f'Critical error in play @ ActiveAlarmBeep')
            logging.exception('Critical error in play @ ActiveAlarmBeep')
        finally:
            # Reset the beep flag
            gpio.setDigital(self._PIN_BEEP, 'ON')
            gpio.setDigital(self._PIN_SONG, 'OFF')

        # display the time
        sleep(5)
        self._broker.publish('alarm-button-stop', 'voice-triggered')
예제 #6
0
 def _check_pressed(self):
     try:
         while True:
             sleep(self._POLLING)
             if (gpio.getDigital(self._PIN)) == 1:
                 # accept only a long press (prevent noisy signals from the buzzer due to the magnetic field)
                 sleep(1)
                 if (gpio.getDigital(self._PIN)) == 1:
                     # notify all interested compontents about the event
                     self._triggered()
                     # debouncetime - 1 second: ignore any buttonpress within the next second
                     sleep(1)
     except:
         get_logger(__name__).error(f'Error in Thread Stop Button')
예제 #7
0
 def _check_pressed(self):
     try:
         while True:
             sleep(self._POLLING)
             if (gpio.getDigital(self._PIN)) == 1:
                 # notify all interested compontents about the event
                 self._triggered()
                 # debouncetime - 4 second: ignore any buttonpress within the next second
                 # set to 4 seconds, because the leds will last 4 seconds
                 # otherwise multiple presses after one another will cause a strange
                 # led effect
                 sleep(4)
     except:
         get_logger(__name__).error(f'Error in Thread Stop Button')
 def _run(self):
     # ensure the mqtt-broker is already running
     sleep(30)
     try:
         self.connect(self._ip_adress, self._port)
         # Subscribe to all topics
         self.subscribe('#')
         """
             !!!Attention!!!
             Adapt the wake word topic to your specific wake word topic, which may vary 
             by wake word engine and your country
         """
         # Wakeword
         self.message_callback_add('hermes/hotword/+/detected',
                                   self._broker_notify_wakeword)
         # Time app
         self.message_callback_add('hermes/intent/GetTime',
                                   self._broker_notify_show_time)
         # light leds
         self.message_callback_add('hermes/intent/LedOn',
                                   self._broker_notify_led_on)
         # led rainbow
         self.message_callback_add('hermes/intent/LedRainbow',
                                   self._broker_notify_led_rainbow)
         # turn led off
         self.message_callback_add('hermes/intent/LedOff',
                                   self._broker_notify_led_off)
         # led mute
         self.message_callback_add('voice-apps/led/mute',
                                   self._broker_notify_led_mute)
         # get alarm status
         self.message_callback_add('hermes/intent/AlarmState',
                                   self._broker_notify_get_alarm_state)
         # get alarm time
         self.message_callback_add('hermes/intent/AlarmTime',
                                   self._broker_notify_get_alarm_time)
         # get alarm info
         self.message_callback_add('hermes/intent/AlarmInfo',
                                   self._broker_notify_get_alarm_time)
         # error (bzw. rc) zeigt den Status des Verbindungsverlustes an
         # returned error > 0 dann ist ein Fehler aufgtreten
         error = 0
         while error == 0:
             error = self.loop()
         return error
     finally:
         get_logger(__name__).info(f'error in mqtt receiver rc = {error}')
         logging.exception("error info: ")
예제 #9
0
    def _beep(self, *args, **kwargs):
        if (self._last_minute_active == False):
            # start beeping
            self._run()
            self._last_minute_active = True
            """stop any request to start beeping for the next minute
			   this is because the time keeper would send the whole 
			   minute in 15 second intervals new command
			"""
            try:
                sleep(60)
            except:
                get_logger(__name__).warning(
                    f'Interrupted debouncing of the buzzer')
            finally:
                self._last_minute_active = False
예제 #10
0
 def _run(self):
     # ensure the mqtt-broker is already running
     sleep(30)
     try:
         self.username_pw_set(self._user, self._password)
         self.connect(self._ip_adress, self._port)
         # Subscribe to all topics
         self.subscribe('#')
         # Callback for Alarm Info
         self.message_callback_add('home-assistant/alarm-clock/nicolas',
                                   self._broker_notify_alarm_info)
         # error (bzw. rc) zeigt den Status des Verbindungsverlustes an
         # returned error > 0 dann ist ein Fehler aufgtreten
         error = 0
         while error == 0:
             error = self.loop()
         return error
     finally:
         get_logger(__name__).info(f'error in mqtt receiver rc = {error}')
         logging.exception("error info: ")
예제 #11
0
 def _check_pressed(self):
     try:
         while True:
             sleep(self._POLLING)
             if (gpio.getDigital(self._PIN)) == 1:
                 # accept only a long press (prevent noisy signals from the buzzer due to the magnetic field)
                 sleep(1)
                 if (gpio.getDigital(self._PIN)) == 1:
                     self._triggered()
                     # debouncetime - 15 second: ignore any buttonpress within the next second
                     # notify all interested compontents about the event
                     # set to 15 seconds, because the leds will last 15 seconds
                     # otherwise multiple presses after one another will cause a strange
                     # led effect
                     if(self.alarm_info_received):
                         self._broker.publish('alarm-button-info', 'pressed')
                     sleep(15)
     except:
         get_logger(__name__).error(f'Error in Thread Info Button')
     finally:
         self.close()
 def __init__(self, broker):
     super().__init__()
     self._broker = broker
     # Callback to active Hotword on button press
     self._broker.subscribe("alarm-button-stop", self._unmute)
     # read mqtt setting 4 connection
     path = os.path.join(os.path.dirname(__file__),
                         'mqtt_intend_settings.json')
     with open(path) as f:
         mqtt_settings = json.load(f)
     self._ip_adress = mqtt_settings["ip"]  # usually 192.168.178.19
     self._port = mqtt_settings["port"]  # usually 1883
     # setup logging
     self.enable_logger(get_logger(__name__))
     # Thread zum empfangen der MQTT Nachrichten
     self._thread_flag = threading.Event()
     self._thread = threading.Thread(target=self._run, daemon=True)
     self._thread.start()
예제 #13
0
 def _http_polling(self):
     try:
         # prevent exceeding requests at startup
         sleep(10)
         while True:
             get_logger(__name__).info(f'http api try')
             time = self._get_alarm_time()
             state = self._get_alarm_state()
             song = self._get_alarm_song()
             # Don't check if song request was successful,
             # because the alarm will work without it
             # Check if the request was successful
             if (time.status_code != 200 or state.status_code != 200):
                 get_logger(__name__).warn(
                     f'GET Request failed with code {time.status_code}!')
                 # Not successful, go on threading
                 self._thread_flag.set()
             else:
                 # Successful
                 alarm_info = self._format_alarm_info(time, state)
                 # Send the alarm_info to all subscribers
                 self._broker.publish('alarm-info', alarm_info)
                 # Send the selected song, if the request was successful
                 if (song.status_code == 200):
                     alarm_song = self._format_alarm_song(song)
                     self._broker.publish('alarm-song-selected', alarm_song)
                 get_logger(__name__).info(
                     f'Successfully received alarm_info={alarm_info}, alarm_song={alarm_song}'
                 )
                 # Request was successful, stop the thread
                 return
             sleep(10)
             self._thread_flag.wait()
     except:
         get_logger(__name__).error(f'Error in Api Handler')
         logging.exception("Error info:")
     finally:
         self.close()
         self._threadActive = False
예제 #14
0
    def __init__(self, broker):
        super().__init__()
        self._broker = broker
        # read mqtt setting 4 connection
        path = os.path.join(os.path.dirname(__file__),
                            'mqtt_home_assistant_settings.json')
        with open(path) as f:
            mqtt_settings = json.load(f)
        path = os.path.join(os.path.dirname(__file__),
                            'MQTT_Home_Assistant_Authorization.json')
        with open(path) as f:
            mqtt_authorization = json.load(f)
        self._ip_adress = mqtt_settings["ip"]  # usually 192.168.178.21
        self._port = mqtt_settings["port"]  # usually 1883
        self._user = mqtt_authorization["user"]
        self._password = mqtt_authorization["password"]

        # setup logging
        self.enable_logger(get_logger(__name__))
        # Thread zum empfangen der MQTT Nachrichten
        self._thread_flag = threading.Event()
        self._thread = threading.Thread(target=self._run, daemon=True)
        self._thread.start()
예제 #15
0
 def _receive_alarm_info_callback(self, alarm_info):
     get_logger(__name__).info(f'received alarm_info={alarm_info}')
     self._alarm_info = alarm_info
예제 #16
0
 def _triggered(self):
     # notify all interested compontents about the event
     self._broker.publish('alarm-button-switch', 'pressed')
     get_logger(__name__).info(f'Toggle alarm state')
예제 #17
0
from Alarm_Buttons.alarm_info_button import AlarmInfoButton
from Alarm_Buttons.alarm_switch_button import AlarmSwitchButton
from Alarm_Time_Keeper.alarm_time_keeper import AlarmTimeKeeper
from Broker.broker import Broker
from LED.led_alarm_status import LEDAlarmStatus
from LED.led_clock import LEDClock
from LED.led_others import LEDOthers
from Logger.logger_init import get_logger, setup_logging
from MQTT_Handler.mqtt_intend_receiver import MQTTIntendReceiver
from MQTT_Handler.mqtt_home_assistant_receiver import MQTTHomeAssistantReceiver
from REST_API_Handler.rest_api_handler import RESTApiHandler

if __name__ == "__main__":
    # Setup logging
    setup_logging(default_filename='logging_config.json')
    get_logger(__name__).info(f'voice-apps started!')
    # Central broker
    broker = Broker()
    # array including all components
    thread_objects = [
        # Alarm sound - PIN-SONG = Passive Buzzer / PIN_BEEP = Active Buzzer
        AlarmSound(broker, PIN_SONG=6, PIN_BEEP=4),
        AlarmStopButton(broker, PIN=0, POLLING=.125),  # Button - stop
        AlarmInfoButton(broker, PIN=2, POLLING=.125),  # Button - info
        # AlarmSwitchButton(broker, PIN=2, POLLING=.125),    # Button - switch
        LEDClock(broker, 0, "blue", "red", "yellow"),  # LED Clock
        # LED alarm status on switch
        LEDAlarmStatus(broker),
        # LED other stuff like lights or rainbow
        LEDOthers(broker),
        # REST-API-Handler for Home Assistant
예제 #18
0
 def _triggered(self):
     get_logger(__name__).info(f'alarm-button-stop fired!')
     # notify all interested compontents about the event
     self._broker.publish('alarm-button-stop', 'pressed')