void setup() {

    // Set the port whis to use for contactign us back
    Udp.begin(8888);

    // Sedn the message to the server
    if (Udp.sendPacket(buffer, 39, remoteIP, port) < 0) {

        Particle.publish("Error");

    }

}
void loop() {
	if (WiFi.ready()) {
		if (firstTimeReady) {
			firstTimeReady = false;

			// First time we get WiFi.ready(), initialize the UDP listener. This happens
			// every time we reconnect to WiFi.
			mcastUdp.begin(MCAST_PORT);
		}

		if (!haveServerAddr && millis() - serverAddrLastCheck >= SERVER_ADDR_CHECK_RETRY_MS) {
			serverAddrLastCheck = millis();

			// If we don't have a server IP address, request it periodically (every 20 seconds)
			Serial.printlnf("requesting server address at %s:%d", mcastAddr.toString().c_str(), MCAST_PORT);

			strcpy(udpBuffer, "\n");
			mcastUdp.sendPacket(udpBuffer, strlen(udpBuffer), mcastAddr, MCAST_PORT);
		}

		int count = mcastUdp.receivePacket(udpBuffer, UDP_BUFFER_SIZE - 1);
		if (count > 0) {
			udpBuffer[count] = 0;

			// Handle a received UDP packet from the server with the IP address and port of the server
			int addr[4], port;

			if (sscanf(udpBuffer, "%u.%u.%u.%u:%u", &addr[0], &addr[1], &addr[2], &addr[3], &port) == 5) {
				serverAddr = IPAddress(addr[0], addr[1], addr[2], addr[3]);
				serverPort = port;
				haveServerAddr = true;

				Serial.printlnf("serverAddr=%s port=%d", serverAddr.toString().c_str(), serverPort);
			}
		}

	}
	else {
		// If WiFi disconnects, we need to reestablish listeners next time
		firstTimeReady = true;
	}
}
Example #3
0
/* executes continuously after setup() runs */
void loop() {
    static system_tick_t last = 0;
    ssize_t s = udp.receivePacket(buf, sizeof(buf));
    if (s > 0) {
        char tmp[IP_ADDR_STRLEN_MAX] = {};
        auto ip = udp.remoteIP();
        Log.trace("Received %d bytes from %s#%u", s,
                inet_inet_ntop(AF_INET6, ip.raw().ipv6, tmp, sizeof(tmp)), udp.remotePort());
    }

    if ((millis() - last) >= PERIOD) {
        size_t len = random(1, sizeof(buf));
        rng.gen((char*)buf, len);
        auto r = udp.sendPacket(buf, len, mcastAddr, PORT);
        Log.trace("Sent %u bytes to %s#%u : %d %d", len, MULTICAST_ADDR, PORT, r, errno);
        last = millis();
        if (r < 0) {
            openSocket();
        }
    }
}