routes.py
27.8 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
# codinf:utf-8
from calendar import Calendar
from tkinter.tix import Tree
from flask import render_template, Response,request,redirect,url_for,send_from_directory
# from flask_socketio import SocketIO, emit, disconnect
from werkzeug.utils import secure_filename
from random import choice
import json
import time
import csv
import threading
import os
import re
from time import sleep
from config import Config
#from rpi_ws281x import Adafruit_NeoPixel, Color,PixelStrip
from app import app,babel
from app.g import shelfconfig as shelfconfigA
from app.led_strip import get_strip,Color,setcolor
from app import driver_gpio
import logging
#import RPi.GPIO as GPIO
from flask_babel import Babel, gettext as _
curren_l = 'zh'
@babel.localeselector
def get_locale():
# if the user has set up the language manually it will be stored in the session,
# so we use the locale from the user settings
try:
language = curren_l
except KeyError:
language = None
if language is not None:
return language
return request.accept_languages.best_match(app.config['LANGUAGES'].keys())
config_dict = {}
option_list = []
basepath = os.path.dirname(__file__)
uploads_path = basepath + Config.UPLOAD_FOLDER
state_path = basepath + Config.STATE_PATH
try:
logging.warning("开始读取库位数据")
# 自动识别文件编码
import chardet
raw = open(uploads_path + '/linePositions.csv', 'rb').read()
enc = chardet.detect(raw)['encoding'] or 'gbk'
logging.warning("检测到的编码:{}".format(enc))
with open(uploads_path + '/linePositions.csv', 'r', encoding=enc) as f:
reader = csv.reader(f)
for row in reader:
if row[0]=='位置':
continue
config_dict[row[0]] = row[7]+'@'+row[6]
option_list.append(row[0])
print(config_dict)
logging.warning("配置文件加载成功...")
config_state =True
except Exception as e:
logging.warning(". 原因: {}".format(e))
config_state = False
SET_CHANNEL = {'greenA':5,'yellowA':6,'redA':16,'greenB':17,'yellowB':27,'redB':23}
#SET_CHANNEL = {'greenB':5,'yellowB':6,'redB':16,'greenA':17,'yellowA':27,'redA':23}
SET_LED_CHANNEL = {'1':12,'2':21}
led_lights1 = {}
led_lights2 = {}
@app.route('/language/<language>')
def set_language(language=None):
global curren_l
curren_l = language
return redirect(url_for('index'))
@app.route('/')
def root():
return send_from_directory('static', 'index.html')
@app.route('/_debug')
def debug():
root = app.static_folder
files = []
for dirpath, _, filenames in os.walk(root):
for f in filenames:
files.append(os.path.relpath(os.path.join(dirpath, f), root))
return json.dumps(files)
@app.route('/<path:filename>')
def my_static(filename):
fpath = os.path.join(app.static_folder, filename)
print('my_static',filename,fpath)
if os.path.isfile(fpath):
return send_from_directory(app.static_folder, filename)
# 文件不存在 → 返回 index.html(状态码仍保持 200,方便单页应用)
return send_from_directory('static', 'index.html')
# 让 Flask 内置的 /static/<path:filename> 继续工作,不干扰
# 下面这个钩子只处理“其它所有路由”
#@app.errorhandler(404)
#def fallback(e):
# 如果你只想把「静态文件」404 吞掉,而保留 API 404,
# 可以在这里按路径过滤:
# if request.path.startswith('/api/'):
# return e # 原样返回 404
# return send_from_directory('static', 'index.html')
#@app.route('/index')
#def index():
# logging.warning("控制界面")
# return render_template('base.html',config_state=config_state)
@app.route('/config_state')
def configstate():
return json.dumps(config_state)
@app.route('/positionlist')
def positionlist():
return json.dumps(option_list)
@app.route('/ledtest')
def ledtest():
logging.warning("测试界面")
return render_template('ledtest.html',option_list=option_list,config_state=config_state)
@app.route('/shelfconfig')
def shelfconfig():
logging.warning("配置界面")
return render_template('shelfconfig.html',config_state=config_state)
@app.route('/workinglight',methods=['POST'])
def workinglight():
data = request.get_json()
channel = data['workchannel']
color = data['workcolor']
msg = SwitchStatusLight(channel,color,True)
info = []
c_dict = {'msg':msg}
info.append(c_dict)
return json.dumps(info)
@app.route('/workingoff',methods=['POST'])
def workingoff():
data = request.get_json()
channel = data['workchannel']
color = data['workcolor']
msg = SwitchStatusLight(channel,color,False)
info = []
c_dict = {'msg':msg}
info.append(c_dict)
return json.dumps(info)
def SwitchStatusLight(channel,color,onoff):
if channel == 'channel1':
if color == 'green':
pin = SET_CHANNEL['greenA']
elif color == 'yellow':
pin = SET_CHANNEL['yellowA']
else:
pin = SET_CHANNEL['redA']
else:
if color == 'green':
pin = SET_CHANNEL['greenB']
elif color == 'yellow':
pin = SET_CHANNEL['yellowB']
else:
pin = SET_CHANNEL['redB']
# GPIO.setmode(GPIO.BCM)
# GPIO.setup(pin,GPIO.OUT)
# GPIO.output(pin,GPIO.HIGH)
driver_gpio.init(pin)
if onoff:
driver_gpio.gpio_high(pin)
else:
driver_gpio.gpio_low(pin)
msg = _("通道")+":"+str(channel)+";"+_("状态灯")+":{};Pin:{};onoff:{}".format(color,pin,onoff)
logging.warning(msg)
return msg
def set_indexcolor(light_led_color):
return setcolor(light_led_color)
# 处理库位操作测试>>亮灯操作
def process_lightindex(data):
global led_lights1
global led_lights2
light_led_color = data['light_led_color']
color = set_indexcolor(light_led_color)
light_led = data['light_led']
channel = config_dict.get(light_led).split('@')[1]
led_index = int(config_dict.get(light_led).split('@')[0])
if channel == '1':
# global led_lights1
if led_index not in led_lights1.keys():
led_lights1[led_index] = color
elif channel == '2':
# global led_lights2
# pin = SET_LED_CHANNEL['2']
# strip = get_strip(pin)
if led_index not in led_lights2.keys():
led_lights2[led_index] = color
else:
if led_index not in led_lights1.keys():
led_lights1[led_index] = color
if led_index not in led_lights2.keys():
led_lights2[led_index] = color
return channel
# 处理库位操作测试>>灭灯操作
def process_offindex(data):
global led_lights1
global led_lights2
off_led = data['off_led']
channel = config_dict.get(off_led).split('@')[1]
led_index = int(config_dict.get(off_led).split('@')[0])
if channel == '1':
# global led_lights1
if led_index in led_lights1.keys():
del led_lights1[led_index]
elif channel == '2':
# global led_lights2
if led_index in led_lights2.keys():
del led_lights2[led_index]
else:
if led_index in led_lights1.keys():
del led_lights1[led_index]
if led_index in led_lights2.keys():
del led_lights2[led_index]
return channel,led_index
@app.route('/ledopen',methods=['POST'])
def ledopen():
global led_lights1
global led_lights2
data = request.get_json()
channel = process_lightindex(data)
if channel == '1':
# global led_lights1
pin = SET_LED_CHANNEL['1']
strip = get_strip(pin)
for key,value in led_lights1.items():
print(key,value)
#c_index=list(map(int,re.split(';',key)))
on_led=key
#for on_led in c_index:
strip.setPixelColor(on_led, value)
# print ("111")
strip.show()
elif channel == '2':
# global led_lights2
pin = SET_LED_CHANNEL['2']
strip = get_strip(pin)
for key,value in led_lights2.items():
#c_index=list(map(int,re.split(';',key)))
on_led=key
#for on_led in c_index:
strip.setPixelColor(on_led, value)
strip.show()
else:
pin1 = SET_LED_CHANNEL['1']
pin2 = SET_LED_CHANNEL['2']
strip1 = get_strip(pin1)
for key,value in led_lights1.items():
c_index=list(map(int,re.split(';',key)))
for on_led in c_index:
strip1.setPixelColor(on_led, value)
strip1.show()
strip2 = get_strip(pin2)
for key,value in led_lights2.items():
c_index=list(map(int,re.split(';',key)))
for on_led in c_index:
strip2.setPixelColor(on_led, value)
strip2.show()
logging.warning("当前通道1ON_LED:{},当前通道2ON_LED:{}".format(led_lights1,led_lights2))
msg = _('灯地址:{},{},{},已点亮').format(data['light_led'],channel,led_lights1,led_lights2)
logging.warning(msg)
info = []
c_dict = {'msg':msg}
info.append(c_dict)
return json.dumps(info)
@app.route('/ledoff',methods=['POST'])
def ledoff():
global led_lights1
global led_lights2
data = request.get_json()
channel,led_index = process_offindex(data)
if channel == '1':
# global led_lights1
pin = SET_LED_CHANNEL['1']
strip = get_strip(pin)
strip.setPixelColor(led_index, 0)
strip.show()
elif channel == '2':
# global led_lights2
pin = SET_LED_CHANNEL['2']
strip = get_strip(pin)
strip.setPixelColor(led_index, 0)
strip.show()
else:
pin1 = SET_LED_CHANNEL['1']
pin2 = SET_LED_CHANNEL['2']
strip1 = get_strip(pin1)
for key,value in led_lights1.items():
c_index=list(map(int,re.split(';',key)))
for on_led in c_index:
strip1.setPixelColor(on_led, value)
strip1.show()
strip2 = get_strip(pin2)
for key,value in led_lights2.items():
c_index=list(map(int,re.split(';',key)))
for on_led in c_index:
strip2.setPixelColor(on_led, value)
strip2.show()
msg = _('灯地址:{},{},{},已关闭').format(data['off_led'],channel,led_index)
logging.warning(msg)
info = []
c_dict = {'msg':msg}
info.append(c_dict)
return json.dumps(info)
@app.route('/resetled',methods=['POST'])
def resetled():
threads = []
threads.append(threading.Thread(target=reset_strip1))
threads.append(threading.Thread(target=reset_strip2))
for t in threads:
t.start()
msg = _('灯条已重置')
logging.warning(msg)
info = []
c_dict = {'msg':msg}
info.append(c_dict)
return json.dumps(info)
def reset_strip1():
global led_lights1
pin=SET_LED_CHANNEL['1']
strip = get_strip(pin)
for i in range(0,strip.numPixels()): #设置个循环(循环次数为LED数量)
strip.setPixelColor(i, Color(0,0,0))
strip.show()
led_lights1 = {}
def reset_strip2():
global led_lights2
pin=SET_LED_CHANNEL['2']
strip = get_strip(pin)
for i in range(0,strip.numPixels()): #设置个循环(循环次数为LED数量)
strip.setPixelColor(i, Color(0,0,0))
strip.show()
led_lights2 = {}
# 上传配置文件
@app.route('/upload/', methods=['GET', 'POST'])
def upload_file():
if request.method == 'POST':
# check if the post request has the file part
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
# if user does not select file, browser also
# submit an empty part without filename
if file.filename == '':
flash('No selected file')
return redirect(request.url)
if file:
basepath = os.path.dirname(__file__)
uploads_path = basepath + Config.UPLOAD_FOLDER
# print (uploads_path)
# print (Config.UPLOAD_FOLDER)
filename = secure_filename(file.filename)
file.save(os.path.join(uploads_path, filename))
print (filename)
reload_config()
return '{"filename":"%s"}' % filename
return True
# 下载日志文件
@app.route('/download/', methods=['GET'], strict_slashes=False)
def download():
log_path = '/prog/smartshelf/logs/'
ls=os.path.join(log_path, 'smart.log')
if request.method == "GET":
if os.path.isfile(os.path.join(log_path, 'smart.log')):
return send_from_directory(log_path, 'smart.log', as_attachment=True)
def reload_config():
global config_dict
global config_state
global option_list
print (config_dict,option_list)
try:
logging.warning("开始读取库位数据")
# 自动识别文件编码
import chardet
raw = open(uploads_path + '/linePositions.csv', 'rb').read()
enc = chardet.detect(raw)['encoding'] or 'gbk'
logging.warning("检测到的编码:{}".format(enc))
with open(uploads_path + '/linePositions.csv', 'r', encoding=enc) as f:
reader = csv.reader(f)
config_dict = {}
option_list = []
for row in reader:
config_dict[row[0]] = row[7]+'@'+row[6]
option_list.append(row[0])
logging.warning("配置文件加载成功")
config_state = True
print (config_dict,option_list)
except Exception as e:
logging.warning("配置文件加载失败,请上传配置文件. 原因: {}".format(e))
config_state = False
def process_linetest(data):
if data['channel_num'] == "channel1":
LED_PIN = SET_LED_CHANNEL['1']
else:
LED_PIN = SET_LED_CHANNEL['2']
# print (data['channel_color'])
if data['channel_color'] == "green":
# print ("绿色")
color = Color(255,0,0)
elif data['channel_color'] == "blue":
# print ("蓝色")
color = Color(0,0,255)
elif data['channel_color'] == "red":
# print ("红色")
color = Color(0,255,0)
elif data['channel_color'] == "yellow":
# print ("黄色")
color = Color(255,255,0)
else:
# print ("白色")
color = Color(255,255,255)
color=setcolor(data['channel_color'])
return LED_PIN,color
@app.route('/lineledon', methods=['POST'])
def lineledon():
data = request.get_json()
pin,color = process_linetest(data)
strip = get_strip(pin)
for i in range(0,strip.numPixels()): #设置个循环(循环次数为LED数量)
strip.setPixelColor(i, color)
strip.show()
msg = _("灯条:{},颜色:{},已开启").format(data['channel_num'],data['channel_color'])
logging.warning(msg)
info = []
c_dict = {'msg':msg}
info.append(c_dict)
return json.dumps(info)
@app.route('/lineledoff', methods=['POST'])
def lineledoff():
data = request.get_json()
pin,color = process_linetest(data)
strip = get_strip(pin)
for i in range(0,strip.numPixels()):
strip.setPixelColor(i, Color(0,0,0))
strip.show()
info = []
msg = _("灯条:{}已关闭").format(data['channel_num'])
logging.warning(msg)
c_dict = {'msg':msg}
info.append(c_dict)
return json.dumps(info)
@app.route('/opAll', methods=['POST'])
def opAll():
data = request.get_json()
info = {"status":0}
if data["op"].lower() =="on":
logging.info('打开所有灯')
return json.dumps(info)
else:
for pin in [SET_LED_CHANNEL['1'],SET_LED_CHANNEL['2']]:
strip = get_strip(pin)
for i in range(0,strip.numPixels()):
strip.setPixelColor(i, Color(0,0,0))
strip.show()
logging.info('关闭所有灯')
return json.dumps(info)
@app.route('/api/open', methods=['POST'])
def apiOpen():
data = request.get_json()
list = data['params'].split(';')
strip1 = get_strip(SET_LED_CHANNEL['1'])
strip2 = get_strip(SET_LED_CHANNEL['2'])
faillist=[]
for li in list:
kv=li.split('=')
key = kv[0].lower()
val = kv[1].lower()
if key == "statusa":
logging.info('打开状态灯A:'+val)
SwitchStatusLight('channel1',val,True)
elif key == "statusb":
logging.info('打开状态灯B:'+val)
SwitchStatusLight('channel2',val,True)
elif key.isdigit():
lightindex = int(key)
if lightindex>len(option_list):
faillist.append(li)
logging.info('打开灯失败:'+li+", c="+val)
else:
storeid = option_list[lightindex]
channel = config_dict.get(storeid).split('@')[1]
led_index = int(config_dict.get(storeid).split('@')[0])
color = set_indexcolor(val)
if channel=='1':
strip1.setPixelColor(led_index, color)
else:
strip2.setPixelColor(led_index, color)
print('打开灯:'+li+",ch:"+channel+",index:"+str(led_index)+",color:"+val+str(color))
logging.info('打开灯:'+li+",ch:"+channel+",index:"+str(led_index)+",color:"+val+str(color))
else:
faillist.append(key+'='+val)
strip1.show()
strip2.show()
if len(faillist) == 0:
return json.dumps({"status":0,"msg":"success"})
else:
msg = ';'.join(faillist)
info = {"status":1,"msg":{"failed":msg}}
return json.dumps(info)
@app.route('/api/close', methods=['POST'])
def apiClose():
data = request.get_json()
list = data['params'].split(';')
strip1 = get_strip(SET_LED_CHANNEL['1'])
strip2 = get_strip(SET_LED_CHANNEL['2'])
faillist=[]
for li in list:
if li.find('=')>0:
kv=li.split('=')
key = kv[0].lower()
val = kv[1].lower()
channel = "channel1"
if key == "statusa":
logging.info('关闭状态灯A:'+val)
elif key == "statusb":
channel='channel2'
logging.info('关闭状态灯B:'+val)
SwitchStatusLight(channel,val,False)
elif li.lower()=='statusa':
logging.info('关闭状态灯A')
for color in ['red','green','yellow']:
SwitchStatusLight('channel1',color,False)
elif li.lower()=='statusb':
logging.info('关闭状态灯B')
for color in ['red','green','yellow']:
SwitchStatusLight('channel2',color,False)
elif li.isdigit():
lightindex = int(li)
if lightindex>len(option_list):
faillist.append(li)
logging.info('关闭灯失败:'+li)
else:
storeid = option_list[lightindex]
channel = config_dict.get(storeid).split('@')[1]
led_index = int(config_dict.get(storeid).split('@')[0])
if channel=='1':
strip1.setPixelColor(led_index, Color(0,0,0))
else:
strip2.setPixelColor(led_index, Color(0,0,0))
print('关闭灯:'+li+",ch:"+channel+",index:"+str(led_index))
logging.info('关闭灯:'+li+",ch:"+channel+",index:"+str(led_index))
else:
faillist.append(li)
strip1.show()
strip2.show()
if len(faillist) == 0:
return json.dumps({"status":0,"msg":"success"})
else:
msg = ';'.join(faillist)
info = {"status":1,"msg":{"failed":msg}}
return json.dumps(info)
#/rest/api/v1/shelf/posOn?posId=1_3_1@green;1_3_2@green;1_3_7@red
#posOn OK 或 posOn FAIL
@app.route('/rest/api/v1/shelf/posOn', methods=['Get'])
def rest_api_v1_shelf_posOn():
"""
亮灯接口:
- 请求参数: posId=库位条码@颜色;库位条码@颜色
- 返回: 'posOn OK' / 'posOn FAIL'
"""
client_ip = request.remote_addr
posId = request.args.get('posId', '').strip()
logging.info(f'[posOn] request from {client_ip}, raw posId="{posId}"')
if not posId:
logging.warning('[posOn] missing posId parameter')
return 'posOn FAIL'
strip1 = get_strip(SET_LED_CHANNEL['1'])
strip2 = get_strip(SET_LED_CHANNEL['2'])
option_list = [x for x in posId.split(';') if x]
success = True
for ol in option_list:
try:
if '@' not in ol:
logging.warning(f'[posOn] invalid format (missing @): "{ol}"')
success = False
continue
posname, color = ol.split('@', 1)
posname = posname.strip()
color = color.strip()
cfg = config_dict.get(posname)
if cfg is None:
logging.warning(f'[posOn] position not found in config: "{posname}"')
success = False
continue
led_index = int(cfg.split('@')[0])
channel = cfg.split('@')[1]
strip = strip1
if channel == '2':
strip = strip2
strip.setPixelColor(led_index, setcolor(color))
logging.info(f'[posOn] turn on light pos="{posname}", color="{color}", channel={channel}, index={led_index}')
except Exception as e:
success = False
logging.error(f'[posOn] error processing "{ol}": {e}')
strip1.show()
strip2.show()
if success:
logging.info('[posOn] finished successfully')
return 'posOn OK'
else:
logging.warning('[posOn] finished with failure')
return 'posOn FAIL'
#/rest/api/v1/shelf/posOff?posId=1_3_1;1_3_2;1_3_4
#posOff OK 或 posOff FAIL
@app.route('/rest/api/v1/shelf/posOff', methods=['Get'])
def rest_api_v1_shelf_posOff():
"""
灭灯接口:
- 请求参数: posId=库位条码;库位条码
- 返回: 'posOff OK' / 'posOff FAIL'
"""
client_ip = request.remote_addr
posId = request.args.get('posId', '').strip()
logging.info(f'[posOff] request from {client_ip}, raw posId="{posId}"')
if not posId:
logging.warning('[posOff] missing posId parameter')
return 'posOff FAIL'
strip1 = get_strip(SET_LED_CHANNEL['1'])
strip2 = get_strip(SET_LED_CHANNEL['2'])
option_list = [x for x in posId.split(';') if x]
success = True
for posname in option_list:
try:
posname = posname.strip()
cfg = config_dict.get(posname)
if cfg is None:
logging.warning(f'[posOff] position not found in config: "{posname}"')
success = False
continue
led_index = int(cfg.split('@')[0])
channel = cfg.split('@')[1]
strip = strip1
if channel == '2':
strip = strip2
strip.setPixelColor(led_index, Color(0,0,0))
logging.info(f'[posOff] turn off light pos="{posname}", channel={channel}, index={led_index}')
except Exception as e:
success = False
logging.error(f'[posOff] error processing "{posname}": {e}')
strip1.show()
strip2.show()
if success:
logging.info('[posOff] finished successfully')
return 'posOff OK'
else:
logging.warning('[posOff] finished with failure')
return 'posOff FAIL'
#/rest/api/v1/shelf/allPosOn
#allPosOn OK 或 allPosOn FAIL
@app.route('/rest/api/v1/shelf/allPosOn', methods=['Get'])
def rest_api_v1_shelf_allPosOn():
client_ip = request.remote_addr
logging.info(f'[allPosOn] start turning on all lights, from {client_ip}')
try:
for pin in [SET_LED_CHANNEL['1'], SET_LED_CHANNEL['2']]:
strip = get_strip(pin)
for i in range(0, strip.numPixels()):
strip.setPixelColor(i, Color(255,255,255))
strip.show()
logging.info('[allPosOn] finished turning on all lights')
return 'allPosOn OK'
except Exception as e:
logging.error(f'[allPosOn] error: {e}')
return 'allPosOn FAIL'
#/rest/api/v1/shelf/allPosOff
#allPosOff OK allPosOff FAIL
@app.route('/rest/api/v1/shelf/allPosOff', methods=['Get'])
def rest_api_v1_shelf_allPosOff():
client_ip = request.remote_addr
logging.info(f'[allPosOff] start turning off all lights, from {client_ip}')
try:
for pin in [SET_LED_CHANNEL['1'], SET_LED_CHANNEL['2']]:
strip = get_strip(pin)
for i in range(0, strip.numPixels()):
strip.setPixelColor(i, Color(0,0,0))
strip.show()
logging.info('[allPosOff] finished turning off all lights')
return 'allPosOff OK'
except Exception as e:
logging.error(f'[allPosOff] error: {e}')
return 'allPosOff FAIL'
@app.route('/rest/api/v1/shelf/keepAlive')
def rest_api_v1_shelf_keepAlive():
return 'OK'
@app.route('/setconfig',methods=['POST'])
def setconfig():
data = request.get_json()
cf={}
for k,v in shelfconfigA.__dict__.items():
if k in data:
print(k,v,data.get(k))
setattr(shelfconfigA,k,data.get(k))
cf[k]=data.get(k)
if len(cf)>0:
shelfconfigA.Save()
return json.dumps(cf)
@app.route('/rest/api/v1/shelf/lightHouse', methods=['GET'])
def rest_api_v1_shelf_lightHouse():
"""
3.6.灯塔控制接口
输入格式: 三色灯@操作;三色灯@操作
三色灯取值: RA,YA,GA,RB,YB,GB
操作: ON/OFF
返回: OK/FAIL
"""
# 灯标识到SET_CHANNEL键的映射
LIGHT_MAP = {
'RA': 'redA',
'YA': 'yellowA',
'GA': 'greenA',
'RB': 'redB',
'YB': 'yellowB',
'GB': 'greenB'
}
try:
# 获取操作参数
operations = request.args.get('op')
if not operations:
return 'FAIL: Missing operations parameter'
# 分割成单独的操作
ops = operations.split(';')
success = True
for op in ops:
if not op:
continue
try:
# 分割每个操作为灯标识和动作
light, action = op.split('@')
light = light.upper()
action = action.upper()
# 获取对应的GPIO引脚
channel_key = LIGHT_MAP.get(light)
if not channel_key:
success = False
logging.warning(f'Invalid light identifier: {light}')
continue
pin = SET_CHANNEL[channel_key]
driver_gpio.init(SET_CHANNEL[channel_key])
# 执行操作
if action == 'ON':
driver_gpio.gpio_high(pin)
logging.info(f'Turned ON {light} (pin: {pin})')
elif action == 'OFF':
driver_gpio.gpio_low(pin)
logging.info(f'Turned OFF {light} (pin: {pin})')
else:
success = False
logging.warning(f'Invalid action: {action}')
except ValueError:
success = False
logging.warning(f'Invalid operation format: {op}')
except KeyError:
success = False
logging.warning(f'Invalid light identifier: {light}')
except Exception as e:
success = False
logging.error(f'Error processing operation {op}: {str(e)}')
return 'OK' if success else 'FAIL'
except Exception as e:
logging.error(f'Error in lightHouse interface: {str(e)}')
return 'FAIL'
import os, glob
@app.route('/getmac')
def getmac():
for root in glob.glob('/sys/class/net/*'):
iface = root.split('/')[-1]
if iface.startswith('eth'):
addr_file = os.path.join(root, 'address')
if os.path.isfile(addr_file):
with open(addr_file) as f:
mac = f.read().strip()
if mac and mac != '00:00:00:00:00:00':
return mac.upper()
return '00:00:00:00:00:00'