Exemplo n.º 1
0
async def pots_health_check():
    all_pots = pots_collection.get()

    for pot in all_pots:
        try:
            pot_id = pot.to_dict()['potId']
            # Alert Pot
            health_check_msg = MessageToPot(
                action=Action.update,
                potId=pot_id,
                data=[
                    PotSendDataDictStr(field=PotSendDataStr.health_check,
                                       value="health check")
                ])
            await ws_manager.send_personal_message_json(
                health_check_msg.dict(), pot_id)
            logger.info("Health check to pot {} success!".format(pot_id))
            firestore_input = {"connected": True}

        except Exception as e:
            logger.error("Health check to Pot {} failed!".format(pot_id))
            firestore_input = {"connected": False}

        # Update Firebase to alert mobile app
        pots_collection.document(pot_id).update(firestore_input)
Exemplo n.º 2
0
async def create(new_pot: PotHttpReq):
    try:
        pot_id = new_pot.id
        new_pot = new_pot_registration(pot_id)
        pots_collection.document(pot_id).set(new_pot.dict())
        logger.info("New Pot {} registered".format(pot_id))
        return {"success": True}
    except Exception as e:
        logger.error(e)
        return f"An Error Occured: {e}"
    async def on_snapshot(col_snapshot, changes, read_time):
        for change in changes:
            try:
                if change.type.name == 'ADDED':
                    # print(f'New Pot: {change.document.id}')
                    pass
                elif change.type.name == 'MODIFIED':
                    # print(f'Modified Pot: {change.document.id}')
                    doc_updated = change.document.__dict__['_data']
                    pot_id = change.document.id
                    # print(pot_id)

                    pot_obj: Pot = Pot.parse_obj(doc_updated)

                    bool_triggers = {
                        PotSendDataBool.ringHappySound: {
                            "fs_path": "sounds.happySound",
                            "value": pot_obj.sounds.happySound
                        },
                        PotSendDataBool.ringSadSound: {
                            "fs_path": "sounds.sadSound",
                            "value": pot_obj.sounds.sadSound
                        }
                    }

                    for trigger_field in bool_triggers:
                        firestore_input = {}
                        if bool_triggers[trigger_field]["value"]:
                            response = MessageToPot(
                                potId=pot_id,
                                data=[
                                    PotSendDataDictBool(field=trigger_field,
                                                        value=True)
                                ])
                            # TODO: Check if plant pot has to turn it off or will be auto turn off
                            # TODO: Better to have mobile app trigger this by sending to backend directly
                            firestore_input[bool_triggers[trigger_field]
                                            ["fs_path"]] = False
                            pots_collection.document(pot_id).update(
                                firestore_input)
                            # Shifted after reverting value in fireestore so that dont have to do so if sending to pot fails (not the best implementation)
                            await ws_manager.send_personal_message_json(
                                response.dict(), pot_id)

            except Exception as e:
                if e.args[0] == "Websocket for Pot {} not found".format(
                        pot_id):
                    logger.error(e)

        callback_done.set()
Exemplo n.º 4
0
async def quiz_alert():
    current_date = datetime.utcnow().strftime('%Y%m%d')
    # NOTE: For Python, all string fields with an integer value like '1' require ``
    retrieved_pots = pots_collection.where('session.quiz.quizDates',
                                           'array_contains',
                                           current_date).get()

    # TODO: parse this properly to Pot object
    for pot in retrieved_pots:
        try:
            pot_id = pot.to_dict()["potId"]
            quiz_day_number_idx = pot.to_dict(
            )['session']['quiz']['quizDates'].index(current_date)
            quiz_day_number = pot.to_dict(
            )['session']['quiz']['quizDayNumbers'][quiz_day_number_idx]
            current_show_quiz_numbers: list = pot.to_dict(
            )['session']['quiz']['showQuizNumbers']
            current_show_quiz_numbers.append(quiz_day_number)
            firestore_input = {
                "session.quiz.showQuizNumbers": current_show_quiz_numbers,
                "session.quiz.currentQuizDayNumber": quiz_day_number
            }

            # Update Firebase to alert mobile app
            pots_collection.document(pot_id).update(firestore_input)
            logger.info("Updated Quiz {} alert for Pot {} to database".format(
                quiz_day_number, pot_id))

            #TODO: Also alert when previous quiz not yet completed
            # Alert Pot
            alert_message = MessageToPot(
                action=Action.update,
                potId=pot_id,
                data=[
                    PotSendDataDictBool(field=PotSendDataBool.showQuiz,
                                        value=True)
                ])
            await ws_manager.send_personal_message_json(
                alert_message.dict(), pot_id)

            logger.info("Sent Quiz {} alert to Pot {}".format(
                quiz_day_number, pot_id))

        except Exception as e:
            logger.error("Quiz {} alert to Pot {} failed!".format(
                quiz_day_number, pot_id))
Exemplo n.º 5
0
async def health(pot: PotHttpReq):
    try:
        pot_id = pot.id
        health_check_msg = MessageToPot(
            potId=pot_id,
            data=[
                PotSendDataDictStr(field=PotSendDataStr.health_check,
                                   value="health check")
            ])
        await ws_manager.send_personal_message_json(health_check_msg.dict(),
                                                    pot_id)
        logger.info("Health check to pot {} success!".format(pot_id))
        firestore_input = {"connected": True}
        pots_collection.document(pot_id).update(firestore_input)
        return {"health check": True}
    except Exception as e:
        logger.error("Health check to pot {} failed!".format(pot_id))
        return {"health check": False}
Exemplo n.º 6
0
async def daily_check_in_alert():
    all_pots = pots_collection.get()

    for pot in all_pots:
        try:
            pot_id = pot.to_dict()['potId']
            firestore_input = {"session.checkIn.showCheckIn": True}
            # Update Firebase to alert mobile app
            pots_collection.document(pot_id).update(firestore_input)
            # Alert Pot
            alert_message = MessageToPot(
                action=Action.update,
                potId=pot_id,
                data=[
                    PotSendDataDictBool(field=PotSendDataBool.showCheckIn,
                                        value=True)
                ])
            await ws_manager.send_personal_message_json(
                alert_message.dict(), pot_id)
            logger.info("Sent Check In alert to Pot {}".format(pot_id))
            # TODO: Need a message queue for messages not sent to pots with failed websocket connection
        except Exception as e:
            logger.error("Check In alert to Pot {} failed!".format(pot_id))