ESP_IOT v2.5
IOT ESP Coding
platglue-posix.h
Go to the documentation of this file.
1#pragma once
2#include "../../../Defines.h"
3
4#ifdef USE_CAMERA_MODULE
5
6#include <sys/socket.h>
7#include <netinet/in.h>
8#include <arpa/inet.h>
9#include <unistd.h>
10
11#include <stdlib.h>
12#include <string.h>
13#include <stdio.h>
14#include <errno.h>
15
16typedef int SOCKET;
17typedef int UDPSOCKET;
18typedef uint32_t IPADDRESS; // On linux use uint32_t in network byte order (per getpeername)
19typedef uint16_t IPPORT; // on linux use network byte order
20
21#define NULLSOCKET 0
22
23inline void closesocket(SOCKET s) {
24 close(s);
25}
26
27#define getRandom() rand()
28
29inline void socketpeeraddr(SOCKET s, IPADDRESS *addr, IPPORT *port) {
30
31 sockaddr_in r;
32 socklen_t len = sizeof(r);
33 if(getpeername(s,(struct sockaddr*)&r,&len) < 0) {
34 printf("getpeername failed\n");
35 *addr = 0;
36 *port = 0;
37 }
38 else {
39 //htons
40
41 *port = r.sin_port;
42 *addr = r.sin_addr.s_addr;
43 }
44}
45
46inline void udpsocketclose(UDPSOCKET s) {
47 close(s);
48}
49
50inline UDPSOCKET udpsocketcreate(unsigned short portNum)
51{
52 sockaddr_in addr;
53
54 addr.sin_family = AF_INET;
55 addr.sin_addr.s_addr = INADDR_ANY;
56
57 int s = socket(AF_INET, SOCK_DGRAM, 0);
58 addr.sin_port = htons(portNum);
59 if (bind(s,(sockaddr*)&addr,sizeof(addr)) != 0) {
60 printf("Error, can't bind\n");
61 close(s);
62 s = 0;
63 }
64
65 return s;
66}
67
68// TCP sending
69inline ssize_t socketsend(SOCKET sockfd, const void *buf, size_t len)
70{
71 // printf("TCP send\n");
72 return send(sockfd, buf, len, 0);
73}
74
75inline ssize_t udpsocketsend(UDPSOCKET sockfd, const void *buf, size_t len,
76 IPADDRESS destaddr, uint16_t destport)
77{
78 sockaddr_in addr;
79
80 addr.sin_family = AF_INET;
81 addr.sin_addr.s_addr = destaddr;
82 addr.sin_port = htons(destport);
83 //printf("UDP send to 0x%0x:%0x\n", destaddr, destport);
84
85 return sendto(sockfd, buf, len, 0, (sockaddr *) &addr, sizeof(addr));
86}
87
88/**
89 Read from a socket with a timeout.
90
91 Return 0=socket was closed by client, -1=timeout, >0 number of bytes read
92 */
93inline int socketread(SOCKET sock, char *buf, size_t buflen, int timeoutmsec)
94{
95 // Use a timeout on our socket read to instead serve frames
96 struct timeval tv;
97 tv.tv_sec = 0;
98 tv.tv_usec = timeoutmsec * 1000; // send a new frame ever
99 setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv);
100
101 int res = recv(sock,buf,buflen,0);
102 if(res > 0) {
103 return res;
104 }
105 else if(res == 0) {
106 return 0; // client dropped connection
107 }
108 else {
109 if (errno == EWOULDBLOCK || errno == EAGAIN)
110 return -1;
111 else
112 return 0; // unknown error, just claim client dropped it
113 };
114}
115#endif