Can someone tell me whats wrong with my code, whenever i delete something, a new error pops up the code is a dumpster fire to be honest. tkinter is having errors with simple task, most of the pip installs aren't required, and the code doesn't connect to the plc. The task the code is supposed to connect to the plc and give the status of the tag into microsoft SQL server management Studio. Would very much appreciate any ideas or help. Thanks.
import threading
import tkinter as tk
from tkinter import ttk
import datetime
import time
import logging
import pyodbc
from pylogix import PLC
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter
import tkinter as tk
import threading
# ... other necessary imports ...
# Define global variables
root = None
tree = None
plc_thread = None
running = False # Flag to control the PLC reading thread
def read_and_write_plc_data():
"""Read data from PLC and write to database."""
global running
plc = PLC()
plc.IPAddress = PLC_IP
while running:
try:
data = plc.Read(TAGS_TO_READ)
write_to_database(data)
except Exception as e:
logging.error(f"PLC read/write error: {e}")
time.sleep(1) # Adjust the frequency as needed
def start_plc_process():
"""Start the PLC reading and writing process."""
global plc_thread, running
if not running:
running = True
plc_thread = threading.Thread(target=read_and_write_plc_data, daemon=True)
plc_thread.start()
def stop_plc_process():
"""Stop the PLC reading and writing process."""
global running
running = False
def setup_gui():
"""Set up the GUI layout and components."""
global root, tree
root = tk.Tk()
root.title("PLC Data Viewer")
# Start button
start_button = tk.Button(root, text="Start PLC Process", command=start_plc_process)
start_button.pack()
# Stop button
stop_button = tk.Button(root, text="Stop PLC Process", command=stop_plc_process)
stop_button.pack()
# Setup other GUI components (treeview, labels, etc.)
# ...
return root
# ... The rest of your existing code ...
if __name__ == "__main__":
root = setup_gui()
# Initialize logging
logging.basicConfig(filename="plc_data.log", level=logging.INFO)
# Database and PLC connection settings
DRIVER = 'driver'
DATABASE = 'AI'
SERVER = 'info...'
PLC_IP = "1111"
TAGS_TO_READ = ['tag']
def create_connection():
"""Create a database connection."""
conn_str = f'DRIVER=};SERVER={SERVER};DATABASE={DATABASE}'
return pyodbc.connect(conn_str, timeout=10)
def read_from_plc(plc):
"""Read data from the PLC."""
# Implement the logic to read from the PLC
# Example: return plc.Read('Some_Tag')
pass
def write_to_database(data):
"""Write data to the database."""
try:
with create_connection() as conn:
cursor = conn.cursor()
# Implement the SQL INSERT logic
# Example: cursor.execute("INSERT INTO table_name (column1, column2) VALUES (?, ?)", data1, data2)
conn.commit()
except Exception as e:
logging.error(f"Database write failed: {e}")
def fetch_from_database():
"""Fetch data from the database."""
try:
with create_connection() as conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM your_table") # Adjust your SQL query
return cursor.fetchall()
except Exception as e:
logging.error(f"Database read failed: {e}")
return []
def setup_gui():
"""Set up the GUI."""
root = tk.Tk()
root.title("PLC Data Viewer")
# Set up GUI elements like buttons, labels, treeview, etc.
# ...
return root
def update_gui(root, tree):
"""Update the GUI with new data."""
data = fetch_from_database()
# Update your treeview or other GUI elements with 'data'
# ...
root.after(1000, lambda: update_gui(root, tree)) # Update GUI every 1000 ms
def plc_data_thread():
"""Thread to read data from PLC and write to database."""
plc = PLC()
plc.IPAddress = PLC_IP
while True:
data = read_from_plc(plc)
write_to_database(data)
time.sleep(1) # Read data every 1 second
if __name__ == "__main__":
root = setup_gui()
tree = None # Replace with actual treeview initialization
update_gui(root, tree)
# Start PLC data thread
threading.Thread(target=plc_data_thread, daemon=True).start()
root.mainloop()
source https://stackoverflow.com/questions/77816464/nameerror-name-run-gui-update-in-thread-is-not-defined
Comments
Post a Comment