Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from pymodbus.client.sync import ModbusSerialClient
- from pymodbus.exceptions import ModbusIOException
- import PySimpleGUI as sg
- from serial.tools.list_ports import comports
- from os.path import isfile
- import time
- import datetime
- import csv
- import threading
- import random
- from vis1 import GRAPH_SIZE
- readings = dict()
- readings_lock = threading.Lock()
- _fieldnames = [
- "Time", "Operating Frequency", "Operating Mode", "Fan Speed", "PMV openness", "Water inlet temp",
- "Water outlet temp", "T3 temp", "T4 temp", "Discharge temp", "Return air temp", "T1", "T1B",
- "T2", "T2B", "Ta", "T5", "Pressure 1", "Pressure 2", "Outdoor uint current", "Outdoor unit voltage",
- "Hydraulic module current 1", "Hydraulic module current 2", "Compressor operating time", "Reserved", "Current fault",
- "Fault 1", "Fault 2", "Fault 3"]
- _fieldsGraphed = ("T1", "Pressure 1")
- GRAPH_SIZE = (500, 250)
- GRAPH_STEP_SIZE = 5
- DELAY = 5000
- def reallyExit():
- layout = [[sg.Text("Do you really wish to exit?")], [
- sg.Button("No"), sg.Button("Yes")]]
- window = sg.Window("HMPL", layout)
- while True:
- event, _ = window.read()
- if event == sg.WIN_CLOSED or event == 'No':
- window.close()
- return
- elif event == "Yes":
- exit()
- def writeToFile(dir, dict):
- if isfile(dir):
- with open(dir, 'a', encoding='UTF8', newline='') as f:
- writer = csv.DictWriter(f, fieldnames=_fieldnames)
- writer.writerow(dict)
- else:
- with open(dir, 'w', encoding='UTF8', newline='') as f:
- writer = csv.DictWriter(f, fieldnames=_fieldnames)
- writer.writeheader()
- writer.writerow(dict)
- def dispErr(msg):
- layout = [[sg.Text("ERROR")], [sg.Text(msg)], [sg.Button("Close")]]
- window = sg.Window("HMPL", layout)
- while True:
- event, _ = window.read()
- if event == sg.WIN_CLOSED or event == 'Close':
- exit()
- def dispWar(msg):
- layout = [[sg.Text("ERROR")], [sg.Text(msg)], [sg.Button("Continue")]]
- window = sg.Window("HMPL", layout)
- while True:
- event, _ = window.read()
- if event == 'Continue':
- window.close()
- return
- # Selecting comport and connecting
- sg.change_look_and_feel("Dark")
- a = [comport.device for comport in comports()]
- layout = [[sg.Text("WELCOME TO HPML!")],
- [sg.InputCombo(values=a), sg.Button("Refresh")],
- [sg.InputText('filename'), sg.Text(".csv")],
- [sg.Button("CONNECT")]]
- window = sg.Window("HMPL", layout)
- while True:
- event, values = window.read()
- if event == sg.WIN_CLOSED:
- reallyExit()
- elif event == 'CONNECT':
- break
- elif event == 'Refresh':
- a = [comport.device for comport in comports()]
- window.close()
- dat = values[1] + ".csv"
- print(dat)
- client = ModbusSerialClient(
- method='rtu',
- port=values[0],
- baudrate=9600,
- timeout=1,
- parity='N',
- stopbits=1,
- bytesize=8
- )
- def _mainLoop():
- global readings
- try:
- while True:
- if client.connect(): # Trying to connect to Modbus Server/Slave
- with readings_lock:
- readings["Time"] = datetime.datetime.now()
- print("Client connected, reading")
- rr = client.read_holding_registers(
- address=100, count=28, unit=1)
- for i, name in enumerate(_fieldnames[1:]):
- if type(rr) == ModbusIOException:
- readings[name] = "/"
- else:
- readings[name] = str(rr.registers[i])
- print("Reading complete, writing to file " + dat)
- writeToFile(dat, readings)
- time.sleep(5)
- else:
- e = 'Cannot connect to the Modbus Server/Slave'
- print(e)
- dispWar(e)
- except Exception as ex:
- template = "An exception of type {0} occurred. Arguments:\n{1!r}"
- message = template.format(type(ex).__name__, ex.args)
- print(message)
- dispErr(message)
- def mainLoop():
- try:
- while True:
- with readings_lock:
- readings["Time"] = datetime.datetime.now()
- print("Client connected, reading")
- for i, name in enumerate(_fieldnames[1:]):
- readings[name] = str(random.randint(10, 250))
- print("Reading complete, writing to file " + dat)
- writeToFile(dat, readings)
- time.sleep(1)
- except Exception as ex:
- template = "An exception of type {0} occurred. Arguments:\n{1!r}"
- message = template.format(type(ex).__name__, ex.args)
- print(message)
- dispErr(message)
- def graph():
- lastval = dict()
- l = [[sg.Text("GRAPHS", font=(None, 14))]]
- x = 0
- for field in _fieldsGraphed:
- lastval[field] = (0, 0)
- l.append([sg.Graph(GRAPH_SIZE, (0, 0), GRAPH_SIZE,
- key='-GRAPH-' + field, background_color='white',)])
- w = sg.Window("Graf", l, resizable=True, element_justification='c', disable_close=True)
- print("GRAPHS: init done")
- while True:
- eve, _ = w.read(timeout=DELAY)
- print("GRAPHS: instide endless loop")
- for field in _fieldsGraphed:
- print("GRAPHS: field: " + field)
- #Display a graph that moves in chronological order
- step_size = GRAPH_STEP_SIZE
- with readings_lock:
- print("GRAPHS: got readings lock for myself")
- y = readings[field]
- if x < GRAPH_SIZE[0]: #First time
- # window['-GRAPH-'].DrawLine((lastx, lasty), (x, y), width=1)
- w["-GRAPH-" + field].DrawLine((lastval[field][0], lastval[field][1]), (x, y), width=1)
- else:
- # window['-GRAPH-'].Move(-step_size, 0) #Shift the entire graph to the left
- # window['-GRAPH-'].DrawLine((lastx, lasty), (x, y), width=1)
- w["-GRAPH-"].Move(-step_size, 0) #Shift the entire graph to the left
- w["-GRAPH-"].DrawLine((lastval[field][0], lastval[field][1]), (x, y), width=1)
- x -= step_size
- lastval[field][0], lastval[field][1] = x, y
- x += step_size
- text_size = 13
- third = ((len(_fieldnames)-1)//3) + 1
- col1 = list()
- col2 = list()
- col3 = list()
- for i, name in enumerate(_fieldnames[1:]):
- l = [[sg.Text("/", key=name, font=(None, text_size+2))]]
- if i % 3 == 0:
- col1.append([sg.Frame(name + ": ", l, element_justification='c')])
- elif i % 3 == 1:
- col2.append([sg.Frame(name + ": ", l, element_justification='c')])
- else:
- col3.append([sg.Frame(name + ": ", l, element_justification='c')])
- layout = [
- [sg.Text("CONNECTED", font=(None, text_size))],
- [sg.Column(col1, element_justification='c'), sg.Column(
- col2, element_justification='c'), sg.Column(col3, element_justification='c')],
- [sg.Button("Close", font=(None, text_size))],
- ]
- window = sg.Window("HMPL", layout, resizable=True, element_justification='c',
- location=(0, 0), disable_close=True, ).Finalize()
- thread = threading.Thread(target=mainLoop)
- thread.daemon = True
- thread.start()
- thread = threading.Thread(target=graph)
- thread.daemon = True
- thread.start()
- while True:
- event, values = window.read(timeout=500)
- if event == "Close":
- reallyExit()
- if not readings_lock.locked():
- with readings_lock:
- for name in _fieldnames[1:]:
- window[str(name)].update(readings[name])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement