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
# codinf:utf-8
from flask import render_template, Response, request,redirect,url_for
from werkzeug.utils import secure_filename
from app import app
import json
import time
import pexpect
#import neopixel
import os
import requests
import threading
import re
import csv
from time import sleep
from config import Config
#from rpi_ws281x import Adafruit_NeoPixel, Color,PixelStrip
#import RPi.GPIO as GPIO
from app.led_strip import get_strip, Color,setcolor
from app.routes import config_dict,SET_CHANNEL,SET_LED_CHANNEL
from app.g import shelfconfig
from app import driver_gpio
import logging
import random
from flask_babel import Babel, gettext as _

basepath = os.path.dirname(__file__)
statusgreenA = False
statusgreenB = False
post_leds = {'1':{},'2':{}}
blink_led = {'1':{},'2':{}}
blink_lock = threading.Lock()
strips = {}
ip_config = {'post':'wait'}
try:
    uploads_path = basepath + Config.STATE_PATH
    with open(uploads_path + 'ipconfig.csv','r') as f:
        reader = csv.reader(f)
        current = [row for row in reader]
        ip_config['ip'] = current[0][0]
        ip_config['cid'] = current[0][1]
        logging.warning("ip&cid...:{}".format(ip_config))
except Exception as e:
    logging.warning("ip,cid未配置")



def confirm_state(state):
    uploads_path = basepath + Config.STATE_PATH
    with open(uploads_path + "state.txt","w") as f:
        f.write(state)
def read_state():
    uploads_path = basepath + Config.STATE_PATH
    with open(uploads_path + "state.txt","r") as f:
        state=f.readline()
    return state

def read_version():
    uploads_path = basepath + "/"
    with open(uploads_path + "version.txt","r") as f:
        s_version=f.readline()
    return s_version

def confirm_ip(data):
    uploads_path = basepath + Config.STATE_PATH
    sipconfig = read_ip()
    with open(uploads_path + 'ipconfig.csv','w') as f:
        if data['ip'] and not data['cid']:
            data['cid'] = sipconfig[0][1]
        elif data['cid'] and not data['ip']:
            data['ip'] = sipconfig[0][0]
        fieldnames = ['ip', 'cid']
        writer = csv.DictWriter(f,fieldnames=fieldnames)
        writer.writerow(data)
    ip_config['ip'] = data['ip']
    ip_config['cid'] = data['cid']
    confirm_autostart()

def confirm_autostart():
    #server_add = ip_config['ip'] + '/storage/accShelf/' + ip_config['cid']
    server_add =ip_config['ip'].rstrip("/").rstrip("-core")
    line1 = "Comment = star chrome and enter the website for \"{}\"".format(server_add)
    line2 = "Exec = chromium-browser -kiosk \"{}\"".format(server_add)
    strs=["[Desktop Entry]","Name = Chrome Autostar","Type = Application"]
    strs.append(line1)
    strs.append(line2)
    filename = "/home/pi/.config/autostart/auto.desktop"
    if os.path.isfile(filename):
        os.remove(filename)
        os.mknod(filename)
        cmd = "chmod 777 " + filename
        run = pexpect.spawn('su -c "%s" root' %cmd)
        time.sleep(0.5)
        run.sendline('123')
        time.sleep(0.1)     
        with open("/home/pi/.config/autostart/auto.desktop","a") as f:
            for i in strs:
                f.write("{}\n".format(i))
            f.close()
    else:
        os.mknod(filename)
        cmd = "chmod 777 " + filename
        run = pexpect.spawn('su -c "%s" root' %cmd)
        time.sleep(0.5)
        run.sendline('123')   
        time.sleep(0.1)     
        with open("/home/pi/.config/autostart/auto.desktop","a") as f:
            for i in strs:
                f.write("{}\n".format(i))
            f.close()
    logging.warning("自启动脚本更新成功")

def read_ip():
    uploads_path = basepath + Config.STATE_PATH
    with open(uploads_path + 'ipconfig.csv','r') as f:
        reader = csv.reader(f)
        sipconfig = [row for row in reader]
    return sipconfig

testonetimes=False

def post(seq):
    global testonetimes
    headers = {'content-type': "application/json"} #请求头信息
    url = ip_config['ip'] + '/service/store/communication'

    if not url.startswith("http"):
        if not testonetimes:
            ele_json={}
            ele_json['data']={}
            ele_json['data']['open'] = '1000001=red=5|1000002=blue' #{'open':'1_1_1=red=1000|1_1_2=blue|1_1_3=red|2_1_1=green'}
            resolve_data(ele_json)
            testonetimes= True
        return
    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)
        # response = requests.post("http://jsonplaceholder.typicode.com/posts", data = "some dummy content")
        ele_json = response.json()
        ip_config['post'] = 'success'
        if ele_json['data']:
            logging.warning("服务器发送数据:{}".format(ele_json['data']))
            resolve_data(ele_json)
        #else:
        #    logging.warning("服务器无返回数据")
    except Exception as e:
        ip_config['post'] = 'failed'
        logging.warning("请求服务器失败:{}".format(e))

#single = "库位","颜色"
def process_open_post(single,channel,led_index):
    global post_leds
    global blink_led
    print(single,channel,led_index)
    if channel == '1' or channel == '2':
        if len(single) == 1:
            post_leds[channel][led_index] = Config.DEFAULT_COLOR
            logging.warning("库位灯开启s1:{},灯索引:{},颜色:{}".format(single[0],led_index,Config.DEFAULT_COLOR))
        elif len(single) == 2:
            post_leds[channel][led_index] = single[1]
            logging.warning("库位灯开启s2:{},灯索引:{},颜色:{}".format(single[0],led_index,single[1]))
        else:
            with blink_lock:
                if led_index not in blink_led[channel].keys():
                    blink_led[channel][led_index] = {}
                blink_led[channel][led_index]['color'] = single[1]
                blink_led[channel][led_index]['waittimecount'] = int(single[2])-1
                blink_led[channel][led_index]['state'] = False
                blink_led[channel][led_index]['posid'] = single[0]
                #post_leds[channel][led_index] = single[1] + '@'+single[2]
                logging.warning("库位灯开启闪烁:{},灯索引:{},颜色:{},时长: {}".format(single[0],led_index,single[1],single[2]))
    else:
        for key in post_leds.keys():
            if len(single) == 1:
                post_leds[key][led_index] = Config.DEFAULT_COLOR
                # logging.warning("库位灯开启(双面):{},灯索引:{},颜色:red".format(single[0],led_index))
            elif len(single) == 2:
                post_leds[key][led_index] = single[1]
                # logging.warning("库位灯开启(双面):{},灯索引:{},颜色:{}".format(single[0],led_index,single[1]))
            else:
                post_leds[key][led_index] = single[1] + '@blink'
                # logging.warning("库位灯开启(双面):{},灯索引:{},颜色:{}".format(single[0],led_index,single[1]))
        logging.warning("库位灯开启(双面):{},灯索引:{}".format(single[0],led_index))

def process_off_post(single,channel,led_index):
    global post_leds
    global strips
    if channel == '1' or channel == '2':
        #print('process_off_post1',channel,led_index)
        post_leds[channel].pop(led_index, None)
        blink_led[channel].pop(led_index, None)
        #print('process_off_post2',channel,led_index)
        strip = strips[channel]
        #print('process_off_post3',channel,led_index)
        #c_index=list(map(int,re.split(';',led_index)))
        #print('process_off_post4',c_index)
        #for on_led in c_index:
            #strip.setPixelColor(on_led, setcolor('off'))
        strip.setPixelColor(led_index, setcolor('off'))
        logging.warning("库位灯关闭:{},灯索引:{}".format(single[0],led_index))
    else:
        for key in post_leds.keys():
            post_leds[key].pop(led_index, None)
            strip = strips[key]
            c_index=list(map(int,re.split(';',led_index)))
            for on_led in c_index:
                strip.setPixelColor(on_led, setcolor('off'))
            strip.show()
        logging.warning("库位灯关闭:{},灯索引:{}".format(single[0],led_index))

def process_closeall_post(color):
    global post_leds
    global blink_led
    global strips
    with blink_lock:
        blink_led = {'1':{},'2':{}}
    for key in post_leds.keys():
        post_leds[key] = {}
    for channel,strip in strips.items():
        colorWipe(strip,setcolor(color))


def resolve_data(datajson):
    global post_leds
    operation=datajson['data']
    if operation != {}:
        print (operation)
    # operation = {'open':'1_1_1=red=1000|1_1_2=blue|1_1_3=red|2_1_1=green'}
    channels = []
    if operation:
        if 'open' in operation.keys():
            openstock=operation['open'].split("|")
            logging.warning("库位灯有open指令:{}".format(operation['open']))
            for stock in openstock:
                single=stock.split("=")
                print (single)
                if config_dict.get(single[0]):
                    channel = config_dict.get(single[0]).split('@')[1]
                    led_index = int(config_dict.get(single[0]).split('@')[0])
                    process_open_post(single,channel,led_index)
                    if channel != '3':
                        channels.append(channel)
                    else:
                        channels += ['1','2']
                else:
                    logging.warning("未找到库位:{},{},{}".format(stock,single[0],config_dict.get(single[0])))
            
        if 'close' in operation.keys():
            offstock = operation['close'].split("|")
            for stock in offstock:
                single = stock.split("=")
                if config_dict.get(single[0]):
                    print('config_dict',config_dict.get(single[0]))
                    channel = config_dict.get(single[0]).split('@')[1]
                    led_index = int(config_dict.get(single[0]).split('@')[0])
                    process_off_post(single,channel,led_index)
                    print(single,channel,led_index)
                    if channel != '3':
                        channels.append(channel)
                    else:
                        channels += ['1','2']
                    print(channels)
                else:
                    logging.warning("未找到库位:{},{},{}".format(stock,single[0],config_dict.get(single[0])))
            for channel in channels:
                strips[channel].show()
            logging.warning("库位灯有关闭指令")
        if 'closeAll' in operation.keys():
            process_closeall_post('off')
            logging.warning("所有库位灯关闭")
        if 'openAll' in operation.keys():
            process_closeall_post(operation['openAll'])
            logging.warning("所有库位灯打开,{}".format(operation['openAll']))
        #"lightHouseOpenOrClose": "close=B=red"
        if 'lightHouseOpenOrClose' in operation.keys():
            offstock = operation['lightHouseOpenOrClose'].split("|")
            for stock in offstock:
                tl = stock.split("=")
                towerLightControl(tl[1],tl[2],tl[0])
                logging.warning("灯塔控制:{},{}.{}".format(tl[0],tl[1],tl[2]))
    if channels:
        channels = set(channels)
        light_led(channels)

def towerLightControl(side, color, onoff):
    #color = color.tolower()
    if side == 'A':
        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']
    driver_gpio.init(pin)
    if onoff=="open":
        driver_gpio.gpio_high(pin)
    else:
        driver_gpio.gpio_low(pin)
    logging.warning("通道:{},状态灯:{} ,pin:{}; onoff:{}".format(side,color,pin,onoff))

def light_led(channels,wait=100):
    global strips
    for _ in range(3):
        for channel in channels:
            strip = strips[channel]
            current_leds = post_leds[channel]
            logging.warning("通道:{},当前开启:{}".format(channel,current_leds))
            for key,value in current_leds.items():
                #c_index=list(map(int,re.split(';',key)))
                #for on_led in c_index:
                #    strip.setPixelColor(on_led, setcolor(value))
                strip.setPixelColor(int(key), setcolor(value))
                logging.warning("通道:{},当前开启:{}".format(channel,key))
            strip.show()
        time.sleep(wait/1000)

@app.route('/startpost',methods=['POST'])
def startpost():
    global is_start
    state = read_state()
    if state != 'on':
        if ip_config['ip'].strip()=='':
            msg = '启动失败'
            current_state = 'off'
            logging.warning("启动失败,没有服务器地址")
        else:
            confirm_state('on')
            is_start = True
            threads = []
            threads.append(threading.Thread(target=serverpost))
            threads.append(threading.Thread(target=blinkLedProcess))
            for t in threads:
                t.start()
            msg = '启动成功'
            current_state = 'on'
            logging.warning("启动成功")
    else:
        msg = '正在运行状态'
        current_state = 'on'
        logging.warning("料架运行中无需重复启动")
    info = []
    c_dict = {'state':current_state,'msg':msg}
    info.append(c_dict)
    return json.dumps(info)

@app.route('/stoppost',methods=['POST'])
def stoppost():
    global is_start
    state = read_state()
    if state != 'off':
        confirm_state('off')
        is_start=False
        # status_light('off')
        reset_strip()
        ip_config['post'] = 'wait'
        logging.warning("关闭成功")
        msg = _('关闭成功')
        current_state = 'off'
    else:
        msg = _('无需关闭')
        current_state = 'off'
        logging.warning("无需关闭")
    info = []
    c_dict = {'state':current_state,'msg':msg}
    info.append(c_dict)
    return json.dumps(info)

def serverpost():
    global is_start
    global post_leds
    global strips
    start_show()
    # 初始化灯条
    for key,value in SET_LED_CHANNEL.items():
        strips[key] = get_strip(value)
    seq = 1
    while is_start:
        try:
            post(seq)
            check_leds()
            seq+=1
            time.sleep(1)
        except Exception as e:
            logging.warning("执行错误:{}".format(e))
def blinkLedProcess():
    global is_start
    global strips
    global blink_led
    try:
        if strips is not None and len(strips)==2:
            with blink_lock:
                to_remove = []
                for channel, leds in blink_led.items():
                    strip = strips[channel]
                    for ledindex, config in leds.items():
                        if not toggle_led_state(channel, ledindex,config):
                            to_remove.append((channel, ledindex))
                    strip.show()
                # 统一移除结束闪烁的LED
                for channel, ledindex in to_remove:
                    del blink_led[channel][ledindex]
                    logging.warning("删除结束闪烁LED: channel={}, ledindex={}".format(channel, ledindex))
    except Exception as e:
        logging.warning("blinkLedProcess执行错误:{}".format(e))
    finally:
    # 重新设置定时器,每333毫秒执行一次
        if is_start:
            threading.Timer(0.333, blinkLedProcess).start()

from datetime import datetime
def toggle_led_state(channel, ledindex ,led_config):
    global strips
    strip = strips[channel]
    #led_config = blink_led[channel][ledindex]
    led_config['waittimecount'] -= 333  # 每次执行减去333毫秒
    if led_config['waittimecount'] > 0:
        led_config['state'] = not led_config['state']  # 切换状态
        color = led_config['color']
        if not led_config['state']:
            color='off'
        now = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
        print(f"{now} 通道:{channel}, POSID:{led_config['posid']} LED索引:{ledindex}, 颜色:{led_config['color']}, 状态:{'开' if led_config['state'] else '关'}, 剩余:{led_config['waittimecount']}")
        strip.setPixelColor(ledindex, setcolor(color))
        return True
    if led_config['waittimecount'] <= 0:
        color='off'
        now = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
        logging.warning(f"{now} 最后一次通道:{channel}, POSID:{led_config['posid']} LED索引:{ledindex}, 颜色:{led_config['color']}, 状态:'关'")
        strip.setPixelColor(ledindex, setcolor(color))
        return False

def check_leds():
    if hasattr(Config, 'TOWER_CUSTCONTROL') and Config.TOWER_CUSTCONTROL:
        return
    if shelfconfig.TOWER_CUSTCONTROL==1:
        return

    global post_leds
    global statusgreenA
    global statusgreenB
    for channel,leds in post_leds.items():
        if leds:
            if channel == '1' and not statusgreenA:
                statusgreenA = True
                driver_gpio.init(SET_CHANNEL['yellowA'])
                driver_gpio.gpio_high(SET_CHANNEL['yellowA'])
                logging.warning("A面黄状态灯开启")
            elif channel == '2' and not statusgreenB:
                statusgreenB = True
                driver_gpio.init(SET_CHANNEL['yellowB'])
                driver_gpio.gpio_high(SET_CHANNEL['yellowB'])
                logging.warning("B面黄状态灯开启")
        else:
            if channel == '1' and statusgreenA:
                statusgreenA = False
                driver_gpio.init(SET_CHANNEL['yellowA'])
                driver_gpio.gpio_low(SET_CHANNEL['yellowA'])
                logging.warning("A面黄状态灯关闭")
            elif channel == '2' and statusgreenB:
                statusgreenB = False
                driver_gpio.init(SET_CHANNEL['yellowB'])
                driver_gpio.gpio_low(SET_CHANNEL['yellowB'])
                logging.warning("B面黄状态灯关闭")


def start_show(wait=10):
    if hasattr(Config, 'TOWER_CUSTCONTROL') and Config.TOWER_CUSTCONTROL:
        return
    if shelfconfig.TOWER_CUSTCONTROL==1:
        return
    global post_leds
    pin1,pin2 = SET_LED_CHANNEL['1'],SET_LED_CHANNEL['2']
    strip1 = get_strip(pin1)
    colorWipe(strip1,Color(255,0,0))
    time.sleep(1)
    colorWipe(strip1,Color(0,255,0))
    time.sleep(1)
    colorWipe(strip1,Color(0,0,255))
    time.sleep(1)
    colorWipe(strip1,Color(0,0,0))
    time.sleep(1)
    strip2 = get_strip(pin2)
    colorWipe(strip2,Color(255,0,0))
    time.sleep(1)
    colorWipe(strip2,Color(0,255,0))
    time.sleep(1)
    colorWipe(strip2,Color(0,0,255))
    time.sleep(1)
    colorWipe(strip2,Color(0,0,0))
    time.sleep(1)
    driver_gpio.init(SET_CHANNEL['greenA'])
    driver_gpio.init(SET_CHANNEL['greenB'])
    driver_gpio.gpio_high(SET_CHANNEL['greenA'])
    driver_gpio.gpio_high(SET_CHANNEL['greenB'])



@app.route('/getstate',methods=['POST'])
def getstate():
    current_state = read_state()
    state_info = []
    version = read_version()
    c_dict = {'state':current_state,'msg':_('未进行测试动作'),'ipconfig':ip_config,'version':version}
    state_info.append(c_dict)
    return json.dumps(state_info)

@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)
    poststate = ip_config['post']
    jsondata = {'msg':p,'poststate':poststate}
    return json.dumps(jsondata)

@app.route('/updateip',methods=['POST'])
def updateip():
    data = request.get_json()
    confirm_ip(data)
    logging.warning("ip&cid:{}".format(ip_config))
    ip_info = []
    ip_info.append(ip_config)
    return json.dumps(ip_info)

def colorWipe(strip, color):
    """一次擦除显示像素的颜色."""
    for i in range(strip.numPixels()):
        strip.setPixelColor(i, color)
    strip.show()

def reset_strip():
    global post_leds
    for channel,strip in strips.items():
        colorWipe(strip,Color(255,255,0))
        time.sleep(1)
        colorWipe(strip,Color(0,0,0))
        post_leds[channel] = {}
        time.sleep(1)
    check_leds()




# 开机启动请求服务器动作
'''
state = read_state()
if state == 'off':
    confirm_state('on')
is_start = True
threads = []
# threads.append(threading.Thread(target=light_led1))
threads.append(threading.Thread(target=serverpost))
for t in threads:
    t.start()
'''