Added README
[apps/agl-service-can-low-level.git] / example / common.c
1 /* Simple binding of nanopb streams to TCP sockets.
2  */
3
4 #include <sys/socket.h>
5 #include <sys/types.h>
6 #include <pb_encode.h>
7 #include <pb_decode.h>
8
9 #include "common.h"
10
11 static bool write_callback(pb_ostream_t *stream, const uint8_t *buf, size_t count)
12 {
13     int fd = (int)stream->state;
14     return send(fd, buf, count, 0) == count;
15 }
16
17 static bool read_callback(pb_istream_t *stream, uint8_t *buf, size_t count)
18 {
19     int fd = (int)stream->state;
20     int result;
21     
22     if (buf == NULL)
23     {
24         /* Well, this is a really inefficient way to skip input. */
25         /* It is only used when there are unknown fields. */
26         char dummy;
27         while (count-- && recv(fd, &dummy, 1, 0) == 1);
28         return count == 0;
29     }
30     
31     result = recv(fd, buf, count, MSG_WAITALL);
32     
33     if (result == 0)
34         stream->bytes_left = 0; /* EOF */
35     
36     return result == count;
37 }
38
39 pb_ostream_t pb_ostream_from_socket(int fd)
40 {
41     pb_ostream_t stream = {&write_callback, (void*)fd, SIZE_MAX, 0};
42     return stream;
43 }
44
45 pb_istream_t pb_istream_from_socket(int fd)
46 {
47     pb_istream_t stream = {&read_callback, (void*)fd, SIZE_MAX};
48     return stream;
49 }