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
# 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
from app.routes import config_dict,SET_CHANNEL,SET_LED_CHANNEL
from app import driver_gpio
import logging
import random

basepath = os.path.dirname(__file__)
post_led_lights1 = {}
post_led_lights2 = {}
# test_data = {'data':{'open':'1_1_1=red','statusLight':'red=twinkle'}}
statuslight = False
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 confirm_redlight(state):
    uploads_path = basepath + Config.STATE_PATH
    with open(uploads_path + "redlight.txt","w") as f:
        f.write(state)
def read_redlight():
    uploads_path = basepath + Config.STATE_PATH
    with open(uploads_path + "redlight.txt","r") as f:
        state=f.readline()
    return state

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'] + '/accshelf/' + ip_config['cid']
    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('xxx')   
        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('xxx')   
        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

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

def post(seq):
    headers = {'content-type': "application/json"} #请求头信息
    # URL = 'http://192.168.1.100:8080/service/store/communication'
    # url = 'http://' + ip_config['ip'] + ':8080/service/store/communication'
    # url = 'http://' + ip_config['ip'] + '/myproject/service/store/communication'
    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)
        # response = requests.post("http://jsonplaceholder.typicode.com/posts", data = "some dummy content")
        ele_json = response.json()
        resolve_data(ele_json)
        ip_config['post'] = 'success'
        if ele_json['data']:
            logging.warning("服务器发送数据:{}".format(ele_json['data']))
    except Exception as e:
        ip_config['post'] = 'failed'
        logging.warning("请求服务器失败:{}".format(e))


def process_open_post(single,channel,led_index):
    global post_led_lights1
    global post_led_lights2
    if channel == '1':
        if len(single) == 1:
            post_led_lights1[led_index] = Config.DEFAULT_COLOR
            logging.warning("库位灯开启:{},灯索引:{},颜色:red".format(single[0],led_index))
        elif len(single) == 2:
            post_led_lights1[led_index] = single[1]
            logging.warning("库位灯开启:{},灯索引:{},颜色:{}".format(single[0],led_index,single[1]))
        else:
            post_led_lights1[led_index] = single[1] + '@blink'
            # blink_led1[led_index] = single[1]
            logging.warning("库位灯开启闪烁:{},灯索引:{},颜色:{}".format(single[0],led_index,single[1]))
    else:
        if len(single) == 1:
            post_led_lights2[led_index] = Config.DEFAULT_COLOR
        elif len(single) == 2:
            post_led_lights2[led_index] = single[1]
        else:
            post_led_lights2[led_index] = single[1] + '@blink'

def process_off_post(single,channel,led_index):
    global post_led_lights1
    global post_led_lights2
    if channel == '1':
        # if led_index in post_led_lights1.keys():
        post_led_lights1[led_index] = 'off'
        logging.warning("库位灯关闭:{},灯索引:{}".format(single[0],led_index))
    else:
        post_led_lights2[led_index] = 'off'
        logging.warning("库位灯关闭:{},灯索引:{}".format(single[0],led_index))

def process_closeall_post():
    global post_led_lights1
    global post_led_lights2
    for led_index in post_led_lights1.keys():
        post_led_lights1[led_index] = 'off'


def resolve_data(datajson):
    global post_led_lights1
    global post_led_lights2
    global statuslight
    operation=datajson['data']
    # if operation:
    if 'open' in operation.keys():
        openstock=operation['open'].split("|")
        for stock in openstock:
            single=stock.split("=")
            channel = config_dict.get(single[0]).split('@')[1]
            led_index = config_dict.get(single[0]).split('@')[0]
            process_open_post(single,channel,led_index)
        logging.warning("库位灯有open指令")
    if 'close' in operation.keys():
        offstock = operation['close'].split("|")
        for stock in offstock:
            single = stock.split("=")
            channel = config_dict.get(single[0]).split('@')[1]
            led_index = config_dict.get(single[0]).split('@')[0]
            process_off_post(single,channel,led_index)
        logging.warning("库位灯有关闭指令")
    if 'closeAll' in operation.keys():
        process_closeall_post()
        # post_led_lights1 = {}
        # post_led_lights2 = {}
        logging.warning("所有库位灯关闭")
    if 'statusLight' in operation.keys():
        color = operation['statusLight']
        if ip_config['redlight'] == 'on':
            if 'red=twinkle' in color and not statuslight:
                statuslight = True
                t = threading.Thread(target=deal_with_redblink)
                t.start()
                logging.warning("红色状态灯开启闪烁")
    if 'statusLight' not in operation.keys():
        if statuslight:
            statuslight = False
            logging.warning("红色状态灯关闭闪烁")
            # elif color == 'green':
            #     pass
            # else:
            #     pass
    # return show_channel_1,show_channel_2
    # 

@app.route('/startpost',methods=['POST'])
def startpost():
    global is_start
    state = read_state()
    if state == 'off':
        confirm_state('on')
        is_start = True
        driver_gpio.init(SET_CHANNEL['green'])
        driver_gpio.gpio_high(SET_CHANNEL['green'])
        threads = []
        threads.append(threading.Thread(target=light_led1))
        # threads.append(threading.Thread(target=set_working_light1))
        threads.append(threading.Thread(target=serverpost))
        for t in threads:
            t.start()
        msg = '启动成功'
        current_state = 'on'
        logging.warning("启动成功")
        logging.warning("ip&cid:{}".format(ip_config))
    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
    global statuslight
    state = read_state()
    if state == 'on':
        confirm_state('off')
        # driver_gpio.init(SET_CHANNEL['green'])
        # driver_gpio.gpio_low(SET_CHANNEL['green'])
        is_start=False
        statuslight = False
        reset_strip1()
        off_working_light1()
        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
    seq = 1
    while is_start:
        post(seq)
        seq+=1
        time.sleep(1)
    # print ("关闭后执行")

@app.route('/getstate',methods=['POST'])
def getstate():
    current_state = read_state()
    state_info = []
    version = read_version()
    redlight = read_redlight()
    c_dict = {'state':current_state,'msg':'未进行测试动作','ipconfig':ip_config,'version':version,'redlight':redlight}
    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)

@app.route('/redconfig',methods=['POST'])
def redconfig():
    global statuslight
    data = request.get_json()
    redlight = data.get('redlight','')
    if redlight == 'off':
        statuslight = False
    ip_config['redlight'] = redlight
    confirm_redlight(redlight)
    logging.warning("ip&cid:{}".format(ip_config))
    ip_info = []
    ip_info.append(ip_config)
    return json.dumps(ip_info)

@app.route('/jump',methods=['POST'])
def jump():
    server_add = ip_config['ip'] + '/accshelf/' + ip_config['cid']
    logging.warning("打开链接:{}".format(server_add))
    add = {'server_add':server_add}
    return json.dumps(add)

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



def reset_strip1():
    global post_led_lights1
    pin = SET_LED_CHANNEL['1']
    strip1 = get_strip(pin)
    colorWipe(strip1,Color(255,255,0))
    time.sleep(1)
    colorWipe(strip1,Color(0,0,0))
    time.sleep(0.02)
    post_led_lights1 = {}

def wheel1(pos,color):
    color = color.lower()
    if color == 'red':
        if pos == 0:
            return Color(0,0,0)
        else:
            return Color(0,255,0)
    elif color == 'green':
        if pos == 0:
            return Color(0,0,0)
        else:
            return Color(255,0,0)
    elif color == 'yellow':
        if pos == 0:
            return Color(0,0,0)
        else:
            return Color(255,255,0)
    elif color == 'blue':
        if pos == 0:
            return Color(0,0,0)
        else:
            return Color(0,0,255)
    else:
        if pos == 0:
            return Color(0,0,0)
        else:
            return Color(0,255,255)

def setcolor(color):
    color = color.lower()
    if color == 'red':
        return Color(0,255,0)
    elif color == 'green':
        return Color(255,0,0)
    elif color == 'yellow':
        return Color(255,255,0)
    elif color == 'off':
        return Color(0,0,0)
    elif color == 'blue':
        return Color(0,0,255)
    else:
        return Color(0,255,255)

def set_state():
    global post_led_lights1
    all_color = []
    all_blink = []
    for i in post_led_lights1.values():
        if '@' in i:
            all_blink.append(i)
        else:
            all_color.append(i)
    deal_with_yellow(all_color)
    # deal_with_red(all_blink)

def deal_with_yellow(all_color):
    if 'yellow' in all_color or 'green' in all_color:
        driver_gpio.init(SET_CHANNEL['yellow'])
        driver_gpio.gpio_high(SET_CHANNEL['yellow'])
    else:
        driver_gpio.init(SET_CHANNEL['yellow'])
        driver_gpio.gpio_low(SET_CHANNEL['yellow'])

def deal_with_red(all_blink):
    global statuslight
    if not statuslight:
        if all_blink:
            driver_gpio.init(SET_CHANNEL['red'])
            driver_gpio.gpio_high(SET_CHANNEL['red'])
        else:
            driver_gpio.init(SET_CHANNEL['red'])
            driver_gpio.gpio_low(SET_CHANNEL['red'])

def deal_with_redblink():
    global statuslight
    driver_gpio.init(SET_CHANNEL['red'])
    while statuslight:
        driver_gpio.gpio_high(SET_CHANNEL['red'])
        time.sleep(1)
        driver_gpio.gpio_low(SET_CHANNEL['red'])
        time.sleep(1)
        logging.warning("红色状态灯闪烁中...")


def off_working_light1():
    driver_gpio.init(SET_CHANNEL['green'])
    driver_gpio.init(SET_CHANNEL['yellow'])
    driver_gpio.init(SET_CHANNEL['red'])
    driver_gpio.gpio_low(SET_CHANNEL['green'])
    driver_gpio.gpio_low(SET_CHANNEL['yellow'])
    driver_gpio.gpio_low(SET_CHANNEL['red'])


def show1(strip):
    # start = time.clock()
    global post_led_lights1
    current_line = {}
    current_blink = {}
    for key,value in post_led_lights1.items():
        if '@blink' in value:
            current_blink[key] = value.split('@')[0]
        else:
            current_line[key] = value
    # logging.info("current_line:{},current_blink:{}".format(current_line,current_blink))
    if current_line:
        for key,value in current_line.items():
            c_index=list(map(int,re.split(';',key)))
            for on_led in c_index:
                strip.setPixelColor(on_led, setcolor(value))
    if current_blink:
        c_lis = []
        color_liss = []
        for key,value in current_blink.items():
            c_index=list(map(int,re.split(';',key)))
            if len(c_index) > 1:
                color_lis = [value]*len(c_index)
            else:
                color_lis = [value]
            c_lis += c_index
            color_liss += color_lis
        for j in range(2):
            for index,on_led in enumerate(c_lis):
                color = color_liss[index]
                strip.setPixelColor(on_led, wheel1(j,color))
            strip.show()
            time.sleep(0.5)
    strip.show()
    # elapsed = (time.clock() - start)
    # print("Time used:",elapsed)


def light_led1(wait_ms=20):
    global is_start
    pin1,pin2 = SET_LED_CHANNEL['1'],SET_LED_CHANNEL['2']
    strip = get_strip(pin1)
    for i in range(strip.numPixels()):
        strip.setPixelColor(i,Color(255,0,0))
        strip.setPixelColor(i+1,Color(0,255,0))
        strip.show()
        time.sleep(wait_ms/2000)
    colorWipe(strip,Color(0,0,0))
    while is_start:
        # strip = get_strip(pin1)
        try:
            set_state()
            show1(strip)
            time.sleep(wait_ms/50)
            # logging.warning("更新灯条")
        except Exception as e:
            time.sleep(1)
            logging.warning("更新灯条进程错误:{}".format(e))
            

# 开机启动请求服务器动作
redlight = read_redlight()
ip_config['redlight'] = redlight
logging.warning("ip&cid:{}".format(ip_config))
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()
driver_gpio.init(SET_CHANNEL['green'])
driver_gpio.gpio_high(SET_CHANNEL['green'])
logging.warning("启动成功")