7 #include <ESP8266WiFi.h> 
   13 #include <Ethernet2.h> 
   14 #include <EthernetUdp2.h> 
   17 #include <EthernetUdp.h> 
   24     uint32_t _magic_header;
 
   31     uint8_t _broadcast[4] = { 0xFF, 0xFF, 0xFF, 0xFF };
 
   35     bool begin(uint16_t port)
 
   38         return udp.begin(_port);
 
   41     uint16_t receive_frame(uint8_t *
data, uint16_t max_length)
 
   43         uint16_t result = PJON_FAIL;
 
   44         int16_t packet_size = udp.parsePacket();
 
   47             int16_t len = udp.read((
char *) &header, 4), remaining = packet_size - len;
 
   51             if(len == 4 && header == _magic_header && (
unsigned)packet_size <= 4 + max_length) {
 
   52                 len = udp.read(
data, packet_size - 4);
 
   56                 if (len == packet_size - 4) {
 
   57                     result = packet_size - 4;
 
   65                 while (remaining > 0 && len > 0) {
 
   66                     len = udp.read(
data, (
unsigned)remaining <= max_length ? remaining : max_length);
 
   76     void send_frame(uint8_t *
data, uint16_t length, 
IPAddress remote_ip, uint16_t remote_port)
 
   79             udp.beginPacket(remote_ip, remote_port);
 
   81             udp.write((
const unsigned char*) &_magic_header, 4);
 
   83             udp.write((
const char*) &_magic_header, 4);
 
   85             udp.write(
data, length);
 
   90     void send_response(uint8_t *
data, uint16_t length)
 
   92         send_frame(
data, length, udp.remoteIP(), udp.remotePort());
 
   95     void send_response(uint8_t response)
 
   97         send_frame(&response, 1, udp.remoteIP(), udp.remotePort());
 
  100     void send_frame(uint8_t *
data, uint16_t length, uint8_t remote_ip[], uint16_t remote_port)
 
  103         send_frame(
data, length, address, remote_port);
 
  106     void send_frame(uint8_t *
data, uint16_t length)
 
  112         broadcastIp = ~(uint32_t)WiFi.subnetMask() | (uint32_t)WiFi.localIP();
 
  114         broadcastIp = _broadcast;
 
  116         send_frame(
data, length, broadcastIp, _port);
 
  119     void set_magic_header(uint32_t magic_header)
 
  121         _magic_header = magic_header;
 
  124     void get_sender(uint8_t *ip, uint16_t &port)
 
  126         uint32_t ip_address = udp.remoteIP();
 
  127         memcpy(ip, &ip_address, 4);
 
  128         port = udp.remotePort();