Instrument Neutral Distributed Interface INDI 2.2.5
platform.h
Go to the documentation of this file.
1#include <errno.h>
2#include <signal.h>
3#include <stdint.h>
4#include <stdio.h>
5#include <stdlib.h>
6
7#include <arpa/inet.h>
8#include <netdb.h>
9#include <netinet/in.h>
10#include <sys/select.h>
11#include <sys/socket.h>
12#include <unistd.h>
13
14#include "nanomodbus.h"
15
16
17#define UNUSED_PARAM(x) ((x) = (x))
18
19// Connection management
23
24void disconnect(void* conn)
25{
26 int fd = *(int*) conn;
27 FD_CLR(fd, &client_connections);
28 close(fd);
29}
30
31// Read/write/sleep platform functions
32
33int32_t read_fd_linux(uint8_t* buf, uint16_t count, int32_t timeout_ms, void* arg)
34{
35 int fd = *(int*) arg;
36
37 uint16_t total = 0;
38 while (total != count)
39 {
40 fd_set rfds;
41 FD_ZERO(&rfds);
42 FD_SET(fd, &rfds);
43
44 struct timeval* tv_p = NULL;
45 struct timeval tv;
46 if (timeout_ms >= 0)
47 {
48 tv_p = &tv;
49 tv.tv_sec = timeout_ms / 1000;
50 tv.tv_usec = (int64_t) (timeout_ms % 1000) * 1000;
51 }
52
53 int ret = select(fd + 1, &rfds, NULL, NULL, tv_p);
54 if (ret == 0)
55 {
56 return total;
57 }
58
59 if (ret == 1)
60 {
61 ssize_t r = read(fd, buf + total, 1);
62 if (r == 0)
63 {
64 disconnect(arg);
65 return -1;
66 }
67
68 if (r < 0)
69 return -1;
70
71 total += r;
72 }
73 else
74 return -1;
75 }
76
77 return total;
78}
79
80
81int32_t write_fd_linux(const uint8_t* buf, uint16_t count, int32_t timeout_ms, void* arg)
82{
83 int fd = *(int*) arg;
84
85 uint16_t total = 0;
86 while (total != count)
87 {
88 fd_set wfds;
89 FD_ZERO(&wfds);
90 FD_SET(fd, &wfds);
91
92 struct timeval* tv_p = NULL;
93 struct timeval tv;
94 if (timeout_ms >= 0)
95 {
96 tv_p = &tv;
97 tv.tv_sec = timeout_ms / 1000;
98 tv.tv_usec = (int64_t) (timeout_ms % 1000) * 1000;
99 }
100
101 int ret = select(fd + 1, NULL, &wfds, NULL, tv_p);
102 if (ret == 0)
103 {
104 return 0;
105 }
106
107 if (ret == 1)
108 {
109 ssize_t w = write(fd, buf + total, count);
110 if (w == 0)
111 {
112 disconnect(arg);
113 return -1;
114 }
115
116 if (w <= 0)
117 return -1;
118
119 total += (int32_t) w;
120 }
121 else
122 return -1;
123 }
124
125 return total;
126}
int fd
int32_t read_fd_linux(uint8_t *buf, uint16_t count, int32_t timeout_ms, void *arg)
Definition platform.h:33
int client_connection
Definition platform.h:20
fd_set client_connections
Definition platform.h:22
int32_t write_fd_linux(const uint8_t *buf, uint16_t count, int32_t timeout_ms, void *arg)
Definition platform.h:81
int client_read_fd
Definition platform.h:21
void disconnect(void *conn)
Definition platform.h:24