routes.py 14.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
# codinf:utf-8
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
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:
            config_dict[row[0]] = row[7]+'@'+row[6]
            option_list.append(row[0])
    logging.warning("配置文件加载成功...")
    config_state = '加载成功...'
except Exception as e:
    logging.warning("配置文件加载失败,请上传配置文件")
    config_state = '加载失败,请在配置页面上传配置文件'
SET_CHANNEL = {'greenA':5,'yellowA':6,'redA':16,'greenB':17,'yellowB':27,'redB':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']
    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)
    driver_gpio.gpio_high(pin)
    msg = "通道:{};状态灯{}点亮".format(channel,color)
    logging.warning(msg)
    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']
    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.LOW)
    driver_gpio.init(pin)
    driver_gpio.gpio_low(pin)
    msg = "通道:{};状态灯{}关闭".format(channel,color)
    logging.warning(msg)
    info = []
    c_dict = {'msg':msg}
    info.append(c_dict)
    return json.dumps(info)


def set_indexcolor(light_led_color):
    if light_led_color == 'red':
        color = Color(0,255,0)
    elif light_led_color == 'yellow':
        color = Color(255,255,0)
    elif light_led_color == 'blue':
        color = Color(0,0,255)
    elif light_led_color == 'green':
        color = Color(255,0,0)
    else:
        color = Color(0,0,0)
    return 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 = '加载成功'
        print (config_dict,option_list)
    except Exception as e:
        logging.warning("配置文件加载失败,请上传配置文件")
        config_state = '重新加载失败,请在配置页面上传配置文件'

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)
    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)