Skip to content

Instantly share code, notes, and snippets.

@ennerf
Created October 25, 2016 18:19
Show Gist options
  • Save ennerf/36a57d432bcff20a58efcdee10f91bd9 to your computer and use it in GitHub Desktop.
Save ennerf/36a57d432bcff20a58efcdee10f91bd9 to your computer and use it in GitHub Desktop.
UDP client and echo server using LWIP and ChibiOS 2.6.x (incomplete example for a blog post)
// ... includes, lwip thread setup, ip/mac address, timer, statistics_recorder
struct udp_pcb * pcb_ = udp_new();
static void udp_receive(void *arg, struct udp_pcb *pcb, struct pbuf *p, struct ip_addr *addr, uint16_t port) {
if (p != NULL) {
// record timestamp complete and send to logging server
stats_recorder.setValue4(timer.nanoTime());
stats_recorder.sendto(&serverAddr, serverPort);
stats_recorder.resetValues();
// free buffer
pbuf_free(p);
}
}
int main(void) {
// setup UDP port
struct udp_pcb * pcb = udp_new();
udp_bind(pcb, IP_ADDR_ANY, ECHO_PORT);
udp_recv(pcb, udp_receive, &pcb);
// send a message every 10ms
uint32_t sequence = 0;
systime_t time = chTimeNow(); // T0
while (TRUE) {
stats_recorder.setValue0(sequence++); // sequence number
stats_recorder.setValue1(timer.nanoTime()); // start of loop
pbuf * p = pbuf_alloc(PBUF_TRANSPORT, 200, PBUF_RAM);
stats_recorder.setValue2(timer.nanoTime()); // start of packet send
// send message to echo server
if (p != NULL) {
udp_sendto(pcb_, p, &echoAddr, ECHO_PORT);
pbuf_free(p);
}
stats_recorder.setValue3(timer.nanoTime()); // end of packet send
// Sleep until the next deadline. There is an unsigned cast because
// there is an issue with the built-in ChibiOS 2.x implementation that
// causes an underflow if a deadline were ever to be missed.
time += MS2ST(2);
int32_t ticks = int32_t(time - chTimeNow());
if(ticks > 0){
chThdSleep(ticks);
}
}
}
// ... includes, lwip thread setup, ip/mac address
static void udp_echo_receive(void *arg, struct udp_pcb *pcb, struct pbuf *p, struct ip_addr *addr, uint16_t port) {
if (p != NULL) {
udp_sendto(pcb, p, addr, port);
pbuf_free(p);
}
}
int main(void) {
// setup UDP port
struct udp_pcb * pcb = udp_new();
udp_bind(pcb, IP_ADDR_ANY, ECHO_PORT);
udp_recv(pcb, udp_receive, &pcb);
// sleep forever
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment