Created
June 1, 2015 07:48
-
-
Save towynlin/cc479890fe292e318552 to your computer and use it in GitHub Desktop.
Photon Multicast Presence Announcement from user app
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
SYSTEM_MODE(SEMI_AUTOMATIC); | |
UDP udp; | |
char binaryDeviceID[12]; | |
const char SKIP_FROM_9_TO_A = 'a' - '9' - 1; | |
int presence_announcement_coap(unsigned char *buf, const char *id) | |
{ | |
buf[0] = 0x50; // Confirmable, no token | |
buf[1] = 0x02; // Code POST | |
buf[2] = 0x00; // message id ignorable in this context | |
buf[3] = 0x00; | |
buf[4] = 0xb1; // Uri-Path option of length 1 | |
buf[5] = 'h'; | |
buf[6] = 0xff; // payload marker | |
memcpy(buf + 7, id, 12); | |
return 19; | |
} | |
void Multicast_Presence_Announcement() { | |
unsigned char buffer[20]; | |
int size = presence_announcement_coap(buffer, binaryDeviceID); | |
udp.begin(4097); | |
udp.beginPacket({ 224, 0, 1, 187 }, 5683); | |
udp.write(buffer, size); | |
udp.endPacket(); | |
udp.stop(); | |
} | |
char asciiToNibble(char c) { | |
char n = c - '0'; | |
if (n > 9) { | |
n -= SKIP_FROM_9_TO_A; | |
} | |
return n; | |
} | |
void convertDeviceIDToBinary() { | |
char highNibble, lowNibble; | |
String stringID = System.deviceID(); | |
Serial.println(stringID); | |
for (int i = 0; i < 12; i++) { | |
highNibble = asciiToNibble(stringID.charAt(2 * i)); | |
lowNibble = asciiToNibble(stringID.charAt(2 * i + 1)); | |
binaryDeviceID[i] = highNibble << 4 | lowNibble; | |
} | |
} | |
void setup() { | |
WiFi.connect(); | |
Serial.begin(115200); | |
pinMode(D7, OUTPUT); | |
convertDeviceIDToBinary(); | |
} | |
void loop() { | |
static system_tick_t t = millis(); | |
if (WiFi.ready() && millis() - t > 10000) { | |
t = millis(); | |
Multicast_Presence_Announcement(); | |
Serial.print("Announced from "); | |
Serial.println(WiFi.localIP()); | |
digitalWrite(D7, HIGH); | |
delay(50); | |
digitalWrite(D7, LOW); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment