Advertisement
MyGrandma

Untitled

Feb 9th, 2022
517
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.74 KB | None | 0 0
  1. from pymodbus.client.sync import ModbusSerialClient
  2. from pymodbus.exceptions import ModbusIOException
  3. import PySimpleGUI as sg
  4. from serial.tools.list_ports import comports
  5. from os.path import isfile
  6. import time
  7. import datetime
  8. import csv
  9. import threading
  10. import random
  11.  
  12. from vis1 import GRAPH_SIZE
  13.  
  14. readings = dict()
  15. readings_lock = threading.Lock()
  16.  
  17. _fieldnames = [
  18.     "Time", "Operating Frequency", "Operating Mode", "Fan Speed", "PMV openness", "Water inlet temp",
  19.     "Water outlet temp", "T3 temp", "T4 temp", "Discharge temp", "Return air temp", "T1", "T1B",
  20.     "T2", "T2B", "Ta", "T5", "Pressure 1", "Pressure 2", "Outdoor uint current", "Outdoor unit voltage",
  21.     "Hydraulic module current 1", "Hydraulic module current 2", "Compressor operating time", "Reserved", "Current fault",
  22.     "Fault 1", "Fault 2", "Fault 3"]
  23.  
  24. _fieldsGraphed = ("T1", "Pressure 1")
  25.  
  26. GRAPH_SIZE = (500, 250)
  27. GRAPH_STEP_SIZE = 5
  28. DELAY = 5000
  29.  
  30. def reallyExit():
  31.     layout = [[sg.Text("Do you really wish to exit?")], [
  32.         sg.Button("No"), sg.Button("Yes")]]
  33.     window = sg.Window("HMPL", layout)
  34.     while True:
  35.         event, _ = window.read()
  36.         if event == sg.WIN_CLOSED or event == 'No':
  37.             window.close()
  38.             return
  39.         elif event == "Yes":
  40.             exit()
  41.  
  42.  
  43. def writeToFile(dir, dict):
  44.     if isfile(dir):
  45.         with open(dir, 'a', encoding='UTF8', newline='') as f:
  46.             writer = csv.DictWriter(f, fieldnames=_fieldnames)
  47.             writer.writerow(dict)
  48.     else:
  49.         with open(dir, 'w', encoding='UTF8', newline='') as f:
  50.             writer = csv.DictWriter(f, fieldnames=_fieldnames)
  51.             writer.writeheader()
  52.             writer.writerow(dict)
  53.  
  54.  
  55. def dispErr(msg):
  56.     layout = [[sg.Text("ERROR")], [sg.Text(msg)], [sg.Button("Close")]]
  57.     window = sg.Window("HMPL", layout)
  58.     while True:
  59.         event, _ = window.read()
  60.         if event == sg.WIN_CLOSED or event == 'Close':
  61.             exit()
  62.  
  63.  
  64. def dispWar(msg):
  65.     layout = [[sg.Text("ERROR")], [sg.Text(msg)], [sg.Button("Continue")]]
  66.     window = sg.Window("HMPL", layout)
  67.     while True:
  68.         event, _ = window.read()
  69.         if event == 'Continue':
  70.             window.close()
  71.             return
  72.  
  73.  
  74. # Selecting comport and connecting
  75. sg.change_look_and_feel("Dark")
  76. a = [comport.device for comport in comports()]
  77.  
  78. layout = [[sg.Text("WELCOME TO HPML!")],
  79.           [sg.InputCombo(values=a), sg.Button("Refresh")],
  80.           [sg.InputText('filename'), sg.Text(".csv")],
  81.           [sg.Button("CONNECT")]]
  82.  
  83. window = sg.Window("HMPL", layout)
  84. while True:
  85.     event, values = window.read()
  86.     if event == sg.WIN_CLOSED:
  87.         reallyExit()
  88.     elif event == 'CONNECT':
  89.         break
  90.     elif event == 'Refresh':
  91.         a = [comport.device for comport in comports()]
  92.  
  93. window.close()
  94. dat = values[1] + ".csv"
  95. print(dat)
  96. client = ModbusSerialClient(
  97.     method='rtu',
  98.     port=values[0],
  99.     baudrate=9600,
  100.     timeout=1,
  101.     parity='N',
  102.     stopbits=1,
  103.     bytesize=8
  104. )
  105.  
  106.  
  107. def _mainLoop():
  108.     global readings
  109.     try:
  110.         while True:
  111.             if client.connect():  # Trying to connect to Modbus Server/Slave
  112.                 with readings_lock:
  113.                     readings["Time"] = datetime.datetime.now()
  114.                     print("Client connected, reading")
  115.                     rr = client.read_holding_registers(
  116.                         address=100, count=28, unit=1)
  117.                     for i, name in enumerate(_fieldnames[1:]):
  118.                         if type(rr) == ModbusIOException:
  119.                             readings[name] = "/"
  120.                         else:
  121.                             readings[name] = str(rr.registers[i])
  122.  
  123.                     print("Reading complete, writing to file " + dat)
  124.                     writeToFile(dat, readings)
  125.                 time.sleep(5)
  126.  
  127.             else:
  128.                 e = 'Cannot connect to the Modbus Server/Slave'
  129.                 print(e)
  130.                 dispWar(e)
  131.  
  132.     except Exception as ex:
  133.         template = "An exception of type {0} occurred. Arguments:\n{1!r}"
  134.         message = template.format(type(ex).__name__, ex.args)
  135.         print(message)
  136.         dispErr(message)
  137.  
  138.  
  139. def mainLoop():
  140.     try:
  141.         while True:
  142.             with readings_lock:
  143.                 readings["Time"] = datetime.datetime.now()
  144.                 print("Client connected, reading")
  145.                 for i, name in enumerate(_fieldnames[1:]):
  146.                     readings[name] = str(random.randint(10, 250))
  147.  
  148.                 print("Reading complete, writing to file " + dat)
  149.                 writeToFile(dat, readings)
  150.             time.sleep(1)
  151.     except Exception as ex:
  152.         template = "An exception of type {0} occurred. Arguments:\n{1!r}"
  153.         message = template.format(type(ex).__name__, ex.args)
  154.         print(message)
  155.         dispErr(message)
  156.  
  157.  
  158. def graph():
  159.    
  160.     lastval = dict()
  161.     l = [[sg.Text("GRAPHS", font=(None, 14))]]
  162.     x = 0
  163.     for field in _fieldsGraphed:
  164.         lastval[field] = (0, 0)
  165.         l.append([sg.Graph(GRAPH_SIZE, (0, 0), GRAPH_SIZE,
  166.                 key='-GRAPH-' + field, background_color='white',)])
  167.    
  168.     w = sg.Window("Graf", l, resizable=True, element_justification='c', disable_close=True)
  169.    
  170.     print("GRAPHS: init done")
  171.     while True:
  172.         eve, _ = w.read(timeout=DELAY)
  173.         print("GRAPHS: instide endless loop")
  174.         for field in _fieldsGraphed:
  175.             print("GRAPHS: field: " + field)
  176.             #Display a graph that moves in chronological order
  177.             step_size = GRAPH_STEP_SIZE
  178.             with readings_lock:
  179.                 print("GRAPHS: got readings lock for myself")
  180.                 y = readings[field]
  181.             if x < GRAPH_SIZE[0]:  #First time
  182.                 # window['-GRAPH-'].DrawLine((lastx, lasty), (x, y), width=1)
  183.                 w["-GRAPH-" + field].DrawLine((lastval[field][0], lastval[field][1]), (x, y), width=1)
  184.             else:
  185.                 # window['-GRAPH-'].Move(-step_size, 0)  #Shift the entire graph to the left
  186.                 # window['-GRAPH-'].DrawLine((lastx, lasty), (x, y), width=1)
  187.                 w["-GRAPH-"].Move(-step_size, 0)  #Shift the entire graph to the left
  188.                 w["-GRAPH-"].DrawLine((lastval[field][0], lastval[field][1]), (x, y), width=1)
  189.                 x -= step_size
  190.             lastval[field][0], lastval[field][1] = x, y
  191.  
  192.             x += step_size
  193.  
  194.        
  195.  
  196.  
  197. text_size = 13
  198. third = ((len(_fieldnames)-1)//3) + 1
  199. col1 = list()
  200. col2 = list()
  201. col3 = list()
  202.  
  203. for i, name in enumerate(_fieldnames[1:]):
  204.     l = [[sg.Text("/", key=name, font=(None, text_size+2))]]
  205.     if i % 3 == 0:
  206.         col1.append([sg.Frame(name + ": ", l, element_justification='c')])
  207.     elif i % 3 == 1:
  208.         col2.append([sg.Frame(name + ": ", l, element_justification='c')])
  209.     else:
  210.         col3.append([sg.Frame(name + ": ", l, element_justification='c')])
  211.  
  212. layout = [
  213.     [sg.Text("CONNECTED", font=(None, text_size))],
  214.     [sg.Column(col1, element_justification='c'), sg.Column(
  215.         col2, element_justification='c'), sg.Column(col3, element_justification='c')],
  216.     [sg.Button("Close", font=(None, text_size))],
  217. ]
  218.  
  219. window = sg.Window("HMPL", layout, resizable=True, element_justification='c',
  220.                    location=(0, 0), disable_close=True, ).Finalize()
  221.  
  222. thread = threading.Thread(target=mainLoop)
  223. thread.daemon = True
  224. thread.start()
  225.  
  226. thread = threading.Thread(target=graph)
  227. thread.daemon = True
  228. thread.start()
  229.  
  230.  
  231. while True:
  232.     event, values = window.read(timeout=500)
  233.     if event == "Close":
  234.         reallyExit()
  235.     if not readings_lock.locked():
  236.         with readings_lock:
  237.             for name in _fieldnames[1:]:
  238.                 window[str(name)].update(readings[name])
  239.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement