当前位置:网站首页>Classic implementation of the basic method of intelligent home of Internet of things
Classic implementation of the basic method of intelligent home of Internet of things
2022-07-05 20:21:00 【St Xiaozhi】
Today I would like to talk with you , The realization of Smart Home Internet of things , Mainly used today Qt Develop an IOT application for smart home . You can use cloud services to remotely control and communicate with devices . This article will realize the remote lighting development board LED As an example .
In the life , We can use WIFI Smart socket , To remotely control household appliances . for example , Turn on the water heater remotely , Turn on the air conditioner remotely , Curtains, etc . In fact, the principle of these devices is to WIFI The socket is registered on the ECS , And then through the cell phone APP Visit and ask about cloud services , To control WIFI Socket .
First of all : Introduction to basic hardware
Need one ESP8266 Serial port to WIFI Module and need to add a USB-TTL modular .USB The cable can be connected to the computer , Use serial port to debug this module .
Be careful : If you use other wifi modular , You need to brush the firmware to access the cloud to access the server .
second : test WIFI Module function
To realize the function of the Internet of things , Need to use ESP8266 WIFI modular . Test first WIFI Whether the module can be used normally , Whether the server can be connected normally .
Design the device in the cloud first , Take your name and equipment number .

Use WIFI The baud rate of module serial port communication is 115200, stay Ubuntu Set up WIFI When the module , The general serial port name is “ttyUSB0”, The default is No Access to this /dev/ttyUSB0 The equipment . So we need to use the following instructions to modify permissions .
sudo chmod 777 /dev/ttyUSB0Third : The specific method of code implementation
#include "esp8266.h"#include <unistd.h>#include <QDebug>Esp82266::Esp82266(QWidget *parent){Q_UNUSED(parent)/* Serial object , Used with Esp8266 Module communication */serialPort = new QSerialPort(this);/* Timer Objects , It is used to send heartbeat packets of the device online at a fixed time */timer = new QTimer();/* led object , It is used to receive data from the cloud through the serial port , Then control the board LED */led = new Led(this);/* Set serial port name */#if __arm__serialPort->setPortName("ttymxc2");#elseserialPort->setPortName("ttyUSB0");#endif/* set baud rate */serialPort->setBaudRate(115200);/* Set the number of data bits */serialPort->setDataBits(QSerialPort::Data8);/* Set parity */serialPort->setParity(QSerialPort::NoParity);/* Set stop bit */serialPort->setStopBits(QSerialPort::OneStop);/* set flow control */serialPort->setFlowControl(QSerialPort::NoFlowControl);if (!serialPort->open(QIODevice::ReadWrite))qDebug()<<" The serial port cannot be opened ! May be in use !"<<endl;else {qDebug()<<" Serial port opened successfully !"<<endl;}/* Start connecting to the cloud */connectToClound();connect(serialPort, SIGNAL(readyRead()),this, SLOT(serialPortReadyRead()));connect(timer, SIGNAL(timeout()), this, SLOT(onTimerTimeOut()));}void Esp82266::serialPortReadyRead(){/* Read data from receive buffer */QByteArray buf = serialPort->readAll();QString temp = QString(buf);readData.append(temp);qDebug()<<temp<<endl;if (readData.contains("ready")) {/* If reset succeeds */sendCmdToEsp8266("AT+CWMODE=1");readData.clear();}if (readData.contains("OK") && readData.contains("AT+CWMODE")) {qDebug()<<" Set up STA Mode success "<<endl;sendCmdToEsp8266("AT+CWJAP=\"ALIENTEK-YF\",\"15902020353\"");qDebug()<<" Start connecting WIFI"<<endl;readData.clear();}if (temp.contains("WIFI GOT IP")) {qDebug()<<" Connect WIFI success "<<endl;sleep(2);/* The device number and password of the atomic cloud */sendCmdToEsp8266("AT+ATKCLDSTA=\"02314701717851074890\",\"12345678\"");qDebug()<<" Please wait for the cloud connection "<<endl;}if (temp.contains("CLOUD CONNECTED")) {qDebug()<<" Successfully connected to the cloud "<<endl;sleep(2);/* 15s Just send a heartbeat packet */timer->start(15000);}if (temp == " open ")led->setLedState(true);else if (temp == " Turn off ")led->setLedState(false);}Esp82266::~Esp82266(){serialPort->close();delete timer;timer = nullptr;}void Esp82266::sendCmdToEsp8266(QString cmd){cmd = cmd + "\r\n";QByteArray data = cmd.toUtf8();serialPort->write(data);}void Esp82266::connectToClound(){/* Restart the module , Note that if the atomic cloud is already connected ,* It needs to be powered on again or short circuited RST Feet to reset the module */sendCmdToEsp8266("AT+RST");}void Esp82266::sleep(int second){usleep(second * 1000000);}void Esp82266::sendTextMessage(QString message){serialPort->write(message.toLatin1());}void Esp82266::onTimerTimeOut(){sendTextMessage("online");qDebug()<<" Send device online heartbeat packets "<<endl;}
analysis : Add router's WiFi Hotspot and password , And the device number and password of the cloud
Fourth : Cloud API Interface and implementation
When communicating with the cloud , You must be familiar with cloud API Interface . The common cloud on the network API Communication flow chart .

Writing QT When the application is implemented , The focus should be on HTTP And WEBSocket In the direction of . Some account information and device information are through HTTPS Obtained by the protocol interface , communication WebSocket Protocol interfaces .
#include "webapi.h"#include <QUuid>#include <QRegularExpression>Webapi::Webapi(QObject *parent){this->setParent(parent);/* Empty array */groupID.clear();deviceID.clear();deviceNumber.clear();timer = new QTimer();connect(timer, SIGNAL(timeout()), this, SLOT(onTimerTimeOut()));networkAccessManager = new QNetworkAccessManager(this);orgURL = "https://cloud.alientek.com/api/orgs";/* Please fill in your own token Information !!! */api_token = "bf591984c8fa417584d18f6328e0ef73";/* Get the list of account institutions */getOrgURL();QUuid uuid = QUuid::createUuid();random_token = uuid.toString();webSocket = new QWebSocket();/* You need to add some security configuration to access https */QSslConfiguration config;config.setPeerVerifyMode(QSslSocket::VerifyNone);config.setProtocol(QSsl::TlsV1SslV3);webSocket->setSslConfiguration(config);connect(webSocket, SIGNAL(connected()), this, SLOT(webSocketConnected()));connect(webSocket, SIGNAL(binaryMessageReceived(QByteArray)),this, SLOT(onBinaryMessageReceived(QByteArray)));}Webapi::~Webapi(){delete timer;delete webSocket;webSocket = nullptr;}void Webapi::getOrgURL(){getDataFromWeb(QUrl(orgURL));}/* Get the device grouping list */void Webapi::getGroupListUrl(){getDataFromWeb(QUrl(groupListUrl));}/* Get information about the device */void Webapi::getDevOfGroupUrl(){getDataFromWeb(QUrl(devOfGroupUrl));}/* Get device connection status */void Webapi::getConStateUrl(){getDataFromWeb(QUrl(conStateUrl));}/* Get data from ECS */void Webapi::getDataFromWeb(QUrl url){/* Network request */QNetworkRequest networkRequest;/* You need to add some security configuration to access https */QSslConfiguration config;config.setPeerVerifyMode(QSslSocket::VerifyNone);config.setProtocol(QSsl::TlsV1SslV3);networkRequest.setSslConfiguration(config);/* Set the access address */networkRequest.setUrl(url);/* Network response */networkRequest.setHeader(QNetworkRequest::ContentTypeHeader,"application/json;charset=UTF-8");/* Parameter 2 is the... Of the atomic cloud account token Information , Fill in your own */networkRequest.setRawHeader("token", api_token.toLatin1());QNetworkReply *newReply =networkAccessManager->get(networkRequest);connect(newReply, SIGNAL(finished()), this, SLOT(replyFinished()));connect(newReply, SIGNAL(readyRead()), this, SLOT(readyReadData()));}
The project code can refer to the following connection :
https://download.csdn.net/download/weixin_41114301/8587538101_smarthome Under the project :
1、 webapi The folder is the application of cloud platform , It is mainly used to communicate with atomic cloud .
2、Headers Folder is the header file of interface design .
3、Sources Folder is the source file of interface design . esp8266 Under the project :
4、led The folder is I.MX6U Development board control LED The interface program of .
5、Headers The folder is esp8266 Header file of communication .
6、Sources The folder is esp8266 Source file of communication ( Use serial port communication ).
The fifth : Running results

边栏推荐
猜你喜欢

Leetcode (695) - the largest area of an island

leetcode刷题:二叉树12(二叉树的所有路径)

IC科普文:ECO的那些事儿

JS implementation prohibits web page zooming (ctrl+ mouse, +, - zooming effective pro test)

Leetcode(695)——岛屿的最大面积

解决php无法将string转换为json的办法

. Net distributed transaction and landing solution

Station B up builds the world's first pure red stone neural network, pornographic detection based on deep learning action recognition, Chen Tianqi's course progress of machine science compilation MLC,

js实现禁止网页缩放(Ctrl+鼠标、+、-缩放有效亲测)

Unity编辑器扩展 UI控件篇
随机推荐
Elk distributed log analysis system deployment (Huawei cloud)
Scala基础【HelloWorld代码解析,变量和标识符】
【数字IC验证快速入门】6、Questasim 快速上手使用(以全加器设计与验证为例)
Is it safe for Galaxy Securities to open an account online?
[quick start of Digital IC Verification] 1. Talk about Digital IC Verification, understand the contents of the column, and clarify the learning objectives
Process file and directory names
信息学奥赛一本通 1338:【例3-3】医院设置 | 洛谷 P1364 医院设置
信息学奥赛一本通 1337:【例3-2】单词查找树 | 洛谷 P5755 [NOI2000] 单词查找树
Leetcode (695) - the largest area of an island
A way to calculate LNX
插值查找的简单理解
【数字IC验证快速入门】8、数字IC中的典型电路及其对应的Verilog描述方法
Rainbond 5.7.1 支持对接多家公有云和集群异常报警
19 mongoose modularization
1:引文;
[quick start of Digital IC Verification] 9. Finite state machine (FSM) necessary for Verilog RTL design
js实现禁止网页缩放(Ctrl+鼠标、+、-缩放有效亲测)
Go language | 02 for loop and the use of common functions
Notes on key vocabulary in the English original of the biography of jobs (12) [chapter ten & eleven]
19 Mongoose模块化