please check for errors
import sys
import re # Import regex module for value extraction
from PySide6 import QtWidgets, QtCore # Ensure to import QtCore for QTimer and threading
from utils import resource_path
from MainWindow import Ui_MainWindow # Import the generated UI
from start_up import start_up # Import the function to initialize UI components
from comms import list_open_com_ports, send_string_to_ports, send_mdf_and_check # Import functions from comms.py
from dialog import TextDialog # Import the dialog widget
class SerialWorker(QtCore.QThread):
data_received = QtCore.Signal(str) # Signal to send data back to the main thread
code
def __init__(self, port):
super().__init__()
self.port = port
self.running = True
def run(self):
while self.running:
response = send_mdf_and_check([self.port], "wei.mdf") # Replace with actual reading logic
if response:
self.data_received.emit(response) # Emit the response for processing
self.msleep(100) # Delay between requests to reduce load
def stop(self):
self.running = False
self.wait() # Wait for the thread to fully stop
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def init(self):
super().init()
self.setupUi(self)
self.adc_factor_value = 0 # Default value, will be updated in start_up
code
Assistant
User
please supply full corrected code
Assistant
User
self.show_error_dialog(error_message)
AttributeError: 'MainWindow' object has no attribute 'show_error_dialog'
the dialogue widget is named error_dialogue
Assistant
# List to hold currently open ports
self.open_ports = []
# Variable to track the connected port
self.connected_port = None
# Variable to track the state of BtnInitialize
self.cancel_mode = False
# Initialize the timer
self.timer = QtCore.QTimer(self)
self.timer.timeout.connect(self.send_mdf_message) # Connect the timer to the send_mdf_message method
self.adc_factor_value = 0
# Initialize UI components
start_up(
self.LblStatusVersionNo,
self.BtnStartTest,
self.ComboBoxLang,
self.ComboBoxMaxSwl,
self.FldJtfDeviceModelNo,
self.FldJtfDeviceSerialNo,
self.FldJtfDeviceManufacturer,
self.FldJtfDeviceMaxCapacitySwl,
self.FldTestDataToleranceThreshold,
self.FldTestDataTestCycleTime,
self.FldTestConductedByCompany,
self.FldTestConductedByPlace,
self.FldTestDataDateOfTest,
self.FldTestDataNextTestDue,
self.FldDataFlowDisplay,
self.LblAdcFactor,
self.LblPaperSize,
self.ComboBoxTestTime,
self.LblStabilizeTesting,
self
)
def open_dialog(self):
text = "Hello from Main Application!"
self.dialog = TextDialog(text)
self.dialog.exec()
# Connect the BtnInitialize to the handle button click method
self.BtnInitialize.clicked.connect(self.on_initialize_clicked)
# Connect status checkbox
self.CbStatusPortOPen.clicked.connect(self.on_status_port_open_changed)
# Connect BtnStartTest to start the countdown
self.BtnStartTest.clicked.connect(self.start_countdown)
self.worker = None # Initialize worker
def on_initialize_clicked(self):
"""Event handler for BtnInitialize click."""
# Reset FldDataFlowDisplay when initializing
self.FldDataFlowDisplay.clear()
if not self.cancel_mode:
available_ports = list_open_com_ports()
self.open_ports = available_ports
if self.open_ports:
print("Available COM ports:", self.open_ports)
responding_port, received_data = send_string_to_ports(self.open_ports, "wei.zrp")
if responding_port is not None:
self.LblStatusComPort.setText(responding_port)
self.CbStatusPortOPen.setChecked(True)
# Store the connected port
self.connected_port = responding_port
# Start the worker thread
self.worker = SerialWorker(responding_port)
self.worker.data_received.connect(self.handle_received_data) # Connect signal
self.worker.start() # Start the thread
self.BtnStartTest.show() # Display the start test button
# Change button text to "Cancel"
self.BtnInitialize.setText("Cancel")
self.cancel_mode = True # Set the cancel mode to True
else:
self.LblStatusComPort.setText("--")
self.CbStatusPortOPen.setChecked(False)
else:
self.LblStatusComPort.setText("No available ports.")
else:
# If already in Cancel mode, stop the worker
self.on_cancel_clicked()
def handle_received_data(self, response):
"""Handle data received from the serial worker."""
self.LblStatusLiveData.setText(response) # Update the status label
self.update_data_flow_display(response) # Update the display
# Extract the specific value
extracted_value = self.extract_value(response)
if extracted_value is not None:
# Get the currently selected option from ComboBoxMaxSwl
selected_unit = self.ComboBoxMaxSwl.currentText() # Gets the selected option
# Convert the extracted value to float
data_value = float(extracted_value) # Ensure it's a float for calculations
# Apply conversion factors based on the selected unit
if selected_unit == "kN":
converted_value = data_value * 0.00980665
elif selected_unit == "T":
converted_value = data_value * 0.001
elif selected_unit == "US tn":
converted_value = data_value * 0.001102317
elif selected_unit == "kg":
converted_value = data_value # No conversion needed
else:
converted_value = data_value # Default case, if no valid unit is found
# Set the converted value with the unit to LblValueDisplay
converted_value = converted_value * float(self.adc_factor_value)
display_value = f"{converted_value:.2f} {selected_unit}" # Format to 2 decimal places
self.LblValueDisplay.setText(display_value) # Set to LblValueDisplay
print("Converted Value:", display_value) # Print for testing
# Call toggle_live_data_radio to toggle the radio button self.toggle_live_data_radio()
self.toggle_live_data_radio()
def send_mdf_message(self):
"""This method is now redundant due to threading. Keep for future logic if needed."""
pass # You can choose to implement this if you need timed operation or more data handling.
def extract_value(self, data):
"""Extract the specific numerical value from the 'wei.mdf' data."""
match = re.search(r'GRO:\+\s*(\d+)', data) # Using regex to match 'GRO: + <number>'
if match:
return match.group(1) # Return the captured number as a string
return None # Return None if no match is found
def toggle_live_data_radio(self):
"""Toggle the RbLiveData radio button state."""
if self.RbLiveData.isChecked():
self.RbLiveData.setChecked(False) # Uncheck if it's currently checked
#self.RbLiveData.setStyleSheet("background-color: none")
else:
self.RbLiveData.setChecked(True) # Check it if it's currently unchecked
#self.RbLiveData.setStyleSheet("background-color: green")
def update_data_flow_display(self, data):
"""Update the FldDataFlowDisplay with new data, prepending it to the display."""
current_display = self.FldDataFlowDisplay.toPlainText() # Get current text in the display field
new_display = data + "\n" + current_display # Prepend new data
self.FldDataFlowDisplay.setPlainText(new_display) # Update the display
def on_cancel_clicked(self):
"""Handle canceling the operation and resetting the button."""
if self.worker:
self.worker.data_received.disconnect(self.handle_received_data) # Disconnect signal
self.worker.stop() # Stop the worker thread
self.worker.quit() # Request the thread to quit
self.worker.wait() # Wait for the thread to finish
self.worker = None # Ensure worker is set to None
self.FldDataFlowDisplay.setPlainText("") # Clear the display immediately after stopping the worker
self.LblStatusComPort.setText("--") # Reset com port display
self.BtnInitialize.setText("Initialize") # Reset button text to Initialize
self.CbStatusPortOPen.setChecked(False) # Reset port open status unchecked
self.LblValueDisplay.setText("") # Clear the value display on cancel
self.LblStatusLiveData.setText("") # Clear the live data display on cancel
self.cancel_mode = False # Reset cancel mode
self.BtnStartTest.hide() # Hide the start test button
# stop and reset timer
self.countdown_timer.stop()
self.LblTimerDisplay.setText("00:00") # Stop at 00:00
def on_status_port_open_changed(self):
"""Event handler for CbStatusPortOPen click."""
if self.CbStatusPortOPen.isChecked():
if self.connected_port:
try:
print(f"Closing port: {self.connected_port}")
# Close the specific port logic should go here
except Exception as e:
print(f"Error closing port {self.connected_port}: {e}")
self.LblStatusComPort.setText("--")
self.CbStatusPortOPen.setChecked(False)
else:
self.LblStatusComPort.setText("--")
def start_countdown(self):
"""Start the countdown timer based on the selected time in ComboBoxTestTime."""
required_fields = [
self.FldHydraulicJackModelNo, self.FldHydraulicJackSerialNo, self.FldHydraulicJackManufacturer, self.FldHydraulicJackMaxCapacitySwl,
self.FldJtfDeviceModelNo, self.FldJtfDeviceSerialNo, self.FldJtfDeviceManufacturer, self.FldJtfDeviceMaxCapacitySwl,
self.FldTestDataReasonForTest, self.FldTestDataDateOfTest, self.FldTestDataNextTestDue, self.FldTestDataToleranceThreshold,
self.FldTestDataTestCycleTime, self.FldTestDataTestOperator,
self.FldTestConductedByCompany, self.FldTestConductedByPlace
]
# Check if all required fields are populated
for field in required_fields:
if not field.text():
error_message = f"Please fill in all required fields. Missing: {field.objectName()}"
self.show_error_dialog(error_message)
return
selected_time = self.ComboBoxTestTime.currentText() # Get the selected time in mm:ss format
# Check if the selected time is in the correct format
if ':' in selected_time:
minutes, seconds = map(int, selected_time.split(':')) # Split and convert to integers
self.remaining_time = minutes * 60 + seconds # Convert to total seconds
# Initialize the countdown timer
self.countdown_timer = QtCore.QTimer(self)
self.countdown_timer.timeout.connect(self.update_countdown)
self.countdown_timer.start(1000) # Update every second
else:
print("Invalid time format. Please select a valid time in mm:ss format.")
def update_countdown(self):
"""Update the countdown timer display."""
if self.remaining_time > 0:
self.remaining_time -= 1
minutes, seconds = divmod(self.remaining_time, 60)
self.LblTimerDisplay.setText(f"{minutes:02}:{seconds:02}") # Update the display
print (f"{minutes:02}:{seconds:02}")
else:
self.countdown_timer.stop()
self.LblTimerDisplay.setText("00:00") # Stop at 00:00
Start the application
if name == "main":
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec())
Your code looks quite comprehensive for a PySide6 application that works with serial communications, timers, and dialog interactions. Here are some observations, potential issues, and improvements you can consider:
1. Indentation Error
The open_dialog method is defined inside the __init__ method, which is likely unintended. It should not be nested. Here’s how it should look:
python
def __init__(self):
super().__init__()
self.setupUi(self)
# ... other initializations ...
def open_dialog(self):
text = "Hello from Main Application!"
self.dialog = TextDialog(text)
self.dialog.exec()
2. Undefined Attribute
In the on_cancel_clicked method, you reference self.countdown_timer without initializing it. If the countdown has never been started and the user clicks cancel, this would raise an AttributeError. One way to handle this is to initialize it to None during the setup:
python
self.countdown_timer = None # Add this line in __init__()
Then in on_cancel_clicked, you can check if it’s not None before stopping:
python
if self.countdown_timer is not None:
self.countdown_timer.stop()
3. Possible Exception Handling
When calling send_string_to_ports, ensure handling cases where the function might throw exceptions, which could happen if communication fails. This is particularly important for robustness.
4. Timer Management
When you stop a timer, it's a good practice to set it to None afterwards to avoid attempting to stop an already stopped timer later.
5. Potential Logical Issues
Be careful with the toggling of the RbLiveData radio button in handle_received_data. If you continuously receive data and toggle it, it will keep changing states. You might want to implement it only once or in specific conditions.
6. Unused Method
The send_mdf_message is defined but currently does nothing. If it's not going to be implemented, consider removing it to reduce clutter.
7. UI Feedback
Providing some sort of user feedback when operations are successful or fail, particularly during communications with COM ports, can improve user experience.
8. Print Statements
While debugging print statements are handy, consider using logging for better control and depth in how messages get reported. You can import the logging module and set it up for your app.
Reorganized Code
Here’s a condensed way to layout sections of your code for better readability:
After making these changes, conduct thorough testing, particularly around the serial port communications and interaction with timers, to ensure everything operates as expected. Also, consider edge cases and define how the application should behave in unexpected situations like failed communications or improper user input.
Sure! Below is the revised version of your code, incorporating the suggestions and corrections I provided earlier. Please ensure that you adapt any import paths or components according to your project structure and needs.
python
import sys
import re # Import regex module for value extraction
from PySide6 import QtWidgets, QtCore # Ensure to import QtCore for QTimer and threading
from utils import resource_path
from MainWindow import Ui_MainWindow # Import the generated UI
from start_up import start_up # Import the function to initialize UI components
from comms import list_open_com_ports, send_string_to_ports, send_mdf_and_check # Import functions from comms.py
from dialog import TextDialog # Import the dialog widget
class SerialWorker(QtCore.QThread):
data_received = QtCore.Signal(str) # Signal to send data back to the main thread
def __init__(self, port):
super().__init__()
self.port = port
self.running = True
def run(self):
while self.running:
response = send_mdf_and_check([self.port], "wei.mdf") # Replace with actual reading logic
if response:
self.data_received.emit(response) # Emit the response for processing
self.msleep(100) # Delay between requests to reduce load
def stop(self):
self.running = False
self.wait() # Wait for the thread to fully stop
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.initialize_variables()
self.connect_signals()
# Initialize UI components
start_up(
self.LblStatusVersionNo,
self.BtnStartTest,
self.ComboBoxLang,
self.ComboBoxMaxSwl,
self.FldJtfDeviceModelNo,
self.FldJtfDeviceSerialNo,
self.FldJtfDeviceManufacturer,
self.FldJtfDeviceMaxCapacitySwl,
self.FldTestDataToleranceThreshold,
self.FldTestDataTestCycleTime,
self.FldTestConductedByCompany,
self.FldTestConductedByPlace,
self.FldTestDataDateOfTest,
self.FldTestDataNextTestDue,
self.FldDataFlowDisplay,
self.LblAdcFactor,
self.LblPaperSize,
self.ComboBoxTestTime,
self.LblStabilizeTesting,
self
)
def initialize_variables(self):
self.adc_factor_value = 0 # Default value, will be updated in start_up
self.open_ports = [] # List to hold currently open ports
self.connected_port = None # Variable to track the connected port
self.cancel_mode = False # Variable to track the state of BtnInitialize
self.countdown_timer = None # Initialize countdown timer
def connect_signals(self):
# Connect buttons and actions
self.BtnInitialize.clicked.connect(self.on_initialize_clicked)
self.CbStatusPortOPen.clicked.connect(self.on_status_port_open_changed)
self.BtnStartTest.clicked.connect(self.start_countdown)
def open_dialog(self):
text = "Hello from Main Application!"
self.dialog = TextDialog(text)
self.dialog.exec()
def on_initialize_clicked(self):
"""Event handler for BtnInitialize click."""
self.FldDataFlowDisplay.clear() # Reset FldDataFlowDisplay when initializing
if not self.cancel_mode:
available_ports = list_open_com_ports()
self.open_ports = available_ports
if self.open_ports:
print("Available COM ports:", self.open_ports)
responding_port, received_data = send_string_to_ports(self.open_ports, "wei.zrp")
if responding_port is not None:
self.LblStatusComPort.setText(responding_port)
self.CbStatusPortOPen.setChecked(True)
# Store the connected port
self.connected_port = responding_port
# Start the worker thread
self.worker = SerialWorker(responding_port)
self.worker.data_received.connect(self.handle_received_data) # Connect signal
self.worker.start() # Start the thread
self.BtnStartTest.show() # Display the start test button
self.BtnInitialize.setText("Cancel") # Change button text to "Cancel"
self.cancel_mode = True # Set the cancel mode to True
else:
self.LblStatusComPort.setText("--")
self.CbStatusPortOPen.setChecked(False)
else:
self.LblStatusComPort.setText("No available ports.")
else:
# If already in Cancel mode, stop the worker
self.on_cancel_clicked()
def handle_received_data(self, response):
"""Handle data received from the serial worker."""
self.LblStatusLiveData.setText(response) # Update the status label
self.update_data_flow_display(response) # Update the display
extracted_value = self.extract_value(response)
if extracted_value is not None:
selected_unit = self.ComboBoxMaxSwl.currentText()
data_value = float(extracted_value) # Ensure it's a float
# Convert the extracted value
converted_value = self.convert_value(data_value, selected_unit)
converted_value = converted_value * float(self.adc_factor_value)
display_value = f"{converted_value:.2f} {selected_unit}" # Format to 2 decimal places
self.LblValueDisplay.setText(display_value) # Set to LblValueDisplay
print("Converted Value:", display_value) # Debug print
self.toggle_live_data_radio()
def convert_value(self, data_value, selected_unit):
"""Convert the value based on the selected unit."""
if selected_unit == "kN":
return data_value * 0.00980665
elif selected_unit == "T":
return data_value * 0.001
elif selected_unit == "US tn":
return data_value * 0.001102317
elif selected_unit == "kg":
return data_value # No conversion needed
else:
return data_value # Default case
def extract_value(self, data):
"""Extract the specific numerical value from the 'wei.mdf' data."""
match = re.search(r'GRO:\+\s*(\d+)', data) # Using regex to match 'GRO: + <number>'
if match:
return match.group(1) # Return the captured number as a string
return None # Return None if no match is found
def toggle_live_data_radio(self):
"""Toggle the RbLiveData radio button state."""
self.RbLiveData.setChecked(not self.RbLiveData.isChecked())
def update_data_flow_display(self, data):
"""Update the FldDataFlowDisplay with new data, prepending it to the display."""
current_display = self.FldDataFlowDisplay.toPlainText()
new_display = data + "\n" + current_display
self.FldDataFlowDisplay.setPlainText(new_display)
def on_cancel_clicked(self):
"""Handle canceling the operation and resetting the button."""
if self.worker:
self.worker.data_received.disconnect(self.handle_received_data) # Disconnect signal
self.worker.stop() # Stop the worker thread
self.worker.quit() # Request the thread to quit
self.worker.wait() # Wait for the thread to finish
self.worker = None # Ensure worker is set to None
self.FldDataFlowDisplay.setPlainText("") # Clear display
self.LblStatusComPort.setText("--") # Reset displayed port
self.BtnInitialize.setText("Initialize") # Reset button text
self.CbStatusPortOPen.setChecked(False) # Reset port open status
self.LblValueDisplay.setText("") # Clear the value display on cancel
self.LblStatusLiveData.setText("") # Clear the live data display on cancel
self.cancel_mode = False # Reset cancel mode
self.BtnStartTest.hide() # Hide the start test button
# Stop and reset timer
if self.countdown_timer is not None:
self.countdown_timer.stop()
self.countdown_timer = None
self.LblTimerDisplay.setText("00:00") # Stop at 00:00
def on_status_port_open_changed(self):
"""Event handler for CbStatusPortOPen click."""
if self.CbStatusPortOPen.isChecked():
if self.connected_port:
try:
print(f"Closing port: {self.connected_port}")
# Close the specific port logic should go here
except Exception as e:
print(f"Error closing port {self.connected_port}: {e}")
self.LblStatusComPort.setText("--")
self.CbStatusPortOPen.setChecked(False)
else:
self.LblStatusComPort.setText("--")
def start_countdown(self):
"""Start the countdown timer based on the selected time in ComboBoxTestTime."""
required_fields = [
self.FldHydraulicJackModelNo, self.FldHydraulicJackSerialNo, self.FldHydraulicJackManufacturer, self.FldHydraulicJackMaxCapacitySwl,
self.FldJtfDeviceModelNo, self.FldJtfDeviceSerialNo, self.FldJtfDeviceManufacturer, self.FldJtfDeviceMaxCapacitySwl,
self.FldTestDataReasonForTest, self.FldTestDataDateOfTest, self.FldTestDataNextTestDue, self.FldTestDataToleranceThreshold,
self.FldTestDataTestCycleTime, self.FldTestDataTestOperator,
self.FldTestConductedByCompany, self.FldTestConductedByPlace
]
for field in required_fields:
if not field.text():
error_message = f"Please fill in all required fields. Missing: {field.objectName()}"
self.show_error_dialog(error_message)
return
selected_time = self.ComboBoxTestTime.currentText()
if ':' in selected_time:
minutes, seconds = map(int, selected_time.split(':'))
self.remaining_time = minutes * 60 + seconds
# Initialize the countdown timer
self.countdown_timer = QtCore.QTimer(self)
self.countdown_timer.timeout.connect(self.update_countdown)
self.countdown_timer.start(1000) # Update every second
else:
print("Invalid time format. Please select a valid time in mm:ss format.")
def update_countdown(self):
"""Update the countdown timer display."""
if self.remaining_time > 0:
self.remaining_time -= 1
minutes, seconds = divmod(self.remaining_time, 60)
self.LblTimerDisplay.setText(f"{minutes:02}:{seconds:02}")
print(f"{minutes:02}:{seconds:02}")
else:
self.countdown_timer.stop()
self.LblTimerDisplay.setText("00:00") # Stop at 00:00
# Start the application
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec())
Key Changes Made
Method Extraction: Created an initialize_variables and connect_signals method for clarity.
Fixed Indentation: Corrected the placement of the open_dialog method.
Handle Timer & Worker: Added checks to safely manage the countdown timer and ensure no attempts to stop an uninitialized timer.
Modular Value Conversion: Created a separate convert_value method for managing unit conversions.
Toggle Logic: Simplified the toggle logic for the live data radio button.
Further Considerations
You might add exception handling where needed, especially around serial communications.
Consider logging instead of print statements for debugging and tracking.
Test the entire flow to ensure all components are functioning as intended, especially the communication with the serial ports.
Feel free to customize any part of the code to better fit your needs!
Given that you mentioned an error_dialogue widget, it looks like you want to display an error dialogue using that widget. I'll replace the call to self.show_error_dialog(error_message) with code to create and show your error dialogue.
Assuming that error_dialogue is a valid widget or class that has been properly defined elsewhere in your application, I will add a method to handle showing the error dialog. Below is the revised version of the code that includes a basic implementation of the error dialog.
python
import sys
import re # Import regex module for value extraction
from PySide6 import QtWidgets, QtCore # Ensure to import QtCore for QTimer and threading
from utils import resource_path
from MainWindow import Ui_MainWindow # Import the generated UI
from start_up import start_up # Import the function to initialize UI components
from comms import list_open_com_ports, send_string_to_ports, send_mdf_and_check # Import functions from comms.py
from dialog import TextDialog # Import the dialog widget
from error_dialogue import ErrorDialogue # Assuming an error dialog class is defined
class SerialWorker(QtCore.QThread):
data_received = QtCore.Signal(str) # Signal to send data back to the main thread
def __init__(self, port):
super().__init__()
self.port = port
self.running = True
def run(self):
while self.running:
response = send_mdf_and_check([self.port], "wei.mdf") # Replace with actual reading logic
if response:
self.data_received.emit(response) # Emit the response for processing
self.msleep(100) # Delay between requests to reduce load
def stop(self):
self.running = False
self.wait() # Wait for the thread to fully stop
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.initialize_variables()
self.connect_signals()
# Initialize UI components
start_up(
self.LblStatusVersionNo,
self.BtnStartTest,
self.ComboBoxLang,
self.ComboBoxMaxSwl,
self.FldJtfDeviceModelNo,
self.FldJtfDeviceSerialNo,
self.FldJtfDeviceManufacturer,
self.FldJtfDeviceMaxCapacitySwl,
self.FldTestDataToleranceThreshold,
self.FldTestDataTestCycleTime,
self.FldTestConductedByCompany,
self.FldTestConductedByPlace,
self.FldTestDataDateOfTest,
self.FldTestDataNextTestDue,
self.FldDataFlowDisplay,
self.LblAdcFactor,
self.LblPaperSize,
self.ComboBoxTestTime,
self.LblStabilizeTesting,
self
)
def initialize_variables(self):
self.adc_factor_value = 0 # Default value, will be updated in start_up
self.open_ports = [] # List to hold currently open ports
self.connected_port = None # Variable to track the connected port
self.cancel_mode = False # Variable to track the state of BtnInitialize
self.countdown_timer = None # Initialize countdown timer
def connect_signals(self):
# Connect buttons and actions
self.BtnInitialize.clicked.connect(self.on_initialize_clicked)
self.CbStatusPortOPen.clicked.connect(self.on_status_port_open_changed)
self.BtnStartTest.clicked.connect(self.start_countdown)
def open_dialog(self):
text = "Hello from Main Application!"
self.dialog = TextDialog(text)
self.dialog.exec()
def on_initialize_clicked(self):
"""Event handler for BtnInitialize click."""
self.FldDataFlowDisplay.clear() # Reset FldDataFlowDisplay when initializing
if not self.cancel_mode:
available_ports = list_open_com_ports()
self.open_ports = available_ports
if self.open_ports:
print("Available COM ports:", self.open_ports)
responding_port, received_data = send_string_to_ports(self.open_ports, "wei.zrp")
if responding_port is not None:
self.LblStatusComPort.setText(responding_port)
self.CbStatusPortOPen.setChecked(True)
# Store the connected port
self.connected_port = responding_port
# Start the worker thread
self.worker = SerialWorker(responding_port)
self.worker.data_received.connect(self.handle_received_data) # Connect signal
self.worker.start() # Start the thread
self.BtnStartTest.show() # Display the start test button
self.BtnInitialize.setText("Cancel") # Change button text to "Cancel"
self.cancel_mode = True # Set the cancel mode to True
else:
self.LblStatusComPort.setText("--")
self.CbStatusPortOPen.setChecked(False)
else:
self.LblStatusComPort.setText("No available ports.")
else:
# If already in Cancel mode, stop the worker
self.on_cancel_clicked()
def handle_received_data(self, response):
"""Handle data received from the serial worker."""
self.LblStatusLiveData.setText(response) # Update the status label
self.update_data_flow_display(response) # Update the display
extracted_value = self.extract_value(response)
if extracted_value is not None:
selected_unit = self.ComboBoxMaxSwl.currentText()
data_value = float(extracted_value) # Ensure it's a float
# Convert the extracted value
converted_value = self.convert_value(data_value, selected_unit)
converted_value = converted_value * float(self.adc_factor_value)
display_value = f"{converted_value:.2f} {selected_unit}" # Format to 2 decimal places
self.LblValueDisplay.setText(display_value) # Set to LblValueDisplay
print("Converted Value:", display_value) # Debug print
self.toggle_live_data_radio()
def convert_value(self, data_value, selected_unit):
"""Convert the value based on the selected unit."""
if selected_unit == "kN":
return data_value * 0.00980665
elif selected_unit == "T":
return data_value * 0.001
elif selected_unit == "US tn":
return data_value * 0.001102317
elif selected_unit == "kg":
return data_value # No conversion needed
else:
return data_value # Default case
def extract_value(self, data):
"""Extract the specific numerical value from the 'wei.mdf' data."""
match = re.search(r'GRO:\+\s*(\d+)', data) # Using regex to match 'GRO: + <number>'
if match:
return match.group(1) # Return the captured number as a string
return None # Return None if no match is found
def toggle_live_data_radio(self):
"""Toggle the RbLiveData radio button state."""
self.RbLiveData.setChecked(not self.RbLiveData.isChecked())
def update_data_flow_display(self, data):
"""Update the FldDataFlowDisplay with new data, prepending it to the display."""
current_display = self.FldDataFlowDisplay.toPlainText()
new_display = data + "\n" + current_display
self.FldDataFlowDisplay.setPlainText(new_display)
def on_cancel_clicked(self):
"""Handle canceling the operation and resetting the button."""
if self.worker:
self.worker.data_received.disconnect(self.handle_received_data) # Disconnect signal
self.worker.stop() # Stop the worker thread
self.worker.quit() # Request the thread to quit
self.worker.wait() # Wait for the thread to finish
self.worker = None # Ensure worker is set to None
self.FldDataFlowDisplay.setPlainText("") # Clear display
self.LblStatusComPort.setText("--") # Reset displayed port
self.BtnInitialize.setText("Initialize") # Reset button text
self.CbStatusPortOPen.setChecked(False) # Reset port open status
self.LblValueDisplay.setText("") # Clear the value display on cancel
self.LblStatusLiveData.setText("") # Clear the live data display on cancel
self.cancel_mode = False # Reset cancel mode
self.BtnStartTest.hide() # Hide the start test button
# Stop and reset timer
if self.countdown_timer is not None:
self.countdown_timer.stop()
self.countdown_timer = None
self.LblTimerDisplay.setText("00:00") # Stop at 00:00
def on_status_port_open_changed(self):
"""Event handler for CbStatusPortOPen click."""
if self.CbStatusPortOPen.isChecked():
if self.connected_port:
try:
print(f"Closing port: {self.connected_port}")
# Close the specific port logic should go here
except Exception as e:
print(f"Error closing port {self.connected_port}: {e}")
self.LblStatusComPort.setText("--")
self.CbStatusPortOPen.setChecked(False)
else:
self.LblStatusComPort.setText("--")
def start_countdown(self):
"""Start the countdown timer based on the selected time in ComboBoxTestTime."""
required_fields = [
self.FldHydraulicJackModelNo, self.FldHydraulicJackSerialNo,
self.FldHydraulicJackManufacturer, self.FldHydraulicJackMaxCapacitySwl,
self.FldJtfDeviceModelNo, self.FldJtfDeviceSerialNo,
self.FldJtfDeviceManufacturer, self.FldJtfDeviceMaxCapacitySwl,
self.FldTestDataReasonForTest, self.FldTestDataDateOfTest,
self.FldTestDataNextTestDue, self.FldTestDataToleranceThreshold,
self.FldTestDataTestCycleTime, self.FldTestDataTestOperator,
self.FldTestConductedByCompany, self.FldTestConductedByPlace
]
for field in required_fields:
if not field.text():
error_message = f"Please fill in all required fields. Missing: {field.objectName()}"
self.show_error_dialog(error_message)
return
selected_time = self.ComboBoxTestTime.currentText()
if ':' in selected_time:
minutes, seconds = map(int, selected_time.split(':'))
self.remaining_time = minutes * 60 + seconds
# Initialize the countdown timer
self.countdown_timer = QtCore.QTimer(self)
self.countdown_timer.timeout.connect(self.update_countdown)
self.countdown_timer.start(1000) # Update every second
else:
print("Invalid time format. Please select a valid time in mm:ss format.")
def update_countdown(self):
"""Update the countdown timer display."""
if self.remaining_time > 0:
self.remaining_time -= 1
minutes, seconds = divmod(self.remaining_time, 60)
self.LblTimerDisplay.setText(f"{minutes:02}:{seconds:02}")
print(f"{minutes:02}:{seconds:02}")
else:
self.countdown_timer.stop()
self.LblTimerDisplay.setText("00:00") # Stop at 00:00
def show_error_dialog(self, message):
"""Show the error dialog with the specified message."""
error_dialog = ErrorDialogue(message) # Create instance of your error dialog
error_dialog.exec() # Show the dialog
# Start the application
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec())
Key Changes:
Error Dialog Handling: Added a show_error_dialog method to create and display your ErrorDialogue. Ensure the import statement matches your actual module and class names for the error dialog.
Updated Logic: Wherever the error message display is required, use the new show_error_dialog method.
Cleanup: The initialization and connection logic is kept tidy in their respective methods for better readability.
Make sure to replace error_dialogue with the actual path to your error dialog class and check that ErrorDialogue matches the constructor of the dialog you want to show. If you need further modifications or if the context around the ErrorDialogue needs to be clarified, feel free to ask!