Subversion Repositories ESP8266_P1_Meter

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
2 raymond 1
#include <ESP8266WiFi.h>
2
#include <ESPAsyncTCP.h>
3
 
4
extern "C" {
5
#include <osapi.h>
6
#include <os_type.h>
7
}
8
 
9
#include "config.h"
10
 
11
static os_timer_t intervalTimer;
12
 
13
static void replyToServer(void* arg) {
14
	AsyncClient* client = reinterpret_cast<AsyncClient*>(arg);
15
 
16
	// send reply
17
	if (client->space() > 32 && client->canSend()) {
18
		char message[32];
19
		sprintf(message, "this is from %s", WiFi.localIP().toString().c_str());
20
		client->add(message, strlen(message));
21
		client->send();
22
	}
23
}
24
 
25
/* event callbacks */
26
static void handleData(void* arg, AsyncClient* client, void *data, size_t len) {
27
	Serial.printf("\n data received from %s \n", client->remoteIP().toString().c_str());
28
	Serial.write((uint8_t*)data, len);
29
 
30
	os_timer_arm(&intervalTimer, 2000, true); // schedule for reply to server at next 2s
31
}
32
 
33
void onConnect(void* arg, AsyncClient* client) {
34
	Serial.printf("\n client has been connected to %s on port %d \n", SERVER_HOST_NAME, TCP_PORT);
35
	replyToServer(client);
36
}
37
 
38
 
39
void setup() {
40
	Serial.begin(115200);
41
	delay(20);
42
 
43
	// connects to access point
44
	WiFi.mode(WIFI_STA);
45
	WiFi.begin(SSID, PASSWORD);
46
	while (WiFi.status() != WL_CONNECTED) {
47
		Serial.print('.');
48
		delay(500);
49
	}
50
 
51
	AsyncClient* client = new AsyncClient;
52
	client->onData(&handleData, client);
53
	client->onConnect(&onConnect, client);
54
	client->connect(SERVER_HOST_NAME, TCP_PORT);
55
 
56
	os_timer_disarm(&intervalTimer);
57
	os_timer_setfn(&intervalTimer, &replyToServer, client);
58
}
59
 
60
void loop() {
61
 
62
}