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

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...

How to split a rinex file if I need 24 hours data

Trying to divide rinex file using the command gfzrnx but getting this error. While doing that getting this error msg 'gfzrnx' is not recognized as an internal or external command Trying to split rinex file using the command gfzrnx. also install'gfzrnx'. my doubt is I need to run this program in 'gfzrnx' or in 'cmdprompt'. I am expecting a rinex file with 24 hrs or 1 day data.I Have 48 hrs data in RINEX format. Please help me to solve this issue. source https://stackoverflow.com/questions/75385367/how-to-split-a-rinex-file-if-i-need-24-hours-data