induction_post.py
39.2 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
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
# 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.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 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
#------------------------------------------------------------
# 自动通信
@app.route('/startpost',methods=['POST'])
def startpost():
global is_start
global ser
global tower_state
test_state = read_test_scan()
if not test_state:
if gg.current_state == 'off':
load_location()
# location_config_init()
# init_msg = origin_location_init()
# if init_msg == 'success':
gg.current_state='on'
is_start = True
ser = SerialCommunication()
logging.warning("启动复位参数 comport_carsh_reboot:{}".format(shelfconfig.comport_carsh_reboot))
logging.warning("shelfconfig: {}".format(shelfconfig.__dict__.items()))
if not shelfconfig.comport_carsh_reboot:
reset_tower()
time.sleep(1)
indresetled()
time.sleep(2)
r = bytes.decode(ser.read_alldata())
logging.warning("复位灯塔,和料架灯:"+r)
time.sleep(1)
tower_state = get_towerstate()
threads = []
threads.append(threading.Thread(target=show_blink))
time.sleep(1)
threads.append(threading.Thread(target=serverboard))
#threads.append(threading.Thread(target=show_tower))
for t in threads:
t.start()
msg = gettext('启动成功')
gg.current_state = 'on'
logging.warning("启动成功")
shelfconfig.comport_carsh_reboot=False
shelfconfig.Save()
# else:
# current_state = 'off'
# msg = '构建库位原始数据表失败/与服务器通信失败'
# logging.warning(msg)
else:
msg = '正在运行状态'
gg.current_state = 'on'
logging.warning("料架运行中无需重复启动")
else:
gg.current_state = 'off'
msg = '测试模式扫描中,请先关闭测试模式'
logging.warning(msg)
info = []
c_dict = {'state':gg.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
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('关闭成功')
gg.current_state = 'off'
else:
msg = gettext('无需关闭')
gg.current_state = 'off'
logging.warning("无需关闭")
info = []
c_dict = {'state':gg.current_state,'msg':msg}
info.append(c_dict)
return json.dumps(info)
sensorindex={}
def load_location():
global locations
global convert_dict
global config_dict
global sensorindex
location_cof = Location()
config_dict,convert_dict = location_cof.read_location_file()
locations = location_cof.production_location_init()
for k,v in locations.items():
if v['addr'] not in sensorindex:
sensorindex[v['addr']] = "0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
s=sensorindex[v['addr']]
n =v['sensor_index']-1
sensorindex[v['addr']] = s[:n] + '1' + s[n+1:]
lastupdatetime=datetime.datetime.min
lastserverHasReelPosList=[]
lastoutTaskInfo=[]
#从服务器定时获取有料的库位列表
def updateServerHasReelPosList():
global serverHasReelPosList
global lastserverHasReelPosList
global lastoutTaskInfo
global outTaskInfo
global locations
global ServerErrorTimes
ls = (datetime.datetime.now() - lastupdatetime).total_seconds()
if ls<3:
return
url = ip_config['ip'] + '/service/store/sensorShelf/shelfStatus'
data = {"cid":ip_config['cid']}
try:
response = requests.get(url, params=data,timeout=15)
in_location = response.json()
print(in_location)
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
if outTaskList!=lastoutTaskInfo:
logging.warning("{} out task:{} ----- {}".format(outTask,locations[pos]['addr'],color))
if "hasReelPosColor" in in_location['data']:
shelfconfig.after_instore_light_color = in_location['data']["hasReelPosColor"].lower()
lastoutTaskInfo=outTaskList
ServerErrorTimes=0
except Exception as 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 = ''
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=60)
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)
ServerErrorTimes=0
except Exception as e:
init_msg = 'failed'
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
from app.induction_admin import ProcessLastSensor
last_sensor_dict={}
# 串口通信
def serverboard():
global is_start
global detail_dict
global autostate
global last_sensor_dict
global lastupdatetime
global ServerAliveTime
gg.sensorChangeFirstRun = True
# 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:
try:
# print ('detai-dict-----------------',detail_dict)
#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.1)
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*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)
print("MC数据出错:",str(cur_dict is None))
if cur_dict is not None and ProcessLastSensor(cur_dict,last_sensor_dict):
lastupdatetime=datetime.datetime.min
last_sensor_dict=cur_dict.copy()
elif cur_dict is None:
continue
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()
print ("serverboard end",end,str(end-start))
# logging.warning("scan运行中---------")
seq += 1
time.sleep(0.1)
autostate['state'] = 'success'
except Exception as e:
autostate['state'] = 'failed'
logging.warning("主循环出错:{}".format(repr(e)))
msg = traceback.format_exc()
logging.warning(msg)
time.sleep(10)
else:
origin_location_init()
updateServerHasReelPosList()
time.sleep(0.6)
autostate['state'] = 'failed'
# logging.warning("检测服务器状态中....")
autostate['state'] = 'wait'
detail_dict = {}
currentdate=None
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
lastupdatetime_server_post = datetime.datetime.now()
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)
if currentdate is None:
currentdate = response.headers.get('date')
if currentdate is not None:
t = time.strptime(currentdate,'%a, %d %b %Y %H:%M:%S GMT')#'Fri, 15 Apr 2022 01:39:52 GMT'
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)
logging.warning("执行时间设定:{}:{}".format(currentdate,dd))
# response = requests.post("http://jsonplaceholder.typicode.com/posts", data = "some dummy content")
print(response.status_code,response.text)
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']))
ServerErrorTimes=0
except Exception as e:
ip_config['post'] = 'failed'
ServerErrorTimes=ServerErrorTimes+1
logging.warning("请求服务器失败:{},ServerErrorTimes:{}".format(e,ServerErrorTimes))
# 解析服务器接收数据
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():
ser.send_data('{"ADDR":"99","ledrange":[16,1,100]}')
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.warning("{} blink no opetion ".format(locnumber))
else:
#有料,且与服务器一致,改灯颜色为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 or locnumber in outTaskInfo.keys():
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.warning("{} blink no opetion ".format(locnumber))
elif locations[locnumber]['outloc_ng']:
#已经NG的,亮红灯
#locations[locnumber]['color'] = 'red'
#locations[locnumber]['action'] = True
logging.warning("{} 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.warning("{} out blink no opetion ".format(locnumber))
elif locations[locnumber]['inloc_ng']:
#已经NG的,亮红灯
#locations[locnumber]['color'] = 'red'
#locations[locnumber]['action'] = True
logging.warning("{} 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.warning("{} blink no opetion ".format(locnumber))
else:
#库位无料,且与服务器一致,关灯
if not locations[locnumber]['color'] == 'off' or locations[locnumber]['inloc_ng']:
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'] = shelfconfig.after_instore_light_color
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
global ServerErrorTimes
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)
if not gg.sensorChangeFirstRun and len(in_loc)==0 and len(out_loc)==0 and len(in_ng_loc)==0 and len(out_ng_loc)==0 :
print("send_loc_server,nochange")
return
gg.sensorChangeFirstRun=False
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)
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"]
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)
ServerErrorTimes=0
except Exception as e:
ServerErrorTimes=ServerErrorTimes+1
print(data)
msg = traceback.format_exc()
logging.warning("send_loc_server error:{},{}".format(e,msg))
# 根据服务器返回出入库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'] = shelfconfig.inok_blink_times
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'] = 4
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
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)
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':
locations[locnum]['color']=shelfconfig.after_instore_light_color
color=shelfconfig.after_instore_light_color
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
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
outlocside = ''
for locnum in list(outTaskInfo.keys()):
#logging.warning('有出库任务闪黄灯:{}'.format(locnum))
if len(locations[locnum]['addr'])==3:
if outlocside=='a':
outlocside='both'
else:
outlocside='b'
else:
if outlocside=='b':
outlocside='both'
else:
outlocside='a'
blink_status['side'] = outlocside
blink_status['status'] = True
logging.warning('locside_out:{},{}'.format(outlocside,locations[locnum]['addr']))
if outlocside=='both':
break
end = timeit.default_timer()
print("show_blink end",end,(end-start),blink_status['status'])
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']:
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):
if blink_leds:
ser=SerialCommunication();
print ('blink_leds:{}'.format(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.append(command + '\n')
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.01)
#ser.read_alldata()
print("blink_convert",timeit.default_timer(),line)
#logging.warning("blink_convert",timeit.default_timer(),line)
#time.sleep(0.005)
gg.sensorChangeFirstRun=True
# 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();
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)
gg.sensorChangeFirstRun=True
ser.send_data(maincommand)
#1@4 红色
#3@6 绿色
#2@5 黄色
if shelfconfig.single_side_tower:
RedTWLed = '1@1'
YellowTWLed = '2@2'
GreenTWLed = '3@3'
else:
RedTWLed = '1@4'
YellowTWLed = '2@5'
GreenTWLed = '3@6'
logging.warning("LEDTOWER {}, {}, {}".format(RedTWLed,YellowTWLed,GreenTWLed))
def update_tower(blink_status,ng_status):
global tower_state
global ServerErrorTimes
print ("blink_status",blink_status['status'],blink_status['side'])
thisYellowTWLed = YellowTWLed
if blink_status['side'].lower()=='a':
thisYellowTWLed=YellowTWLed.partition('@')[0]
elif blink_status['side'].lower()=='b':
thisYellowTWLed=YellowTWLed.partition('@')[2]
elif blink_status['side'].lower()=='both' and YellowTWLed.partition('@')[0]==YellowTWLed.partition('@')[2]:
thisYellowTWLed=YellowTWLed.partition('@')[0]
if blink_status['status']:
for led in thisYellowTWLed.split('@'):
print ("tower_state",led,tower_state[led]['status'])
if tower_state[led]['status'] == 'off':
tower_state[led]['action'] = True
tower_state[led]['status'] = 'on'
else:
tower_state[led]['action'] = True
tower_state[led]['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'
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']:
for led in thisRedTWLed.split('@'):
if tower_state[led]['status'] == 'off':
tower_state[led]['action'] = True
tower_state[led]['status'] = 'on'
else:
tower_state[led]['action'] = True
tower_state[led]['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()
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():
if gg.current_state == 'on':
gg.current_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("启动成功")