Created
November 30, 2016 07:39
-
-
Save towynlin/8eeb5dbd752436ce859cf93d4eb58794 to your computer and use it in GitHub Desktop.
Multicast demo between several Photons on the same local network
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const int multicastPort = 23232; | |
const IPAddress multicastAddress(233,252,1,64); | |
UDP udp; | |
char buf[100]; | |
void setup() { | |
udp.begin(multicastPort); | |
udp.joinMulticast(multicastAddress); | |
} | |
void sendPeriodically() { | |
static unsigned long lastSend = millis(); | |
// every five seconds | |
if (millis() - lastSend > 5000) { | |
lastSend = millis(); | |
// fill buffer with some random ASCII data | |
for (int i = 0; i < sizeof(buf); i++) { | |
buf[i] = random(40, 127); | |
} | |
// send a multicast packet and publish the result | |
int bytesWritten = udp.sendPacket(buf, sizeof(buf), | |
multicastAddress, multicastPort); | |
if (bytesWritten < 0) { | |
String msg = String("udp.sendPacket returned ") + String(bytesWritten); | |
Particle.publish("error", msg, 60, PRIVATE); | |
} else { | |
Particle.publish("bytes-written", String(bytesWritten), 60, PRIVATE); | |
} | |
} | |
} | |
void receivePeriodically() { | |
static unsigned long lastReceive = millis(); | |
// every second and a half | |
if (millis() - lastReceive > 1500) { | |
lastReceive = millis(); | |
// try to receive multicast data and publish the result | |
int bytesReceived = udp.receivePacket(buf, sizeof(buf)); | |
if (bytesReceived < 0) { | |
String msg = String("udp.receivePacket returned ") + String(bytesReceived); | |
Particle.publish("error", msg, 60, PRIVATE); | |
} else if (bytesReceived > 0) { | |
int terminatorIndex = min(bytesReceived, sizeof(buf) - 1); | |
buf[terminatorIndex] = 0; | |
String msg = String(bytesReceived) + String(" bytes from ") + | |
String(udp.remoteIP()) + String(": ") + buf; | |
Particle.publish("received", msg, 60, PRIVATE); | |
} | |
// do nothing if bytesReceived == 0 | |
} | |
} | |
void loop() { | |
sendPeriodically(); | |
receivePeriodically(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It's also fun while this is humming along to multicast a message from your computer (on the same local network) to all the Photons, by running this command in your terminal:
In your event stream (viewable at https://console.particle.io/logs for instance) you'll see, in addition to all the random data they're multicasting to each other, this shout out show up as received by all the Photons.