ESP_IOT v2.5
IOT ESP Coding
platglue-esp32.h
Go to the documentation of this file.
1#pragma once
2#include "../../../Defines.h"
3
4#ifdef USE_CAMERA_MODULE
5
6#include <Arduino.h>
7#include <WiFiClient.h>
8#include <WiFiUdp.h>
9#include <sys/socket.h>
10#include <netinet/in.h>
11//#include <arpa/inet.h>
12#include <unistd.h>
13
14#include <stdlib.h>
15#include <string.h>
16#include <stdio.h>
17#include <errno.h>
18
19
20typedef WiFiClient *SOCKET;
21typedef WiFiUDP *UDPSOCKET;
22typedef IPAddress IPADDRESS; // On linux use uint32_t in network byte order (per getpeername)
23typedef uint16_t IPPORT; // on linux use network byte order
24
25#define NULLSOCKET NULL
26
27inline void closesocket(SOCKET s) {
28 printf("closing TCP socket\n");
29
30 if(s) {
31 s->stop();
32 // delete s; TDP WiFiClients are never on the heap in arduino land?
33 }
34}
35
36#define getRandom() random(65536)
37
38inline void socketpeeraddr(SOCKET s, IPADDRESS *addr, IPPORT *port) {
39 *addr = s->remoteIP();
40 *port = s->remotePort();
41}
42
43inline void udpsocketclose(UDPSOCKET s) {
44 printf("closing UDP socket\n");
45 if(s) {
46 s->stop();
47 delete s;
48 }
49}
50
51inline UDPSOCKET udpsocketcreate(unsigned short portNum)
52{
53 UDPSOCKET s = new WiFiUDP();
54
55 if(!s->begin(portNum)) {
56 printf("Can't bind port %d\n", portNum);
57 delete s;
58 return NULL;
59 }
60
61 return s;
62}
63
64// TCP sending
65inline ssize_t socketsend(SOCKET sockfd, const void *buf, size_t len)
66{
67 return sockfd->write((uint8_t *) buf, len);
68}
69
70inline ssize_t udpsocketsend(UDPSOCKET sockfd, const void *buf, size_t len,
71 IPADDRESS destaddr, IPPORT destport)
72{
73 sockfd->beginPacket(destaddr, destport);
74 sockfd->write((const uint8_t *) buf, len);
75 if(!sockfd->endPacket())
76 printf("error sending udp packet\n");
77
78 return len;
79}
80
81/**
82 Read from a socket with a timeout.
83
84 Return 0=socket was closed by client, -1=timeout, >0 number of bytes read
85 */
86inline int socketread(SOCKET sock, char *buf, size_t buflen, int timeoutmsec)
87{
88 if(!sock->connected()) {
89 printf("client has closed the socket\n");
90 return 0;
91 }
92
93 int numAvail = sock->available();
94 if(numAvail == 0 && timeoutmsec != 0) {
95 // sleep and hope for more
96 delay(timeoutmsec);
97 numAvail = sock->available();
98 }
99
100 if(numAvail == 0) {
101 // printf("timeout on read\n");
102 return -1;
103 }
104 else {
105 // int numRead = sock->readBytesUntil('\n', buf, buflen);
106 int numRead = sock->readBytes(buf, buflen);
107 // printf("bytes avail %d, read %d: %s", numAvail, numRead, buf);
108 return numRead;
109 }
110}
111
112#endif