Git Product home page Git Product logo

khoih-prog / asyncudp_rp2040w Goto Github PK

View Code? Open in Web Editor NEW
2.0 3.0 0.0 219 KB

Fully Asynchronous UDP Library for RASPBERRY_PI_PICO_W using CYW43439 WiFi with arduino-pico core. The library is easy to use and includes support for Unicast, Broadcast and Multicast environments. This library is the base for future and more advanced Async libraries, such as AsyncWebServer_RP2040W, AsyncHTTPRequest_RP2040W, AsyncHTTPSRequest_RP2040W, AsyncDNSServer_RP2040W

License: GNU Lesser General Public License v3.0

C++ 78.61% C 15.98% Shell 5.41%
arduino-pico async async-udp broadcast cyw43439 lwip multicast ntp ntp-client rp2040

asyncudp_rp2040w's Introduction

AsyncUDP_RP2040W Library

arduino-library-badge GitHub release contributions welcome GitHub issues

Donate to my libraries using BuyMeACoffee



Table of Contents



Why do we need this AsyncUDP_RP2040W library

Features

This AsyncUDP_RP2040W library is a fully asynchronous UDP library, designed for a trouble-free, multi-connection network environment, for RASPBERRY_PI_PICO_W using CYW43439 WiFi. The library is easy to use and includes support for Unicast, Broadcast and Multicast environments.

This library is based on, modified from:

  1. Hristo Gochkov's ESPAsyncUDP
  2. Khoi Hoang's AsyncUDP_STM32

to apply the better and faster asynchronous feature of the powerful ESPAsyncUDP Library into RASPBERRY_PI_PICO_W using CYW43439 WiFi using arduino-pico core v2.4.0+.

Why Async is better

  • Using asynchronous network means that you can handle more than one connection at the same time
  • You are called once the request is ready and parsed
  • When you send the response, you are immediately ready to handle other connections while the server is taking care of sending the response in the background
  • Speed is OMG
  • After connecting to a UDP server as an Async Client, you are immediately ready to handle other connections while the Client is taking care of receiving the UDP responding packets in the background.
  • You are not required to check in a tight loop() the arrival of the UDP responding packets to process them.

Currently supported Boards

  1. RASPBERRY_PI_PICO_W with CYW43439 WiFi using arduino-pico core v2.4.0+



Prerequisites

  1. Arduino IDE 1.8.19+ for Arduino. GitHub release
  2. Earle Philhower's arduino-pico core v2.6.3+ for RASPBERRY_PI_PICO_W with CYW43439 WiFi, etc. GitHub release

Installation

The suggested way to install is to:

Use Arduino Library Manager

The best way is to use Arduino Library Manager. Search for AsyncUDP_RP2040W, then select / install the latest version. You can also use this link arduino-library-badge for more detailed instructions.

Manual Install

  1. Navigate to AsyncUDP_RP2040W page.
  2. Download the latest release AsyncUDP_RP2040W-main.zip.
  3. Extract the zip file to AsyncUDP_RP2040W-main directory
  4. Copy the whole AsyncUDP_RP2040W-main folder to Arduino libraries' directory such as ~/Arduino/libraries/.

VS Code & PlatformIO:

  1. Install VS Code
  2. Install PlatformIO
  3. Install AsyncUDP_RP2040W library by using Library Manager. Search for AsyncUDP_RP2040W in Platform.io Author's Libraries
  4. Use included platformio.ini file from examples to ensure that all dependent libraries will installed automatically. Please visit documentation for the other options and examples at Project Configuration File


HOWTO Fix Multiple Definitions Linker Error

The current library implementation, using xyz-Impl.h instead of standard xyz.cpp, possibly creates certain Multiple Definitions Linker error in certain use cases.

You can include this .hpp file

// Can be included as many times as necessary, without `Multiple Definitions` Linker Error
#include "AsyncUDP_RP2040W.hpp"         //https://github.com/khoih-prog/AsyncUDP_RP2040W

in many files. But be sure to use the following .h file in just 1 .h, .cpp or .ino file, which must not be included in any other file, to avoid Multiple Definitions Linker Error

// To be included only in main(), .ino with setup() to avoid `Multiple Definitions` Linker Error
#include "AsyncUDP_RP2040W.h"           //https://github.com/khoih-prog/AsyncUDP_RP2040W

Check the multiFileProject example for a HOWTO demo.

Have a look at the discussion in Different behaviour using the src_cpp or src_h lib #80



HOWTO Setting up the Async UDP Client

#include "defines.h"
#include <time.h>

// To be included only in main(), .ino with setup() to avoid `Multiple Definitions` Linker Error
#include <AsyncUDP_RP2040W.h>         // https://github.com/khoih-prog/AsyncUDP_RP2040W

// 0.ca.pool.ntp.org
IPAddress timeServerIP = IPAddress(208, 81, 1, 244);
// time.nist.gov
//IPAddress timeServerIP = IPAddress(132, 163, 96, 1);

#define NTP_REQUEST_PORT      123

//char timeServer[] = "time.nist.gov";  // NTP server
char timeServer[] = "0.ca.pool.ntp.org";

const int NTP_PACKET_SIZE = 48;       // NTP timestamp is in the first 48 bytes of the message

byte packetBuffer[NTP_PACKET_SIZE];   // buffer to hold incoming and outgoing packets

// A UDP instance to let us send and receive packets over UDP
AsyncUDP Udp;

int status = WL_IDLE_STATUS;

// send an NTP request to the time server at the given address
void createNTPpacket()
{
  Serial.println("============= createNTPpacket =============");

  // set all bytes in the buffer to 0
  memset(packetBuffer, 0, NTP_PACKET_SIZE);
  // Initialize values needed to form NTP request
  // (see URL above for details on the packets)

  packetBuffer[0]   = 0b11100011;   // LI, Version, Mode
  packetBuffer[1]   = 0;     // Stratum, or type of clock
  packetBuffer[2]   = 6;     // Polling Interval
  packetBuffer[3]   = 0xEC;  // Peer Clock Precision
  
  // 8 bytes of zero for Root Delay & Root Dispersion
  packetBuffer[12]  = 49;
  packetBuffer[13]  = 0x4E;
  packetBuffer[14]  = 49;
  packetBuffer[15]  = 52;
}

void parsePacket(AsyncUDPPacket packet)
{
  ...
}

void sendNTPPacket()
{
  createNTPpacket();

  Serial.println("Sending UDP Packet");
  
  //Send unicast
  Udp.write(packetBuffer, sizeof(packetBuffer));

  Serial.println("Sent UDP Packet");
}

void printWifiStatus()
{
  ...
}

void setup()
{
  Serial.begin(115200);
  while (!Serial && millis() < 5000);

  Serial.print("\nStart AsyncUdpNTPClient on "); Serial.println(BOARD_NAME);
  Serial.println(ASYNC_UDP_RP2040W_VERSION);
  
  ///////////////////////////////////
  
  // check for the WiFi module:
  if (WiFi.status() == WL_NO_MODULE)
  {
    Serial.println("Communication with WiFi module failed!");
    // don't continue
    while (true);
  }

  Serial.print(F("Connecting to SSID: "));
  Serial.println(ssid);

  status = WiFi.begin(ssid, pass);

  delay(1000);
   
  // attempt to connect to WiFi network
  while ( status != WL_CONNECTED)
  {
    delay(500);
        
    // Connect to WPA/WPA2 network
    status = WiFi.status();
  }

  printWifiStatus();

  ///////////////////////////////////

  //NTP requests are to port NTP_REQUEST_PORT = 123
  if (Udp.connect(timeServerIP, NTP_REQUEST_PORT))
  {
    Serial.println("UDP connected");

    Udp.onPacket([](AsyncUDPPacket packet)
    {
      parsePacket(packet);
    });
  }
}

void loop()
{
  sendNTPPacket();

  // wait 60 seconds before asking for the time again
  delay(60000);
}


Examples

1. For RASPBERRY_PI_PICO_W

  1. AsyncUDPClient
  2. AsyncUdpNTPClient
  3. AsyncUdpSendReceive
  4. AsyncUDPServer
  5. AsyncUDPMulticastServer
  6. multiFileProject

2. Python test program

  1. UDP_packet_send.py

#include "defines.h"
#include <time.h>
// To be included only in main(), .ino with setup() to avoid `Multiple Definitions` Linker Error
#include <AsyncUDP_RP2040W.h> // https://github.com/khoih-prog/AsyncUDP_RP2040W
// 0.ca.pool.ntp.org
IPAddress timeServerIP = IPAddress(208, 81, 1, 244);
// time.nist.gov
//IPAddress timeServerIP = IPAddress(132, 163, 96, 1);
#define NTP_REQUEST_PORT 123
//char timeServer[] = "time.nist.gov"; // NTP server
char timeServer[] = "0.ca.pool.ntp.org";
const int NTP_PACKET_SIZE = 48; // NTP timestamp is in the first 48 bytes of the message
byte packetBuffer[NTP_PACKET_SIZE]; // buffer to hold incoming and outgoing packets
// A UDP instance to let us send and receive packets over UDP
AsyncUDP Udp;
int status = WL_IDLE_STATUS;
// send an NTP request to the time server at the given address
void createNTPpacket()
{
Serial.println("============= createNTPpacket =============");
// set all bytes in the buffer to 0
memset(packetBuffer, 0, NTP_PACKET_SIZE);
// Initialize values needed to form NTP request
// (see URL above for details on the packets)
packetBuffer[0] = 0b11100011; // LI, Version, Mode
packetBuffer[1] = 0; // Stratum, or type of clock
packetBuffer[2] = 6; // Polling Interval
packetBuffer[3] = 0xEC; // Peer Clock Precision
// 8 bytes of zero for Root Delay & Root Dispersion
packetBuffer[12] = 49;
packetBuffer[13] = 0x4E;
packetBuffer[14] = 49;
packetBuffer[15] = 52;
}
void parsePacket(AsyncUDPPacket packet)
{
struct tm ts;
char buf[80];
memcpy(packetBuffer, packet.data(), sizeof(packetBuffer));
Serial.print("Received UDP Packet Type: ");
Serial.println(packet.isBroadcast() ? "Broadcast" : packet.isMulticast() ? "Multicast" : "Unicast");
Serial.print("From: ");
Serial.print(packet.remoteIP());
Serial.print(":");
Serial.print(packet.remotePort());
Serial.print(", To: ");
Serial.print(packet.localIP());
Serial.print(":");
Serial.print(packet.localPort());
Serial.print(", Length: ");
Serial.print(packet.length());
Serial.println();
unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
// combine the four bytes (two words) into a long integer
// this is NTP time (seconds since Jan 1 1900):
unsigned long secsSince1900 = highWord << 16 | lowWord;
Serial.print(F("Seconds since Jan 1 1900 = "));
Serial.println(secsSince1900);
// now convert NTP time into )everyday time:
Serial.print(F("Epoch/Unix time = "));
// Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
const unsigned long seventyYears = 2208988800UL;
// subtract seventy years:
unsigned long epoch = secsSince1900 - seventyYears;
time_t epoch_t = epoch; //secsSince1900 - seventyYears;
// print Unix time:
Serial.println(epoch);
// print the hour, minute and second:
Serial.print(F("The UTC/GMT time is ")); // UTC is the time at Greenwich Meridian (GMT)
ts = *localtime(&epoch_t);
strftime(buf, sizeof(buf), "%a %Y-%m-%d %H:%M:%S %Z", &ts);
Serial.println(buf);
}
void sendNTPPacket()
{
createNTPpacket();
Serial.println("Sending UDP Packet");
//Send unicast
Udp.write(packetBuffer, sizeof(packetBuffer));
Serial.println("Sent UDP Packet");
}
void printWifiStatus()
{
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your board's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("Local IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}
void setup()
{
Serial.begin(115200);
while (!Serial && millis() < 5000);
Serial.print("\nStart AsyncUdpNTPClient on "); Serial.println(BOARD_NAME);
Serial.println(ASYNC_UDP_RP2040W_VERSION);
///////////////////////////////////
// check for the WiFi module:
if (WiFi.status() == WL_NO_MODULE)
{
Serial.println("Communication with WiFi module failed!");
// don't continue
while (true);
}
Serial.print(F("Connecting to SSID: "));
Serial.println(ssid);
status = WiFi.begin(ssid, pass);
delay(1000);
// attempt to connect to WiFi network
while ( status != WL_CONNECTED)
{
delay(500);
// Connect to WPA/WPA2 network
status = WiFi.status();
}
printWifiStatus();
///////////////////////////////////
//NTP requests are to port NTP_REQUEST_PORT = 123
if (Udp.connect(timeServerIP, NTP_REQUEST_PORT))
{
Serial.println("UDP connected");
Udp.onPacket([](AsyncUDPPacket packet)
{
parsePacket(packet);
});
}
}
void loop()
{
sendNTPPacket();
// wait 60 seconds before asking for the time again
delay(60000);
}

2. File defines.h

/****************************************************************************************************************************
defines.h
AsyncUDP_RP2040W is a library for the RP2040W with CYW43439 WiFi
Based on and modified from ESPAsyncUDP (https://github.com/me-no-dev/ESPAsyncUDP)
Built by Khoi Hoang https://github.com/khoih-prog/AsyncUDP_RP2040W
*****************************************************************************************************************************/
#ifndef defines_h
#define defines_h
#if !( defined(ARDUINO_RASPBERRY_PI_PICO_W) )
#error For RASPBERRY_PI_PICO_W only
#endif
//#include <WiFi.h>
// To be included only in main(), .ino with setup() to avoid `Multiple Definitions` Linker Error
//#include <AsyncUDP_RP2040W.h> // https://github.com/khoih-prog/AsyncUDP_RP2040W
char ssid[] = "your_ssid"; // your network SSID (name)
char pass[] = "12345678"; // your network password (use for WPA, or use as key for WEP), length must be 8+
#endif //defines_h


Debug Terminal Output Samples

1. AsyncUdpNTPClient on RASPBERRY_PI_PICO_W using CYW43439 WiFi

This is terminal debug output when running AsyncUdpNTPClient on PRASPBERRY_PI_PICO_W using CYW43439 WiFi. It connects to NTP Server 0.ca.pool.ntp.org (IP=208.81.1.244:123) using AsyncUDP_RP2040W library, and requests NTP time every 60s. The packet is then received and processed asynchronously to print current UTC/GMT time.

Start AsyncUdpNTPClient on RASPBERRY_PI_PICO_W
AsyncUDP_RP2040W v1.0.0
Connecting to SSID: HueNet1
SSID: HueNet1
Local IP Address: 192.168.2.87
signal strength (RSSI):-25 dBm
UDP connected
============= createNTPpacket =============
Sending UDP Packet
Sent UDP Packet
Received UDP Packet Type: Unicast
From: 208.81.1.244:123, To: 192.168.2.87:58997, Length: 48
Seconds since Jan 1 1900 = 3842738319
Epoch/Unix time = 1633749519
The UTC/GMT time is Sat 2021-10-09 03:18:39 GMT
============= createNTPpacket =============
Sending UDP Packet
Sent UDP Packet
Received UDP Packet Type: Unicast
From: 208.81.1.244:123, To: 192.168.2.87:58997, Length: 48
Seconds since Jan 1 1900 = 3842738378
Epoch/Unix time = 1633749578
The UTC/GMT time is Sat 2021-10-09 03:19:38 GMT

2. AsyncUDPServer on RASPBERRY_PI_PICO_W using CYW43439 WiFi

This is terminal debug output when running AsyncUDPServer on RASPBERRY_PI_PICO_W using CYW43439 WiFi. It receives UDP packets from a PC running test Python program UDP_packet_send.py to send UDP packets.

Start AsyncUDPServer on RASPBERRY_PI_PICO_W
AsyncUDP_RP2040W v1.0.0
Connecting to SSID: HueNet1
SSID: HueNet1
Local IP Address: 192.168.2.87
signal strength (RSSI):-25 dBm
UDP Listening on IP: 192.168.2.87
UDP Packet Type: Unicast, From: 192.168.2.30:33380, To: 192.168.2.87:1234, Length: 27, Data: Hello, RASPBERRY_PI_PICO_W!

3. AsyncUDPMulticastServer on RASPBERRY_PI_PICO_W using CYW43439 WiFi

This is terminal debug output when running AsyncUDPMulticastServer on RASPBERRY_PI_PICO_W using CYW43439 WiFi. It receives UDP packets from from a PC running test Python program UDP_packet_send.py to send UDP packets.

Start AsyncUDPMulticastServer on RASPBERRY_PI_PICO_W
AsyncUDP_RP2040W v1.0.0
Connecting to SSID: HueNet1
SSID: HueNet1
Local IP Address: 192.168.2.87
signal strength (RSSI):-25 dBm
UDP Listening on IP: 192.168.2.87
UDP Packet Type: Unicast, From: 192.168.2.30:50119, To: 192.168.2.87:1234, Length: 27, Data: Hello, RASPBERRY_PI_PICO_W!


Debug

Debug is enabled by default on Serial. To disable, use level 0

#define AUDP_RP2040W_DEBUG_PORT      Serial

// Use from 0 to 4. Higher number, more debugging messages and memory usage.
#define _AUDP_RP2040W_LOGLEVEL_      0

You can also change the debugging level from 0 to 4, default is 1 to output only error messages

#define AUDP_RP2040W_DEBUG_PORT      Serial

// Use from 0 to 4. Higher number, more debugging messages and memory usage.
#define _AUDP_RP2040W_LOGLEVEL_      4

Troubleshooting

If you get compilation errors, more often than not, you may need to install a newer version of the arduino-pico core

Sometimes, the library will only work if you update the arduino-pico core core to the latest version because I am using newly added functions.



Issues

Submit issues to: AsyncUDP_RP2040W issues


TO DO

  1. Fix bug. Add enhancement

DONE

  1. Add support to RASPBERRY_PI_PICO_W with CYW43439 WiFi, using arduino-pico core v2.4.0+
  2. Add Table of Contents
  3. Add astyle using allman style. Restyle the library


Contributions and Thanks

  1. Based on and modified from Hristo Gochkov's ESPAsyncUDP. Many thanks to Hristo Gochkov for great ESPAsyncUDP Library
me-no-dev
⭐️⭐️ Hristo Gochkov


Contributing

If you want to contribute to this project:

  • Report bugs and errors
  • Ask for enhancements
  • Create issues and pull requests
  • Tell other people about this library

License

  • The library is licensed under GPLv3

Copyright

Copyright (c) 2022- Khoi Hoang

asyncudp_rp2040w's People

Contributors

khoih-prog avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.