Newer
Older
#include <WiFiUdp.h>
#include "arduino_secrets.h"
int status = WL_IDLE_STATUS;
int keyIndex = 0;
unsigned int localPort = 2390;
char ssid[] = SECRET_SSID;
char pass[] = SECRET_PASS;
char key[22] = SECRET_KEY;
char servKey[22] = SECRET_SERV_KEY;
char separateur[] = ":";
IPAddress multicastAddress = IPAddress(229, 97, 225, 142);
char packetBuffer[256]; //buffer to hold incoming packet
char *token;
WiFiUDP Udp;
void setup() {
WiFi.mode(WIFI_STA);
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
Serial.print("Connecting");
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
WiFi.begin(ssid, pass);
do
{
delay(1000);
Serial.print(".");
} while (WiFi.status() != WL_CONNECTED);
Serial.print("Connected! IP address: ");
Serial.println(WiFi.localIP());
Serial.printf("UDP server on port %d\n", localPort);
Udp.beginMulticast(WiFi.localIP(), multicastAddress, localPort);
Serial.println(multicastAddress);
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
}
void loop() {
int packetSize = Udp.parsePacket();
if (packetSize) {
int len = Udp.read(packetBuffer, 255);
if (len > 0) {
packetBuffer[len] = 0;
}
printData(packetSize);
token = strtok(packetBuffer, separateur);
if (strcmp(token, key) == 0) {
token = strtok(NULL, separateur);
if (strcmp(token, servKey) == 0) {
token = strtok(NULL, separateur);
if (strcmp(token, "SERVER_TEST") == 0) {
sendMsg("TEST_RECEIVED");
} else if (strcmp(token, "SERVER_STILLCONNECTED") == 0) {
sendMsg("STILLCONNECTED");
}
}
}
}
}
void printData(int packetSize) {
Serial.print("Received packet of size ");
Serial.println(packetSize);
Serial.print("From ");
IPAddress remoteIp = Udp.remoteIP();
Serial.print(remoteIp);
Serial.print(", port ");
Serial.println(Udp.remotePort());
Serial.println("Contents : ");
Serial.println(packetBuffer);
}
void sendMsg(char *msg){
char str[256];
sprintf(str,"%s%s%s%s%s",servKey, separateur, key, separateur, msg);
Udp.beginPacket(multicastAddress, localPort);
Udp.write(str);
Udp.endPacket();
}