Skip to main content

NameError: name 'run_gui_update_in_thread' is not defined

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

Popular posts from this blog

Prop `className` did not match in next js app

I have written a sample code ( Github Link here ). this is a simple next js app, but giving me error when I refresh the page. This seems to be the common problem and I tried the fix provided in the internet but does not seem to fix my issue. The error is Warning: Prop className did not match. Server: "MuiBox-root MuiBox-root-1" Client: "MuiBox-root MuiBox-root-2". Did changes for _document.js, modified _app.js as mentioned in official website and solutions in stackoverflow. but nothing seems to work. Could someone take a look and help me whats wrong with the code? Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

How to show number of registered users in Laravel based on usertype?

i'm trying to display data from the database in the admin dashboard i used this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count(); echo $users; ?> and i have successfully get the correct data from the database but what if i want to display a specific data for example in this user table there is "usertype" that specify if the user is normal user or admin i want to user the same code above but to display a specific usertype i tried this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count()->WHERE usertype =admin; echo $users; ?> but it didn't work, what am i doing wrong? source https://stackoverflow.com/questions/68199726/how-to-show-number-of-registered-users-in-laravel-based-on-usertype

Why is my reports service not connecting?

I am trying to pull some data from a Postgres database using Node.js and node-postures but I can't figure out why my service isn't connecting. my routes/index.js file: const express = require('express'); const router = express.Router(); const ordersCountController = require('../controllers/ordersCountController'); const ordersController = require('../controllers/ordersController'); const weeklyReportsController = require('../controllers/weeklyReportsController'); router.get('/orders_count', ordersCountController); router.get('/orders', ordersController); router.get('/weekly_reports', weeklyReportsController); module.exports = router; My controllers/weeklyReportsController.js file: const weeklyReportsService = require('../services/weeklyReportsService'); const weeklyReportsController = async (req, res) => { try { const data = await weeklyReportsService; res.json({data}) console