#include #include #include #include // hirotakaster/CoAP simple library // ===== Wi-Fi creds ===== const char* WIFI_SSID = "UPB-Guest"; const char* WIFI_PASS = ""; // ===== CoAP server (Californium demo) ===== const char* COAP_HOST = "californium.eclipseprojects.io"; const uint16_t COAP_PORT = 5683; // RFC 7252 default port // UDP + CoAP objects WiFiUDP udp; Coap coap(udp); // ----- Response callback: prints payload as text ----- void onCoapResponse(CoapPacket &packet, IPAddress ip, int port) { // Copy payload into a printable buffer const size_t n = packet.payloadlen; String from = ip.toString() + ":" + String(port); Serial.printf("[CoAP] Response from %s code=%u (0x%02X) len=%u\n", from.c_str(), (packet.code >> 5), packet.code, (unsigned)n); if (n > 0) { // Make it printable; not all payloads are ASCII size_t m = n; if (m > 1023) m = 1023; // clamp for serial char buf[1024]; memcpy(buf, packet.payload, m); buf[m] = '\0'; Serial.println(F("[CoAP Payload]")); Serial.println(buf); } } // Re-resolves hostname and sends GET to "/" bool coapGetRoot() { IPAddress remote; if (!WiFi.hostByName(COAP_HOST, remote)) { Serial.println(F("[CoAP] DNS failed")); return false; } Serial.printf("[CoAP] GET coap://%s:%u/\n", COAP_HOST, COAP_PORT); // Path is "" for "/", per library examples int msgid = coap.get(remote, COAP_PORT, ""); (void)msgid; // not used further in this demo return true; } unsigned long lastGetMs = 0; const unsigned long GET_PERIOD_MS = 10000; void setup() { Serial.begin(115200); delay(200); Serial.println(F("\n== CoAP client (Californium demo) ==")); // Wi-Fi WiFi.mode(WIFI_STA); WiFi.begin(WIFI_SSID, WIFI_PASS); Serial.print(F("Connecting")); while (WiFi.status() != WL_CONNECTED) { delay(300); Serial.print('.'); } Serial.println(); Serial.print(F("Wi-Fi OK. IP: ")); Serial.println(WiFi.localIP()); // Bind UDP so we can receive responses (use standard CoAP port or 0 for ephemeral) udp.begin(5683); // Register response handler and start CoAP coap.response(onCoapResponse); coap.start(); // First GET right away coapGetRoot(); lastGetMs = millis(); } void loop() { // Let the library process incoming UDP (and fire onCoapResponse) coap.loop(); // Periodic GET unsigned long now = millis(); if (now - lastGetMs >= GET_PERIOD_MS) { lastGetMs = now; coapGetRoot(); } }