#include <WiFi.h>
#include <WiFiUdp.h>
#include <coap-simple.h>
int num = 0;
String temp_1 = "";
String temp_2 = "";
bool LEDSTATE = true;
//int num = 47;
int Led[] = {23, 13, 12, 14, 27, 32, 25, 26};
// CoAP client response callback
void callback_response(CoapPacket &packet, IPAddress ip, int port);
// UDP and CoAP class
// other initialize is "Coap coap(Udp, 512);"
// 2nd default parameter is COAP_BUF_MAX_SIZE(defaulit:128)
// For UDP fragmentation, it is good to set the maximum under
// 1280byte when using the internet connection.
WiFiUDP udp;
Coap coap(udp);
void setup() {
Serial.begin(9600);
WiFi.begin("Wokwi-GUEST", "", 6);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.print("IP address: "); Serial.println(WiFi.localIP());
for (int i = 0; i < 8; i++) {
pinMode(Led[i], OUTPUT);
}
//coap.server(callback_light, "coap");
coap.response(callback_response);
// start coap server/client
coap.start();
delay(2000);
int msgid = coap.get(IPAddress(82, 223, 151, 26), 5683, "coap");
}
void loop() {
delay(1000);
coap.loop();
if (temp_2 != temp_1) {
temp_2 = temp_1;
}
int msgid = coap.get(IPAddress(82, 223, 151, 26), 5683, "coap");
}
// CoAP client response callback
void callback_response(CoapPacket &packet, IPAddress ip, int port) {
char p[packet.payloadlen + 1];
memcpy(p, packet.payload, packet.payloadlen);
p[packet.payloadlen] = NULL;
String message(p);
temp_1 = p;
num = message.toInt();
String prova = toBinary(num);
prova = addLeadingZeros(prova, 8);
if (temp_2 != temp_1) {
//Serial.print("[Coap Response got]: "); Serial.println(p);
Serial.print("Numero: "); Serial.println(temp_1);
Serial.print("binario: "); Serial.println(prova);
coap.sendResponse(ip, port, packet.messageid, "ACK"); // restituisco ACKc
}
for (int i = 0; i < 8; i++) {
if (prova[i] == '1') {
digitalWrite(Led[i], HIGH);
}
else {
digitalWrite(Led[i], LOW);
}
}
num = 0;
}
String addLeadingZeros(String str, int len) {
while (str.length() < len) {
str = "0" + str;
}
return str;
}
String toBinary(int num) {
String result = "";
if (num == 0) {
result = "0";
}
while (num > 0) {
int bit = num % 2;
result = String(bit) + result;
num = num / 2;
}
return result;
}
/*
void callback_light(CoapPacket &packet, IPAddress ip, int port) {
Serial.println("[Light] ON/OFF");
// send response
char p[packet.payloadlen + 1];
memcpy(p, packet.payload, packet.payloadlen);
p[packet.payloadlen] = NULL;
String message(p);
}
*/
2
1
4
8
16
32
64
128