routes.py 20.5 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
# 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 import socketio
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:
    with open(uploads_path +'/linePositions.csv', 'r',encoding='gbk') 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("配置文件加载失败,请上传配置文件")
    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('/taillog',methods=['POST'])
# def taillog():
#     a=os.popen("tail -n 20 /prog/smartshelf/logs/smart.log").readlines()
#     s = '<br>'
#     p = s.join(a)
#     jsondata = {'msg':p}
#     return json.dumps(jsondata)
#     
@app.route('/language/<language>')
def set_language(language=None):
    global curren_l
    curren_l = language
    return redirect(url_for('index'))

@app.route('/')
@app.route('/index')
def index():
    logging.warning("控制界面")
    return render_template('base.html',config_state=config_state)


@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)+";"+_("状态灯")+":{}; onoff:{}".format(channel,color,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 = 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 = 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

@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():
            c_index=list(map(int,re.split(';',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)))
            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'])
    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 = process_offindex(data)
    if channel == '1':
        # global led_lights1
        pin = SET_LED_CHANNEL['1']
        strip = get_strip(pin)
        for key,value in led_lights1.items():
            c_index=list(map(int,re.split(';',key)))
            for on_led in c_index:
                strip.setPixelColor(on_led, value)
        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)))
            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()
    msg = _('灯地址:{},已关闭').format(data['off_led'])
    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:
        with open(uploads_path +'/linePositions.csv', 'r',encoding='gbk') 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("配置文件加载失败,请上传配置文件")
        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():
    strip1 = get_strip(SET_LED_CHANNEL['1'])
    strip2 = get_strip(SET_LED_CHANNEL['2'])
    posId = request.args.get('posId')
    option_list = posId.split(';')
    success = True
    for ol in option_list:
        ds = ol.split('@')
        posname = ds[0]
        color = ds[1]
        x = config_dict.get(posname)
        if x is None:
            success=False
            continue
        channel = config_dict.get(posname).split('@')[1]
        led_index = int(config_dict.get(posname).split('@')[0])
        s = strip1
        if channel == '2':
            s = strip2
        s.setPixelColor(led_index, setcolor(color))
    strip1.show()
    strip2.show()
    if success:
        return 'posOn OK'
    else:
        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():
    strip1 = get_strip(SET_LED_CHANNEL['1'])
    strip2 = get_strip(SET_LED_CHANNEL['2'])
    posId = request.args.get('posId')
    option_list = posId.split(';')
    success = True
    for posname in option_list:
        x = config_dict.get(posname)
        if x is None:
            success=False
            continue
        channel = config_dict.get(posname).split('@')[1]
        led_index = int(config_dict.get(posname).split('@')[0])
        s = strip1
        if channel == '2':
            s = strip2
        s.setPixelColor(led_index, Color(0,0,0))
    strip1.show()
    strip2.show()
    if success:
        return 'posOff OK'
    else:
        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():
    logging.info('开始打开所有灯')
    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('完成打开所有灯')
    return 'allPosOn OK'
#/rest/api/v1/shelf/allPosOff
#allPosOff OK allPosOff FAIL
@app.route('/rest/api/v1/shelf/allPosOff', methods=['Get'])
def rest_api_v1_shelf_allPosOff():
    logging.info('开始关闭所有灯')
    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 'allPosOff OK'