post.py
13.9 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
# 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__)
statusgreenA = False
statusgreenB = False
post_leds = {'1':{},'2':{}}
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 + Config.STATE_PATH
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'] + '/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 post(seq):
headers = {'content-type': "application/json"} #请求头信息
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")
print (response.json())
ele_json = response.json()
ip_config['post'] = 'success'
resolve_data(ele_json)
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_leds
if len(single) == 1:
post_leds[channel][led_index] = Config.DEFAULT_COLOR
logging.warning("库位灯开启:{},灯索引:{},颜色:red".format(single[0],led_index))
elif len(single) == 2:
post_leds[channel][led_index] = single[1]
logging.warning("库位灯开启:{},灯索引:{},颜色:{}".format(single[0],led_index,single[1]))
else:
post_leds[channel][led_index] = single[1] + '@blink'
logging.warning("库位灯开启闪烁:{},灯索引:{},颜色:{}".format(single[0],led_index,single[1]))
def process_off_post(single,channel,led_index):
global post_leds
global strips
post_leds[channel].pop(led_index, None)
strip = strips[channel]
c_index=list(map(int,re.split(';',led_index)))
for on_led in c_index:
strip.setPixelColor(on_led, setcolor('off'))
# strip.setPixelColor()
logging.warning("库位灯关闭:{},灯索引:{}".format(single[0],led_index))
def process_closeall_post():
global post_leds
global strips
for channel,strip in strips.items():
colorWipe(strip,Color(0,0,0))
for key in post_leds.keys():
post_leds[key] = {}
def resolve_data(datajson):
global post_leds
operation=datajson['data']
# operation = {'open':'1_1_1=red|1_1_2=blue|1_1_3=red|2_1_1=green'}
channels = []
if operation:
if 'open' in operation.keys():
openstock=operation['open'].split("|")
for stock in openstock:
single=stock.split("=")
if config_dict.get(single[0]):
channel = config_dict.get(single[0]).split('@')[1]
led_index = config_dict.get(single[0]).split('@')[0]
process_open_post(single,channel,led_index)
if channel not in channels:
channels.append(channel)
else:
logging.warning("未找到库位:{}".format(config_dict.get(single[0])))
logging.warning("库位灯有open指令")
if 'close' in operation.keys():
offstock = operation['close'].split("|")
for stock in offstock:
single = stock.split("=")
if config_dict.get(single[0]):
channel = config_dict.get(single[0]).split('@')[1]
led_index = config_dict.get(single[0]).split('@')[0]
process_off_post(single,channel,led_index)
if channel not in channels:
channels.append(channel)
else:
logging.warning("未找到库位:{}".format(config_dict.get(single[0])))
logging.warning("库位灯有关闭指令")
if 'closeAll' in operation.keys():
process_closeall_post()
# for k in post_leds.keys():
# if k not in channels:
# channels.append(k)
logging.warning("所有库位灯关闭")
if channels:
light_led(channels)
def light_led(channels,wait=50):
global strips
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.show()
time.sleep(wait/1000)
@app.route('/startpost',methods=['POST'])
def startpost():
global is_start
state = read_state()
if state == 'off':
confirm_state('on')
is_start = True
threads = []
threads.append(threading.Thread(target=serverpost))
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
global statusgreenA
global statusgreenB
state = read_state()
if state == 'on':
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 check_leds():
global post_leds
global statusgreenA
global statusgreenB
for channel,leds in post_leds.items():
if leds:
if channel == '1' and not statusgreenA:
statusgreenA = True
t = threading.Thread(target=deal_with_greenA)
t.start()
logging.warning("A面绿状态灯开启闪烁")
elif channel == '2' and not statusgreenB:
statusgreenB = True
t = threading.Thread(target=deal_with_greenB)
t.start()
logging.warning("B面绿状态灯开启闪烁")
else:
if channel == '1' and statusgreenA:
statusgreenA = False
logging.warning("A面绿状态灯停止闪烁")
elif channel == '2' and statusgreenB:
statusgreenB = False
logging.warning("B面绿状态灯停止闪烁")
# def deal_with_red():
# pass
def deal_with_greenA():
global statusgreenA
driver_gpio.init(SET_CHANNEL['greenA'])
while statusgreenA:
driver_gpio.gpio_high(SET_CHANNEL['greenA'])
time.sleep(1)
driver_gpio.gpio_low(SET_CHANNEL['greenA'])
time.sleep(1)
driver_gpio.gpio_high(SET_CHANNEL['greenA'])
def deal_with_greenB():
global statusgreenB
driver_gpio.init(SET_CHANNEL['greenB'])
while statusgreenB:
driver_gpio.gpio_high(SET_CHANNEL['greenB'])
time.sleep(1)
driver_gpio.gpio_low(SET_CHANNEL['greenB'])
time.sleep(1)
driver_gpio.gpio_high(SET_CHANNEL['greenB'])
def start_show(wait=10):
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()
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)
# 开机启动请求服务器动作
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()
logging.warning("启动成功")