8266做的量产插座产品带源码
本帖最后由 fangqingyu 于 2021-6-23 09:54 编辑软件、硬件都是自己一手打造,不一定专业,但测试非常稳定!
1、使用AP配网+贝壳物联APKEY配置,并保存,带高精度SI7021温湿度传感器(不接也可工作),可外部复位、外部开关、AP复位等功能。使用方法,附下图:A、联接FQY开头的SSID,B、地址栏输入IP“6.6.6.6”C,输入管理员密码“8888”,D,进入主页面,如果没有温度传感器就不显示温湿度计了。E,配置网络和贝壳物联的APKEY,F、可以更改管理员密码
2、编译和上传方法:A、下载相关的库文件;B、安装Dateupload工具;C、选择FLASH SIZE 1M或2M; D、主程序编写上传,再点击Dataupload上传
HTML文件。
3、附arduino源码:
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <WiFiUDP.h>
#include <Wire.h>
#include <SI7021.h>
#include <aJSON.h>
#include <FS.h>
#include <Ticker.h>
#include <EEPROM.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#define SDA 14 // GPIO14 on ESP-01 module
#define SCL 12 // GPIO0 on ESP-01 module
SI7021 sensor;
uint8_t kzd = 4; //定义继电器接口
uint8_t key = 5; //定义手动控制端
uint8_t keyFW = 13; //定义手动复位端
uint8_t led_wifi = 2; //定义WiFi指示灯,D4
unsigned long lastCheckInTime = 0;
const unsigned long postingInterval = 30000; // 每隔40秒向服务器报到一次
const char* host = "www.bigiot.net";
const int httpPort = 8181;
//EEPROM 数据存放地址说明
//|---1-------2---|-3------4-|-5----------------||-33----------------|
//0 id(2 byte) port(2) ip(32) password(32)
#define MAGIC_WORD 0x55
int Signal_filtering = -80; //扫描wifi的信号强度过滤值,单位dBm
IPAddress apIP(6, 6, 6, 6); //定义web服务器的IP地址
ESP8266WebServer webServer(80); //创建web服务器对象,端口80
char loginPassword = "8888";
int id = 0;
char serverIP = "a"; //定义服务器的IP地址,初始为广播地址
int port = 0;
int port1 = 0;
Ticker ticker_0;//创建定时器中断变量
byte isAlive = 1; //定义TTL,用于判断是否从服务器断开连接
void paraInitFromEERom();
void waitConnect()
{
for (int i = 0; i < 450; i++)
{
if (WiFi.status() == WL_CONNECTED || WiFi.status() == WL_CONNECT_FAILED || WiFi.status() == WL_NO_SSID_AVAIL)
{
break;
}
else if (i % 10 == 0)
{
digitalWrite(led_wifi, !digitalRead(led_wifi));
}
delay(10);
}
}
void wwwroot()
{
File file = SPIFFS.open("/config.html", "r");
webServer.streamFile(file, "text/html");
file.close();
}
void setSetting()
{
if (webServer.hasArg("id") && webServer.hasArg("ip") && webServer.hasArg("port")&& webServer.hasArg("port1"))
{
String idStr = webServer.arg("id");
String ipStr = webServer.arg("ip");
String portStr = webServer.arg("port");
String port1Str = webServer.arg("port1");
int newId = idStr.toInt();
int newPort = portStr.toInt();
int newPort1 = port1Str.toInt();
Serial.println(ipStr);
id = newId;
port = newPort;
port1 = newPort1;
memset(serverIP, 0, 32);
ipStr.toCharArray(serverIP, 32);
Serial.println(serverIP);
Serial.println(port1);
writeParaToEERom();
delay(500);
webServer.send(200, "text/plain", "1");
delay(500);
ESP.restart();
}
webServer.send(200, "text/plain", "0");
}
void wifiConfig()
{
if (webServer.hasArg("ssid") && webServer.hasArg("password") && webServer.hasArg("login") && webServer.arg("login") == loginPassword)
{
String ssid_str = webServer.arg("ssid");
String password_str = webServer.arg("password");
const char *ssid = ssid_str.c_str();
const char *password = password_str.c_str();
WiFi.begin(ssid, password);
waitConnect();
if (WiFi.isConnected())
{
webServer.send(200, "text/plain", "1");
WiFi.setAutoConnect(true);
WiFi.setAutoReconnect(true);
}
else
{
webServer.send(200, "text/plain", "0");
}
}
}
/*
return the type of ENC
called by wifiScan()
*/
String wifi_type(int typecode)
{
if (typecode == ENC_TYPE_NONE)
return "Open";
if (typecode == ENC_TYPE_WEP)
return "WEP";
if (typecode == ENC_TYPE_TKIP)
return "WPA";
if (typecode == ENC_TYPE_CCMP)
return "WPA2";
if (typecode == ENC_TYPE_AUTO)
return "WPA*";
}
void readSetting()
{
String ip = "";
String ssid = "";
if (webServer.hasArg("login") && webServer.arg("login") == loginPassword)
{
for (int i = 0; i < 32; i++)
{
if (serverIP != 0)
{
ip += serverIP;
}
else
{
break;
}
Serial.println("read APIKEY:"+ip);
}
if(WiFi.isConnected())
{
ssid = WiFi.SSID();
}
else
{
ssid = "\t";
}
String req_json = "[" + String(id) + ",\"" + ip + "\"," + String(port) + ",\"" + ssid + "\"," + String(port1) + "]";
Serial.println(req_json);
webServer.send(200, "text/json;charset=UTF-8", req_json);
}
}
void pasSetting()
{
if (webServer.hasArg("loginPassword"))
{
String loginPasswordStr = webServer.arg("loginPassword");
memset(loginPassword, 0, 32);
loginPasswordStr.toCharArray(loginPassword, 32);
Serial.println(loginPassword);
writeParaToEERom();
delay(500);
webServer.send(200, "text/plain", "1");
delay(200);
}
webServer.send(200, "text/plain", "0");
}
int kg =1;
void readTHNO()
{
int temperature = sensor.getCelsiusHundredths();
float vaT=175.72*temperature/65536 - 46.85;
int humidity = sensor.getHumidityPercent();
float vaH=125.0*humidity/65536 - 6;;
String req_json = "[" + String(id) + ",\"" + vaT + "\"," + vaH + ",\"" + kg + "\"]";
webServer.send(200, "text/json;charset=UTF-8", req_json);
}
void kgkz()
{
if (webServer.hasArg("kgkz"))
{
String kgStr = webServer.arg("kgkz");
Serial.println(kgStr);
if(kgStr == "1"){
Serial.println("onok");
digitalWrite(kzd, HIGH);
kg = 1;
webServer.send(200, "text/plain", "1");
}else
{
Serial.println("offok");
digitalWrite(kzd, LOW);
kg = 0;
webServer.send(200, "text/plain", "0");
}
}
}
void restD(){
Serial.println("RST.....!");
String idStr = "";
String ipStr = "a";
String portStr = "";
String port1Str = "";
String loginPasswordStr ="8888";
int newId = idStr.toInt();
int newPort = portStr.toInt();
int newPort1 = port1Str.toInt();
id = newId;
port = newPort;
port1 = newPort1;
memset(serverIP, 0, 32);
memset(loginPassword, 0, 32);
ipStr.toCharArray(serverIP, 32);
loginPasswordStr.toCharArray(loginPassword, 32);
Serial.println(serverIP);
Serial.println(port1);
writeParaToEERom();
delay(500);
webServer.send(200, "text/plain", "1");
Serial.println("RST NO!");
ESP.eraseConfig();
ESP.restart();
}
void restarts(){
Serial.println("ESP restart!");
webServer.send(200, "text/plain", "1");
ESP.restart();
}
/*
*
*
scan AP and send the json of AP list
*/
void wifiScan()
{
String req_json = "";
// //Serial.println("Scan WiFi");
if (webServer.hasArg("login") && webServer.arg("login") == loginPassword)
{
int n = WiFi.scanNetworks();
if (n > 0)
{
int m = 0;
req_json = "{\"req\":[";
for (int i = 0; i < n; i++)
{
if ((int)WiFi.RSSI(i) >= Signal_filtering)
{
m++;
req_json += "{\"ssid\":\"" + (String)WiFi.SSID(i) + "\"," + "\"encryptionType\":\"" + wifi_type(WiFi.encryptionType(i)) + "\"," + "\"rssi\":" + (int)WiFi.RSSI(i) + "},";
}
}
delay(10);
req_json.remove(req_json.length() - 1);
req_json += "]}";
webServer.send(200, "text/json;charset=UTF-8", req_json);
}
}
}
void writeParaToEERom()
{
int i = 0;
EEPROM.write(0, MAGIC_WORD);
EEPROM.write(1, id % 256);
EEPROM.write(2, id / 256);
EEPROM.write(3, port % 256);
EEPROM.write(4, port / 256);
EEPROM.write(5, port1 % 256);
EEPROM.write(6, port1 / 256);
for (i = 0; i < 32; i++)
{
EEPROM.write(i + 7, serverIP);
EEPROM.write(i + 39, loginPassword);
}
EEPROM.commit();
//paraInitFromEERom();
}
void paraInitFromEERom()
{
char eeromBuff;
for (int i = 0; i < 71; i++)
{
eeromBuff = EEPROM.read(i);
}
if (MAGIC_WORD != eeromBuff)
{
writeParaToEERom();
}
else
{
id = (int)eeromBuff + (int)eeromBuff * 256;
port = (int)eeromBuff + (int)eeromBuff * 256;
port1 = (int)eeromBuff + (int)eeromBuff * 256;
for (int i = 0; i < 32; i++)
{
serverIP = eeromBuff;
loginPassword = eeromBuff;
}
}
}
void login()
{
digitalWrite(2, HIGH);
Serial.println("enter");
if (webServer.hasArg("login"))
{
Serial.println("login");
if (webServer.arg("login") == loginPassword)
{
Serial.println("login yes");
webServer.send(200, "text/plain", "1");
}
else
{
Serial.println("login no");
webServer.send(200, "text/plain", "0");
}
}
}
int timer0 = 0;
int maxTimer0 = 30; //发送频率
unsigned long mcuRestartTime_ms = 24*3600ul * 1000ul; //单片机自动重启时间,120s,据说最大是50天
void timerPlus()
{
timer0++;
}
void keydo(){
if (digitalRead(key) ==0) {
delay(100);
if (digitalRead(kzd) ==0) {
Serial.println("onok");
digitalWrite(kzd,HIGH);
kg = 1;
}
else{
Serial.println("offok");
digitalWrite(kzd,LOW);
kg = 0;
}
digitalWrite(key,HIGH);
}
}
int fwd=1;
void keyfw(){
if (digitalRead(keyFW) ==0) {
fwd++;
Serial.print("Reset countdown:");
Serial.print(fwd);
Serial.println("S");
if (fwd>15){
fwd=1;
Serial.println("restart OK");
restD();
}
}
}
void setup()
{
pinMode(led_wifi, OUTPUT); //wifi指示灯
pinMode(kzd, OUTPUT); //控制端
pinMode(key, OUTPUT);
pinMode(keyFW, OUTPUT);
digitalWrite(led_wifi, LOW);
digitalWrite(key,HIGH);
digitalWrite(keyFW,HIGH);
sensor.begin(SDA,SCL);
Serial.setRxBufferSize(2200);
Serial.begin(115200);
//从rom初始化参数
EEPROM.begin(1024);
paraInitFromEERom();
WiFi.setAutoReconnect(false);
WiFi.mode(WIFI_AP_STA);
WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0));
String apName = ("FQY_"+(String)ESP.getChipId());
const char *softAPName = apName.c_str();
WiFi.softAP(softAPName);
SPIFFS.begin();
delay(10);
webServer.begin();
webServer.on("/", wwwroot);
webServer.on("/wificonfig", wifiConfig);
webServer.on("/wifiscan", wifiScan);
webServer.on("/readTHNO", readTHNO);
webServer.on("/readSetting", readSetting);
webServer.on("/setSetting", setSetting);
webServer.on("/pasSetting", pasSetting);
webServer.on("/restD", restD);
webServer.on("/restarts", restarts);
webServer.on("/login", login);
webServer.on("/kgkz", kgkz);
delay(10);
waitConnect(); //等待连接
if (WiFi.isConnected())
{
WiFi.setAutoConnect(true);
WiFi.setAutoReconnect(true);
digitalWrite(led_wifi, HIGH);
Serial.println("WIFI is Connected!");
}
ticker_0.attach(1, timerPlus);
}
WiFiClient client;
void loop()
{
webServer.handleClient();
keydo();
keyfw();
if(millis() - lastCheckInTime > postingInterval || lastCheckInTime==0) {
checkIn();
}
webServer.handleClient();
if (client.available()) {
String inputString = client.readStringUntil('\n');
inputString.trim();
Serial.println(inputString);
int len = inputString.length()+1;
if(inputString.startsWith("{") && inputString.endsWith("}")){
char jsonString;
inputString.toCharArray(jsonString,len);
aJsonObject *msg = aJson.parse(jsonString);
processMessage(msg);
aJson.deleteItem(msg);
}
}
webServer.handleClient();
int temperature = sensor.getCelsiusHundredths();
float vaT=175.72*temperature/65536 - 46.85;
webServer.handleClient();
int humidity = sensor.getHumidityPercent();
float vaH=125.0*humidity/65536 - 6;;
webServer.handleClient();
if (WiFi.isConnected())
{
digitalWrite(led_wifi, HIGH);
if (!client.connected()) {
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
delay(5000);
return;
}
}
if (timer0 >= maxTimer0)
{
timer0 = 0;
webServer.handleClient();
String ssid = "";
ssid = WiFi.SSID();
Serial.print("SSID:");
Serial.print(ssid);
Serial.print(" localIP:");
Serial.println(WiFi.localIP().toString().c_str());
Serial.print("DEVID:");
Serial.print(id);
Serial.print(" APIKEY:");
Serial.println(serverIP);
Serial.print("Port1:");
Serial.print(port);
Serial.print(" Port2:");
Serial.println(port1);
Serial.print("Password:");
Serial.println(loginPassword);
Serial.print("T:");
Serial.print(vaT);
Serial.print("*C");
Serial.print("H:");
Serial.print(vaH);
Serial.println("%");
Serial.print("\r\n");
updata();
}
webServer.handleClient();
}
else
{
Serial.println("Wifi is not connected!");
Serial.print("Please link WIFI:");
Serial.print("FQY_"+(String)ESP.getChipId());
Serial.println(" loginIP:6.6.6.6");
Serial.print("LoginPassword:");
Serial.println(loginPassword);
Serial.print("\r\n");
for (int i = 0; i < 30; i++)
{
webServer.handleClient();
delay(10);
}
digitalWrite(led_wifi, !digitalRead(2));
}
webServer.handleClient();
delay(1000);
}
void processMessage(aJsonObject *msg){
aJsonObject* method = aJson.getObjectItem(msg, "M");
aJsonObject* content = aJson.getObjectItem(msg, "C");
aJsonObject* client_id = aJson.getObjectItem(msg, "ID");
if (!method) {
return;
}
String M = method->valuestring;
if(M == "say"){
String C = content->valuestring;
String F_C_ID = client_id->valuestring;
if(C == "play"){
sayToClient(F_C_ID,"onok");
Serial.println("onok");
digitalWrite(kzd, HIGH);
kg = 1;
}else if(C == "stop"){
sayToClient(F_C_ID,"offok");
Serial.println("offok");
digitalWrite(kzd, LOW);
kg = 0;
}else{
sayToClient(F_C_ID,"TEST:");
}
}
}
void updata() {
int temperature = sensor.getCelsiusHundredths();
float vaT=175.72*temperature/65536 - 46.85;
int humidity = sensor.getHumidityPercent();
float vaH=125.0*humidity/65536 - 6;;
if (vaT<100){
String msg = "{\"M\":\"update\",\"ID\":\""+String(id)+"\",\"V\":{\""+ String(port) + "\":\""+ String(vaT) + "\",\""+String(port1)+"\":\""+vaH+"\"}}\n";
client.print(msg);
lastCheckInTime = millis();
}
}
void checkIn() {
String msg = "{\"M\":\"checkin\",\"ID\":\"" + String(id) + "\",\"K\":\"" + String(serverIP) + "\"}\n";
client.print(msg);
lastCheckInTime = millis();
}
void sayToClient(String client_id, String content){
String msg = "{\"M\":\"say\",\"ID\":\"" + client_id + "\",\"C\":\"" + content + "\"}\n";
client.print(msg);
lastCheckInTime = millis();
}
2、在项目文档里,新建一个“data”文件夹,建立一份“config.html”文件,附项目文件:
占楼 支持 老板6666666 老板 厉害 新手表示,很有参考价值,但是不知如何操作,可否详细一点 相比源码,我更关心硬件部分。请问那个变压器和外壳是定制的还是公模的,能否给个购买或者定制途径? 不知道能不能二次配网呢? 期待楼主的回复 丘山鹤 发表于 2021-7-5 14:32
相比源码,我更关心硬件部分。请问那个变压器和外壳是定制的还是公模的,能否给个购买或者定制途径? ...
一丁智能插座我论坛收了百十个 向高手致敬 软硬一体化,真强
页:
[1]
2