from umqtt import MQTTClient
# from usr.umqtt import MQTTClient
import modem
import _thread
import checkNet
import utime
from misc import Power

def sub_cb(topic, msg):
    global c
    print(
        "Subscribe Recv: Topic={},Msg={}".format(
            topic.decode(),
            msg.decode()))


def wait_msg():
    global c
    while True:
        utime.sleep_ms(100)
        try:
            if c is not None:
                ret = c.get_mqttsta()
                print('wait_msg get_mqttsta:', ret)
                if ret == 0:
                    c.wait_msg()
        except:
            pass

def MQTT_PUB():
    global c
    global IMEI
    while True:
        utime.sleep_ms(3000)
        try:
            if c is not None:
                c.publish(PUB_TOPIC.format(IMEI), "test publish 你好")
                c.publish(PUB_TOPIC.format(IMEI), bytearray(b'\x30\x31\x32\x33\x00\x01\x02\x03'))
                ret = c.get_mqttsta()
                print('MQTT_PUB get_mqttsta:', ret)
            else:
                print('MQTT_PUB(): c is None')
        except BaseException as e:
            print('BaseException, Resatrting...', e)


def MQTT_Init(CLIENT_ID,SERVER,PORT,USER,PASSWORD,keepalive):
    global c
    global IMEI

    # 创建一个mqtt实例
    c = MQTTClient(
        client_id=CLIENT_ID,
        server=SERVER,
        port=PORT,
        user=USER,
        password=PASSWORD,
        keepalive=keepalive)  # 必须要 keepalive=30 ,否则连接不上
    # 设置消息回调
    c.set_callback(sub_cb)
    # 设置遗嘱消息
    c.set_last_will(
        topic='set_last_will',
        msg='set_last_will',
        retain=False,
        qos=1)
    # 建立连接
    c.connect()
    # 订阅主题
    c.subscribe(SUB_TOPIC.format(IMEI))
    # 发布消息
    c.publish(PUB_TOPIC.format(IMEI), "test publish 你好")

    # 关闭连接
    # c.disconnect()

def GetDevImei():
    global IMEI
    IMEI = modem.getDevImei()
    print(IMEI)


def main():
    global SUB_TOPIC
    global PUB_TOPIC
    SUB_TOPIC = '{}'
    PUB_TOPIC = SUB_TOPIC
    try:
        stagecode, subcode = checkNet.wait_network_connected(30)
        print('stagecode = {}, subcode = {}'.format(stagecode, subcode))
    except BaseException:
        print('Not Net, Resatrting...')
        utime.sleep_ms(200)
        Power.powerRestart()
    GetDevImei()
    # MQTT_Init(b'uMQTT', b'www.chic.xn--6qq986b3xl', 6000, None, None, keepalive=50)
    MQTT_Init(b'uMQTT', b'120.197.216.227', 6000, None, None, keepalive=50)
    _thread.start_new_thread(MQTT_PUB, ())
    _thread.start_new_thread(wait_msg, ())


if __name__ == '__main__':
    main()
