|
| 1 | +#include <micro_ros_platformio.h> |
| 2 | + |
| 3 | +#include <uxr/client/util/time.h> |
| 4 | +#include <uxr/client/profile/transport/custom/custom_transport.h> |
| 5 | + |
| 6 | +#include <sys/types.h> |
| 7 | +#include <sys/socket.h> |
| 8 | +#include <netdb.h> |
| 9 | +#include <stdlib.h> |
| 10 | +#include <unistd.h> |
| 11 | +#include <poll.h> |
| 12 | +#include <string> |
| 13 | + |
| 14 | +extern "C" { |
| 15 | + |
| 16 | +static int fd; |
| 17 | + |
| 18 | +bool platformio_transport_open(struct uxrCustomTransport * transport) |
| 19 | +{ |
| 20 | + const auto * locator = (const struct micro_ros_agent_locator *) transport->args; |
| 21 | + |
| 22 | + struct addrinfo hints; |
| 23 | + |
| 24 | + memset(&hints, 0, sizeof(hints)); |
| 25 | + |
| 26 | + hints.ai_family = AF_UNSPEC; |
| 27 | + hints.ai_socktype = SOCK_DGRAM; |
| 28 | + hints.ai_flags = AI_NUMERICSERV; |
| 29 | + hints.ai_protocol = 0; |
| 30 | + |
| 31 | + const auto port_s = std::to_string(locator->port); |
| 32 | + struct addrinfo * p_addrs = nullptr; |
| 33 | + |
| 34 | + if(getaddrinfo(locator->address, port_s.c_str(), &hints, &p_addrs) != 0) |
| 35 | + return false; |
| 36 | + |
| 37 | + struct addrinfo * p_addr; |
| 38 | + |
| 39 | + for(p_addr = p_addrs; p_addr != nullptr; p_addr = p_addr->ai_next){ |
| 40 | + if(0 > (fd = socket(p_addr->ai_family, p_addr->ai_socktype, p_addr->ai_protocol))) |
| 41 | + continue; |
| 42 | + |
| 43 | + if(0 == connect(fd, p_addr->ai_addr, p_addr->ai_addrlen)) |
| 44 | + break; |
| 45 | + |
| 46 | + close(fd); |
| 47 | + } |
| 48 | + |
| 49 | + freeaddrinfo(p_addrs); |
| 50 | + |
| 51 | + return p_addr != nullptr; |
| 52 | +} |
| 53 | + |
| 54 | +bool platformio_transport_close(struct uxrCustomTransport * transport) |
| 55 | +{ |
| 56 | + close(fd); |
| 57 | + return true; |
| 58 | +} |
| 59 | + |
| 60 | +size_t platformio_transport_write(struct uxrCustomTransport * transport, const uint8_t *buf, size_t len, uint8_t *) |
| 61 | +{ |
| 62 | + auto ret = send(fd, buf, len, 0); |
| 63 | + return ret < 0 ? 0 : (size_t)ret; |
| 64 | +} |
| 65 | + |
| 66 | +size_t platformio_transport_read(struct uxrCustomTransport * transport, uint8_t *buf, size_t len, int timeout, uint8_t *) |
| 67 | +{ |
| 68 | + struct pollfd pfd; |
| 69 | + int ret; |
| 70 | + |
| 71 | + pfd.fd = fd; |
| 72 | + pfd.events = POLLIN; |
| 73 | + ret = poll(&pfd, 1, timeout); |
| 74 | + switch(ret){ |
| 75 | + case -1: |
| 76 | + case 0: |
| 77 | + return 0; |
| 78 | + default: |
| 79 | + ret = recv(fd, buf, len, 0); |
| 80 | + return ret < 0 ? 0 : (size_t)ret; |
| 81 | + } |
| 82 | +} |
| 83 | + |
| 84 | +} |
0 commit comments