Hey
I was receiving a 'Guru meditation error' often when my server running A* algorithm sends my microcontroller the path. my microcontroller reboots and tries to communicate with the server, this way, at some point, it receives the path from the server but it would be great if i can avoid this error.
A part of the code running in my ESP 32 wroom:
Serial.println("Starting loop");
// Check if the client is not connected
if (!client.connected()) {
// Attempt to connect to the server
Serial.println("Client not connected, attempting connection...");
if (!client.connect(server_ip, server_port)) {
Serial.println("Connection failed");
delay(5000); // Wait before retrying
return;
}
Serial.println("Connected to server");
} else {
Serial.println("Client already connected");
}
// Send request to the server
client.println("Request path");
// Wait for a response from the server
unsigned long timeout = millis();
while (!client.available()) {
if (millis() - timeout > 5000) {
Serial.println("Timeout: No response from server");
client.stop();
return;
}
}
// Read response from server
String response;
while (client.available()) {
response = client.readStringUntil('\r');
Serial.println("Response from server: " + response);
// Parse the path received from the server and move the robot accordingly
parsePathAndMove(response);
}
// Check if response is empty (no response received)
if (response.length() == 0) {
Serial.println("No response from server");
}
// Disconnect from the server
client.stop();
A part of my server side code:
while True:
# Accept incoming connection from client 2
client_socket, client_address = server_socket.accept()
# Check if client 2 address matches the expected address
if client_address[0] == '192.168.152.46':
print("Connection from Client 2:", client_address)
# Run ML model and A* algorithm
try:
image_files = os.listdir(image_dir1)
image_files2 = os.listdir(image_dir) # Added line to get files from image_dir
# Perform image mapping
image_mapping = {}
for i1 in image_files:
for i2 in image_files2:
print("Comparing:", i1, i2)
if i1 == i2:
print("Match found:", i1, i2)
image_mapping[os.path.join(image_dir1, i1)] = os.path.join(image_dir, i2)
# Use image_mapping as needed
print("Image Mapping:", image_mapping)
def a_star_search(start, goal):
def heuristic(node, goal):
return ((node[0] - goal[0]) * 2 + (node[1] - goal[1]) * 2) ** 0.5
def get_neighbors(point):
x, y = point
neighbors = [(x - 1, y), (x + 1, y), (x, y - 30), (x, y + 30)]
return [neighbor for neighbor in neighbors]
open_list = [(heuristic(start, goal), start)]
came_from = {}
g_score = {start: 0}
while open_list:
_, current = heapq.heappop(open_list)
if current == goal:
path = []
while current in came_from:
path.append(current)
current = came_from[current]
path.append(start)
return path[::-1]
for neighbor in get_neighbors(current):
tentative_g_score = g_score[current] + 1
if tentative_g_score < g_score.get(neighbor, float('inf')):
came_from[neighbor] = current
g_score[neighbor] = tentative_g_score
f_score = tentative_g_score + heuristic(neighbor, goal)
heapq.heappush(open_list, (f_score, neighbor))
return None
diseased_plants_coordinates = []
# Plot the output of the ML model
num_cols = 3
num_rows = (len(image_files) - 1) // num_cols + 1
fig, axs = plt.subplots(num_rows, num_cols, figsize=(12, 6))
# Flatten the array of subplots
axs = axs.flatten()
# Iterate through image files and coordinates
for idx, (img_file, coordinate) in enumerate(zip(image_files, image_coordinates.values())):
# Create the full path to the image
img_path = os.path.join(image_dir1, img_file)
# Preprocess the new image with the correct target size
img = image.load_img(img_path, target_size=model_input_size)
img_array = img_to_array(img)
img_array = img_array.reshape((1,) + img_array.shape)
img_array /= 255.0
# Make predictions
predictions = model.predict(img_array)
# Decode predictions
predicted_class = np.argmax(predictions)
predicted_class_name = class_names[predicted_class]
# Display the image with its predicted class name and ID
axs[idx].imshow(img)
axs[idx].set_title(f'ID: {idx}, Predicted class: {predicted_class_name}')
axs[idx].axis('off')
# Adjust spacing between subplots
plt.subplots_adjust(hspace=0.8, wspace=0.7)
# Extract coordinates of diseased plants based on model predictions
if predicted_class_name == 'Bacterial_spot':
# Append the coordinates to the list
diseased_plants_coordinates.append(coordinate)
print("Diseased Plants Coordinates:", diseased_plants_coordinates)
# Save the plot as an image
plt.savefig('output_plot.png')
# Close the plot to avoid blocking execution
plt.close()
# After iterating through all images, if there are any diseased plants detected, send the list of coordinates to the A* algorithm
if diseased_plants_coordinates:
# Define the initial start position for the first movement
start_position = (0, 0) # Assuming initial position is (0, 0)
# Perform A* for each start and goal pair sequentially
paths = {}
for goal_position in diseased_plants_coordinates:
# Perform A* search from start_position to goal_position
path = a_star_search(start_position, goal_position)
paths[(start_position, goal_position)] = path
# Update start_position for the next movement
start_position = goal_position
# Prepare the paths to send to the client
response_data = {"paths": {}}
for start_goal_pair, path in paths.items():
start, goal = start_goal_pair
if path:
path_str = ';'.join([f'{x},{y}' for x, y in path])
else:
path_str = "NoPathFound"
response_data["paths"][str(start)] = path_str # Convert start position tuple to string
# Send the path result back to the client
client_socket.sendall(json.dumps(response_data).encode())
print("Response sent to client:", response_data) # Print the response data sent to the client
else:
print("No diseased plants detected, sending empty response to client")
client_socket.sendall(json.dumps({"paths": {}}).encode())
except Exception as e:
print("Error occurred:", str(e))
client_socket.close()