LaserGameV1.ino 2,17 ko
Newer Older
#include <SPI.h>
#include <ESP8266WiFi.h>
#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() {
  Serial.begin(115200);
	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);
}



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();
}