communication between server and matrix process working

This commit is contained in:
Neythen 2021-05-01 11:39:20 +01:00
parent 00bf284d33
commit d7c905a339
6 changed files with 123 additions and 39 deletions

BIN
final.ppm

Binary file not shown.

View File

@ -12,9 +12,10 @@ import os
import datetime import datetime
import threading import threading
import csv import csv
import pexpect
from multiprocessing import Process
stock_ticker = StockTicker() from subprocess import Popen, PIPE
#stock_ticker = StockTicker()
command = 300 command = 300
tickerList = 0 tickerList = 0
@ -26,6 +27,13 @@ LOGO_FOLDER = 'logos/'
CSV_FOLDER = 'csv/new/' CSV_FOLDER = 'csv/new/'
ALLOWED_EXTENSIONS = {'csv', 'png'} ALLOWED_EXTENSIONS = {'csv', 'png'}
#ticker.stdin.write(b'from server')
#print(ticker.stdout.readlines())
#(output, errs)
child = pexpect.spawn("sudo -E python3 stockTicker.py")
#stock_ticker = StockTicker()
def allowed_file(filename): def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@ -38,7 +46,7 @@ def process_file(path, filename):
def ShutdownPI(): def ShutdownPI():
print('SHUTTING DOWN') print('SHUTTING DOWN')
os.system("sudo shutdown --poweroff") os.system("sudo shutdown now")
app = Flask(__name__) app = Flask(__name__)
@app.route("/", methods=['GET', 'POST']) @app.route("/", methods=['GET', 'POST'])
@ -128,14 +136,27 @@ def matrix():
global LastCommand global LastCommand
if "Run Display" in request.form: if "Run Display" in request.form:
pass pass
print('run display')
#stock_ticker.runStockTicker(command, DelayTime, speedTime) #stock_ticker.runStockTicker(command, DelayTime, speedTime)
stock_ticker.displayMatrix() #stock_ticker.displayMatrix()
#os.system("sudo -E python3 test.py")
#
#child.sendline('sent from server')
#process = Popen(["sudo", "-E", "python3", "stockTicker.py"], stdin=PIPE, stdout=PIPE, stderr=PIPE)
child.sendline('R')
print('back in flask')
LastCommand = 'Run display' LastCommand = 'Run display'
elif "Stop Display (at next refresh)" in request.form: elif "Stop Display (at next refresh)" in request.form:
pass pass
#ticker.kill()
try: try:
stock_ticker.stopStockTicker() #stock_ticker.stopStockTicker()
LastCommand = 'Stop display at next checkpoint' LastCommand = 'Stop display at next checkpoint'
child.sendline('K')
except: except:
print("none running") print("none running")
elif "Shutdown the pi" in request.form: elif "Shutdown the pi" in request.form:
@ -148,6 +169,6 @@ def matrix():
return hello() return hello()
if __name__ == "__main__": if __name__ == "__main__":
app.run(host='0.0.0.0', port=1024, debug=True) app.run(host='0.0.0.0', port=1024, debug=False) # the debuggger causes flickering
#sudo ./demo -D1 final.ppm -t 50 -m 25 --led-gpio-mapping=adafruit-hat --led-rows=32 --led-cols=256 --led-slowdown-gpio=4 #sudo ./demo -D1 final.ppm -t 50 -m 25 --led-gpio-mapping=adafruit-hat --led-rows=32 --led-cols=256 --led-slowdown-gpio=4

View File

@ -6,7 +6,7 @@
# permission of Daniel Richardson # permission of Daniel Richardson
import sys import sys, select
import os import os
import threading import threading
from PIL import Image, ImageDraw, ImageFont from PIL import Image, ImageDraw, ImageFont
@ -17,6 +17,16 @@ import requests
from rgbmatrix import RGBMatrix, RGBMatrixOptions from rgbmatrix import RGBMatrix, RGBMatrixOptions
import finnhub import finnhub
def getInput(Block=False):
if Block or select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], []):
msg = sys.stdin.read(1)
#sys.stdin.flush()
else:
msg = ''
return msg
class StockTicker(): class StockTicker():
def __init__(self): def __init__(self):
#Define global resources #Define global resources
@ -59,14 +69,14 @@ class StockTicker():
return image return image
def SetImage(self, image, offset_x = 0, offset_y = 0, unsafe=True): def SetImage(self, image, offset_x = 0, offset_y = 0, unsafe=False):
if (image.mode != "RGB"): if (image.mode != "RGB"):
raise Exception("Currently, only RGB mode is supported for SetImage(). Please create images with mode 'RGB' or convert first with image = image.convert('RGB'). Pull requests to support more modes natively are also welcome :)") raise Exception("Currently, only RGB mode is supported for SetImage(). Please create images with mode 'RGB' or convert first with image = image.convert('RGB'). Pull requests to support more modes natively are also welcome :)")
if unsafe: if unsafe:
#In unsafe mode we directly access the underlying PIL image array #In unsafe mode we directly acceshow to send commands to running python processs the underlying PIL image array
#in cython, which is considered unsafe pointer accecss, #in cython, which is considered unsafe pointer accecss,
#however it's super fast and seems to work fine #however it's super fast and seems to work fine
#https://groups.google.com/forum/#!topic/cython-users/Dc1ft5W6KM4 #https://groups.google.com/forum/#!topic/cython-users/Dc1ft5W6KM4
@ -84,7 +94,7 @@ class StockTicker():
for y in range(max(0, -offset_y), min(img_height, self.matrix.height - offset_y)): for y in range(max(0, -offset_y), min(img_height, self.matrix.height - offset_y)):
(r, g, b) = pixels[x, y] (r, g, b) = pixels[x, y]
self.matrix.SetPixel(x + offset_x, y + offset_y, r*brightness, g*brightness, b*brightness) self.matrix.SetPixel(x + offset_x, y + offset_y, r*self.brightness, g*self.brightness, b*self.brightness)
def ScrollImage(self, image_file, offset_x = 0, offset_y = 0, delay = 0.05): def ScrollImage(self, image_file, offset_x = 0, offset_y = 0, delay = 0.05):
@ -102,23 +112,38 @@ class StockTicker():
def ScrollImageTransition(self, image_files, offset_x = 0, offset_y = 0, delay = 0.05): def ScrollImageTransition(self, image_files, offset_x = 0, offset_y = 0, delay = 0.05):
# use two image files and switch between them with a seemless transition # use two image files and switch between them with a seemless transition
current_img = 1 current_img = 1
while True:
#while True:
if current_img == 1: if current_img == 1:
image = self.openImage(image_files[0]) image = self.openImage(image_files[0])
elif current_img == 2: elif current_img == 2:
image = self.openImage(image_files[2]) image = self.openImage(image_files[1])
img_width, img_height = image.size img_width, img_height = image.size
print('hw', img_width, img_height)
print(offset_x, offset_y)
while offset_x > -img_width: while offset_x > -img_width:
offset_x -= 1 offset_x -= 1
self.SetImage(image, offset_x = offset_x, offset_y = offset_y) self.SetImage(image, offset_x = offset_x, offset_y = offset_y)
time.sleep(delay) time.sleep(delay)
try:
if getInput() == 'K':
self.resetMatrix()
break
except KeyboardInterrupt:
sys.stdout.flush()
pass
if current_img == 1: if current_img == 1:
current_img = 2 current_img = 2
elif current_img == 2: elif current_img == 2:
@ -129,6 +154,7 @@ class StockTicker():
#Get the logo from file that is the same as ticker name #Get the logo from file that is the same as ticker name
def getLogo(self, Ticker): def getLogo(self, Ticker):
try: try:
@ -240,6 +266,12 @@ class StockTicker():
print(e) print(e)
self.ApiCalledError = True self.ApiCalledError = True
def resetMatrix(self):
for x in range(self.matrix.width):
for y in range(self.matrix.height):
self.matrix.SetPixel(x , y , 0,0,0)
#Connect all the pieces togeather creating 1 long final stock image #Connect all the pieces togeather creating 1 long final stock image
def GetfullStockImage(self): def GetfullStockImage(self):
@ -341,3 +373,18 @@ class StockTicker():
self.keySwapper = 0 self.keySwapper = 0
self.running = False self.running = False
print('MATRIX DISPLAY STOP CALLED') print('MATRIX DISPLAY STOP CALLED')
if __name__ == '__main__':
#print(sys.stdin.readlines())
stock_ticker = StockTicker()
while True:
msg = getInput()
if msg == 'R':
stock_ticker.displayMatrix()

Binary file not shown.

28
test.py
View File

@ -1,4 +1,4 @@
from twelvedata import TDClient
import sys import sys
import os import os
import threading import threading
@ -10,16 +10,32 @@ from rgbmatrix import RGBMatrix, RGBMatrixOptions
from stockTicker import StockTicker from stockTicker import StockTicker
import finnhub import finnhub
import pexpect
if __name__ == '__main__': if __name__ == '__main__':
stock_ticker = StockTicker() #stock_ticker = StockTicker()
SandboxApiKey = "sandbox_c24qddqad3ickpckgg8g" SandboxApiKey = "sandbox_c24qddqad3ickpckgg8g"
ApiKey = "c24qddqad3ickpckgg80" ApiKey = "c24qddqad3ickpckgg80"
#stock_ticker.runStockTicker('', 1, 1) #stock_ticker.runStockTicker('', 1, 1)
stock_ticker.GetSymbols() #stock_ticker.GetSymbols()
stock_ticker.GetfullStockImage() #stock_ticker.GetfullStockImage()
stock_ticker.ScrollImageTransition(['final.ppm', 'final.ppm'], offset_x = 0, offset_y = 0, delay = 0.02) #stock_ticker.ScrollImageTransition(['final.ppm', 'final.ppm'], offset_x = 0, offset_y = 0, delay = 0.02)
print('hello')
child = pexpect.spawn("sudo -E python3 stockTicker.py")
time.sleep(3)
child.sendline('R')
print('sent stocks')
time.sleep(3)
child.sendline('K')
print('sent kill')
time.sleep(3)
#time.sleep(3)
#child.sendline('stop')
#print('sent stop')
#stock_ticker.displayMatrix()