# Let's modify the code to include error handling, loop safeguards, and logging to ensure that the code is more robust and less likely to crash.
import logging
# Setting up logging to track the execution and identify issues
#logging.basicConfig(filename='/FocusWobble.log', level=logging.DEBUG,
# format='%(asctime)s - %(levelname)s - %(message)s')
from win32com.client import gencache
import SEM_API_fix as SEM_API
import matplotlib.pyplot as plt
import numpy as np
import time
import math
from imageio import imread
# Imitate focus wobble
def FocusWobble():
try:
# Get values
with SEM_API.SEM_API("remote") as sem:
wd_get = sem.GetValue("AP_WD")
# Set wobble parameters
number_of_images = 15
number_of_overlaps = 1
wd_percentage_range = 0.002
# Set image parameters
#store_resolution = 512 # set *3/4, DP_IMAGE_STORE
#file_name = "fliptest"
# Set imaging conditions
with SEM_API.SEM_API("remote") as sem:
sem.Execute("CMD_UNFREEZE_ALL")
sem.Execute("CMD_SCANRATE7")
# Loop to capture and save images
for i in range(number_of_images):
wd = wd_get * (1 + wd_percentage_range * math.sin(2 * math.pi * i / (number_of_images - number_of_overlaps)))
logging.info(f"Image {i}: WD={wd}")
try:
with SEM_API.SEM_API("remote") as sem:
s = sem.SetValue("AP_WD", wd)
sem.Execute("CMD_UNFREEZE_ALL")
time.sleep(0.5)
sem.Execute("CMD_FREEZE_ALL")
retries = 0
max_retries = 10
while sem.GetState("DP_BEAM_BLANKED") == "No":
if retries >= max_retries:
logging.warning(f"Max retries reached for image {i}, exiting loop.")
break
#print(retries)
time.sleep(1)
retries += 1
sem.Execute("CMD_TAKE_PHOTO")
except Exception as e:
logging.error(f"Error during image capture {i}: {e}")
except Exception as e:
logging.critical(f"Critical error in FocusWobble: {e}")
# Call the function
#FocusWobble()
number_of_images = 25
wd_get = 4.5
wd_percentage_range= 0.002
number_of_overlaps = 4
for i in range(number_of_images):
wd = wd_get * (1 + wd_percentage_range * math.sin(2 * math.pi * i / (number_of_images - number_of_overlaps)))
print(i,wd)