当前位置:网站首页>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/ttyUSB0
Third : 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");
#else
serialPort->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/85875381
01_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
边栏推荐
- DP:树DP
- 信息学奥赛一本通 1338:【例3-3】医院设置 | 洛谷 P1364 医院设置
- 零道云新UI设计中
- 怎么挑选好的外盘平台,安全正规的?
- 信息学奥赛一本通 1339:【例3-4】求后序遍历 | 洛谷 P1827 [USACO3.4] 美国血统 American Heritage
- Leetcode: binary tree 15 (find the value in the lower left corner of the tree)
- .Net分布式事务及落地解决方案
- - Oui. Net Distributed Transaction and Landing Solution
- E. Singhal and Numbers(质因数分解)
- 关于BRAM IP复位的优先级
猜你喜欢
无卷积骨干网络:金字塔Transformer,提升目标检测/分割等任务精度(附源代码)...
Leetcode (695) - the largest area of an island
鸿蒙系统控制LED的实现方法之经典
Leetcode(695)——岛屿的最大面积
【数字IC验证快速入门】3、数字IC设计全流程介绍
解决php无法将string转换为json的办法
[quick start of Digital IC Verification] 9. Finite state machine (FSM) necessary for Verilog RTL design
[quick start of Digital IC Verification] 1. Talk about Digital IC Verification, understand the contents of the column, and clarify the learning objectives
Leetcode brush questions: binary tree 11 (balanced binary tree)
Scala basics [HelloWorld code parsing, variables and identifiers]
随机推荐
Fundamentals - configuration file analysis
ICTCLAS用的字Lucene4.9捆绑
A solution to PHP's inability to convert strings into JSON
基金网上开户安全吗?去哪里开,可以拿到低佣金?
leetcode刷题:二叉树10(完全二叉树的节点个数)
mongodb基操的练习
Informatics Olympiad 1340: [example 3-5] extended binary tree
ByteDance dev better technology salon was successfully held, and we joined hands with Huatai to share our experience in improving the efficiency of web research and development
常用的视图容器类组件
死信队列入门(两个消费者,一个生产者)
Leetcode(695)——岛屿的最大面积
炒股开户最低佣金,低佣金开户去哪里手机上开户安全吗
Document method
leetcode刷题:二叉树16(路径总和)
【数字IC验证快速入门】6、Questasim 快速上手使用(以全加器设计与验证为例)
Leetcode skimming: binary tree 10 (number of nodes of a complete binary tree)
走入并行的世界
Leetcode skimming: binary tree 16 (path sum)
【c语言】归并排序
Go language | 01 wsl+vscode environment construction pit avoidance Guide