You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

125 lines
3.3 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <Arduino_JSON.h>
#ifndef STASSID
#define STASSID "1"
#define STAPSK "16888qwe"
#endif
const char* ssid = STASSID;
const char* password = STAPSK;
const char* host = "www.bigiot.net";
const int tcpPort = 8181;
String line = "";
String cmd="";
WiFiClient client;
const int LedPin = D2;//在本demo中是控制的ESP8266的D4 口,可根据自己需求更改。
const String DevConnectStr = "{\"M\":\"checkin\",\"ID\":\"31051\",\"K\":\"5f0c618aa\"}\n";
//软件调试
void setup()
{
Serial.begin(115200);
pinMode(LedPin, OUTPUT);
for(int i=0;i<2;i++) //端口测试
{
digitalWrite(LedPin, HIGH);
Serial.println("Turn Off");
delay(2000);
digitalWrite(LedPin, LOW);
Serial.println("Turn Off");
delay(2000);
}
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
int i = 0;
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.println("connecting AP...");
i++;
}
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
while (!client.connected())//若未连接到服务端,则客户端进行连接。
{
if (!client.connect(host, tcpPort))//实际上这一步就在连接服务端如果连接上该函数返回true
{
Serial.println("connecting....");
delay(500);
}
}
client.print(DevConnectStr);//发送http连接Json数据包
}
int connSecond=0;
unsigned long lastTimeMs=0;
unsigned long nowTimeMs=0;
void loop()
{
nowTimeMs=millis();
if(nowTimeMs-lastTimeMs>10000)//发送心跳周期:10秒
{
lastTimeMs= nowTimeMs;
if(client.connected()) //已经连接到云服务器
{
client.print(DevConnectStr);
//Serial.print("send heartbeat.");
}
}
if (client.connected()) //接收处理
{
line = client.readStringUntil('\n');
if(line.length()>0)
{
JSONVar myObject = JSON.parse(line);
//Serial.print(line);
if (myObject.hasOwnProperty("C"))
{
cmd = (const char*) myObject["C"];
//Serial.println(cmd);
if(cmd.indexOf("play")!=-1)
{
//增加指令处理函数
//digitalWrite(LedPin, HIGH); // (第一阶段)
//增加串口输出控制zigbee节点的LED (第二阶段)
Serial.println("A:0");
}
else if(cmd.indexOf("stop")!=-1)
{
//增加指令处理函数
//digitalWrite(LedPin, LOW); // (第一阶段)
//增加串口输出控制zigbee节点的LED (第二阶段)
Serial.println("A:1");
}
}
}
}
else //已经断开连接
{
while (!client.connected())//若未连接到服务端,则客户端进行连接。
{
if (!client.connect(host, tcpPort))//实际上这一步就在连接服务端如果连接上该函数返回true
{
Serial.println("connection....");
delay(500);
}
}
}
}