Python server-side code:
import socket
from playsound import playsound
localIP = "127.0.0.1"
localPort = 3030
bufferSize = 1024
UDPServerSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
UDPServerSocket.bind((localIP, localPort))
print("UDP server up and listening")
while(True):
bytesAddressPair = UDPServerSocket.recvfrom(bufferSize)
message = bytesAddressPair[0]
if 'notify' in str(message):
try:
playsound('sound.mp3')
except:
print('sound error')
print(message)
ESP8266 C client-side code:
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <EasyButton.h>
#define BUTTON_PIN 0
const char* ssid = "***";
const char* password = "***";
WiFiUDP Udp;
EasyButton button(BUTTON_PIN);
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED){
delay(500);
Serial.print(".");
}
button.begin();
button.onPressed(onPressed);
}
void loop() {
button.read();
}
void onPressed() {
digitalWrite(LED_BUILTIN, LOW);
Udp.beginPacket("127.0.0.1", 3030);
Udp.write("notify");
Udp.endPacket();
digitalWrite(LED_BUILTIN, HIGH);
}
By pressing the button on the board, the socket should be sent, and the computer with the server should receive it and play the sound. The server-side code works correctly but the client side doesn't send the socket.
CodePudding user response:
Your ESP8266 code is trying to send data to 127.0.0.1. This is the “loopback” address. It means send to self. “localhost” is also used as a name for it. It will never be used to send to a different computer.
You need to figure out the correct IP address for the server you’re trying to send to. You also need to change the server to bind to that IP address (or 0.0.0.0) and not 127.0.0.1 in order for it to be able to receive data. Binding to 127.0.0.1 will allow it to only receive data sent from itself.