1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
| #include <SPI.h> #include <Dhcp.h> #include <Dns.h> #include <Ethernet.h> #include <EthernetUdp.h> #include <coap-simple.h>
#define USE\_STATIC 0 byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; #if USE\_STATIC IPAddress ip(192, 168, 0, 177); #endif
// CoAP客户端响应回调函数 void callback\_response(CoapPacket &packet, IPAddress ip, int port);
// CoAP服务器URL回调函数 void callback\_light(CoapPacket &packet, IPAddress ip, int port);
EthernetUDP Udp; Coap coap(Udp);
// LED STATE bool LEDSTATE; #define LEDP 13
// CoAP server endpoint URL void callback\_light(CoapPacket &packet, IPAddress ip, int port) { Serial.println("[Light] ON/OFF"); // 发送响应 char p[packet.payloadlen + 1]; memcpy(p, packet.payload, packet.payloadlen); p[packet.payloadlen] = NULL; String message(p); Serial.println(p); if (message.equals("0")) LEDSTATE = false; else if(message.equals("1")) LEDSTATE = true; if (LEDSTATE) { digitalWrite(LEDP, HIGH) ; coap.sendResponse(ip, port, packet.messageid, "1"); } else { digitalWrite(LEDP, LOW) ; coap.sendResponse(ip, port, packet.messageid, "0"); } }
void callback\_response(CoapPacket &packet, IPAddress ip, int port) { Serial.println("[Coap Response got]"); char p[packet.payloadlen + 1]; memcpy(p, packet.payload, packet.payloadlen); p[packet.payloadlen] = NULL; Serial.println(p); }
void setup() { Serial.begin(115200); Serial.println("Ethernet CoAP Server Example"); #if USE\_STATIC Ethernet.begin(mac,ip); #else Ethernet.begin(mac); #endif
if (Ethernet.hardwareStatus() == EthernetNoHardware) { Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :("); while (true) { delay(1); } } if (Ethernet.linkStatus() == LinkOFF) { Serial.println("Ethernet cable is not connected."); while(true){ delay(1); } }
Serial.print("IP:"); Serial.println(Ethernet.localIP()); Serial.print("Subnet Mask:"); Serial.println(Ethernet.subnetMask()); Serial.print("Gateway:"); Serial.println(Ethernet.gatewayIP()); Serial.print("DNS Server:"); Serial.println(Ethernet.dnsServerIP());
// LED State pinMode(LEDP, OUTPUT); digitalWrite(LEDP, HIGH); LEDSTATE = true;
Serial.println("Setup Callback Light"); coap.server(callback_light, "light"); Serial.println("Setup Response Callback"); coap.response(callback_response);
coap.start(); }
void loop() { //Serial.println("Send Request"); //int msgid = coap.get(IPAddress(XXX, XXX, XXX, XXX), 5683, "time");
//delay(1000); coap.loop(); }
|