RP2040_Teleplot_C/picow_udp_beacon.c

91 lines
2.4 KiB
C

/**
* Copyright (c) 2022 Andrew McDonnell
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include "pico/stdlib.h"
#include "pico/cyw43_arch.h"
#include "lwip/pbuf.h"
#include "lwip/udp.h"
// Si le fichier n'existe pas, créez-le à partir du modèle "wifi_settings.h.default"
#include "wifi_settings.h"
#define UDP_PORT 47269
#define BEACON_MSG_LEN_MAX 127
#define BEACON_TARGET "192.168.1.58"
#define BEACON_INTERVAL_MS 25
void run_udp_beacon() {
struct udp_pcb* pcb = udp_new();
ip_addr_t addr;
ipaddr_aton(BEACON_TARGET, &addr);
int counter = 0;
while (true) {
struct pbuf *p = pbuf_alloc(PBUF_TRANSPORT, BEACON_MSG_LEN_MAX+1, PBUF_RAM);
char *req = (char *)p->payload;
memset(req, 0, BEACON_MSG_LEN_MAX+1);
snprintf(req, BEACON_MSG_LEN_MAX, "t:%d\nsin:%.2f\n", counter, sinf(counter/10.));
err_t er = udp_sendto(pcb, p, &addr, UDP_PORT);
pbuf_free(p);
if (er != ERR_OK) {
printf("Failed to send UDP packet! error=%d", er);
} else {
printf("Sent packet %d\n", counter);
counter++;
}
// Note in practice for this simple UDP transmitter,
// the end result for both background and poll is the same
#if PICO_CYW43_ARCH_POLL
// if you are using pico_cyw43_arch_poll, then you must poll periodically from your
// main loop (not from a timer) to check for Wi-Fi driver or lwIP work that needs to be done.
cyw43_arch_poll();
sleep_ms(BEACON_INTERVAL_MS);
#else
// if you are not using pico_cyw43_arch_poll, then WiFI driver and lwIP work
// is done via interrupt in the background. This sleep is just an example of some (blocking)
// work you might be doing.
sleep_ms(BEACON_INTERVAL_MS);
#endif
}
}
int init_wifi(void){
if (cyw43_arch_init()) {
printf("failed to initialise\n");
return 1;
}
cyw43_arch_enable_sta_mode();
printf("Connecting to Wi-Fi...\n");
if (cyw43_arch_wifi_connect_timeout_ms(WIFI_SSID, WIFI_PASSWORD, CYW43_AUTH_WPA2_AES_PSK, 30000)) {
printf("failed to connect.\n");
return 1;
} else {
printf("Connected.\n");
}
return 0;
}
int main() {
int erreur;
stdio_init_all();
erreur = init_wifi();
if(!erreur){
run_udp_beacon();
}
cyw43_arch_deinit();
return 0;
}