#!/usr/bin/env python3 from flask import Flask, request, jsonify from werkzeug.utils import secure_filename app = Flask(__name__) import threading import tkinter as tk from tkinter import * from tkinter import messagebox import matplotlib matplotlib.use('TkAgg') from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk#, NavigationToolbar2TkAgg from matplotlib.figure import Figure import matplotlib.animation as animation from matplotlib import style import numpy as np import os.path import os import random from datetime import datetime as t import socket import fcntl import struct import time import gc import sys style.use("ggplot") #listboxDevices = 0 time.sleep(0.5) selectedItem = "" class values: gasSGP = 0 gasBME = 0 tempBME = 0 humBME = 0 presBME = 0 class jsonContentTeds: nodeMac = "" nodeTime = "" nodePrefix = "BAM" nodeDescription = "" #nodeManufacture = "SENS" #nodeVersion = "A" nodeSerialnr = "" nodeQuantity = "2" class jsonContentIndex: mac = 0 sensor = 0 time = 0 data = 0 nodeList = [] ##flask SERVER begin ##sTEDS JSON func @app.route('/steds', methods=['GET', 'POST']) def indexSteds(): pass time.sleep(0.5) ##main JSON func @app.route('/', methods=['GET', 'POST']) def index(): content = request.json nodeSerialnr = jsonContentIndex.mac if content: jsonContentIndex.mac = content['mac'] jsonContentTeds.nodeMac = jsonContentIndex.data jsonContentIndex.sensor = content['sensor'] jsonContentTeds.nodeTime = content['time'] values.time = jsonContentIndex.data jsonContentIndex.data = content['gasSGP'] values.gasSGP = jsonContentIndex.data jsonContentIndex.data = content['gasBME'] values.gasBME = jsonContentIndex.data jsonContentIndex.data = content['tempBME'] values.tempBME = jsonContentIndex.data jsonContentIndex.data = content['humBME'] values.humBME = jsonContentIndex.data jsonContentIndex.data = content['presBME'] values.presBME = jsonContentIndex.data jsonContentTeds.nodeDescription = jsonContentIndex.sensor jsonContentTeds.nodeManufacture = jsonContentTeds.nodePrefix jsonContentTeds.nodeQuantity = "5" #print(mac) #print(sensor) #print(time) #print(gasSGP) #print(gasBME) #print(tempBME) #print(humBME) #print(presBME) file_path = "/home/rpi/Desktop/Multisensor/" + str(jsonContentIndex.mac) currentT = t.now().strftime('%H:%M:%S') currentD = t.today().strftime('%Y/%m/%d') locTimeDate = str(currentD) + "\t" + str(currentT) stringCont = str(locTimeDate) + "\t" + str(values.gasSGP) + "\t" + str(float(values.gasBME)) + "\t" + str(values.tempBME) + "\t" + str(values.humBME) + "\t" + str(values.presBME) newMeasurements(file_path, stringCont) # remove any config files, if they may exist return jsonify({'mgs': "data received"}) #class network(threading.Thread): # def __init__(self): # threading.Thread.__init__(self) # self.daemon=True # self.start() # def run(self): # index() ##flask SERVER ende class helperInfo(): def __init__(self): ##Infocontent self.autor = "Autor: M.Eng. S. Johann" self.email = "Email: Sergej.Johann@bam.de" self.company = "Company: BAM" self.date = "Date: 06.2020" self.versionInfo = "Version: " + str(0.10) self.cpuTemp = 0 self.rPiCpuTemp = 0 self.tempInfo = "" self.apIpInfo = "" self.apIpInfo = "" def get_net_ip(self, ifname): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', bytes(ifname[:15], 'utf-8')))[20:24]) def action_get_info_dialog(self): #About tempFile = open("/sys/class/thermal/thermal_zone0/temp") cpuTemp = tempFile.read() tempFile.close() self.rPiCpuTemp = float(cpuTemp)/1000 self.tempInfo = "CPU Temp: " + str(self.rPiCpuTemp) + " °C" self.apIpInfo = "AaccesPoint IP: " + self.get_net_ip('wlan0') m_text = self.autor + "\n" + self.email + "\n" + self.company + "\n" + self.date + "\n" + self.versionInfo + "\n\n" + self.apIpInfo + "\n" + self.tempInfo + "\n" messagebox.showinfo(message=m_text, title="About") def exit_action(self): os._exit(1) def button_action(self): #Application print("Menubutton was klicked") #def btn_action(self): # print("update") helper = helperInfo() def newMeasurements(fileName, value): #print("filename " + fileName) file = open(fileName, 'a') file.write(value + "\n") file.close() class GUI: #windowW = "800" #windowH = "410" stedsWidth = 12 update = 0 listboxDevices = 0 updateTime = 5000 selectedListItem = "" tick = t.now().second tack = t.now().second def mainWindow(self): self.window = tk.Tk() self.fullScreenState = True self.window.attributes('-fullscreen', self.fullScreenState) self.window.bind("", self.toggleFullScreen) self.window.bind("", self.quitFullScreen) self.window.title("BAM-GTSD v0.10") #self.window.geometry(self.windowW + "x" + self.windowH) def windowContent(self): self.image1 = PhotoImage(file="/home/rpi/Desktop/Multisensor/logo.png") self.panel1 = Label(self.window, image=self.image1) self.panel1.grid(row=0, column=0, sticky=W + E + N + S, padx=3, pady=3) self.lableMacList = Label(self.window, text="Connected Devices").grid(row=1, column=0) self.listboxDevices = Listbox(self.window) self.listboxDevices.grid(row=2, column=0, rowspan=12, sticky=W + E + N + S, padx=2, pady=3) self.yScroll = Scrollbar(master=self.listboxDevices, orient='vertical') self.yScroll.place(x=145, y=0, width=15, height=290) self.listboxDevices.config(yscrollcommand=self.yScroll.set) self.yScroll.config(command=self.listboxDevices.yview) self.listboxDevices.bind('<>', self.selectedDevice) self.lablePrefix = Label(self.window, text="Präfix").grid(row=1, column=1) self.txtNodePrefix = Text(self.window, height=1, width=self.stedsWidth) self.txtNodePrefix.grid(row=2, column=1,) self.lableDescription = Label(self.window, text="Description").grid(row=3, column=1) self.txtNodeDescription = Text(self.window, height=1, width=self.stedsWidth) self.txtNodeDescription.grid(row=4, column=1,) self.lableSerialnr = Label(self.window, text="Serialnumber").grid(row=5, column=1) self.txtNodeSerialnr = Text(self.window, height=1, width=self.stedsWidth) self.txtNodeSerialnr.grid(row=6, column=1,) self.lableQuantity = Label(self.window, text="Sensorquantity").grid(row=7, column=1) self.txtNodeQuantity = Text(self.window, height=1, width=self.stedsWidth) self.txtNodeQuantity.grid(row=8, column=1,) self.lableIAQ = Label(self.window, text="IAQ").grid(row=9, column=1) self.txtNodeIAQ = Text(self.window, height=1, width=self.stedsWidth) self.txtNodeIAQ.grid(row=10, column=1,) self.lableTemp = Label(self.window, text="Temp/Hum").grid(row=11, column=1) self.txtNodeTemp = Text(self.window, height=1, width=self.stedsWidth) self.txtNodeTemp.grid(row=12, column=1,) #self.btnUpdate = Button(self.window, text = "Update", command=helper.btn_action).grid(row=13, column=1) # create menue self.menuleiste = Menu(self.window) # Menü Datei und Help erstellen self.datei_menu = Menu(self.menuleiste, tearoff=0) self.help_menu = Menu(self.menuleiste, tearoff=0) self.time_menu = Menu(self.menuleiste, tearoff=0) # Beim Klick auf Datei oder auf Help sollen nun weitere Einträge erscheinen. # Diese werden also zu "datei_menu" und "help_menu" hinzugefügt self.datei_menu.add_command(label="Execute", command=helper.button_action) self.datei_menu.add_separator() # Fügt eine Trennlinie hinzu self.datei_menu.add_command(label="Exit", command=helper.exit_action) self.help_menu.add_command(label="About", command=helper.action_get_info_dialog) # Nun fügen wir die Menüs (Datei und Help) der Menüleiste als # "Drop-Down-Menü" hinzu self.menuleiste.add_cascade(label="File", menu=self.datei_menu) self.menuleiste.add_cascade(label="Help", menu=self.help_menu) # Die Menüleiste mit den Menüeinrägen noch dem Fenster übergeben self.window.config(menu=self.menuleiste) self.window.after(self.updateTime, self.update) #time in ms self.window.mainloop() def update(self): ##current date time begin #selectItem = selectedItem selectItem = self.listboxDevices.get(0) #print("list " + selectItem) if selectItem != "": file_path = "/home/rpi/Desktop/Multisensor/" + str(selectItem) fileExist = os.path.exists(file_path) if fileExist == True: #if 1 == 2: y = [] gas1 = [] gas2 = [] temp = [] hum = [] pres = [] self.fig = Figure(figsize=(5.3, 4), facecolor="white") self.axis = self.fig.add_subplot(111) self.axis.clear() self.axis.set_title("Measurements " + selectItem) self.axis.set_xlabel('count') self.axis.set_ylabel('amplitude') self.axis2 = self.axis.twinx() self.axis2.set_xlabel('count') self.axis2.set_ylabel('amplitude') #v = np.loadtxt(file_path, delimiter="\t") v = np.genfromtxt(fname=file_path, delimiter="\t") for line in v: gas1.append(line[2]) gas2.append(line[3]) temp.append(line[4]) hum.append(line[5]) pres.append(line[6]) self.y = np.arange(0, v.size/7) self.axis.plot(self.y, gas1, color='yellow', label="IAQ") self.axis.plot(self.y, gas2, color='green', label="VOC") self.axis2.plot(self.y, temp, color='red', label="Temp") self.axis2.plot(self.y, hum, color='blue', label="Hum") #axis.plot(y, pres, color='brown', label="Pres") leg = self.axis.legend(loc='center left', frameon=True) leg2 = self.axis2.legend(loc='center right', frameon=True) #axis.grid() self.txtNodePrefix.delete("1.0", "end") self.txtNodePrefix.insert(END, jsonContentTeds.nodePrefix) self.txtNodeDescription.delete("1.0", "end") self.txtNodeDescription.insert(END, jsonContentTeds.nodeDescription) self.txtNodeIAQ.delete("1.0", "end") self.txtNodeIAQ.insert(END, values.gasSGP) self.txtNodeTemp.delete("1.0", "end") self.txtNodeTemp.insert(END, values.tempBME + " / " + values.humBME) self.txtNodeSerialnr.delete("1.0", "end") self.txtNodeSerialnr.insert(END, str("BAM-" + selectItem)) self.txtNodeQuantity.delete("1.0", "end") self.txtNodeQuantity.insert(END, jsonContentTeds.nodeQuantity) del v, y, gas1, gas2, temp, hum, pres gc.collect() self.updateDiagramm(self.fig, selectItem) else: print("no file") if (t.now().second - self.tick) >= 1: currentT = t.now().strftime('%H:%M:%S') currentD = t.today().strftime('%Y/%m/%d') locTimeDate = str(currentD) + "\n" + str(currentT) locTime = Label(self.window, text=locTimeDate).grid(row=0, column=1) else: self.tick = t.now().second ##current date time end if jsonContentIndex.mac != 0: if len(jsonContentIndex.nodeList) == 0: jsonContentIndex.nodeList.append(jsonContentIndex.mac) self.listboxDevices.insert(END, jsonContentIndex.mac) #print('node1') else: if jsonContentIndex.mac not in jsonContentIndex.nodeList: jsonContentIndex.nodeList.append(jsonContentIndex.mac) self.listboxDevices.insert(END, jsonContentIndex.mac) #print('node2') self.window.after(self.updateTime, self.update) #time in ms def toggleFullScreen(self, event): self.fullScreenState = not self.fullScreenState self.window.attributes('-fullscreen', self.fullScreenState) def quitFullScreen(self, event): self.fullScreenState = False self.window.attributes('-fullscreen', self.fullScreenState) def updateDiagramm(self, fig, file_path): canvas = FigureCanvasTkAgg(fig, master=self.window) canvas._tkcanvas.grid(row=0, column=2, rowspan=14, sticky=W + E + N + S, padx=3, pady=3) def selectedDevice(self, event): selectList = self.listboxDevices.curselection() selectItem = selectList[0] selectDevice = self.listboxDevices.get(selectItem) global selectedItem selectedItem = selectDevice self.selectedListItem = selectDevice print("selected " + selectedItem) class visualisation(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.daemon=True self.start() def run(self): app = GUI() app.mainWindow() app.windowContent() t1 = visualisation() #t2 = network() if __name__ == '__main__': #time.sleep(2) app.run(debug=False, host='0.0.0.0') t1.join() #t2.join()