예제 #1
0
    def start_single(cls, client_id, order, circle, _time):
        print_db(f'start: {client_id}, circle: {circle}, time: {_time}')

        if circle:  # 大于0,计圈
            # 保持 client_id 记录
            cls._all_cars[client_id] = CarInfo(client_id, order, circle,
                                               cls._sql_str,
                                               cls._send_mqtt_cmd_func)

            # 计数器清零,等测试(或放在开车时)
            cls._send_mqtt_cmd_func(
                f'{settings.TOPIC_ROOT_H}{client_id}/{settings.TP_DRVO}',
                '6,1000,1')  # 计数器清零
            # 一直通电
            return cls._send_mqtt_cmd_func(
                f'{settings.TOPIC_ROOT_H}{client_id}/{settings.TP_RELAY}',
                f's,-1,{circle}')

        elif _time:  # 计时
            return cls._send_mqtt_cmd_func(
                f'{settings.TOPIC_ROOT_H}{client_id}/{settings.TP_RELAY}',
                f's,{_time},0')
        else:  # 都为0,强制停车
            cls.force_stop(client_id)
            return cls._send_mqtt_cmd_func(
                f'{settings.TOPIC_ROOT_H}{client_id}/{settings.TP_RELAY}',
                f's,0,0')
예제 #2
0
def mqtt2():
    # noinspection PyBroadException
    try:
        form = SendCommandField()
        if request.method == 'GET':
            return render_template('mqtt2.html', form=form)
    except Exception as err:
        log_err(err)
        return err.__str__()

    res = ''
    if form.validate_on_submit():
        cmd_type = request.form.get('cmd_type')
        client_id = request.form.get('client_id')
        func = request.form.get('func')
        payload = request.form.get('payload')
        no_check = request.form.get('no_check')
        password = request.form.get('password')

        print_db('cmd_type:', cmd_type, 'client_id:', client_id, 'func:', func,
                 'payload:', payload, 'no_check:', no_check, 'password:'******'success' if wait_for_publish(mid) else 'timeout'
        else:
            res = err.__str__()
    else:
        res = "参数有误或者不完整"

    print_db('res:', res)
    # return render_template('mqtt2.html', string=res)
    return res
예제 #3
0
def mqtt():
    # noinspection PyBroadException
    try:
        cmd_type = request.form.get('cmd_type')
        client_id = request.form.get('client_id')
        func = request.form.get('func')
        payload = request.form.get('payload')
        no_check = request.form.get('no_check')
        password = request.form.get('password')

        if password != get_md5_hex(
            [cmd_type, client_id, func, payload, no_check]):
            return 'password error'

        print(password)
        can_send, mid, err = on_http_post(cmd_type, client_id, func, payload,
                                          no_check)
        if can_send:
            res = 'success' if wait_for_publish(mid) else 'timeout'
        else:
            log_err(err)
            res = err

        print_db('res:', res)
    except Exception as err:
        log_err(err)
        res = err
    return res if res else 'unknown error'
예제 #4
0
def on_http_post(cmd_type, client_id, func, payload, no_check) -> (bool, list, str):
    log_info(f'ct:{cmd_type}, cid:{client_id}, func:{func}, pl:{payload}, nc:{no_check}')
    if settings.VERSION == 1.0:
        settings.CLIENT_IDS.add(client_id)
        print_db(settings.CLIENT_IDS)

    ft = HTTP_FUNC_TYPE.get(cmd_type)
    if ft:
        return ft[0](client_id, func, payload, no_check) if cmd_type == 'through' else ft[0](client_id, payload)
    return False, -1, 'cmd_type 不可用'
예제 #5
0
def http_func_car_single(client_id, payload) -> (bool, list, str):
    # noinspection PyBroadException
    try:
        info = json.loads(payload)
        order, circle, _time = info.get("order", None), info.get("circle", None), info.get("time", None)
        if not order or not (circle or _time):
            return False, -1, '参数不正确'
        if not order.isnumeric() or circle and not circle.isnumeric() or _time and not _time.isnumeric():
            print_db(f"order:{order} {order.isnumeric()}, circle:{circle} {circle.isnumeric()}")
            return False, -1, '订单号或圈数或时间错误'
        return True, kd_car_mgr.start_single(client_id, order, int(circle), _time), ''
    except Exception as err:
        return False, -1, err
예제 #6
0
def on_publish(client, userdata, mid):
    print_db("on_publish: mid:" + str(mid))
    dict_on_publish[mid] = 1
예제 #7
0
def main():

    # 未激活不可使用
    if not is_active(settings.ACTIVATE_CODE_FILE):
        return
    print('Activate success!')

    # ------------------- 从文件读取配置 -------------------
    if not init_from_json(settings.ENABLE_INIT_PARAMS):
        init_from_ini(settings.ENABLE_INIT_PARAMS)

    argv = sys.argv[1:]
    # ------------------- 从命令行读取配置 -------------------
    try:
        opts, args = getopt.getopt(argv, "d:p:a:m:j:")
    except getopt.GetoptError:
        opts = []
        pass

    for opt, arg in opts:
        # 设置本应用的 DEV_ID, PRO_ID, AUTH_INFO, (SERVER_IP = '183.230.40.39', SERVER_PORT = 6002)
        if opt == '-d':
            settings.DEV_ID = arg
        elif opt == '-p':
            settings.PRO_ID = arg
        elif opt == '-a':
            settings.AUTH_INFO = arg
        # 设置数据库  'root:[email protected]:3306/tz_game?charset=utf8'
        elif opt == '-m':
            settings.Config.SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://' + arg
        # 设置Java服务器通讯地址  'http://127.0.0.1:8000/mqtt'
        elif opt == '-j':
            settings.JAVA_IP = arg

    # 不提供默认DIV_ID,设置好了才能使用
    if settings.DEV_ID == '' or settings.PRO_ID == '' or settings.AUTH_INFO == '':
        tips_only('《config.json》中必须设置“唯一的”\n DEV_ID:\n PRO_ID:\n AUTH_INFO:\n 三项,且不能与其他系统共用\n否则将造成连接异常', '配置提示')
        return

    # 加载,要放到配置之后
    from app import app
    from my_mqtt.mqtt_func import mqtt_init, mqtt_set_id_group

    # ------------------- 再从本地文档、数据库表 'tz_zry_car_relay' 读取 设备ID -------------------
    settings.CLIENT_IDS = settings.get_client_ids_from_database(settings.CLIENT_IDS)
    try:
        with open(settings.OUTSIDE_CONFIG_CLIENT_IDS) as f:
            ls = f.read().split(sep=',')
            for cid in ls:
                settings.CLIENT_IDS.add(cid.strip())
                print(f'Adding cid: {cid}')
            print(f'get {len(settings.CLIENT_IDS)} client_ids')
    except Exception:
        pass

    # Todo: 加载设备ID组
    # 先把Version1.0 的数据合并过来
    for cid in settings.CLIENT_IDS:
        settings.CLIENT_IDS_DICT[cid] = settings.DevType.DT_CAR.value
    # 再把Version1.1 加进来
    try:
        with open(settings.OUTSIDE_CONFIG_CLIENT_IDS_GROUP) as f:
            groups = f.read().split(sep='&')
            for group in groups:
                try:
                    group_type, ids_in_group = group.split('=')
                    group_type = int(group_type)
                    settings.CLIENT_IDS_GROUP.setdefault(group_type, [])
                    ls = [x.strip() for x in ids_in_group.split(',')]
                    for cid in ls:
                        settings.CLIENT_IDS_GROUP[group_type].append(cid)
                    print_db(f'get {group_type} : {settings.CLIENT_IDS_GROUP[group_type]}')
                except IndexError or ValueError or Exception as err:
                    log_err(f'init client_id error: {group} ==> {err.__str__()}')
                    continue

    except Exception:
        pass
    print('mqtt_main.py: ', settings.CLIENT_IDS_DICT)
    settings.update_client_ids_dict()
    print('mqtt_main.py: ', settings.CLIENT_IDS_DICT)
    pass

    # ------------------- 正式启动 -------------------
    client = mqtt_init(cid=settings.DEV_ID, username=settings.PRO_ID, pwd=settings.AUTH_INFO)
    print('connect finish!')
    # ------------------- 启动后才能设置设备功能 -------------------
    for cid, _type in settings.CLIENT_IDS_DICT.items():
        mqtt_set_id_group(cid, _type)
        time.sleep(0.02)
    log_info('启动成功')

    # ------------------- 隐藏窗口 -------------------
    whnd = ctypes.windll.kernel32.GetConsoleWindow()
    if whnd != 0:
        ctypes.windll.user32.ShowWindow(whnd, 0)
        ctypes.windll.kernel32.CloseHandle(whnd)

    app.run(host=settings.HTTP_HOST, port=settings.HTTP_PORT)

    print('run finish')
예제 #8
0
 def update(cls):
     while True:
         time.sleep(0.01)
         if not cls._sql_str.empty():
             print_db('want to update sql')
             db_car.update(*cls._sql_str.get())