Exemple #1
0
def start_alarm():

    if request.method == "POST":
        t = request.form["time"]
        hm = t.split(":")
        h = hm[0]
        m = hm[1]

        a = Alarm(int(h), int(m))
        a.start()


    return ("", 204)
class Animation:
    def __init__(self, frameList):
        self.frameList = frameList  # 设置帧列表, frameList为一个list, 每一个成员均为surface
        self.maxFrame = len(self.frameList)  # 动画帧数量
        self.currentFrameIdx = 0  # 当前动画帧id
        self.frameDurationMsec = 0  # 播放动画时使用的帧间隔
        self.pos = [0, 0]  # 动画发生地点, 单位为像素
        self.surface = None  # 动画发生的surface
        self.repeat = 0  # 循环次数 0-无限循环
        self.state = ANIME_READY  # 动画就绪
        self.alarm = Alarm()
        self.playTimes = 0  # 动画被播放的次数

    def setFrameDuration(self, duration_msec):
        self.frameDurationMsec = duration_msec

    def setPostion(self, surface, pos):
        # 设置动画发生的地点
        self.pos = pos
        self.surface = surface

    def setRepeat(self, repeat):
        # 设置循环模式, 0-无限循环, >0-循环几次
        self.repeat = repeat

    def draw(self):
        # 周期性的调用此函数即可进行动画描画
        if self.state == ANIME_READY:
            self.state = ANIME_RUNNING
            self.alarm.setTimeout(self.frameDurationMsec)
            self.alarm.start()
        elif self.state == ANIME_RUNNING:
            if self.alarm.isTimeout():
                self.currentFrameIdx += 1
                if self.currentFrameIdx == self.maxFrame:
                    self.currentFrameIdx = 0
                    if self.repeat != 0:
                        # 不是无限循环
                        self.playTimes += 1
                        if self.playTimes == self.repeat:
                            # 到达播放次数
                            self.state = ANIME_FINISHED
            self.surface.blit(self.frameList[self.currentFrameIdx], self.pos)
        else:
            pass  # 不做任何事

    def isAlive(self):
        # 判断动画是否存活
        if self.state == ANIME_FINISHED:
            return False
        return True
def main():
    global myAlarm
    # create an alarm
    g_alarm = Alarm()

    # set alarm data
    # should be updated before the alarm is triggered
    g_alarm.set({'time': datetime.now().strftime("%H:%M:%S")})

    # starts the alarm
    g_alarm.start()

    time.sleep(10)

    # stops the alarm
    # sensors may also stop the alarm
    g_alarm.stop()

    time.sleep(10)
    print "done"

    # call this at program exit to kill child threads
    g_alarm.destr_cb()
class BattleWindow():
    def __init__(self, screen):
        self.screen = screen
        self.ctrlList = []
        # 创建导演
        self.director = Director(self.screen)
        # 创建定时器
        self.alarm = Alarm()
        self.alarm.setTimeout(1000)
        self.alarm.start()
        # 创建调试信息
        self.debugInfo = DebugInfo(screen)
        # fps相关
        self.fps_count = 0
        self.fps = 0

    def processEvent(self, event):
        pass

    def doModel(self):
        while True:
            for event in pygame.event.get():
                self.director.processEvent(event)
            # 导演类描画主窗体
            self.director.draw()
            # debug类描画调试信息
            self.debugInfo.clean()
            self.debugInfo.drawLine("fps: %d" % self.fps)

            if self.alarm.isTimeout():
                self.fps = self.fps_count
                self.fps_count = 0
            else:
                self.fps_count += 1

            pygame.display.update()
        )
    )
    return render_template('index.html', status=alarm.status(), alarm_t=alarm.time())


@app.route('/deactivate')
def deactivate():
    alarm.deactivate()
    return 'deactivated'


@app.route('/activate')
def activate():
    alarm.activate()
    return 'activated'


@app.route('/status')
def status():
    return 'Status: {}, Time: {}'.format(alarm.status(), alarm.time())


if __name__ == '__main__':
    parser = ArgumentParser()
    parser.add_argument('--host')
    parser.add_argument('--port')
    kwargs = vars(parser.parse_args())

    alarm.start()
    app.run(debug=True, **kwargs)
Exemple #6
0
def main():
    global BACKLIGHT_STATUS
    ALARM_TIME, TONE, DURATION, WEEKDAYS_ONLY, ENABLED = load_config(SETTINGS)

    # Initialize the buttons
    GPIO.setmode(GPIO.BCM)

    GPIO.setup(GREEN_BUTTON, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
    GPIO.setup(BLUE_BUTTON, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
    GPIO.setup(RED_BUTTON, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

    # Backlight Toggle
    GPIO.setup(BACKLIGHT, GPIO.OUT)
    GPIO.output(BACKLIGHT, BACKLIGHT_STATUS)
    GPIO.add_event_detect(GREEN_BUTTON, GPIO.RISING, callback=toggle_backlight)

    # Initialize the lcd object
    lcd = characterlcd.Character_LCD_Mono(lcd_rs, lcd_en, lcd_d4, lcd_d5,
                                          lcd_d6, lcd_d7, LCD_COLUMNS,
                                          LCD_ROWS)
    lcd.clear()

    # Initialize logger
    logging.basicConfig(filename="clock.log",
                        format='%(asctime)s - %(message)s',
                        datefmt='%d-%b-%y %H:%M:%S',
                        level=logging.INFO)

    alarm = Alarm(ALARM_TIME, lcd, TONE, DURATION)
    if ENABLED:
        alarm.start()
        logging.info("Started - Alarm ENABLED")

    # Setup the logger
    logging.basicConfig(filename="Rpi-Clock.log",
                        level=LOGGING_LEVEL,
                        format='%(asctime)s - %(message)s',
                        datefmt='%d-%b-%y %H:%M:%S')
    logging.info(START_TEXT)

    try:
        while True:
            # Don't overwrite alarm text with stock times
            # Ensure backlight is on during alarm
            while alarm.alarming:
                # Stop the alarm with blue button press.
                while GPIO.input(BLUE_BUTTON) == GPIO.HIGH:
                    alarm.stop_alarm()
                    message(lcd, "STOPPED ALARM")
                    logging.info("Stopped alarm from BLUE button.")
                    BACKLIGHT_STATUS = True
                    GPIO.output(BACKLIGHT, BACKLIGHT_STATUS)
                sleep(1)

            # Grab and display time
            lcd.message = get_formatted_times(ALARM_TIME.strftime("%H:%M"),
                                              weekdays_only=WEEKDAYS_ONLY,
                                              enabled=ENABLED)
            logging.debug("Updated time")

            # Power off if red button is held for 3 seconds
            while GPIO.input(RED_BUTTON) == GPIO.HIGH:
                for i in range(3):
                    if i == 0:
                        lcd.clear()
                    lcd.message = f"Shutting down {3 - i}"
                    if i == 3:
                        logging.info("Poweroff from RED button.")
                        safe_exit(lcd, alarm)
                    sleep(1)

            # Reload the config on blue button press.
            while GPIO.input(BLUE_BUTTON) == GPIO.HIGH and not alarm.alarming:
                ALARM_TIME, TONE, DURATION, WEEKDAYS_ONLY, ENABLED = load_config(
                    SETTINGS)
                alarm.kill()

                if ENABLED:
                    logging.info("Config Reloaded - Alarm Enabled")
                    alarm = Alarm(ALARM_TIME, lcd, TONE, DURATION)
                    alarm.start()
                else:
                    logging.info("Config Reloaded - Alarm Disabled")

                message(lcd, "Reloaded Config")
            sleep(1)

    except KeyboardInterrupt:
        safe_exit(lcd, alarm)

    except Exception:
        logging.fatal("Exception occured", exc_info=True)