Commit e1d50aec 刘韬

1

1 个父辈 8b38abfa
......@@ -10,22 +10,23 @@ import re
import csv
from app.scan_collection import production_filter
from app.utils.g import shelfconfig
import app.utils.g as gg
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
from app.induction_config import ip_config,get_towerstate,read_addrs
from flask_babel import gettext
import datetime
import logging
import traceback
detail_dict = {}
serverHasReelPosList = []
outTaskInfo = {}
COLORS = Config.COLORS
autostate = {'state':'wait'}
ServerErrorTimes=0
ser=None
#------------------------------------------------------------
# 自动通信
......@@ -37,18 +38,20 @@ def startpost():
global tower_state
test_state = read_test_scan()
if not test_state:
state = read_state()
if state == 'off':
if gg.current_state == 'off':
load_location()
# location_config_init()
# init_msg = origin_location_init()
# if init_msg == 'success':
confirm_state('on')
gg.current_state='on'
is_start = True
ser = SerialCommunication()
logging.warning("启动复位参数 comport_carsh_reboot:{}".format(shelfconfig.comport_carsh_reboot))
if not shelfconfig.comport_carsh_reboot:
reset_tower()
tower_state = get_towerstate()
indresetled()
logging.warning("复位灯塔,和料架灯")
tower_state = get_towerstate()
threads = []
threads.append(threading.Thread(target=serverboard))
threads.append(threading.Thread(target=show_blink))
......@@ -57,23 +60,24 @@ def startpost():
for t in threads:
t.start()
msg = gettext('启动成功')
current_state = 'on'
gg.current_state = 'on'
logging.warning("启动成功")
shelfconfig.comport_carsh_reboot=False
shelfconfig.Save()
# else:
# current_state = 'off'
# msg = '构建库位原始数据表失败/与服务器通信失败'
# logging.warning(msg)
else:
msg = '正在运行状态'
current_state = 'on'
gg.current_state = 'on'
logging.warning("料架运行中无需重复启动")
else:
current_state = 'off'
gg.current_state = 'off'
msg = '测试模式扫描中,请先关闭测试模式'
logging.warning(msg)
info = []
c_dict = {'state':current_state,'msg':msg}
c_dict = {'state':gg.current_state,'msg':msg}
info.append(c_dict)
return json.dumps(info)
......@@ -87,24 +91,24 @@ def get_auto_state():
@app.route('/stoppost',methods=['POST'])
def stoppost():
global is_start
# global autostate
state = read_state()
if state == 'on':
confirm_state('off')
if gg.current_state == 'on':
gg.current_state='off'
if not shelfconfig.comport_carsh_reboot:
indresetled()
reset_tower()
logging.warning("复位灯塔,和料架灯")
is_start=False
# status_light('off')
ip_config['post'] = 'wait'
logging.warning("关闭成功")
msg = gettext('关闭成功')
current_state = 'off'
gg.current_state = 'off'
else:
msg = gettext('无需关闭')
current_state = 'off'
gg.current_state = 'off'
logging.warning("无需关闭")
info = []
c_dict = {'state':current_state,'msg':msg}
c_dict = {'state':gg.current_state,'msg':msg}
info.append(c_dict)
return json.dumps(info)
......@@ -117,11 +121,15 @@ def load_location():
locations = location_cof.production_location_init()
lastupdatetime=datetime.datetime.min
lastserverHasReelPosList=[]
lastoutTaskInfo=[]
#从服务器定时获取有料的库位列表
def updateServerHasReelPosList():
global serverHasReelPosList
global lastserverHasReelPosList
global lastoutTaskInfo
global outTaskInfo
global ServerErrorTimes
ls = (datetime.datetime.now() - lastupdatetime).total_seconds()
if ls<3:
return
......@@ -142,16 +150,24 @@ def updateServerHasReelPosList():
pos = posInfo[0]
color = posInfo[1].lower()
outTaskInfo[pos] = color
if outTaskList!=lastoutTaskInfo:
logging.warning("{} out task:{} ----- {}".format(outTask,pos,color))
lastupdatetime==datetime.datetime.now()
lastoutTaskInfo=outTaskList
ServerErrorTimes=0
except Exception as e:
logging.warning("从服务器获取有料的库位列表失败:{}".format(e))
msg = traceback.format_exc()
ServerErrorTimes=ServerErrorTimes+1
logging.warning("从服务器获取有料的库位列表失败:{},{}".format(e,msg))
logging.warning(response.content.decode())
finally:
lastupdatetime==datetime.datetime.now()
# 构建库位原始数据表/更新当前有库存的库位状态
def origin_location_init():
global locations
global detail_dict
global is_start
global ServerErrorTimes
url = ip_config['ip'] + '/service/store/sensorShelf/hasReelPosList'
data = {"cid":ip_config['cid']}
init_msg = ''
......@@ -182,9 +198,13 @@ def origin_location_init():
logging.warning('库位配置表未查询到该库位号:{}'.format(locnum))
init_msg = 'success'
# print ('-----------detail_dict',detail_dict)
ServerErrorTimes=0
except Exception as e:
init_msg = 'failed'
logging.warning("构建库位原始数据表/更新当前有库存的库位状态失败:{}".format(e))
ServerErrorTimes=ServerErrorTimes+1
msg = traceback.format_exc()
logging.warning("构建库位原始数据表/更新当前有库存的库位状态失败:{},{}".format(e,msg))
print(response.status_code,response.request.url)
return init_msg
ServerAliveTime=datetime.datetime.min
......@@ -212,23 +232,29 @@ def serverboard():
if detail_dict:
try:
# print ('detai-dict-----------------',detail_dict)
shelfconfig.after_instore_light_color
#shelfconfig.after_instore_light_color
print("================================================")
start = timeit.default_timer()
print("serverboard being",start)
server_post(seq)
print("serverboard server_post",str(timeit.default_timer()-start))
ser.send_data(command)
time.sleep(0.05)
location_status=ser.read_alldata()
print("serverboard read_alldata",str(timeit.default_timer()-start))
ls = (datetime.datetime.now() - ServerAliveTime).total_seconds()
print("ServerAliveTime",ls)
if ls>60:
if ls>60*5:
ServerAliveTime=datetime.datetime.now()
logging.warning("ServerAlive:"+location_status.decode().replace('\n','\\n'))
print("serverboard startprocesslocation",str(timeit.default_timer()-start))
cur_dict = production_filter(location_status)
if ProcessLastSensor(cur_dict,last_sensor_dict):
lastupdatetime=datetime.datetime.min
last_sensor_dict=cur_dict.copy()
print("serverboard endprocesslocation",str(timeit.default_timer()-start))
updateServerHasReelPosList()
print("serverboard updateServerHasReelPosList",str(timeit.default_timer()-start))
in_loc,out_loc = compare_detail(cur_dict)
send_loc_server(in_loc,out_loc)
end = timeit.default_timer()
......@@ -239,7 +265,9 @@ def serverboard():
autostate['state'] = 'success'
except Exception as e:
autostate['state'] = 'failed'
logging.warning("主循环出错:{}".format(e))
logging.warning("主循环出错:{}".format(repr(e)))
msg = traceback.format_exc()
logging.warning(msg)
time.sleep(10)
else:
origin_location_init()
......@@ -254,6 +282,7 @@ lastupdatetime_server_post=datetime.datetime.min
def server_post(seq):
global currentdate
global lastupdatetime_server_post
global ServerErrorTimes
ls = (datetime.datetime.now() - lastupdatetime_server_post).total_seconds()
if ls<1:
return
......@@ -271,7 +300,7 @@ def server_post(seq):
if os.name != 'nt':
t = time.gmtime(time.mktime(t)+8*60*60)
dd= 'date '+time.strftime('%m%d%H%M%Y.%S',t)
os.system(dd)
#os.system(dd)
logging.warning("执行时间设定:{}:{}".format(currentdate,dd))
# response = requests.post("http://jsonplaceholder.typicode.com/posts", data = "some dummy content")
ele_json = response.json()
......@@ -280,9 +309,11 @@ def server_post(seq):
resolve_data(ele_json)
if ele_json['data']:
logging.warning("服务器发送数据:{}".format(ele_json['data']))
ServerErrorTimes=0
except Exception as e:
ip_config['post'] = 'failed'
logging.warning("请求服务器失败:{}".format(e))
ServerErrorTimes=ServerErrorTimes+1
logging.warning("请求服务器失败:{},ServerErrorTimes:{}".format(e,ServerErrorTimes))
# 解析服务器接收数据
def resolve_data(datajson):
......@@ -315,7 +346,7 @@ def resolve_data(datajson):
logging.warning("未找到库位配置:{}".format(config_dict.get(single[0])))
logging.warning("库位灯有关闭指令")
if 'closeAll' in operation.keys():
# deal_alloff()
ser.send_data('{"ADDR":"99","ledrange":[16,1,100]}')
logging.warning("所有库位灯关闭")
return True
......@@ -350,7 +381,7 @@ def compare_detail(cur_dict):
#有料,且与服务器一致,改灯颜色为orange
posColor = outTaskInfo.get(locnumber,shelfconfig.after_instore_light_color)
logging.debug("location:{}, old color:{}, new color:{}".format(locnumber,locations[locnumber]['color'],posColor))
if not locations[locnumber]['color'] == posColor:
if not locations[locnumber]['color'] == posColor or locnumber in outTaskInfo.keys():
locations[locnumber]['outloc_ng'] = False
locations[locnumber]['inloc_ng'] = False
locations[locnumber]['color'] = posColor
......@@ -429,6 +460,7 @@ def send_loc_server(in_loc,out_loc):
# print ('--------------------origin_in_loc',in_loc)
# print ('--------------------origin_out_loc',out_loc)
global locations
global ServerErrorTimes
in_ng_loc = []
out_ng_loc = []
for locnum, locvalue in locations.items():
......@@ -441,13 +473,16 @@ def send_loc_server(in_loc,out_loc):
print("send_loc_server,nochange")
return
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}
print("send_loc_server send",data)
try:
response = requests.post(url, data=data,headers= headers,timeout=5)
response = requests.post(url, data=data,headers= headers,timeout=60)
rec_data = response.json()
print("send_loc_server",rec_data)
logging.warning("send_loc_server send:{} , recive:{}".format(data,rec_data))
if rec_data['code'] == 0:
in_ok = rec_data['data']["inOkList"]
out_ok = rec_data['data']["outOkList"]
......@@ -464,8 +499,13 @@ def send_loc_server(in_loc,out_loc):
# print ('--------------------out_ok',out_ok)
# print ('--------------------in_ng',in_ng)
# print ('--------------------out_ng',out_ng)
ServerErrorTimes=0
except Exception as e:
logging.warning("send_loc_server error:{}".format(e))
ServerErrorTimes=ServerErrorTimes+1
print(data)
print(response.text)
msg = traceback.format_exc()
logging.warning("send_loc_server error:{},{}".format(e,msg))
# 根据服务器返回出入库OK/NG更新库位状态
def update_to_location(locdata,flag):
......@@ -478,14 +518,14 @@ def update_to_location(locdata,flag):
logging.warning('入库ng库位,亮红色灯:{}'.format(loc))
elif flag == 1:
for loc in locdata:
locations[loc]['blink_num'] = 6
locations[loc]['blink_num'] = 4
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]['blink_num'] = 4
locations[loc]['out_blink'] = True
locations[loc]['color'] = 'yellow'
locations[loc]['action'] = True
......@@ -508,27 +548,22 @@ def update_to_location(locdata,flag):
# thread control led
def show_blink():
global locations
global outTaskInfo
blink_leds = {}
while is_start:
try:
start = timeit.default_timer()
print("show_blink being",start)
blink_status = {'side':'both','status':False}
ng_status = {'side':'both','status':False}
blink_leds = {}
locside='both'
#locations = {'addr': 'A1', 'led_index': 1, 'sensor_index': 1, 'in_blink': False, 'out_blink': False, 'inloc_ng': False, 'outloc_ng': False, 'color': 'off', 'blink': False, 'blink_num': 0, 'action': False}
#locnum = S10392-A1-001
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']
......@@ -570,11 +605,43 @@ def show_blink():
else:
update_locations(blink_leds,addr,color,led_index)
locations[locnum]['action'] = False
if 'locside' in locvalue:
locside = locvalue['locside']
if len(locvalue['addr'])==3:
locside='b'
else:
locside='a'
# print ('--------------action_value',action_value)
#if locvalue['out_blink']:#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
for locnum in outTaskInfo.keys():
#logging.warning('有出库任务闪黄灯:{}'.format(locnum))
if len(locations[locnum]['addr'])==3:
if locside=='a':
locside='both'
locside='b'
else:
if locside=='b':
locside='both'
locside='a'
blink_status['side'] = locside
blink_status['status'] = True
if locside=='both':
break;
end = timeit.default_timer()
print("show_blink end",end,(end-start))
blink_convert(blink_leds)
update_tower(blink_status,ng_status)
time.sleep(0.5)
except Exception as e:
msg = traceback.format_exc()
logging.warning("show_blink error:{},{}".format(e,msg))
def check_pre(locvalue):
if locvalue['action']:
......@@ -599,7 +666,7 @@ def check_pre(locvalue):
check_value = {'c_state':True,'c_act':'out_blink_end'}
# check_value = 'out_blink_end'
else:
check_value = 'normal'
#check_value = 'normal'
check_value = {'c_state':True,'c_act':'normal'}
else:
check_value = {'c_state':False,'c_act':'no_action'}
......@@ -615,34 +682,47 @@ def update_locations(blink_leds,addr,color,led_index):
blink_leds[addr] = {color:[led_index]}
return blink_leds
def blink_convert(blink_leds):
if 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():
if (len(leds)<40):
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()))
else:
ix=0
while(True):
ca=leds[ix:ix+33]
ca.insert(0,COLORS.get(color,[15,255,255,255])[0])
command = {"ADDR":addr,"color":[ca]}
command = str(json.dumps(command)).replace(" ","") #去除指令中的空格
texts.append(command + '\n')
ix=ix+33
if (ix>=len(leds)): break
# 分地址发送
if texts:
for line in texts:
ser.send_data(line)
time.sleep(0.05)
ser.read_alldata()
print("blink_convert",timeit.default_timer(),line)
time.sleep(0.005)
# return texts
#blink_leds={}
#blink_leds['A5']={}
#blink_leds['A5']['red']=[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]
#blink_convert(blink_leds)
#控制状态灯
def show_tower():
ser=SerialCommunication();
......@@ -700,12 +780,13 @@ YellowTWLed = '2@5'
GreenTWLed = '3@6'
def update_tower(blink_status,ng_status):
global tower_state
global ServerErrorTimes
#print (blinks,ngs)
thisYellowTWLed = YellowTWLed
if blink_status['side'].lower()=='a':
thisYellowTWLed=YellowTWLed.partition('@')[0]
elif blink_status['side'].lower()=='b':
thisYellowTWLed=YellowTWLed.partition('@')[1]
thisYellowTWLed=YellowTWLed.partition('@')[2]
if blink_status['status']:
if tower_state[thisYellowTWLed]['status'] == 'off':
......@@ -715,6 +796,10 @@ def update_tower(blink_status,ng_status):
tower_state[thisYellowTWLed]['action'] = True
tower_state[thisYellowTWLed]['status'] = 'off'
else:
for led in thisYellowTWLed.split('@'):
if tower_state[led]['status'] == 'on':
tower_state[led]['action'] = True
tower_state[led]['status'] = 'off'
if tower_state[thisYellowTWLed]['status'] == 'on':
tower_state[thisYellowTWLed]['action'] = True
tower_state[thisYellowTWLed]['status'] = 'off'
......@@ -732,14 +817,30 @@ def update_tower(blink_status,ng_status):
tower_state[thisRedTWLed]['action'] = True
tower_state[thisRedTWLed]['status'] = 'off'
else:
for led in thisRedTWLed.split('@'):
if tower_state[led]['status'] == 'on':
tower_state[led]['action'] = True
tower_state[led]['status'] = 'off'
if tower_state[thisRedTWLed]['status'] == 'on':
tower_state[thisRedTWLed]['action'] = True
tower_state[thisRedTWLed]['status'] = 'off'
# print ('---------------------------------tower_state',tower_state)
if gg.current_state =='on':
if ServerErrorTimes>3:
if tower_state[GreenTWLed]['status'] == 'on':
tower_state[GreenTWLed]['action'] = True
tower_state[GreenTWLed]['status'] = 'off'
else:
tower_state[GreenTWLed]['action'] = True
tower_state[GreenTWLed]['status'] = 'on'
else:
if tower_state[GreenTWLed]['status'] == 'off':
tower_state[GreenTWLed]['action'] = True
tower_state[GreenTWLed]['status'] = 'on'
send_tower_status_light()
def reset_tower():
ser=SerialCommunication();
ser=SerialCommunication()
command_dicts = {"ADDR":"0","lightoff":[1,2,3,4,5,6]}
maincommand = str(json.dumps(command_dicts)) + '\n'
print (maincommand)
......@@ -748,9 +849,8 @@ def reset_tower():
# 开机启动
def auto_start():
state = read_state()
if state == 'on':
confirm_state('off')
if gg.current_state == 'on':
gg.current_state ='off'
time.sleep(2)
logging.warning("11111111111")
startpost()
......
支持 Markdown 格式
你添加了 0 到此讨论。请谨慎行事。
Finish editing this message first!