import asyncio
import time
from uuid import uuid4

import pendulum


import logging
import sys

sys.path.append("/home/ubuntu/data/code/unify_api2/pot_libs")
sys.path.append("/home/ubuntu/data/code/unify_api2")
from pot_libs.aiomqtt_util.hbmqtt_utils import MqttUtil
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(name)s - %(filename)s - %(process)d_%(thread)d "
           "- line:%(lineno)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger()


async def main1():
    SID = "A1911000050"
    while True:
        dt_now = pendulum.now()
        dt_h = dt_now.hour
        # 1. 代码在00:00 - 06:00执行
        logger.info(f"dt_h:{dt_h}")

        # if dt_h > 0:
        # if 6 >= dt_h >= 0:
        if dt_h > 0:

            # 2. 下发get命令
            request_id_get = str(uuid4())
            get_data = {
                "sid": SID,
                "request_id": request_id_get,
                "method": "get",
                "time": pendulum.now().to_datetime_string()
            }
            try:
                async with MqttUtil() as emq:
                    result = await emq.device_response(
                        sid=SID, request_id=request_id_get, data=get_data
                    )
                    logger.info(f"result:{result}")
            except Exception as e:
                logger.warning(e)
                time.sleep(1*60)
                continue
            if result and result["status_code"] == 200:
                res_data = result.get("data")
                software_version = res_data.get("software").get(
                    "software_version")
                logger.info(f"software_version: {software_version}")
                if software_version == "v2.2.1_YUEDIAN":
                    logger.info("upgrade success")
                    break
                else:
                    # 3.下发upgrade命令
                    request_id_com = str(uuid4())
                    time.sleep(3)
                    upgrade_data = {
                        "sid": SID,
                        "request_id": request_id_com,
                        "method": "command",
                        "time": pendulum.now().to_datetime_string(),
                        "data": {
                            "command": "upgrade",
                            "params": {
                                "md5": "9614c514090db731f4e442a94aec9d7c",
                                "url": "http://www.uplus.soejh.com/uplus/unify-api/upgrade/device/download"
                            }
                        }
                    }
                    try:
                        async with MqttUtil() as emq:
                            logger.info("start upgrade")
                            logger.info(f"upgrade_data:{upgrade_data}")
                            upgrade_result = await emq.device_response(
                                sid=SID, request_id=request_id_com,
                                data=upgrade_data
                            )
                            logger.info(f"upgrade_result:{upgrade_result}")
                    except Exception as e:
                        logger.warning(e)
        time.sleep(1 * 60)


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main1())
