-
Notifications
You must be signed in to change notification settings - Fork 9
/
serialServer.h
73 lines (59 loc) · 1.21 KB
/
serialServer.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#ifndef SERIALSERVER_H
#define SERIALSERVER_H
#include <Arduino.h>
#ifdef ARDUINO_ARCH_ESP32
#include <WiFi.h>
#else
#include <ESP8266WiFi.h>
#endif
#include <WiFiClient.h>
struct SerialServer {
WiFiServer s;
WiFiClient c;
SerialServer(int port) : s(port) {};
void begin(int baud);
void stop();
void loop();
} serialServer(9600);
void SerialServer::begin(int baud) {
s.begin();
Serial.begin(baud);
}
void SerialServer::stop() {
c.stop();
// s.end();
Serial.end();
}
void SerialServer::loop() {
// Handle disconnects
if (!c.connected()) {
c.stop();
}
// Accept incoming connections
if (!c) {
c = s.available();
}
// Handle communicatons
if (c) {
size_t bytes;
int maxbytes = 128;
uint8_t buff[maxbytes];
// Network to serial
bytes = c.available();
if (bytes) {
if (bytes > maxbytes) bytes = maxbytes;
c.read(buff, bytes);
Serial.write(buff, bytes);
Serial.write((char*)0, 0);
}
// Serial to network
bytes = 0;
while (Serial.available() && bytes < maxbytes) {
buff[bytes++] = Serial.read();
}
c.write(buff,bytes);
}
}
#endif
// This is to enforce arduino-like formatting in kate
// kate: space-indent on; indent-width 2; mixed-indent off; indent-mode cstyle;