induction_post.py 29.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
# codinf:utf-8
from app import app
import json
import time
import timeit
import os
import requests
import threading
import re
import csv
from app.scan_collection import production_filter
from app.utils.serial_communication import SerialCommunication
from app.utils.location import Location
from config import Config
from app.induction_test import indresetled,read_test_scan
from app.induction_config import read_state,ip_config,confirm_state,get_towerstate,read_addrs

import logging


detail_dict = {}
serverHasReelPosList = []
outTaskInfo = {}
COLORS = Config.COLORS
autostate = {'state':'wait'}

ser=None
#------------------------------------------------------------
# 自动通信

@app.route('/startpost',methods=['POST'])
def startpost():
    global is_start
    global ser
    global tower_state
    test_state = read_test_scan()
    if not test_state:
        state = read_state()
        if state == 'off':
            load_location()
            # location_config_init()
            # init_msg = origin_location_init()
            # if init_msg == 'success':
            confirm_state('on')
            is_start = True
            ser = SerialCommunication()
            reset_tower()
            tower_state = get_towerstate()            
            threads = []
            threads.append(threading.Thread(target=serverboard))
            threads.append(threading.Thread(target=show_blink))
            #threads.append(threading.Thread(target=show_tower))
            
            for t in threads:
                t.start()
            msg = '启动成功'
            current_state = 'on'
            logging.warning("启动成功")
            
            # else:
            #     current_state = 'off'
            #     msg = '构建库位原始数据表失败/与服务器通信失败'
            #     logging.warning(msg)
        else:
            msg = '正在运行状态'
            current_state = 'on'
            logging.warning("料架运行中无需重复启动")
    else:
        current_state = 'off'
        msg = '测试模式扫描中,请先关闭测试模式'
        logging.warning(msg)
    info = []
    c_dict = {'state':current_state,'msg':msg}
    info.append(c_dict)
    return json.dumps(info)

@app.route('/getauto',methods=['POST'])
def get_auto_state():
    global autostate
    # print (autostate)
    return json.dumps({'msg':autostate['state']})


@app.route('/stoppost',methods=['POST'])
def stoppost():
    global is_start
    # global autostate
    state = read_state()
    if state == 'on':
        confirm_state('off')
        indresetled()
        reset_tower()
        is_start=False
        # status_light('off')
        ip_config['post'] = 'wait'
        logging.warning("关闭成功")
        msg = '关闭成功'
        current_state = 'off'
    else:
        msg = '无需关闭'
        current_state = 'off'
        logging.warning("无需关闭")
    info = []
    c_dict = {'state':current_state,'msg':msg}
    info.append(c_dict)
    return json.dumps(info)

def load_location():
    global locations
    global convert_dict
    global config_dict
    location_cof = Location()
    config_dict,convert_dict = location_cof.read_location_file()
    locations = location_cof.production_location_init()

#从服务器定时获取有料的库位列表
def updateServerHasReelPosList():
    global serverHasReelPosList
    global outTaskInfo
    url = ip_config['ip'] + '/service/store/sensorShelf/shelfStatus'
    data = {"cid":ip_config['cid']}
    try:
        response = requests.get(url, params=data,timeout=2)
        in_location = response.json()
        
        serverHasReelPosList = []
        outTaskInfo = {}
        if in_location['code'] == 0:
            serverHasReelPosList = in_location['data']["hasReelPosList"]
            outTaskList = in_location['data']["outTaskList"]
            for outTask in outTaskList:
                posInfo=outTask.split("=")
                pos = posInfo[0]
                color = posInfo[1].lower()
                outTaskInfo[pos] = color
                logging.warning("{} out task:{}   ----- {}".format(outTask,pos,color))
    except Exception as e:
        logging.warning("从服务器获取有料的库位列表失败:{}".format(e))
        
# 构建库位原始数据表/更新当前有库存的库位状态
def origin_location_init():
    global locations
    global detail_dict
    global is_start
    url = ip_config['ip'] + '/service/store/sensorShelf/hasReelPosList'
    data = {"cid":ip_config['cid']}
    init_msg = ''
    try:
        # dataaddrs = read_addrs()
        # addrs=dataaddrs.split('@')
        # for line_addr in addrs:
        #     detail_dict[line_addr] = ['0'] * 100
        response = requests.get(url, params=data,timeout=2)
        in_location = response.json()
        # print ('-----------locations',in_location['data'])
        if in_location['code'] == 0:
            dataaddrs = read_addrs()
            addrs=dataaddrs.split('@')
            for line_addr in addrs:
                detail_dict[line_addr] = ['0'] * 100
            for locnum in in_location['data']:
                if locations.get(locnum,''):
                    # loctions[locnum]['sensor_state'] = '1'
                    # locations[locnum]['color'] = 'orange'
                    locations[locnum]['action'] = False
                    if detail_dict.get(locations[locnum]['addr'],''):
                        sensor_index = locations[locnum]['sensor_index'] - 1
                        detail_dict[locations[locnum]['addr']][sensor_index] = '1'
                    else:
                        logging.warning('灯条地址未配置该地址号:{}'.format(locations[locnum]['addr']))
                else:
                    logging.warning('库位配置表未查询到该库位号:{}'.format(locnum))
            init_msg = 'success'
        # print ('-----------detail_dict',detail_dict)
    except Exception as e:
        init_msg = 'failed'
        logging.warning("构建库位原始数据表/更新当前有库存的库位状态失败:{}".format(e))
    return init_msg



# 串口通信
def serverboard():
    global is_start
    global detail_dict
    global autostate
    # serial_cf = ReadConfig()
    command = ""
    # addrs = serial_cf.get_serial("addrs")
    # addrs = addrs.split('@')
    dataaddrs = read_addrs()
    addrs=dataaddrs.split('@')
    for addr in addrs:
        command +=addr + '\n'
    seq = 1
    ser=SerialCommunication();
    while is_start:
        if detail_dict:
            # print ('detai-dict-----------------',detail_dict)
            start = timeit.default_timer()
            server_post(seq)
            ser.send_data(command)
            location_status=ser.read_alldata()
           # print (location_status)
            cur_dict = production_filter(location_status)
            updateServerHasReelPosList()
            in_loc,out_loc = compare_detail(cur_dict)
            send_loc_server(in_loc,out_loc)
            end = timeit.default_timer()
            print (str(end-start))
            # logging.warning("scan运行中---------")
            seq += 1
            time.sleep(0.6)
            autostate['state'] = 'success'
        else:
            origin_location_init()
            updateServerHasReelPosList()
            time.sleep(0.6)
            autostate['state'] = 'failed'
            # logging.warning("检测服务器状态中....")
    autostate['state'] = 'wait'
    detail_dict = {}

def server_post(seq):
    headers = {'content-type': "application/json"} #请求头信息
    url = ip_config['ip'] + '/service/store/communication'
    cid = ip_config['cid']
    body = {"boxStatus":{"1":{"boxId":1,"status":1,"msg":None,"temperature":None,"humidity":None,"data":{}}},"alarmList":[],"cid":cid,"seq":seq,"op":0,"data":{},"status":1,"msg":None}
    try:
        response = requests.post(url, data = json.dumps(body),headers = headers,timeout=2)
        # response = requests.post("http://jsonplaceholder.typicode.com/posts", data = "some dummy content")
        ele_json = response.json()
        print ('ele_json:{}'.format(ele_json))
        ip_config['post'] = 'success'
        resolve_data(ele_json)
        if ele_json['data']:
            logging.warning("服务器发送数据:{}".format(ele_json['data']))
    except Exception as e:
        ip_config['post'] = 'failed'
        logging.warning("请求服务器失败:{}".format(e))

# 解析服务器接收数据
def resolve_data(datajson):
    operation=datajson['data']
    global locations
    # operation = {'open':'1_1_1=red|1_1_2=blue|1_1_3=red|2_1_1=green'}
    if operation:
        if 'open' in operation.keys():
            openstock=operation['open'].split("|")
            for stock in openstock:
                single=stock.split("=")
                if locations.get(single[0]):
                    #print (single[1].lower())
                    locations[single[0]]['color'] = single[1].lower()
                    locations[single[0]]['action'] = True
                else:
                    logging.warning("未找到库位配置:{}".format(single[0]))
            logging.warning("库位灯有open指令")
        if 'close' in operation.keys():
            offstock = operation['close'].split("|")
            for stock in offstock:
                single = stock.split("=")
                if config_dict.get(single[0]):
                    locations[single[0]]['color'] = 'off'
                    locations[single[0]]['action'] = True
                    single.append('off')
                    logging.warning("close{}".format(single[0]))
                    # guide_leds.append(single)
                else:
                    logging.warning("未找到库位配置:{}".format(config_dict.get(single[0])))
            logging.warning("库位灯有关闭指令")
        if 'closeAll' in operation.keys():
            # deal_alloff()
            logging.warning("所有库位灯关闭")
    return True

def compare_detail(cur_dict):
    global detail_dict
    global locations
    
    global serverHasReelPosList
    global outTaskInfo
    in_loc = []
    out_loc = []
    for addr,cursensors in cur_dict.items():
        if len(cursensors) == 100:
            if detail_dict.get(addr,''):
                old_sensors=detail_dict[addr]
                for i,oldsensor in enumerate(old_sensors):
                    # sensorindex = str(i+1) + addr
                    sensorindex = "{}@{}".format(str(i+1),addr)
                    if convert_dict.get(sensorindex,''):
                        led_add_loc = convert_dict[sensorindex]
                        # led_index = int(led_add_loc.split('@')[0])
                        locnumber = led_add_loc.split('@')[2] 
                        #与服务器有库位进行比对
                        if locnumber in serverHasReelPosList:
                            #服务器该库位有数据
                            if cursensors[i] == '1':
                                #库位有料,与服务器一致
                                if locations[locnumber]['in_blink'] or locations[locnumber]['out_blink']:
                                    #正在闪烁的不处理
                                    logging.debug("{} blink no opetion ".format(locnumber))
                                else:
                                    #有料,且与服务器一致,改灯颜色为orange
                                    posColor = outTaskInfo.get(locnumber,'orange')
                                    logging.info("location:{}, old color:{}, new color:{}".format(locnumber,locations[locnumber]['color'],posColor))
                                    if not locations[locnumber]['color'] == posColor:
                                        locations[locnumber]['outloc_ng'] = False
                                        locations[locnumber]['inloc_ng'] = False
                                        locations[locnumber]['color'] = posColor
                                        locations[locnumber]['action'] = True
                            if cursensors[i] == '0':
                                #库位无料,与服务器不一致
                                if locations[locnumber]['in_blink'] or locations[locnumber]['out_blink']:
                                    #正在闪烁的不处理
                                    logging.debug("{} blink no opetion ".format(locnumber))
                                elif locations[locnumber]['outloc_ng']:
                                    #已经NG的,亮红灯
                                    #locations[locnumber]['color'] = 'red'
                                    #locations[locnumber]['action'] = True
                                    logging.debug("{} outloc_ng to red ".format(locnumber))
                                else:
                                    #没处理过,需要发送到服务器
                                    out_loc.append(locnumber)
                        else:
                            #服务器该库位无料
                            if cursensors[i] == '1':
                                #库位有料,与服务器不一致
                                if locations[locnumber]['in_blink'] or locations[locnumber]['out_blink']:
                                    #正在闪烁的不处理
                                    logging.debug("{} out blink no opetion ".format(locnumber))
                                elif locations[locnumber]['inloc_ng']:
                                    #已经NG的,亮红灯
                                    #locations[locnumber]['color'] = 'red'
                                    #locations[locnumber]['action'] = True
                                    logging.debug("{} inloc_ng to red ".format(locnumber))
                                else: 
                                    #没处理过,需要发送到服务器
                                    in_loc.append(locnumber)
                            if cursensors[i] == '0':
                                #库位无料,且与服务器一致
                                if locations[locnumber]['in_blink'] or locations[locnumber]['out_blink']:
                                    #正在闪烁的不处理
                                    logging.debug("{} blink no opetion ".format(locnumber))
                                else: 
                                    #库位无料,且与服务器一致,关灯
                                    if not locations[locnumber]['color'] == 'off':
                                        locations[locnumber]['outloc_ng'] = False
                                        locations[locnumber]['inloc_ng'] = False
                                        locations[locnumber]['color'] = 'off'
                                        locations[locnumber]['action'] = True
            detail_dict[addr] = cursensors
    # print ('--------------------in_lock',in_loc)
    # print ('--------------------out_loc',out_loc)
    real_in_loc,real_out_lock=filter_ng(in_loc,out_loc)
    # if cur_dict:
    #     detail_dict = cur_dict
    return real_in_loc,real_out_lock
# 检查并清除入库/出库ng
def filter_ng(in_loc,out_loc):
    global locations
    for loc in in_loc[::-1]:
        if locations[loc]['outloc_ng']:
            locations[loc]['outloc_ng'] = False
            locations[loc]['color'] = 'orange'
            locations[loc]['action'] = True
            in_loc.remove(loc)
            logging.warning('出库ng恢复:{}'.format(loc))
    for out in out_loc[::-1]:
        if locations[out]['inloc_ng']:
            locations[out]['inloc_ng'] = False
            locations[out]['color'] = 'off'
            locations[out]['action'] = True
            out_loc.remove(out)
            logging.warning('入库ng恢复:{}'.format(out))
    return in_loc,out_loc


# 发送入库/出库库位到服务器
def send_loc_server(in_loc,out_loc):
    # http://ip/smdbox/service/store/sensorShelf/sensorChange
    # global current_on
    # print ('--------------------origin_in_loc',in_loc)
    # print ('--------------------origin_out_loc',out_loc)
    global locations
    in_ng_loc = []
    out_ng_loc = []
    for locnum, locvalue in locations.items():
        if locvalue['inloc_ng']:
            in_ng_loc.append(locnum)
        if locvalue['outloc_ng']:
            out_ng_loc.append(locnum)

    headers = {'content-type': "application/x-www-form-urlencoded"}
    url = ip_config['ip'] + '/service/store/sensorShelf/sensorChange'
    data = {"cid":ip_config['cid'],"hasReelPosList":in_loc,"hasReelPosErrorList": in_ng_loc,"noReelPosList":out_loc,"noReelPosErrorList":out_ng_loc}
    try:
        response = requests.post(url, data=data,headers= headers,timeout=2)
        rec_data = response.json()
        print(rec_data)
        if rec_data['code'] == 0:
            in_ok = rec_data['data']["inOkList"]
            out_ok = rec_data['data']["outOkList"]
            in_ng = rec_data['data']["inNgList"]
            out_ng = rec_data['data']["outNgList"]
            ng_to_ok = rec_data['data']["ngToOk"]
            update_to_location(in_ng,flag=0)
            update_to_location(out_ng,flag=4)
            update_to_location(in_ok,flag=1)
            update_to_location(out_ok,flag=2)
            update_to_location(ng_to_ok,flag=5)
            # show_response(in_leds,out_leds,ng_leds)
            # print ('--------------------in_ok',in_ok)
            # print ('--------------------out_ok',out_ok)
            # print ('--------------------in_ng',in_ng)
            # print ('--------------------out_ng',out_ng)
    except Exception as e:
        logging.warning("send_loc_server error:{}".format(e))

# 根据服务器返回出入库OK/NG更新库位状态
def update_to_location(locdata,flag):
    global locations
    if flag == 0:
        for loc in locdata:
            locations[loc]['inloc_ng'] = True
            locations[loc]['color'] = 'red'
            locations[loc]['action'] = True
            logging.warning('入库ng库位,亮红色灯:{}'.format(loc))
    elif flag == 1:
        for loc in locdata:
            locations[loc]['blink_num'] = 6
            locations[loc]['in_blink'] = True
            locations[loc]['color'] = 'green'
            locations[loc]['action'] = True
            logging.warning('入库中,绿灯闪烁3秒后转为橘色:{}'.format(loc))
    elif flag == 2:
        for loc in locdata:
            locations[loc]['blink_num'] = 6
            locations[loc]['out_blink'] = True
            locations[loc]['color'] = 'yellow'
            locations[loc]['action'] = True
            logging.warning('出库中,黄灯闪烁3秒后关闭:{}'.format(loc))
    if flag == 4:
        for loc in locdata:
            locations[loc]['outloc_ng'] = True
            locations[loc]['color'] = 'red'
            locations[loc]['action'] = True
            logging.warning('出库ng库位,亮红色灯:{}'.format(loc))
    if flag == 5:
        for loc in locdata:
            if locations[loc]['outloc_ng']:
                locations[loc]['outloc_ng'] = False
                locations[loc]['color'] = 'off'
                locations[loc]['action'] = True
                logging.warning('ng库位恢复:{}'.format(loc))


# thread control led
def show_blink():
    global locations
    blink_leds = {}
    while is_start:
        blink_status = {'side':'both','status':False}
        ng_status = {'side':'both','status':False}
        blink_leds = {}
        for locnum,locvalue in locations.items():
            action_value = check_pre(locvalue)
            locside='both'
            if 'locside' in locvalue:
                locside = locvalue['locside']
            # print ('--------------action_value',action_value)
            if locvalue['in_blink'] or locvalue['out_blink']:
                blink_status['side'] = locside
                blink_status['status'] = True
            if locvalue['inloc_ng'] or locvalue['outloc_ng']:
                ng_status['side'] = locside
                ng_status['status'] = True
            addr = locvalue['addr']
            color = locvalue['color']
            led_index = locvalue['led_index']
            if action_value['c_state']:
                if action_value['c_act'] == 'in_blink_light':
                    update_locations(blink_leds,addr,color,led_index)
                    locations[locnum]['color'] = 'off'
                    locations[locnum]['blink_num'] = locvalue['blink_num'] - 1
                elif action_value['c_act'] == 'in_blink_off':
                    update_locations(blink_leds,addr,color,led_index)
                    if locvalue['blink_num'] == 1:
                        locations[locnum]['color'] = 'orange'
                        locations[locnum]['blink_num'] = locvalue['blink_num'] - 1
                    else:
                        locations[locnum]['color'] = 'green'
                        locations[locnum]['blink_num'] = locvalue['blink_num'] - 1
                elif action_value['c_act'] == 'in_blink_end':
                    update_locations(blink_leds,addr,color,led_index)
                    locations[locnum]['action'] = False
                    locations[locnum]['in_blink'] = False
                    # locations[locnum]['blink_num'] = locvalue['blink_num'] - 1
                elif action_value['c_act'] == 'out_blink_light':
                    update_locations(blink_leds,addr,color,led_index)
                    locations[locnum]['color'] = 'off'
                    locations[locnum]['blink_num'] = locvalue['blink_num'] - 1
                elif action_value['c_act'] == 'out_blink_off':
                    update_locations(blink_leds,addr,color,led_index)
                    if locvalue['blink_num'] == 1:
                        locations[locnum]['color'] = 'off'
                        locations[locnum]['blink_num'] = locvalue['blink_num'] - 1
                    else:
                        locations[locnum]['color'] = 'yellow'
                        locations[locnum]['blink_num'] = locvalue['blink_num'] - 1
                elif action_value['c_act'] == 'out_blink_end':
                    locations[locnum]['action'] = False
                    locations[locnum]['out_blink'] = False
                else:
                    update_locations(blink_leds,addr,color,led_index)
                    locations[locnum]['action'] = False
        blink_convert(blink_leds)
        update_tower(blink_status,ng_status)
        time.sleep(0.5)

def check_pre(locvalue):
    if locvalue['action']:
        if locvalue['in_blink']:
            if (locvalue['blink_num']%2) ==0 and locvalue['blink_num']>0:
                # return 'in_blink_light'
                check_value = {'c_state':True,'c_act':'in_blink_light'}
            elif (locvalue['blink_num']%2) !=0 and locvalue['blink_num']>0:
                # check_value = 'in_blink_off'
                check_value = {'c_state':True,'c_act':'in_blink_off'}
            elif locvalue['blink_num'] == 0:
                # check_value = 'in_blink_end'
                check_value = {'c_state':True,'c_act':'in_blink_end'}
        elif locvalue['out_blink']:
            if (locvalue['blink_num']%2) ==0 and locvalue['blink_num']>0:
                # check_value = 'out_blink_light'
                check_value = {'c_state':True,'c_act':'out_blink_light'}
            elif (locvalue['blink_num']%2) !=0 and locvalue['blink_num']>0:
                check_value = {'c_state':True,'c_act':'out_blink_off'}
                # check_value = 'out_blink_off'
            elif locvalue['blink_num'] == 0:
                check_value = {'c_state':True,'c_act':'out_blink_end'}
                # check_value = 'out_blink_end'
        else:
            check_value = 'normal'
            check_value = {'c_state':True,'c_act':'normal'}
    else:
        check_value = {'c_state':False,'c_act':'no_action'}
    return check_value

def update_locations(blink_leds,addr,color,led_index):
    if blink_leds.get(addr,''):
        if blink_leds[addr].get(color,''):
            blink_leds[addr][color].append(led_index)
        else:
            blink_leds[addr][color] = [led_index]
    else:
        blink_leds[addr] = {color:[led_index]}
    return blink_leds


def blink_convert(blink_leds):
    ser=SerialCommunication();
    print ('blink_leds:{}'.format(blink_leds))
    if blink_leds:
        # texts = ""
        texts = []
        for addr,blink_led in blink_leds.items():
            color_arry = []
            addr = addr.split("A")[1]
            for color,leds in blink_led.items():
                leds.insert(0,COLORS.get(color,[15,255,255,255])[0])
                color_arry.append(leds)
            command = {"ADDR":addr,"color":color_arry}
            command = str(json.dumps(command)).replace(" ","") #去除指令中的空格
            # texts += command + '\n'
            texts.append(command + '\n')
            # texts += str(json.dumps(command)) + '\n'
        #logging.warning(texts)
        # print ('-------------------------------------texts',len(texts.encode()))
        # 分地址发送
        if texts:
            for line in texts:
                ser.send_data(line)
                print(line)
                time.sleep(0.1)
    # return texts

#控制状态灯 
def show_tower():
    ser=SerialCommunication();
    global tower_state
    time.sleep(1)
    while is_start:
        lightons = []
        lightoffs = []
        for tower,state in tower_state.items():
            if state['action']:
                towers = [int(i) for i in tower.split('@')]
                if state['status'] == 'on':
                    lightons.extend(towers)
                    logging.warning('--------------状态灯{}打开'.format(towers))
                    # tower_state[tower]['status'] = ''
                else:
                    #关闭该状态灯
                    logging.warning('--------------状态灯{}关闭'.format(towers))
                    lightoffs.extend(towers)
                tower_state[tower]['action'] = False
        if lightons or lightoffs:
            command_dicts = {"ADDR":"0","lighton":lightons,"lightoff":lightoffs}
            maincommand = str(json.dumps(command_dicts)) + '\n'
            # print ('------------------maincommand',maincommand)
            ser.send_data(maincommand)
        time.sleep(0.5)


def send_tower_status_light():
    global tower_state
    lightons = []
    lightoffs = []
    for tower,state in tower_state.items():
        if state['action']:
            towers = [int(i) for i in tower.split('@')]
            if state['status'] == 'on':
                lightons.extend(towers)
                logging.warning('--------------status light {} open'.format(towers))
                # tower_state[tower]['status'] = ''
            else:
                #关闭该状态灯
                logging.warning('--------------status light {} close'.format(towers))
                lightoffs.extend(towers)
            tower_state[tower]['action'] = False
    if lightons or lightoffs:
        command_dicts = {"ADDR":"0","lighton":lightons,"lightoff":lightoffs}
        maincommand = str(json.dumps(command_dicts)) + '\n'
        # print ('------------------maincommand',maincommand)
        ser.send_data(maincommand)
#1@4 红色
#2@5 绿色
#3@6 黄色
RedTWLed = '1@4'
YellowTWLed = '2@5'
GreenTWLed = '3@6'
def update_tower(blink_status,ng_status):
    global tower_state
    #print (blinks,ngs)
    thisYellowTWLed = YellowTWLed
    if blink_status['side'].lower()=='a':
        thisYellowTWLed=YellowTWLed.partition('@')[0]
    elif blink_status['side'].lower()=='b':
        thisYellowTWLed=YellowTWLed.partition('@')[0]

    if blink_status['status']:
        if tower_state[thisYellowTWLed]['status'] == 'off':
            tower_state[thisYellowTWLed]['action'] = True
            tower_state[thisYellowTWLed]['status'] = 'on'
        else:
            tower_state[thisYellowTWLed]['action'] = True
            tower_state[thisYellowTWLed]['status'] = 'off'
    else:
        if tower_state[thisYellowTWLed]['status'] == 'on':
            tower_state[thisYellowTWLed]['action'] = True
            tower_state[thisYellowTWLed]['status'] = 'off'

    thisRedTWLed = RedTWLed
    if ng_status['side'].lower()=='a':
        thisRedTWLed=RedTWLed.partition('@')[0]
    elif ng_status['side'].lower()=='b':
        thisRedTWLed=RedTWLed.partition('@')[2]
    if ng_status['status']:
        if tower_state[thisRedTWLed]['status'] == 'off':
            tower_state[thisRedTWLed]['action'] = True
            tower_state[thisRedTWLed]['status'] = 'on'
        else:
            tower_state[thisRedTWLed]['action'] = True
            tower_state[thisRedTWLed]['status'] = 'off'
    else:
        if tower_state[thisRedTWLed]['status'] == 'on':
            tower_state[thisRedTWLed]['action'] = True
            tower_state[thisRedTWLed]['status'] = 'off'
    # print ('---------------------------------tower_state',tower_state)
    send_tower_status_light()

def reset_tower():
    ser=SerialCommunication();
    command_dicts = {"ADDR":"0","lightoff":[1,2,3,4,5,6]}
    maincommand = str(json.dumps(command_dicts)) + '\n'
    print (maincommand)
    ser.send_data(maincommand)


# 开机启动
def auto_start():
    state = read_state()
    if state == 'on':
        confirm_state('off')
    time.sleep(2)
    logging.warning("11111111111")
    startpost()

#auto_start()
# 开机启动请求服务器动作
# state = read_state()
# is_start = True
# threads = []
# threads.append(threading.Thread(target=serverpost))
# threads.append(threading.Thread(target=serverboard))
# for t in threads:
#     t.start()
# logging.warning("启动成功")