Skip to content

Instantly share code, notes, and snippets.

@towynlin
Created November 30, 2016 07:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save towynlin/8eeb5dbd752436ce859cf93d4eb58794 to your computer and use it in GitHub Desktop.
Save towynlin/8eeb5dbd752436ce859cf93d4eb58794 to your computer and use it in GitHub Desktop.
Multicast demo between several Photons on the same local network
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();
}
@towynlin
Copy link
Author

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:

echo "shout out to all my photons" | nc -u 233.252.1.64 23232 -w 1

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment