]> git.scottworley.com Git - tattlekey/blobdiff - client/net.c
client: Send UDP packets
[tattlekey] / client / net.c
diff --git a/client/net.c b/client/net.c
new file mode 100644 (file)
index 0000000..da33727
--- /dev/null
@@ -0,0 +1,58 @@
+#include "net.h"
+#include "blink.h"
+#include "config.h"
+
+#include "pico/cyw43_arch.h"
+
+#include "lwip/pbuf.h"
+#include "lwip/udp.h"
+
+/* We only ever send to one address, and we only ever have one thread, so just
+ * use one udp_pcb */
+static struct udp_pcb *the_pcb = NULL;
+
+static void initialize_the_pcb() {
+  if (the_pcb)
+    return;
+
+  the_pcb = udp_new();
+  if (!the_pcb)
+    signal_error_by_blinking();
+
+  ip_addr_t ipaddr;
+  if (ip4addr_aton(tattle_server_ip_address, &ipaddr) == 0)
+    signal_error_by_blinking();
+
+  if (udp_connect(the_pcb, &ipaddr, htons(tattle_port)) != ERR_OK)
+    signal_error_by_blinking();
+}
+
+struct tattle_message_wire_format {
+  u16_t sender;
+  u16_t seq;
+  u16_t ago;
+};
+
+void send_report(u16_t seq, u16_t ago) {
+  cyw43_arch_lwip_begin();
+
+  initialize_the_pcb();
+
+  struct pbuf *p = pbuf_alloc(
+      PBUF_TRANSPORT, sizeof(struct tattle_message_wire_format), PBUF_RAM);
+  if (!p)
+    signal_error_by_blinking();
+
+  struct tattle_message_wire_format *msg =
+      (struct tattle_message_wire_format *)(p->payload);
+  msg->sender = htons(this_tattler_identity);
+  msg->seq = htons(seq);
+  msg->ago = htons(ago);
+
+  if (udp_send(the_pcb, p) != ERR_OK)
+    signal_error_by_blinking();
+
+  pbuf_free(p);
+
+  cyw43_arch_lwip_end();
+}