我嘗試在AMB82上建立WiFi AP,電腦可以連上AP,然後電腦的python程式可以跟AMB82透過訊息溝通,但是當透過WiFi client建立連線,馬上就會client disconnected。訊息根本無法傳送。
我用的是arduino IDE,版本是4.0.9-build20250325。同樣的程式碼在esp32上面不會有馬上client disconnect的問題,拜託幫幫忙
以下是簡單的ino程式碼:
#include <WiFi.h>
// AP configuration
char ssid = “AMB82_AP”; // AP SSID
char pass = “12345678”; // AP password (minimum 8 characters)
char channel = “1”; // AP channel
int ssid_status = 0; // 0 = visible SSID, 1 = hidden SSID
int status = WL_IDLE_STATUS; // WiFi status indicator
WiFiServer server(80); // Create server on port 80
void setup() {
// Initialize serial communication
Serial.begin(115200);
while (!Serial) {
; // wait for serial port to connect
}
// Start Access Point
Serial.print("Setting up Access Point with SSID: ");
Serial.println(ssid);
status = WiFi.apbegin(ssid, pass, channel, ssid_status);
// Wait for AP to initialize
delay(5000);
if (status != WL_CONNECTED) {
Serial.println("Failed to set up AP. Retrying...");
while (status != WL_CONNECTED) {
status = WiFi.apbegin(ssid, pass, channel, ssid_status);
delay(5000);
}
}
// AP started
Serial.println("AP mode started successfully");
printWifiData();
// Start the server
server.begin();
Serial.println("Server started and listening on port 80");
}
void loop() {
// Check if a client has connected
WiFiClient client = server.available();
if (client) {
Serial.println("New client connected");
// While client is connected
while (client.connected()) {
// If there's data available to read
if (client.available()) {
String message = client.readStringUntil('\n');
// Print received message to serial monitor
Serial.print("Received: ");
Serial.println(message);
// Send a response back to the client
String response = "AMB82 received: " + message;
client.println(response);
// Ensure the data is sent
client.flush();
}
}
Serial.println("Client disconnected");
}
}
void printWifiData() {
// Print WiFi AP information
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// Print the MAC address of AP
byte bssid[6];
WiFi.BSSID(bssid);
Serial.print("BSSID: ");
for (int i = 0; i < 5; i++) {
Serial.print(bssid[i], HEX);
Serial.print(":");
}
Serial.println(bssid[5], HEX);
// Print the encryption type
byte encryption = WiFi.encryptionType();
Serial.print("Encryption Type: ");
Serial.println(encryption, HEX);
Serial.println();
}
與之對應的python程式碼:
import socket
import time
def connect_to_amb82():
print(“Attempting to connect to AMB82-Mini AP…”)
# AMB82 AP information
host = "192.168.1.1" # Default IP of AMB82 when in AP mode
port = 80 # Port the server is running on
# Create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# Connect to the AMB82
s.connect((host, port))
print(f"Connected to AMB82 at {host}:{port}")
return s
except socket.error as e:
print(f"Connection failed: {e}")
print("Make sure your computer is connected to the AMB82_AP WiFi network")
return None
def send_message(sock, message):
if sock is None:
print(“Not connected to AMB82”)
return
try:
# Send message with newline terminator
sock.send((message + "\n").encode())
# Receive response
response = sock.recv(1024)
# Display the response
if response:
print("\nResponse from AMB82:")
print(response.decode('utf-8', errors='ignore'))
else:
print("\nNo response received from AMB82")
except socket.error as e:
print(f"Error sending/receiving: {e}")
def interactive_mode():
# Connect to AMB82
sock = connect_to_amb82()
if sock is None:
return
print("\nEntering interactive mode. Type 'exit' to quit.")
try:
while True:
# Get message from user
message = input("> ")
if message.lower() == 'exit':
break
# Send message
send_message(sock, message)
except KeyboardInterrupt:
print("\nExiting...")
finally:
if sock:
sock.close()
print("Connection closed")
if name == “main”:
print(“AMB82-Mini Communication Client”)
print(“-------------------------------”)
interactive_mode()