my gui and mcu some times after a long time not communicating, it would freeze after a restarting. how to stop that
Assistant
When dealing with intermittent freezing issues between a graphical user interface (GUI) and a microcontroller unit (MCU), especially after they've stopped communicating for a long time, there are several potential causes and solutions to consider:
Software Reset Handling:
Ensure that both the GUI and the MCU have proper startup and reset routines. Sometimes improper initialization can lead to freezing.
Implement watchdog timers on the MCU to reset it if it becomes unresponsive for a certain period.
Communication Protocol:
Verify the communication protocol between the GUI and the MCU. Common protocols include UART, SPI, I2C, etc. Ensure that all settings (baud rate, parity, etc.) are correctly configured on both ends.
Implement error handling and retransmission logic to recover from communication errors.
Buffer Overflows:
Check for buffer overflows on both the GUI and MCU, which can cause freezing if not properly managed. Use circular buffers and ensure all data is handled timely.
Memory Management:
Ensure adequate memory management, especially on the MCU. Memory leaks can cause crashes or freeze your device after prolonged use.
Free dynamic resources when no longer needed and watch for excessive memory allocation.
Power Supply:
Check the power supply to ensure it is stable and sufficient for both the GUI and MCU. Voltage fluctuations can cause the system to behave erratically.
Error Logging:
Implement logging on both the GUI and MCU to identify when the issue occurs and what might be causing it.
Analyze logs after a freeze to identify patterns or errors leading up to the problem.
Event Loop and Threading:
Ensure that the GUI's event loop is not being blocked by long-running tasks. Use threading or asynchronous operations to handle such tasks.
For the MCU, ensure it can handle multiple operations efficiently without waiting unnecessarily.
Firmware/Software Updates:
Ensure that both the GUI and MCU firmware are up-to-date with the latest patches and bug fixes.
Hardware Reliability:
Check all physical connections between the GUI and MCU, like cables or connectors, to make sure they're not loose or damaged.
Confirm the hardware components themselves are functioning correctly and are suitable for your operational environment.
Timeouts and Keep-Alives:
Implement timeouts for communication actions and a keep-alive signal to ensure the connection is still active.
If these strategies don't resolve your issue, consider debugging further with a more detailed trace of the operations leading up to the freeze or consulting with a specialist familiar with your specific hardware and software setup.
User
libpng warning: iCCP: known incorrect sRGB profile
how to fix this
Assistant
The warning message “libpng warning: iCCP: known incorrect sRGB profile” occurs when the PNG image being processed contains an sRGB color profile that is not fully compliant with the standards expected by the libpng library. This is generally more of a warning than an actual error and often doesn’t affect the displayed image quality. However, if you want to eliminate this warning, you can fix the PNG file by correcting or removing the problematic color profile.
Here’s how to handle this issue:
Using Image Editing Software
GIMP (GNU Image Manipulation Program):
Open the PNG file in GIMP.
Go to Image > Mode and select RGB.
Go to File > Export As and save the image as PNG. Ensure the option Save color profile is checked.
This process should strip any problematic color profiles during the save operation.
Adobe Photoshop:
Open the image in Photoshop.
Go to Edit > Convert to Profile, and choose a valid RGB profile, like sRGB IEC61966-2.1.
Save the image.
Using Command Line Tools
ImageMagick:
Use ImageMagick to strip out the color profiles:
code
magick convert input.png -strip output.png
This command removes all profile information, including any potentially incorrect sRGB profiles.
pngcrush:
You can use pngcrush to specifically address the embedded profiles in PNG files:
code
pngcrush -ow -rem allb -reduce input.png
The -ow flag overwrites the original file, -rem allb removes all ancillary chunks, and -reduce optimizes the PNG.
Using Python
If you are working within a Python environment, you can use the PIL (Pillow) library to handle the problem:
Pillow:
python
from PIL import Image
with Image.open('input.png') as img:
img.save('output.png', icc_profile=None)
The icc_profile=None argument will remove any embedded ICC profile.
These methods should help you remove or correct the ICC profile and remove the warning during processing. If you need to maintain a color profile, ensure that you reassign a correct sRGB profile during the saving process.
User
here is my multi threading code. sometimes it is not responding. how might I fix it.
here is it on the subfunction:
########################threading and button unlock ################
thread_running = False
burn_button.config(state=tk.NORMAL) # Enable the button
validate_button.config(state=tk.NORMAL) # Enable the button
load_button.config(state=tk.NORMAL) # Enable the button
connect_button.config(state=tk.NORMAL) # Enable the button
here is the function that is calling it
################# validation buttion add threading ############
def validate_button_func_threading():
global thread_running
if not thread_running:
thread_running = True
validate_button.config(state=tk.DISABLED) # Disable the butto
burn_button.config(state=tk.DISABLED) # Disable the button
load_button.config(state=tk.DISABLED) # Disable the button
connect_button.config(state=tk.DISABLED) # Disable the button
t = threading.Thread(target=validate_button_func)
t.start()
Assistant
There are several potential reasons why your multithreaded application may become unresponsive, and some areas to consider for improvement. Here are a few suggestions to help you debug and possibly resolve the issue:
Global Variable Management:
Make sure that the thread_running variable is correctly accessed and modified in a thread-safe manner. Consider using a threading.Lock to prevent race conditions:
python
thread_lock = threading.Lock()
def validate_button_func_threading():
global thread_running
with thread_lock:
if not thread_running:
thread_running = True
# Your button-disabled logic here
t = threading.Thread(target=validate_button_func_wrapper)
t.start()
def validate_button_func_wrapper():
try:
validate_button_func() # Your existing function logic
finally:
with thread_lock:
global thread_running
thread_running = False
# Your button-enabled logic here
UI Updates from Background Threads:
In GUI frameworks like Tkinter, it's essential to update the UI from the main thread. If validate_button_func tries to manipulate the UI from the background thread, it can cause issues. Consider using the queue module to pass information between threads and let the main thread update the UI.
Thread Completion:
Ensure the function running in the thread (validate_button_func) completes correctly and updates the thread_running flag back to False.
Error Handling:
Add error handling within your threaded function to prevent exceptions from leaving threads hanging:
python
User
thread_lock what does this do
Assistant
In Python, thread_lock typically refers to an instance of the threading.Lock class. Locks are used in multithreading contexts to ensure that only one thread can access a piece of code or data at a time. This mechanism helps prevent race conditions and ensures data consistency when multiple threads try to modify shared data simultaneously.
What a Lock Does:
Exclusive Access:
A lock allows serialized access to a particular section of code. When one thread acquires the lock and enters a critical section, other threads are blocked from entering until the lock is released.
Preventing Race Conditions:
Race conditions occur when the behavior of software depends on the relative timing of events, such as the order in which different threads reach a specific point in code. A lock helps prevent these conditions by ensuring that only one thread can execute critical code sections at any one time.
Thread Synchronization:
Locks are a synchronization primitive used to coordinate the access to shared resources, preventing multiple threads from simultaneously executing code that can modify shared state.
How to Use a Lock:
Here's a basic usage example with threading and locks in Python:
python
import threading
# Create a lock instance
thread_lock = threading.Lock()
# Shared counter
counter = 0
def increment():
global counter
with thread_lock: # Acquire the lock
for _ in range(1000):
counter += 1
# The lock is automatically released here due to the `with` statement
# Create multiple threads to increment the counter
threads = [threading.Thread(target=increment) for _ in range(10)]
# Start all threads
for thread in threads:
thread.start()
# Wait for all threads to complete
for thread in threads:
thread.join()
print(counter) # Should be 10000 if correctly managed
In this example:
thread_lock ensures that the critical section of code (the block where counter is incremented) is never executed by more than one thread simultaneously.
The with statement is used for acquiring and releasing the lock; it ensures that the lock is released automatically when the block is exited, even if an error occurs within the block.
By using threading.Lock, you can protect shared resources and ensure your program's data remains consistent across threads.
User
most powerful god in DND
Assistant
In Dungeons & Dragons (D&D), the pantheon of gods is vast and complex, with different gods holding sway over different aspects of the game world. The notion of "most powerful" can vary depending on the edition, campaign setting, and the criteria used to define power. However, one deity often considered among the most powerful in various D&D settings is Ao.
Ao
Role: Ao is not a god in the traditional sense but rather the overgod in the Forgotten Realms setting. As an overgod, Ao is responsible for maintaining balance and has authority over all other deities. He is above the pantheon itself and oversees all divine beings.
Powers: Ao's powers are largely mysterious and transcendent, as he governs the very fabric of the multiverse and the rules that other gods must follow.
Not Directly Worshipped: Unlike traditional deities, Ao is not typically worshiped by mortals in the same manner, as his concerns are far beyond mortal affairs.
Other Notable Powerful Deities
The Lady of Pain (Planescape Setting):
Though not a god per se, the Lady of Pain is an incredibly powerful entity that rules over Sigil, the City of Doors. She discourages worship and maintains strict control over her realm.
Asmodeus:
As the Lord of the Nine Hells, Asmodeus is an archdevil with immense power, often depicted as a major antagonist and a god of tyranny and domination.
Lolth:
Known as the Demon Queen of Spiders, Lolth is a powerful deity in the Drow pantheon with substantial influence over her followers and a complex hierarchy of power.
Mystra:
Goddess of Magic, Mystra holds significant power over the Weave, the source of all magic in the Forgotten Realms, making her instrumental in any magical endeavors.
Tiamat and Bahamut:
As the queen of evil dragons, Tiamat is a formidable deity, while Bahamut, the Platinum Dragon, stands as her counterpart in terms of power among the good dragons.
The power and influence of these deities often tie into the thematic elements of a given campaign or setting, making them central to various conflicts and narratives within the D&D universe. Ultimately, the perception of power among gods often ties into the narrative a Dungeon Master wishes to create, and they can depict deities as powerful as serves their story.
User
what about Moradin
Assistant
Moradin is a major deity in Dungeons & Dragons, particularly in campaign settings like the Forgotten Realms and Greyhawk. He is a significant figure among the dwarven pantheon and revered by dwarves across many worlds. Here’s an overview of Moradin and his role:
Moradin
Title: Moradin is also known as "The Soul Forger," "The Dwarffather," and "The All-Father."
Domains: Primary domains include creation, craftsmanship, family, dwarves, and smithing. He is often associated with the Forge domain in Fifth Edition.
Alignment: Typically portrayed as Lawful Good, emphasizing the values of law, community, and the betterment of society through hard work and innovation.
Symbol: His symbol is often a hammer and anvil, reflecting his strong association with crafting and blacksmithing.
Influence and Worship
Dwarven Culture: Moradin is the chief deity of the dwarves, credited with creating the dwarven race from metal and gems, imbuing them with life, resilience, and a never-ending quest for excellence in their crafts.
Craftsmanship: Dwarves and their followers look to Moradin for guidance in crafting and smithing, drawing inspiration for new creations.
Clan and Justice: He is also a guardian of family and community values, promoting unity and justice within dwarven society.
Power and Role
As a Deity: Moradin's influence extends through his role as a divine figure who oversees crafts and diligence. While powerful, his focus is more on the constructive and nurturing aspects of power, promoting growth and stability over dominance.
In Campaigns: Moradin often plays a role in campaigns that involve dwarven lore, ancient crafts, or underground settings. His values might be central to solving conflicts or protecting communities.
In terms of power relative to other deities, Moradin's influence lies heavily on his devoted followers and the strength of dwarven societies rather than sheer dominance over other gods. In campaigns, his achievements often serve as a beacon of hope and resilience for dwarves and those who share his values. His role can evolve depending on the story being told but usually reflects themes of craftsmanship, order, and tradition.
User
I made a gui with mcu code using tkinter. it works fine. but after the exe rest a while, and activitated again, it doesnt respond, also Im using multithreading. and I have value saved in a var
Assistant
When a GUI application created with Tkinter becomes unresponsive after a period of inactivity, especially when multithreading is involved, there are a few potential areas to investigate and optimize. Let's go through some common solutions and debugging strategies:
Potential Causes and Solutions
Thread Management:
Ensure Proper Thread Closure: Check if all threads are completing their execution or if they're left hanging. If a thread remains active while you think the application is idle, it might conflict when re-activating.
Use Daemon Threads: Set threads as daemon threads if they should not prevent the program from exiting. This can be done by setting t.daemon = True before starting the thread.
Updating GUI Safely:
Tkinter is not thread-safe, meaning you should not update the GUI from any thread other than the main thread. Use thread-safe methods like queue.Queue to communicate between threads and the main GUI thread.
Another approach is using tkinter's after() method to schedule GUI updates in the main thread.
Synchronization Issues:
Ensure shared resources or variables accessed by multiple threads are appropriately synchronized to prevent race conditions, which can lead to unresponsiveness.
Resource Management:
Check for Memory Leaks: If your application is consuming excessive memory over time, it might become unresponsive due to resource exhaustion.
Close Connections Properly: If your application involves network connections or file operations, make sure all resources are opened and closed correctly.
Error Handling:
Implement comprehensive error handling to catch and log exceptions in your functions, especially in threaded functions. This can help identify issues you may not notice during typical operation.
Debugging Strategies
Logging:
Use Python's logging module to log events and errors. This will provide insights into what the application is doing and where it might be failing.
Simplify the Code:
Isolate sections of your code to pinpoint where the problem may arise. Start by simplifying the threading logic and gradually add components back.
User
so Im using a kl25z as the mcu, and sometimes it does not responds after a few minutes. is it because it went to low power mode?
Assistant
If you are using a KL25Z microcontroller and notice that it becomes unresponsive after a few minutes, it's possible that the device is entering a low-power mode unintentionally. The KL25Z, like many microcontrollers, has built-in energy-saving features that allow it to enter various low-power states to conserve energy. Here's how you might address this issue:
Potential Causes and Solutions
Check Power Modes:
Understand Power Modes: The KL25Z supports several power modes, including Run, Wait, Stop, and VLPR (Very Low Power Run). If the device transitions into a low-power state, it may suspend operations or reduce clock speed.
Review Configuration: Ensure that your application isn’t configuring the microcontroller to enter a low-power mode after a period of inactivity unless intended. Check your code for any low-power configuration functions.
Preventing Low-Power Mode Entry:
Disable Unintentional Transitions: If low-power modes are not needed, ensure that any code triggering these modes is disabled or removed.
Keep-alive Signals: Implement periodic "keep-alive" signals to prevent the MCU from entering low-power states if its intended operating mode requires constant full-speed operation.
Revisiting Power Management Code:
Inspect Power Management Functions: Look at any power management functions in your code that might configure the MCU's clock or power states inadvertently. Remove or adjust them as necessary.
Watchdog Timers: Implement or configure a watchdog timer to reset the device if it becomes unresponsive, which can help recover from unintended states.
Interrupt Management:
Ensure that interrupts used to wake the MCU from low-power modes are correctly configured and functioning.
Verify that the interrupt service routines are exiting correctly and not leaving the device in a low-power state.
Check External Influences:
Ensure a stable and sufficient power supply to the board. Voltage dips could inadvertently place the MCU in a low-power mode.
Consider external influences or other devices that might affect the power state on shared buses or peripherals.
Debugging and Monitoring:
Use a debugger to monitor the state of the MCU and see if it enters a low-power state.
User
is it possible to just make sure my serial is open before I send all the signals,
Assistant
Yes, ensuring that your serial connection is open before sending signals is a crucial step in maintaining robust communication between your GUI application and the microcontroller (such as the KL25Z). Here are some strategies to ensure your serial communication is correctly managed:
Strategies to Ensure Serial Connection is Open
Explicit Connection Check:
Before sending any data, explicitly check if the serial port is open. Most serial communication libraries provide methods to open, close, and check the status of the connection.
Example using Python's pyserial:
python
import serial
# Attempt to open a serial connection
ser = serial.Serial('COM3', 9600, timeout=1)
# Check if the serial port is open before sending data
if ser.is_open:
ser.write(b'Your data here')
else:
print("Serial port is not open.")
Reopen if Not Open:
If the connection is found to be closed, attempt to reopen it before trying to send data. Handle exceptions that might occur during this process.
python
if not ser.is_open:
try:
ser.open()
if ser.is_open:
ser.write(b'Your data here')
except serial.SerialException as e:
print(f"Failed to open serial port: {e}")
Use a Connection Wrapper:
Wrap the serial read/write operations in functions that check for the connection status, making your code cleaner and more centralized.
python
def send_serial_data(data):
if ser.is_open or reopen_serial():
ser.write(data)
else:
print("Failed to maintain open serial connection.")
def reopen_serial():
try:
ser.open()
return ser.is_open
except serial.SerialException as e:
print(f"Error opening serial port: {e}")
return False
User
how to do a try in python
Assistant
In Python, a try statement is used to handle exceptions, which are errors that occur during the execution of the program. By using try, you can write code that may potentially raise exceptions and handle them gracefully, preventing your program from crashing unexpectedly.
Basic Structure of try Statement
Here's how you can use a try block in Python:
python
try:
# Code that might raise an exception
risky_operation()
except SomeSpecificException as e:
# Code to handle the specific exception
print(f"An error occurred: {e}")
except AnotherException as e:
# Code to handle another type of exception
print(f"Different error occurred: {e}")
else:
# Code to execute if no exceptions are raised
print("Operation successful, no exceptions raised.")
finally:
# Code that will run no matter what, whether an exception occurred or not
print("This will run regardless of exceptions.")
Explanation
try block:
Contains code that might raise an exception. Python will attempt to execute this code first.
except block:
Catches and handles specific exceptions that are specified. If an exception of the specified type occurs in the try block, control goes to the corresponding except block.
Exceptions can be any built-in exceptions like ValueError, TypeError, IOError, etc., or user-defined exceptions.
else block (optional):
If the try block does not raise an exception, the else block will be executed.
This block is executed only if no exceptions occur.
finally block (optional):
Contains code that needs to run regardless of whether an exception was raised. This is often used to release resources, like file handlers or database connections.
User
try:
ser.open()
else:
pass
would this work
Assistant
The syntax you provided is not quite correct for a try block in Python. Specifically, the else statement cannot be directly used after a try statement without the preceding except clause. The else clause in a try block is used to execute code if no exceptions are raised, and it must come after any except clauses. Here’s a fixed version of your code:
python
try:
ser.open() # Attempt to open the serial port
except Exception as e: # Change Exception to a more specific exception if possible
print(f"An error occurred: {e}")
else:
# This block runs only if no exceptions were raised in the try block
print("Serial port opened successfully.")
# There's no need for a pass statement unless you explicitly need to do nothing
Explanation:
try block: You attempt to execute a potentially error-prone operation (ser.open()).
except block: You catch and handle exceptions that might be raised. It’s good practice to catch only specific exceptions if you know which ones to expect, such as serial.SerialException for serial operations with pyserial.
else block: This block executes only if the try block executes without raising any exceptions. It is often used when you want to run some code that should only execute if the operation was successful.
finally block (if needed): Optionally, you could add a finally block to perform cleanup actions regardless of success or failure.
The use of pass is generally unnecessary unless you're developing the code incrementally and just want to hold places for where you intend to implement logic later. In production code, you should replace pass with meaningful logic, typically error handling or logging.
User
try:
ser.open()
else:
pass
I dont want any print , just try to open it so it wont go to sleep.
Assistant
If you want to attempt an operation without any output or additional handling when it succeeds, you still need to handle it correctly according to Python's syntax for try statements. You want to open the serial connection and ignore any exceptions silently. In this case, you can use an except block with a pass statement, which means "do nothing" if an exception occurs.
Here’s how you can write this:
python
try:
ser.open() # Attempt to open the serial port
except Exception: # Catch all exceptions and do nothing
pass
Explanation:
try block: This attempts the potentially failing operation (ser.open()).
except Exception:: Catches any exception that might occur during the try block without specifying any particular action afterward. This pattern allows the program to continue running even if an exception is raised, but nothing will be printed or otherwise visible to the user.
Using pass in the except block ensures that no errors are raised to the user, and the program will continue executing subsequent lines of code. If you're aware of specific exceptions that can occur when trying to open the serial port, it's better practice to catch those specific exceptions. If you're using pyserial, exceptions like SerialException could be handled specifically if you prefer a more precise approach.
However, if you explicitly want no action and no error output, the pattern above achieves that.
User
this is my gui, my mcu sometimes stops responding after I waited for a while how do I add some code to pre wake up my MCU serial communication.
import os
import time
import serial.tools.list_ports
import tkinter as tk
import threading
from tkinter import ttk
from tkinter import *
from tkinter import filedialog
from tkinter import messagebox
from tkinter.scrolledtext import ScrolledText
os.system('clear') #clear console
thread_running = False
thread_lock = threading.Lock()
################################ declaring global variables ################################
version = '1' #version comparesion require to check with MCU as it connects
device_selected = '' #Com port selects
ser = None #var for communication with MCU
timeout = 1 #timeout timers for connection lost
file_type = '' #identify if IHEX file is used
file_data = '' #otp code pulled from IHEX file
product_data = '' #device code for the device burn setup
validate_data = '' #log data when validating
status = 'unknown' #pass or fall
current_directory = os.getcwd() #get current file directory
otp_devices_directory = os.path.join(current_directory, 'otp_devices') #go to otp deivces directory
OTP_devices = [] #var for the device list
OTP_devices = os.listdir(otp_devices_directory) #get device lists
OTP_devices = [file[:-4] for file in OTP_devices] #gets rid of the .txt in the device name
CRC_ENABLE = '0' #CRC enable disable
################################ Functons ###################################
#################### check the com port and return a list #####################
def get_ports():
ports = serial.tools.list_ports.comports()
ports_descriptions = [] #create an empty list to store port descriptions
for p in ports:
ports_descriptions.append(p.description) #Add the description to the list
return ports_descriptions
#################### connect the port #####################
def find_port(ports_description):
com_port = 'None'
numConnection = len(ports_description)
for i in range(0,numConnection):
port = ports_description[i]
strport = str(port)
if 'OpenSDA' in strport: #check for Opensda for ports name and autoselect
splitport = strport.split(' ')
com_port_b = splitport[-1]
com_port = com_port_b.strip("()")
return com_port
#################### read from MCU uart and decode the message
def read_string(ser, delimiter=b'\r'):
response = b""
while True:
char = ser.read(1)
if char == delimiter:
break
response += char
return response.decode()
#################### load button function: ##########################
def load_button():
global file_data
global file_type
validate_button.config(state=tk.DISABLED) # Disable the button
burn_button.config(state=tk.DISABLED) # Disable the button
connect_button.config(state=tk.DISABLED) # Disable the button
file_path = tk.filedialog.askopenfilename()
path_list = file_path.split('/')
path_number = len(path_list) - 1
path_display = path_list[path_number]
otp_file['text'] = path_display #set displace txt file name
file_name = path_display.replace('_','') #set file type for identification
if 'IHEX' in file_name:
log.insert(END,'IHEX file found\n')
file_type = 'IHEX'
else:
messagebox.showinfo('warning','can not identify IHEX file')
return None
with open(file_path, 'r') as file: #load data to var
file_data = file.read()
burn_button.config(state=tk.NORMAL) # Enable the button
validate_button.config(state=tk.NORMAL) # Enable the button
connect_button.config(state=tk.NORMAL) # Enable the button
#################### connect button function: #################################
def connect_button():
############### get device info #############
global product_data
global ser
device_selected = device_list.get()
#connect device
if connect_button['text'] == 'Disconnected':
#if none value selected
if device_selected == '':
messagebox.showinfo('warning','No value found in device selection')
return None
else:
device_selected_directory = os.path.join(otp_devices_directory, device_selected + '.txt')
with open(device_selected_directory, 'r') as file: #save the device configure file to product_data
product_data = file.read()
############### connect to device #############
connect_port = find_port(get_ports())
if connect_port != 'None':
ser = serial.Serial(connect_port, baudrate = 9600, timeout = 1)
else:
messagebox.showinfo('warning','No connection found')
return None
############### verify mcu code versions #############
ser.write(b'a')
connect_check = ser.read().decode()
if connect_check == (version): ### check version and check connection ###
log.insert(END,'device conneted\n')
connect_button.config(bg='#83b079', text='conneted')
burn_button.config(state="normal")
validate_button.config(state="normal")
device_list.config(state="disabled")
else:
messagebox.showinfo('warning','no correct device found\n(please check connected device and check version)')
return None
else:
############### disconnect device ###############
ser.close()
log.insert(END,'device disconneted\n')
connect_button.config(bg='#dce3df', text='Disconnected')
burn_button.config(state="disabled")
validate_button.config(state="disabled")
device_list.config(state="normal")
Assistant
To ensure your MCU stays "awake" and responsive to incoming serial commands, you can implement a periodic "keep-alive" signal. This is a common technique used to prevent devices from going into a low-power mode. Here's how you might implement it in your Tkinter GUI:
Steps to Implement a Keep-Alive Mechanism
Define a Keep-Alive Function: Create a function that sends a simple command or signal to the MCU. You could send a no-operation signal or a command that you know will not alter the state of the device but serves to keep the connection active.
Schedule Periodic Calls: Use the Tkinter after() method to schedule your keep-alive function to run at regular intervals. This method runs your function in the main thread at a specified time interval without interrupting the GUI's event loop.
Check Serial Connection: Before sending the keep-alive signal, ensure the serial connection is open.
Here is an example of how you might incorporate this into your existing code:
python
def send_keep_alive():
"""Send a keep-alive signal periodically to keep the MCU awake."""
try:
if ser and ser.is_open: # Check if the serial connection is open
# Send a simple command or character as keep-alive
ser.write(b'k') # 'k' could be any character that acts as a keep-alive
print("Keep-alive signal sent.") # Optional logging to monitor activity
else:
print("Serial connection not open. Cannot send keep-alive.")
except serial.SerialException as e:
print(f"Error sending keep-alive: {e}")
# Schedule the send_keep_alive function to call itself every 5 minutes (300000 ms)
window.after(300000, send_keep_alive) # Adjust the time as needed for your application
# Start sending keep-alive signals after the GUI has started
window.after(300000, send_keep_alive) # Initial scheduling to start the keep-alive process
Not yet included in a published release.
def validate_button_func():
try:
# Your existing code
except Exception as e:
print(f"Thread encountered an error: {e}")
finally:
# Ensure this runs to re-enable the buttons
with thread_lock:
global thread_running
thread_running = False
# Your button-enabled logic here
Long-running Operations:
If your function performs long-running operations, break it down into smaller tasks or ensure it regularly checks for an abort condition (like threading events or a time check).
Concurrency Issues:
Look for shared resources accessed by multiple threads without proper locking mechanisms, as this could lead to deadlocks or race conditions causing the application to hang.
Use of the after() Method:
For long-running tasks that need to frequently update the UI, consider periodically using the after() method to schedule updates on the UI thread.
By ensuring proper thread management, UI update practices, and error handling in your threaded application, you can prevent the program from becoming unresponsive. Debugging with extensive logging will also be helpful in tracking down where the problem occurs.
Check Blocking Operations:
Ensure no part of the code inside threads is blocking for an extended period, especially if waiting for network responses or input.
Run Performance Profiling:
Use tools or libraries to profile your code and identify parts that cause blocking or consume excessive resources.
User Interface Feedback:
Ensure the UI provides feedback, such as disabling buttons or showing loading indicators when it’s busy or when threads are running.
By following these potential solutions and debugging strategies, you should be able to pinpoint or resolve the issue causing your Tkinter application to become unresponsive after a period of inactivity. Remember, multithreading and GUI operations can be complex, so analyze your architecture carefully to keep threads and the GUI in harmony.
Log activity or status indicators to help determine the conditions leading to unresponsiveness.
Additional Tips
Review the KL25Z reference manual to understand specific instructions related to power modes and state transitions.
If low-power modes are needed for power savings, ensure proper wake-up sources and handling are implemented.
Consider reaching out to forums or communities specific to the KL25Z for shared experiences and solutions.
By carefully assessing the power management options and current configuration, you can identify why the KL25Z is becoming unresponsive and adjust your setup to prevent it from unintentionally entering low-power modes.
Implement Connection Monitoring:
Periodically check the connection status and log any disconnection events. Reconnect as needed.
python
from threading import Timer
def monitor_serial_connection():
if not ser.is_open:
print("Serial port closed. Attempting to reopen...")
reopen_serial()
Timer(5.0, monitor_serial_connection).start()
# Start monitoring before main logic
monitor_serial_connection()
Exception Handling:
Implement try-except blocks around serial.write() operations to catch disconnection or other errors, and possibly attempt to reopen the connection.
python
try:
ser.write(b'Your data here')
except serial.SerialException as e:
print(f"Serial communication error: {e}")
reopen_serial()
Logging and Debugging:
Use logging to track connection status and data transmission errors, which can provide insights into why and when the connection closes if unexpected.
By ensuring that your serial connection is managed properly, you can avoid issues related to attempting to write to a closed port. These strategies should help diagnose and maintain reliable communication with your microcontroller.
Example: File Operations
Here's an example using file operations where exceptions might occur due to missing files or permission errors:
python
try:
with open('somefile.txt', 'r') as file:
content = file.read()
print(content)
except FileNotFoundError as e:
print(f"Error: {e}. File not found.")
except IOError as e:
print(f"Error: {e}. I/O error occurred.")
else:
print("File has been read successfully.")
finally:
print("File operation attempted.")
Best Practices
Use specific exceptions in the except block to handle known errors. Avoid using a bare except: without specifying an exception type, as it can catch unexpected errors, including system-exiting exceptions like SystemExit and KeyboardInterrupt.
Always consider using the finally block for clean-up actions.
When debugging, logging exception messages and stack traces can be helpful for understanding what went wrong.
These practices will help you handle exceptions properly and make your code more robust and error-tolerant.
#################### burn button loop & function: #################################
def burn_button_func():
global product_data
global file_data
global timeout
global CRC_ENABLE
global status
global thread_running
status = 'pass' #pass or fall
lines = product_data.splitlines()
OTP_lines = file_data.splitlines()
result.config(text='UNKNOW', bg='yellow')
code
############## Device info section: ###############
COM_TYPE = lines[lines.index("Device info:") + 1].split(":")[0] #SPI/I2C
OTP_TYPE = lines[lines.index("Device info:") + 1].split(":")[1] #MIRROR/DIRECT
BYTE_SIZE = lines[lines.index("Device info:") + 2].split(":")[1] #BYTE_SIZE
FS_REG = lines[lines.index("Device info:") + 3].split(":")[1] #FS_REGISTER: YES/NO
CRC = lines[lines.index("Device info:") + 4].split(":")[1] #CRC: YES/NO
VOTP = lines[lines.index("Device info:") + 5].split(":")[1] #VOTP: YES/NO
MAIN_I2C_ADDRESS = lines[lines.index("Device info:") + 6].split(":")[1] #MAIN_I2C_ADDRESS
FAILSAFE_I2C_ADDRESS = lines[lines.index("Device info:") + 7].split(":")[1] #FAILSAFE_I2C_ADDRESS
############## Ihex info section: ###############
MAIN_OTP_IHEX_START = int(lines[lines.index("Ihex info:") + 1].split(":")[1]) #MAIN_OTP_IHEX_START_AD
MAIN_OTP_IHEX_END = int(lines[lines.index("Ihex info:") + 1].split(":")[2]) #MAIN_OTP_IHEX_END_AD
FS_OTP_IHEX_START = int(lines[lines.index("Ihex info:") + 2].split(":")[1]) #FS_OTP_IHEX_START_AD
FS_OTP_IHEX_END = int(lines[lines.index("Ihex info:") + 2].split(":")[2]) #FS_OTP_IHEX_START_AD
MAIN_VOTP_IHEX_START = int(lines[lines.index("Ihex info:") + 3].split(":")[1]) #MAIN_VOTP_IHEX_START_AD
MAIN_VOTP_IHEX_END = int(lines[lines.index("Ihex info:") + 3].split(":")[2]) #MAIN_VOTP_IHEX_END_AD
FS_VOTP_IHEX_START = int(lines[lines.index("Ihex info:") + 4].split(":")[1]) #FS_VOTP_IHEX_START_AD
FS_VOTP_IHEX_END = int(lines[lines.index("Ihex info:") + 4].split(":")[2]) #FS_VOTP_IHEX_END_AD
M_MIRRORCMD = lines[lines.index("Ihex info:") + 5].split(":")[1] #M_MIRRORCMD_AD
M_MIRRORDATA = lines[lines.index("Ihex info:") + 6].split(":")[1] #M_MIRRORDATA_AD
FS_MIRRORCMD = lines[lines.index("Ihex info:") + 7].split(":")[1] #FS_MIRRORCMD_AD
FS_MIRRORDATA = lines[lines.index("Ihex info:") + 8].split(":")[1] #FS_MIRRORDATA_AD
####################### validation info section #######################
Validate_CMD = lines[lines.index("validation info:") + 1].split(":")[1] #Validate_CMD
VALIDATION_DATA_FORMAT = lines[lines.index("validation info:") + 2].split(":")[1] #Validate_DATA_format
MAIN_ADD_START = int(lines[lines.index("validation info:") + 3].split(":")[1],16) #Main_OTP_ADD_RANGE_START
MAIN_ADD_END = int(lines[lines.index("validation info:") + 3].split(":")[2],16) #Main_OTP_ADD_RANGE_END
FS_ADD_START = int(lines[lines.index("validation info:") + 4].split(":")[1],16) #FS_OTP_ADD_RANGE_START
FS_ADD_END = int(lines[lines.index("validation info:") + 4].split(":")[2],16) #FS_OTP_ADD_RANGE_END
VMAIN_ADD_START = int(lines[lines.index("validation info:") + 5].split(":")[1],16) #Main_VOTP_ADD_RANGE_START
VMAIN_ADD_END = int(lines[lines.index("validation info:") + 5].split(":")[2],16) #Main_VOTP_ADD_RANGE_END
VFS_ADD_START = int(lines[lines.index("validation info:") + 6].split(":")[1],16) #FS_VOTP_ADD_RANGE_START
VFS_ADD_END = int(lines[lines.index("validation info:") + 6].split(":")[2],16) #FS_VOTP_ADD_RANGE_START
####################### byte size #######################
BYTE_SIZE_INT = int(BYTE_SIZE)
ser.write('J'.encode('utf-8'))
############### CRC_Enable disable check
if CRC =='YES':
CRC_ENABLE = '1' #CRC enable
else:
CRC_ENABLE = '0' #CRC disable
############### send byte number info to MCU ############
ser.write('y'.encode('utf-8'))
ser.write((BYTE_SIZE + '%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
log.see("end")
log.insert(END,'start otp burning process\n')
#########################################################
############## Device Power Up: ################
for line in lines[lines.index("Power up:") + 1:lines.index("Power up complete:")]:
setup = line.split('/')
ser.write(setup[0].encode('utf-8'))
ser.write((setup[1]+'%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
log.see("end")
log.see("end")
log.insert(END,'Power up process complete\n\n')
##################################################
############## Test mode entry: ################
for line in lines[lines.index("Main test mode entry:") + 1:lines.index("Main test mode entry complete:")]:
setup = line.split('/')
ser.write(setup[0].encode('utf-8'))
ser.write((setup[1]+'%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
log.see("end")
log.see("end")
log.insert(END,'Main test mode entry process complete\n\n')
##################################################
################ save main Ihex value #########################################
for line in OTP_lines[MAIN_OTP_IHEX_START:MAIN_OTP_IHEX_END]:
Byte_count = int((line)[1:3],16)
Starting_ad = (line)[3:7]
Record_type = (line)[7:9]
data = (line)[9:9+Byte_count*2]
Check_sum = (line)[9+Byte_count*2:9+Byte_count*2+2]
##############end check################
if (Record_type == '01'): #01 indicate the end
break
for i in range(0, len(data),2):
otp_value = data[i:i+2]
########### sidence controller scheme ############## adding 00 based on BYTE_SIZE
if OTP_TYPE == 'MIRROR':
M_MIRRIOR_CMD_length = len('01')
Starting_ad_hex_send = int(Starting_ad, 16) + (i // 2)
required_length = 2 * BYTE_SIZE_INT
otp_add = format(Starting_ad_hex_send, f'0{required_length - M_MIRRIOR_CMD_length}x')
otp_add = '01' + otp_add
if MAIN_ADD_START <= Starting_ad_hex_send <= MAIN_ADD_END:
if COM_TYPE == 'SPI':
signal = 'm'
ser.write(signal.encode('utf-8'))
ser.write((M_MIRRORDATA + ';' + otp_value + ';' + CRC_ENABLE + '%' ).encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
ser.write(signal.encode('utf-8'))
ser.write((M_MIRRORCMD + ';' + otp_add + ';' + CRC_ENABLE + '%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
else:
signal = 'l'
ser.write(signal.encode('utf-8'))
ser.write((MAIN_I2C_ADDRESS+';'+ M_MIRRORDATA + ';' + otp_value + ';' + CRC_ENABLE + '%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
ser.write(signal.encode('utf-8'))
ser.write((MAIN_I2C_ADDRESS+';'+ M_MIRRORCMD +';'+ otp_add + ';' + CRC_ENABLE + '%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
else:
continue
else:
########### non-sidence controller scheme ##############
Starting_ad_hex_send = hex(int(Starting_ad,16) + i // 2)
Starting_ad_int_send = int(Starting_ad, 16) + (i // 2)
otp_add = str(Starting_ad_hex_send).replace('0x', '')
if MAIN_ADD_START <= Starting_ad_int_send <= MAIN_ADD_END:
if COM_TYPE == 'SPI':
signal = 'm'
ser.write(signal.encode('utf-8'))
ser.write((otp_add + ';' + otp_value + ';' + CRC_ENABLE + ';M%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
else:
signal = 'l'
ser.write(signal.encode('utf-8'))
ser.write((MAIN_I2C_ADDRESS +';'+ otp_add + ';' + otp_value + ';' + CRC_ENABLE + '%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
else:
continue
log.see("end")
log.see("end")
log.insert(END,'Main OTP Ihex loading process complete\n\n')
############## Config OTP Controller and burn ###############
for line in lines[lines.index("Config main OTP controller:") + 1:lines.index("Config main OTP controller complete:")]:
setup = line.split('/')
ser.write(setup[0].encode('utf-8'))
ser.write((setup[1]+'%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
log.see("end")
log.see("end")
log.insert(END,'Main OTP burn process complete\n\n')
############## Burn BE and WP ###############
for line in lines[lines.index("Burn main OTP BE and WP:") + 1:lines.index("Burn main OTP BE and WP complete:")]:
setup = line.split('/')
ser.write(setup[0].encode('utf-8'))
ser.write((setup[1]+'%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
log.see("end")
log.see("end")
log.insert(END,'Burn main OTP BE and WP process complete\n\n')
#################################################################################
################ VOTP main ##################################################
if (VOTP != 'YES'): #01 indicate the end
pass
else:
############## Test mode entry: ################
for line in lines[lines.index("Main test mode entry:") + 1:lines.index("Main test mode entry complete:")]:
setup = line.split('/')
ser.write(setup[0].encode('utf-8'))
ser.write((setup[1]+'%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
log.see("end")
log.see("end")
log.insert(END,'Main test mode entry process complete\n\n')
##################################################
################ save main otp Ihex value #################
for line in OTP_lines[MAIN_VOTP_IHEX_START:MAIN_VOTP_IHEX_END]:
Byte_count = int((line)[1:3],16)
Starting_ad = (line)[3:7]
Record_type = (line)[7:9]
data = (line)[9:9+Byte_count*2]
Check_sum = (line)[9+Byte_count*2:9+Byte_count*2+2]
##############end check################
if (Record_type == '01'): #01 indicate the end
break
for i in range(0, len(data),2):
otp_value = data[i:i+2]
########### sidence controller scheme ###########
if OTP_TYPE == 'MIRROR':
M_VMIRRIOR_CMD_length = len('01')
Starting_ad_hex_send = int(Starting_ad, 16) + (i // 2)
required_length = 2 * BYTE_SIZE_INT
otp_add = format(Starting_ad_hex_send, f'0{required_length - M_VMIRRIOR_CMD_length}x')
otp_add = '01' + otp_add
if VMAIN_ADD_START <= Starting_ad_hex_send <= VMAIN_ADD_END:
if COM_TYPE == 'SPI':
signal = 'm'
ser.write(signal.encode('utf-8'))
ser.write((M_MIRRORDATA + ';' + otp_value + ';' + CRC_ENABLE + '%' ).encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
ser.write(signal.encode('utf-8'))
ser.write((M_MIRRORCMD + ';' + otp_add + ';' + CRC_ENABLE + '%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
else:
signal = 'l'
ser.write(signal.encode('utf-8'))
ser.write((MAIN_I2C_ADDRESS+';'+ M_MIRRORDATA + ';' + otp_value + ';' + CRC_ENABLE + '%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
ser.write(signal.encode('utf-8'))
ser.write((MAIN_I2C_ADDRESS+';'+ M_MIRRORCMD +';'+ otp_add + ';' + CRC_ENABLE + '%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
else:
continue
else:
########### non-sidence controller scheme ##############
Starting_ad_hex_send = hex(int(Starting_ad,16) + i // 2)
Starting_ad_int_send = int(Starting_ad, 16) + (i // 2)
otp_add = str(Starting_ad_hex_send).replace('0x', '')
if VMAIN_ADD_START <= Starting_ad_int_send <= VMAIN_ADD_END:
if COM_TYPE == 'SPI':
signal = 'm'
ser.write(signal.encode('utf-8'))
ser.write((otp_add + ';' + otp_value + ';' + CRC_ENABLE + '%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
else:
signal = 'l'
ser.write(signal.encode('utf-8'))
ser.write((MAIN_I2C_ADDRESS +';'+ otp_add + ';' + otp_value + ';' + CRC_ENABLE + '%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
else:
continue
log.see("end")
log.see("end")
log.insert(END,'Main VOTP Ihex loading process complete\n\n')
############## Config OTP Controller and burn ###############
for line in lines[lines.index("Config main VOTP controller:") + 1:lines.index("Config main VOTP controller complete:")]:
setup = line.split('/')
ser.write(setup[0].encode('utf-8'))
ser.write((setup[1]+'%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
log.see("end")
log.see("end")
log.insert(END,'Main VOTP burn process complete\n\n')
############## Burn BE and WP ###############
for line in lines[lines.index("Burn main VOTP BE and WP:") + 1:lines.index("Burn main VOTP BE and WP complete:")]:
setup = line.split('/')
ser.write(setup[0].encode('utf-8'))
ser.write((setup[1]+'%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
log.see("end")
log.see("end")
log.insert(END,'Burn main VOTP BE and WP process complete\n\n')
#############################################################################
################################### Safety otp ############################################
############## Run Ihex for Safety otp ###############
if (FS_REG != 'YES'): #01 indicate the end
pass
else:
################### FS test mode entry #################
for line in lines[lines.index("FS test mode entry:") + 1:lines.index("FS test mode entry complete:")]:
setup = line.split('/')
ser.write(setup[0].encode('utf-8'))
ser.write((setup[1]+'%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
log.see("end")
log.see("end")
log.insert(END,'FS test mode entry process complete\n\n')
######################################################
################ save FS Ihex value #################
for line in OTP_lines[FS_OTP_IHEX_START:FS_OTP_IHEX_END]:
Byte_count = int((line)[1:3],16)
Starting_ad = (line)[3:7]
Record_type = (line)[7:9]
data = (line)[9:9+Byte_count*2]
Check_sum = (line)[9+Byte_count*2:9+Byte_count*2+2]
##############end check################
if (Record_type == '01'): #01 indicate the end
break
for i in range(0, len(data),2):
otp_value = data[i:i+2]
########### start sending OTP burning code ##############
if OTP_TYPE == 'MIRROR':
M_MIRRIOR_CMD_length = len('01')
Starting_ad_hex_send = int(Starting_ad, 16) + (i // 2)
required_length = 2 * BYTE_SIZE_INT
otp_add = format(Starting_ad_hex_send, f'0{required_length - M_MIRRIOR_CMD_length}x')
otp_add = '01' + otp_add
if FS_ADD_START <= Starting_ad_hex_send <= FS_ADD_END:
if COM_TYPE == 'SPI':
signal = 'm'
ser.write(signal.encode('utf-8'))
ser.write((FS_MIRRORDATA + ';' + otp_value + ';' + CRC_ENABLE + '%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
ser.write(signal.encode('utf-8'))
ser.write((FS_MIRRORCMD +';'+ otp_add + ';' + CRC_ENABLE + '%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
else:
signal = 'l'
ser.write(signal.encode('utf-8'))
ser.write((FAILSAFE_I2C_ADDRESS +';' + FS_MIRRORDATA + ';' + otp_value + ';' + CRC_ENABLE + '%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
ser.write(signal.encode('utf-8'))
ser.write((FAILSAFE_I2C_ADDRESS + ';' + FS_MIRRORCMD +';'+ otp_add + ';' + CRC_ENABLE + '%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
else:
continue
else:
Starting_ad_hex_send = hex(int(Starting_ad,16) + i//2)
otp_add = str(Starting_ad_hex_send).replace('0x', '')
if FS_ADD_START <= Starting_ad_hex_send <= FS_ADD_END:
if COM_TYPE == 'SPI':
signal = 'm'
ser.write(signal.encode('utf-8'))
ser.write((otp_value + ';' + otp_add + ';' + CRC_ENABLE + '%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
else:
signal = 'l'
ser.write(signal.encode('utf-8'))
ser.write((FAILSAFE_I2C_ADDRESS + ';' + otp_add + ';' + otp_value + ';' + CRC_ENABLE + '%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
else:
continue
log.see("end")
log.insert(END,'FS OTP Ihex loading process complete\n\n')
############## config FS OTP controller and burn ###############
for line in lines[lines.index("Config FS OTP controller:") + 1:lines.index("Config FS OTP controller complete:")]:
setup = line.split('/')
ser.write(setup[0].encode('utf-8'))
ser.write((setup[1]+'%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
log.see("end")
log.see("end")
log.insert(END,'FS OTP burn process complete\n\n')
############## Burn FS BE and WP ###############
for line in lines[lines.index("Burn FS OTP BE and WP:") + 1:lines.index("Burn FS OTP BE and WP complete:")]:
setup = line.split('/')
ser.write(setup[0].encode('utf-8'))
ser.write((setup[1]+'%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
log.see("end")
log.see("end")
log.insert(END,'Burn FS OTP BE and WP process complete\n\n')
################## VOTP FS ##################
if (VOTP != 'YES'):
pass
else:
################### FS test mode entry #################
for line in lines[lines.index("FS test mode entry:") + 1:lines.index("FS test mode entry complete:")]:
setup = line.split('/')
ser.write(setup[0].encode('utf-8'))
ser.write((setup[1]+'%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
log.see("end")
log.see("end")
log.insert(END,'FS test mode entry process complete\n\n')
################################################################
for line in OTP_lines[FS_VOTP_IHEX_START:FS_VOTP_IHEX_END]:
Byte_count = int((line)[1:3],16)
Starting_ad = (line)[3:7]
Record_type = (line)[7:9]
data = (line)[9:9+Byte_count*2]
Check_sum = (line)[9+Byte_count*2:9+Byte_count*2+2]
##############end check################
if (Record_type == '01'): #01 indicate the end
break
for i in range(0, len(data),2):
otp_value = data[i:i+2]
########### sidence controller scheme ###########
if OTP_TYPE == 'MIRROR':
FS_VMIRRIOR_CMD_length = len('01')
Starting_ad_hex_send = int(Starting_ad, 16) + (i // 2)
required_length = 2 * BYTE_SIZE_INT
otp_add = format(Starting_ad_hex_send, f'0{required_length - FS_VMIRRIOR_CMD_length}x')
otp_add = '01' + otp_add
if VFS_ADD_START <= Starting_ad_hex_send <= VFS_ADD_END:
if COM_TYPE == 'SPI':
signal = 'm'
ser.write(signal.encode('utf-8'))
ser.write((FS_MIRRORDATA + ';' + otp_value + ';' + CRC_ENABLE + '%' ).encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
ser.write(signal.encode('utf-8'))
ser.write((FS_MIRRORCMD + ';' + otp_add + ';' + CRC_ENABLE + '%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
else:
signal = 'l'
ser.write(signal.encode('utf-8'))
ser.write((FAILSAFE_I2C_ADDRESS+';'+ FS_MIRRORDATA + ';' + otp_value + ';' + CRC_ENABLE + '%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
ser.write(signal.encode('utf-8'))
ser.write((FAILSAFE_I2C_ADDRESS+';'+ FS_MIRRORCMD +';'+ otp_add + ';' + CRC_ENABLE + '%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
else:
continue
else:
########### non-sidence controller scheme ##############
Starting_ad_hex_send = hex(int(Starting_ad,16) + i // 2)
Starting_ad_int_send = int(Starting_ad, 16) + (i // 2)
otp_add = str(Starting_ad_hex_send).replace('0x', '')
if VFS_ADD_START <= Starting_ad_int_send <= VFS_ADD_END:
if COM_TYPE == 'SPI':
signal = 'm'
ser.write(signal.encode('utf-8'))
ser.write((otp_add + ';' + otp_value + ';' + CRC_ENABLE + '%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
else:
signal = 'l'
ser.write(signal.encode('utf-8'))
ser.write((FAILSAFE_I2C_ADDRESS +';'+ otp_add + ';' + otp_value + ';' + CRC_ENABLE + '%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
else:
continue
log.see("end")
log.insert(END,'FS VOTP Ihex loading process complete\n\n')
############## config FS OTP controller and burn ###############
for line in lines[lines.index("Config FS VOTP controller:") + 1:lines.index("Config FS VOTP controller complete:")]:
setup = line.split('/')
ser.write(setup[0].encode('utf-8'))
ser.write((setup[1]+'%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
log.see("end")
log.see("end")
log.insert(END,'FS VOTP burn process complete\n\n')
##################### Burn FS BE and WP #######################
for line in lines[lines.index("Burn FS VOTP BE and WP:") + 1:lines.index("Burn FS VOTP BE and WP complete:")]:
setup = line.split('/')
ser.write(setup[0].encode('utf-8'))
ser.write((setup[1]+'%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
log.see("end")
log.see("end")
log.insert(END,'Burn FS VOTP BE and WP process complete\n\n')
#################################################################
############## Shutdown: ###############
for line in lines[lines.index("Shutdown:") + 1:lines.index("End:")]:
setup = line.split('/')
ser.write(setup[0].encode('utf-8'))
ser.write((setup[1]+'%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
log.see("end")
log.see("end")
########################## add later ################################
ser.write(b'z') #deactivate device
log.insert(END,'Device shutdown\n\n')
######################### restart and validate ######################
log.insert(END,'\n\n\n')
validate_button_func()
############## Ihex info section: ###############
MAIN_OTP_IHEX_START = int(lines[lines.index("Ihex info:") + 1].split(":")[1]) #MAIN_OTP_IHEX_START_AD
MAIN_OTP_IHEX_END = int(lines[lines.index("Ihex info:") + 1].split(":")[2]) #MAIN_OTP_IHEX_END_AD
FS_OTP_IHEX_START = int(lines[lines.index("Ihex info:") + 2].split(":")[1]) #FS_OTP_IHEX_START_AD
FS_OTP_IHEX_END = int(lines[lines.index("Ihex info:") + 2].split(":")[2]) #FS_OTP_IHEX_START_AD
MAIN_VOTP_IHEX_START = int(lines[lines.index("Ihex info:") + 3].split(":")[1]) #MAIN_VOTP_IHEX_START_AD
MAIN_VOTP_IHEX_END = int(lines[lines.index("Ihex info:") + 3].split(":")[2]) #MAIN_VOTP_IHEX_END_AD
FS_VOTP_IHEX_START = int(lines[lines.index("Ihex info:") + 4].split(":")[1]) #FS_VOTP_IHEX_START_AD
FS_VOTP_IHEX_END = int(lines[lines.index("Ihex info:") + 4].split(":")[2]) #FS_VOTP_IHEX_END_AD
M_MIRRORCMD = lines[lines.index("Ihex info:") + 5].split(":")[1] #M_MIRRORCMD_AD
M_MIRRORDATA = lines[lines.index("Ihex info:") + 6].split(":")[1] #M_MIRRORDATA_AD
FS_MIRRORCMD = lines[lines.index("Ihex info:") + 7].split(":")[1] #FS_MIRRORCMD_AD
FS_MIRRORDATA = lines[lines.index("Ihex info:") + 8].split(":")[1] #FS_MIRRORDATA_AD
####################### validation info section #######################
Validate_CMD = lines[lines.index("validation info:") + 1].split(":")[1] #Validate_CMD
VALIDATION_DATA_FORMAT = lines[lines.index("validation info:") + 2].split(":")[1] #Validate_DATA_format
MAIN_ADD_START = int(lines[lines.index("validation info:") + 3].split(":")[1],16) #Main_OTP_ADD_RANGE_START
MAIN_ADD_END = int(lines[lines.index("validation info:") + 3].split(":")[2],16) #Main_OTP_ADD_RANGE_END
FS_ADD_START = int(lines[lines.index("validation info:") + 4].split(":")[1],16) #FS_OTP_ADD_RANGE_START
FS_ADD_END = int(lines[lines.index("validation info:") + 4].split(":")[2],16) #FS_OTP_ADD_RANGE_END
VMAIN_ADD_START = int(lines[lines.index("validation info:") + 5].split(":")[1],16) #Main_VOTP_ADD_RANGE_START
VMAIN_ADD_END = int(lines[lines.index("validation info:") + 5].split(":")[2],16) #Main_VOTP_ADD_RANGE_END
VFS_ADD_START = int(lines[lines.index("validation info:") + 6].split(":")[1],16) #FS_VOTP_ADD_RANGE_START
VFS_ADD_END = int(lines[lines.index("validation info:") + 6].split(":")[2],16) #FS_VOTP_ADD_RANGE_START
####################### byte size #######################
BYTE_SIZE_INT = int(BYTE_SIZE)
ser.write('J'.encode('utf-8'))
############### CRC_Enable disable check
if CRC =='YES':
CRC_ENABLE = '1' #CRC enable
else:
CRC_ENABLE = '0' #CRC disable
#####send byte size#######
ser.write('y'.encode('utf-8'))
ser.write((BYTE_SIZE + '%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
log.see("end")
log.insert(END,'start otp validating process\n')
##################################################
############## Device Power Up: ################
for line in lines[lines.index("Power up:") + 1:lines.index("Power up complete:")]:
setup = line.split('/')
ser.write(setup[0].encode('utf-8'))
ser.write((setup[1]+'%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
log.see("end")
log.see("end")
log.insert(END,'Power up process complete\n\n')
##################################################
############## Test mode entry: ################
for line in lines[lines.index("Main test mode entry:") + 1:lines.index("Main test mode entry complete:")]:
setup = line.split('/')
ser.write(setup[0].encode('utf-8'))
ser.write((setup[1]+'%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
log.see("end")
log.see("end")
log.insert(END,'Main test mode entry process complete\n\n')
##################################################
######################## Run Ihex validation for main otp ###########################
log.insert(END,'valitaion starting\n')
if (VOTP != 'YES'): #01 indicate the end
pass
else:
for line in OTP_lines[MAIN_VOTP_IHEX_START:MAIN_VOTP_IHEX_END]:
Byte_count = int((line)[1:3],16)
Starting_ad = (line)[3:7]
Record_type = (line)[7:9]
data = (line)[9:9+Byte_count*2]
Check_sum = (line)[9+Byte_count*2:9+Byte_count*2+2]
##############end check################
if (Record_type == '01'): #01 indicate the end of the Ihex
break
for i in range(0, len(data),2):
otp_value = data[i:i+2]
########### start otp validate code ##############
if OTP_TYPE == 'MIRROR':
Validate_CMD_length = len(Validate_CMD)
Starting_ad_hex_send = int(Starting_ad, 16) + (i // 2)
required_length = 2 * BYTE_SIZE_INT
otp_add = format(Starting_ad_hex_send, f'0{required_length - Validate_CMD_length}x')
otp_add = Validate_CMD + otp_add
if VMAIN_ADD_START <= Starting_ad_hex_send <= VMAIN_ADD_END:
########### read data #######################
if COM_TYPE == 'SPI':
signal = 'm'
ser.write(signal.encode('utf-8'))
ser.write((M_MIRRORCMD + ';' + otp_add + ';' + CRC_ENABLE +'%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
log.see("end")
else:
signal = 'l'
ser.write(signal.encode('utf-8'))
ser.write((MAIN_I2C_ADDRESS + ';' + M_MIRRORCMD + ';' + otp_add + ';' + CRC_ENABLE +'%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
log.see("end")
########### check read #######################
if COM_TYPE == 'SPI':
signal = 'o'
ser.write(signal.encode('utf-8'))
ser.write((M_MIRRORDATA +';'+ CRC_ENABLE + '%').encode('utf-8'))
respond = read_string(ser)
check = compare_values(otp_value.lower(), extract_value(respond), VALIDATION_DATA_FORMAT)
if check:
log.insert(END,'Correct, ' + respond + '\n')
else:
log.insert(END,'Error, ' + respond + '\n')
status = 'fail'
result.config(text='FAIL', bg='red')
log.update_idletasks()
log.see("end")
else:
signal = 'n'
ser.write(signal.encode('utf-8'))
ser.write((MAIN_I2C_ADDRESS + ';' + M_MIRRORDATA + ';' + CRC_ENABLE +'%').encode('utf-8'))
respond = read_string(ser)
check = compare_values(otp_value.lower(), extract_value(respond), VALIDATION_DATA_FORMAT)
if check:
log.insert(END,'Correct, ' + respond + '\n')
else:
log.insert(END,'Error, ' + respond + '\n')
status = 'fail'
result.config(text='FAIL', bg='red')
log.update_idletasks()
log.see("end")
else:
continue
else:
########### non-sidence controller scheme ##############
Starting_ad_hex_send = hex(int(Starting_ad, 16) + i // 2)
Starting_ad_int_send = int(Starting_ad, 16) + (i // 2)
otp_add = str(Starting_ad_hex_send).replace('0x', '')
########### check read #######################
if VMAIN_ADD_START <= Starting_ad_int_send <= VMAIN_ADD_END:
if COM_TYPE == 'SPI':
signal = 'o'
ser.write(signal.encode('utf-8'))
ser.write((otp_add +';'+ CRC_ENABLE +'%').encode('utf-8'))
respond = read_string(ser)
check = compare_values(otp_value.lower(), extract_value(respond), VALIDATION_DATA_FORMAT)
if check:
log.insert(END,'Correct, ' + respond + '\n')
else:
log.insert(END,'Error, ' + respond + '\n')
status = 'fail'
result.config(text='FAIL', bg='red')
log.update_idletasks()
log.see("end")
else:
signal = 'n'
ser.write(signal.encode('utf-8'))
ser.write((MAIN_I2C_ADDRESS + ';' + otp_add +';'+ CRC_ENABLE +'%').encode('utf-8'))
respond = read_string(ser)
check = compare_values(otp_value.lower(), extract_value(respond), VALIDATION_DATA_FORMAT)
if check:
log.insert(END,'Correct, ' + respond + '\n')
else:
log.insert(END,'Error, ' + respond + '\n')
status = 'fail'
result.config(text='FAIL', bg='red')
log.update_idletasks()
log.see("end")
else:
continue
log.see("end")
log.insert(END,'main VOTP check complete\n\n')
for line in OTP_lines[MAIN_OTP_IHEX_START:MAIN_OTP_IHEX_END]:
Byte_count = int((line)[1:3],16)
Starting_ad = (line)[3:7]
Record_type = (line)[7:9]
data = (line)[9:9+Byte_count*2]
Check_sum = (line)[9+Byte_count*2:9+Byte_count*2+2]
##############end check################
if (Record_type == '01'): #01 indicate the end of the Ihex
break
for i in range(0, len(data),2):
otp_value = data[i:i+2]
########### start otp validate code ##############
if OTP_TYPE == 'MIRROR':
Validate_CMD_length = len(Validate_CMD)
Starting_ad_hex_send = int(Starting_ad, 16) + (i // 2)
required_length = 2 * BYTE_SIZE_INT
otp_add = format(Starting_ad_hex_send, f'0{required_length - Validate_CMD_length}x')
otp_add = Validate_CMD + otp_add
if MAIN_ADD_START <= Starting_ad_hex_send <= MAIN_ADD_END:
########### read data #######################
if COM_TYPE == 'SPI':
signal = 'm'
ser.write(signal.encode('utf-8'))
ser.write((M_MIRRORCMD + ';' + otp_add + ';' + CRC_ENABLE +'%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
log.see("end")
else:
signal = 'l'
ser.write(signal.encode('utf-8'))
ser.write((MAIN_I2C_ADDRESS + ';' + M_MIRRORCMD + ';' + otp_add + ';' + CRC_ENABLE +'%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
log.see("end")
########### check read #######################
if COM_TYPE == 'SPI':
signal = 'o'
ser.write(signal.encode('utf-8'))
ser.write((M_MIRRORDATA +';'+ CRC_ENABLE +'%').encode('utf-8'))
respond = read_string(ser)
check = compare_values(otp_value.lower(), extract_value(respond), VALIDATION_DATA_FORMAT)
if check:
log.insert(END,'Correct, ' + respond + '\n')
else:
log.insert(END,'Error, ' + respond + '\n')
status = 'fail'
result.config(text='FAIL', bg='red')
log.update_idletasks()
log.see("end")
else:
signal = 'n'
ser.write(signal.encode('utf-8'))
ser.write((MAIN_I2C_ADDRESS + ';' + M_MIRRORDATA + ';' + CRC_ENABLE +'%').encode('utf-8'))
respond = read_string(ser)
check = compare_values(otp_value.lower(), extract_value(respond), VALIDATION_DATA_FORMAT)
if check:
log.insert(END,'Correct, ' + respond + '\n')
else:
log.insert(END,'Error, ' + respond + '\n')
status = 'fail'
result.config(text='FAIL', bg='red')
log.update_idletasks()
log.see("end")
else:
continue
else:
########### non-sidence controller scheme ##############
Starting_ad_hex_send = hex(int(Starting_ad, 16) + i // 2)
Starting_ad_int_send = int(Starting_ad, 16) + (i // 2)
otp_add = str(Starting_ad_hex_send).replace('0x', '')
########### check read #######################
if MAIN_ADD_START <= Starting_ad_int_send <= MAIN_ADD_END:
if COM_TYPE == 'SPI':
signal = 'o'
ser.write(signal.encode('utf-8'))
ser.write((otp_add +';'+ CRC_ENABLE +'%').encode('utf-8'))
respond = read_string(ser)
check = compare_values(otp_value.lower(), extract_value(respond), VALIDATION_DATA_FORMAT)
if check:
log.insert(END,'Correct, ' + respond + '\n')
else:
log.insert(END,'Error, ' + respond + '\n')
status = 'fail'
result.config(text='FAIL', bg='red')
log.update_idletasks()
log.see("end")
else:
signal = 'n'
ser.write(signal.encode('utf-8'))
ser.write((MAIN_I2C_ADDRESS + ';' + otp_add +';'+ CRC_ENABLE +'%').encode('utf-8'))
respond = read_string(ser)
check = compare_values(otp_value.lower(), extract_value(respond), VALIDATION_DATA_FORMAT)
if check:
log.insert(END,'Correct, ' + respond + '\n')
else:
log.insert(END,'Error, ' + respond + '\n')
status = 'fail'
result.config(text='FAIL', bg='red')
log.update_idletasks()
log.see("end")
else:
continue
log.see("end")
log.insert(END,'main OTP check complete\n\n')
############## checking SAFETY REG is needed ###############
if (FS_REG != 'YES'): #01 indicate the end
pass
else:
################### FS test mode entry #################
for line in lines[lines.index("FS test mode entry:") + 1:lines.index("FS test mode entry complete:")]:
setup = line.split('/')
ser.write(setup[0].encode('utf-8'))
ser.write((setup[1] + '%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
log.see("end")
log.see("end")
log.insert(END,'FS test mode entry process complete\n\n')
######################## Run Ihex validation for FS otp ##############################
if (VOTP != 'YES'): #01 indicate the end
pass
else:
for line in OTP_lines[FS_VOTP_IHEX_START:FS_VOTP_IHEX_END]:
Byte_count = int((line)[1:3],16)
Starting_ad = (line)[3:7]
Record_type = (line)[7:9]
data = (line)[9:9+Byte_count*2]
Check_sum = (line)[9+Byte_count*2:9+Byte_count*2+2]
##############end check################
if (Record_type == '01'): #01 indicate the end of the Ihex
break
for i in range(0, len(data),2):
otp_value = data[i:i+2]
########### start otp validate code ##############
if OTP_TYPE == 'MIRROR':
Validate_CMD_length = len(Validate_CMD)
Starting_ad_hex_send = int(Starting_ad, 16) + (i // 2)
required_length = 2 * BYTE_SIZE_INT
otp_add = format(Starting_ad_hex_send, f'0{required_length - Validate_CMD_length}x')
otp_add = Validate_CMD + otp_add
if VFS_ADD_START <= Starting_ad_hex_send <= VFS_ADD_END:
########### read data #######################
if COM_TYPE == 'SPI':
signal = 'm'
ser.write(signal.encode('utf-8'))
ser.write((FS_MIRRORCMD + ';' + otp_add + ';' + CRC_ENABLE +'%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
log.see("end")
else:
signal = 'l'
ser.write(signal.encode('utf-8'))
ser.write((FAILSAFE_I2C_ADDRESS + ';' + FS_MIRRORCMD + ';' + otp_add + ';' + CRC_ENABLE +'%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
log.see("end")
########### check read #######################
if COM_TYPE == 'SPI':
signal = 'o'
ser.write(signal.encode('utf-8'))
ser.write((FS_MIRRORDATA +';'+ CRC_ENABLE +'%').encode('utf-8'))
respond = read_string(ser)
check = compare_values(otp_value.lower(), extract_value(respond), VALIDATION_DATA_FORMAT)
if check:
log.insert(END,'Correct, ' + respond + '\n')
else:
log.insert(END,'Error, ' + respond + '\n')
status = 'fail'
result.config(text='FAIL', bg='red')
log.update_idletasks()
log.see("end")
else:
signal = 'n'
ser.write(signal.encode('utf-8'))
ser.write((FAILSAFE_I2C_ADDRESS + ';' + FS_MIRRORDATA + ';' + CRC_ENABLE +'%').encode('utf-8'))
respond = read_string(ser)
check = compare_values(otp_value.lower(), extract_value(respond), VALIDATION_DATA_FORMAT)
if check:
log.insert(END,'Correct, ' + respond + '\n')
else:
log.insert(END,'Error, ' + respond + '\n')
status = 'fail'
result.config(text='FAIL', bg='red')
log.update_idletasks()
log.see("end")
else:
continue
else:
########### non-sidence controller scheme ##############
Starting_ad_hex_send = hex(int(Starting_ad, 16) + i // 2)
Starting_ad_int_send = int(Starting_ad, 16) + (i // 2)
otp_add = str(Starting_ad_hex_send).replace('0x', '')
########### check read #######################
if VFS_ADD_START <= Starting_ad_int_send <= VFS_ADD_END:
if COM_TYPE == 'SPI':
signal = 'o'
ser.write(signal.encode('utf-8'))
ser.write((otp_add +';'+ CRC_ENABLE +'%').encode('utf-8'))
respond = read_string(ser)
check = compare_values(otp_value.lower(), extract_value(respond), VALIDATION_DATA_FORMAT)
if check:
log.insert(END,'Correct, ' + respond + '\n')
else:
log.insert(END,'Error, ' + respond + '\n')
status = 'fail'
result.config(text='FAIL', bg='red')
log.update_idletasks()
log.see("end")
else:
signal = 'n'
ser.write(signal.encode('utf-8'))
ser.write((FAILSAFE_I2C_ADDRESS + ';' + otp_add +';'+ CRC_ENABLE +'%').encode('utf-8'))
respond = read_string(ser)
check = compare_values(otp_value.lower(), extract_value(respond), VALIDATION_DATA_FORMAT)
if check:
log.insert(END,'Correct, ' + respond + '\n')
else:
log.insert(END,'Error, ' + respond + '\n')
status = 'fail'
result.config(text='FAIL', bg='red')
log.update_idletasks()
log.see("end")
else:
continue
log.see("end")
log.insert(END,'FS VOTP check complete\n\n')
for line in OTP_lines[FS_OTP_IHEX_START:FS_OTP_IHEX_END]:
Byte_count = int((line)[1:3],16)
Starting_ad = (line)[3:7]
Record_type = (line)[7:9]
data = (line)[9:9 + Byte_count*2]
Check_sum = (line)[9 + Byte_count*2:9 + Byte_count*2 + 2]
##############end check################
if (Record_type == '01'): #01 indicate the end
break
for i in range(0, len(data),2):
otp_value = data[i:i + 2]
########### start otp validate code ##############
if OTP_TYPE == 'MIRROR':
FS_MIRRIOR_CMD_length = len(Validate_CMD)
Starting_ad_hex_send = int(Starting_ad, 16) + (i // 2)
required_length = 2 * BYTE_SIZE_INT
otp_add = format(Starting_ad_hex_send, f'0{required_length - FS_MIRRIOR_CMD_length}x')
otp_add = Validate_CMD + otp_add
if FS_ADD_START <= Starting_ad_hex_send <= FS_ADD_END:
########### read data #######################
if COM_TYPE == 'SPI':
signal = 'm'
ser.write(signal.encode('utf-8'))
ser.write((FS_MIRRORCMD + ';' + otp_add + ';' + CRC_ENABLE +'%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
log.see("end")
else:
signal = 'l'
ser.write(signal.encode('utf-8'))
ser.write((FAILSAFE_I2C_ADDRESS + ';' + FS_MIRRORCMD + ';' + otp_add + ';' + CRC_ENABLE +'%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
log.see("end")
########### check read #######################
if COM_TYPE == 'SPI':
signal = 'o'
ser.write(signal.encode('utf-8'))
ser.write((FS_MIRRORDATA + ';' + CRC_ENABLE + '%').encode('utf-8'))
respond = read_string(ser)
check = compare_values(otp_value.lower(), extract_value(respond), VALIDATION_DATA_FORMAT)
if check:
log.insert(END,'Correct, ' + respond + '\n')
else:
log.insert(END,'Error,' + respond + '\n')
status = 'fail'
result.config(text='FAIL', bg='red')
log.update_idletasks()
log.see("end")
else:
signal = 'n'
ser.write(signal.encode('utf-8'))
ser.write((FAILSAFE_I2C_ADDRESS + ';' + FS_MIRRORDATA + ';' + CRC_ENABLE + '%').encode('utf-8'))
respond = read_string(ser)
check = compare_values(otp_value.lower(), extract_value(respond), VALIDATION_DATA_FORMAT)
if check:
log.insert(END,'Correct, ' + respond + '\n')
else:
log.insert(END,'Error, ' + respond + '\n')
status = 'fail'
result.config(text='FAIL', bg='red')
log.update_idletasks()
log.see("end")
else:
continue
else:
log.insert(END,'PF product currently not implemented\n\n')
log.update_idletasks()
log.see("end")
log.see("end")
log.insert(END,'FS OTP check complete\n\n')
############## check result: ###############
if status == 'pass':
result.config(text='PASS', bg='green')
else:
result.config(text='FAIL', bg='red')
############## Shutdown: ###############
for line in lines[lines.index("Shutdown:") + 1:lines.index("End:")]:
setup = line.split('/')
ser.write(setup[0].encode('utf-8'))
ser.write((setup[1]+'%').encode('utf-8'))
respond = read_string(ser)
log.insert(END,respond)
log.update_idletasks()
log.see("end")
log.see("end")
ser.write(b'z') #deactivate device
log.insert(END,'Device shutdown\n\n')
thread_running = False #stop threading
burn_button.config(state=tk.NORMAL) # Enable the button
validate_button.config(state=tk.NORMAL) # Enable the button
load_button.config(state=tk.NORMAL) # Enable the button
connect_button.config(state=tk.NORMAL) # Enable the button
#######################END#####################
################# extract the returned readback value ############
def extract_value(received_string):
# Split the received string by whitespace and ‘0x’
parts = received_string.split()
# Initialize variables to keep track of the count and extracted value
count = 0
extracted_value = None
# Iterate through the parts to find the value following the second “0x”
for part in parts:
if "0x" in part:
count += 1
if count == 2:
extracted_value = part.replace("0x", "")[:10] # Extract the next four characters
break
return extracted_value
################# compare the value of readback and otp ############
def compare_values(otp_value, readback_value, reading_format):
# Ensure reading_format is the same length as the readback_value
if len(reading_format) != len(readback_value):
print("Length of reading_format must match the length of readback_value.")
return False
# Iterate through the format and compare accordingly
check_value_index = 0
for i, char in enumerate(reading_format):
if char == 'd': # Compare only the ‘dd’ parts
if check_value_index >= len(otp_value) or otp_value[check_value_index] != readback_value[i]:
return False
check_value_index += 1 # Move to the next character in otp_value
elif char == 'x': # Ignore the ‘xx’ parts
continue
else:
print("Invalid character in reading_format. Use ‘d’ for compare and ‘x’ for ignore.")
return False
code
return check_value_index == len(otp_value) # Ensure all of otp_value was used
################# burn button add threading ############
def burn_button_func_threading():
global thread_running
with thread_lock:
if not thread_running:
thread_running = True
validate_button.config(state=tk.DISABLED) # Disable the butto
burn_button.config(state=tk.DISABLED) # Disable the button
load_button.config(state=tk.DISABLED) # Disable the button
connect_button.config(state=tk.DISABLED) # Disable the button
t = threading.Thread(target=burn_button_func)
t.start()
################# validation buttion add threading ############
def validate_button_func_threading():
global thread_running
with thread_lock:
if not thread_running:
thread_running = True
validate_button.config(state=tk.DISABLED) # Disable the butto
burn_button.config(state=tk.DISABLED) # Disable the button
load_button.config(state=tk.DISABLED) # Disable the button
connect_button.config(state=tk.DISABLED) # Disable the button
t = threading.Thread(target=validate_button_func)
t.start()
################# clear log ############
def clear_log_button():
log.delete(1.0, tk.END)
################ save log to a txt file #################
def save_log_button():
file_path = tk.filedialog.askopenfilename()
with open(file_path, 'w') as file: #save the device configure file to product_data
file.write(log.get(1.0, tk.END))
Check Connection: Ensure the serial connection (ser) is still open before sending the signal.
Use after() Method: The send_keep_alive function calls itself periodically using after(). The second parameter in after() is the delay in milliseconds between calls (e.g., 300000 ms for 5 minutes).
Error Handling: Use try-except to catch any potential serial exceptions during the send operation, which is crucial for robust communication.
Integration:
Add the send_keep_alive() function above within your GUI code, possibly at the end of the connect_button() function where the connection is initially established, or right after setting up the window.
Adjust the interval (300000 ms in the example) to suit your application's requirements and communication protocol with the MCU.
By implementing this keep-alive mechanism, you're more likely to maintain a steady connection with the MCU, preventing it from entering sleep modes due to inactivity.