目录
1 项目简介
本项目旨在开发一个基于TCP/IP技术的智能家居系统,利用Arduino平台和多种传感器模块实现家庭环境的智能监控和控制。该系统的设计目标是提升家庭生活的便利性、安全性和舒适性。通过集成温湿度传感器、MQ-2烟雾传感器、红外传感器、蜂鸣器模块和LED灯,系统能够实时监测家庭环境中的各项参数,并通过TCP/IP协议实现数据传输和远程控制。
系统的核心功能包括环境监测、设备控制和数据传输显示。温湿度传感器能够实时监测室内的温湿度情况,确保环境的舒适度。在炎热的夏季,如果温度过高,系统可以自动开启空调或风扇来降温;而在寒冷的冬季,系统则可以启动加热设备,保持室内温暖舒适。此外,湿度传感器还能帮助控制家中的加湿器或除湿机,维持适宜的空气湿度,避免干燥或潮湿带来的不适。
MQ-2烟雾传感器则用于检测室内的烟雾浓度。当烟雾浓度超过设定阈值时,系统将触发警报,确保家庭成员的安全。此时,蜂鸣器模块会发出响亮的警报声,提醒家庭成员立即采取措施,如打开窗户通风或拨打紧急电话。此外,系统还可以通过TCP/IP协议将警报信息上传至远程服务器,通知用户当前的危险情况,即使用户不在家中也能及时获知并处理。
红外传感器用于检测是否有人经过,当检测到有人经过时,可以触发相应的控制动作,如自动打开或关闭LED灯,实现智能照明功能。这不仅能提高生活便利性,还能节约能源。例如,在夜晚,红外传感器可以自动检测到人的移动,并开启室内的照明设备,避免用户摸黑前行;而当人离开后,系统又会自动关闭灯光,防止不必要的电力浪费。
系统通过TCP/IP通信实现与远程服务器的连接,用户可以通过网页或手机APP实时查看环境数据和控制家中的设备。无论用户身在何处,只需通过智能设备即可监控和管理家庭环境。数据可视化功能使用户能够方便地查看实时数据和历史记录,从而更好地了解和管理家庭环境。通过图表和统计数据,用户可以直观地看到温湿度变化趋势、烟雾浓度历史记录以及家中设备的使用情况,从而做出更加科学合理的决策。
综上所述,本项目不仅通过各种传感器模块实现了家庭环境的智能监控和控制,还通过TCP/IP技术实现了数据的实时传输和远程控制,为用户提供了全面、便捷的智能家居解决方案,提升了家庭生活的安全性、舒适性和便利性。
2 需求分析
在设计基于TCP/IP技术的智能家居系统时,首先需要进行详细的需求分析,以确保系统能够满足用户的需求和期望。这一过程至关重要,因为它帮助我们明确用户的具体要求、预期的系统性能以及系统应具备的特性。需求分析主要分为功能需求和非功能需求,下面将对这两个方面进行详细阐述。
2.1功能需求
物联网智能家居系统旨在提供便捷的远程和本地智能控制功能,以及实时环境监测和安全警报功能。系统的主要功能需求包括但不限于:
2.1.1实时环境监测功能
温湿度监测: 系统能够实时监测室内温度和湿度,用户可以通过客户端、远控端和手机端查看当前的温湿度数值和历史数据。
CO2浓度监测: 系统能够实时检测室内CO2浓度水平,用户可以获取当前CO2值,并在达到预设阈值时接收警报通知。
2.1.2远程控制功能
灯光控制: 用户可以通过远控端和手机端远程控制LED灯的开关状态,实现对室内照明的远程管理。
报警器控制: 用户可以通过手机端控制蜂鸣器的开关状态,用于安全警报或其他提示功能。
2.1.3物体检测与安全功能
烟雾检测: 系统通过MQ-2烟雾传感器实时监测室内烟雾浓度,当检测到异常情况时,自动触发警报和通知用户。
红外传感器检测: 使用TCR红外传感器进行物体检测,当有物体进入特定区域时,系统能够检测到并触发相关响应。
2.1.4数据可视化与用户界面
实时数据曲线: 系统能够生成实时温湿度曲线,并在客户端和手机端展示,帮助用户了解室内环境变化趋势。
用户界面设计: 客户端、远控端和手机端均设计了直观的用户界面,支持简单直观的操作和数据查看。
2.1.5智能控制:
基于红外传感器数据,自动控制LED灯以及蜂鸣器的开关。
2.2非功能需求
2.2.1系统可靠性:
确保数据传输的稳定性和可靠性,防止数据丢失或传输延迟。
系统在异常情况下能够快速恢复,确保持续监控和控制。
2.2.2用户友好性:
界面设计简洁直观,用户能够轻松查看和控制家中设备。
提供详细的使用说明和帮助文档。
2.2.3安全性:
确保数据传输的安全性,防止数据被篡改或泄露。
系统对用户进行身份验证,防止未经授权的访问。
2.2.4扩展性:
系统能够支持更多传感器和设备的接入,满足未来扩展需求。
软件架构设计灵活,便于功能扩展和升级。
2.2.5兼容性:
系统能够兼容多种操作系统和设备,包括Windows、Android等。
3 总体设计
3.1系统架构
系统架构设计旨在确保物联网智能家居系统能够高效、稳定地运行,实现各项功能需求并满足非功能性需求。
图 1 设计流程图
3.1.1系统架构
系统采用分层架构,以支持模块化开发和各部分功能的独立管理,主要包括以下几个关键层次:
- 传感器层:
- 硬件设备: 包括连接到Arduino板上的各种传感器,如DHT11温湿度传感器、MQ-2烟雾传感器和TCR红外传感器。
- 数据采集与传输: 传感器层负责实时采集环境数据,并通过适当的通信协议将数据传输到控制层。
- 控制层:
- Arduino控制单元: 这一层负责接收和解析传感器层传来的数据,执行相应的控制指令,如控制LED灯的开关、响应烟雾检测和物体检测。
- 局部服务器: 搭建了TCP服务器,用于与本地客户端和远控端的通信,管理和转发数据以及控制指令。
- 应用层:
- 客户端应用: 包括本地客户端和远控端应用,通过TCP连接与局部服务器通信,实现用户交互和远程控制功能。
- 手机应用: 基于Android Studio开发的手机应用,提供用户友好的界面,支持远程监控、数据可视化和远程控制功能。
- 数据存储与管理:
- 实时数据存储: 使用数据库或文件系统存储系统实时采集的温湿度数据、CO2浓度数据以及安全警报数据。
- 历史数据分析: 针对长期数据存储,系统可选用数据库技术以支持历史数据分析和生成温湿度曲线等功能。
该架构设计允许系统在不同层次上进行功能扩展和优化,同时保证了各部分之间的松耦合,提升了系统的可维护性和可扩展性。
3.2硬件设计
3.2.1Arduino Uno开发板:
作为设备端核心,连接各传感器和执行器。
3.2.2传感器:
DHT11温湿度传感器:监测室内温湿度;
MQ-2烟雾传感器:监测室内烟雾浓度;
红外传感器:检测是否有人经过。
3.2.3执行器:
LED灯:实现智能照明+警报;
蜂鸣器:实现警报功能。
3.3软件设计
3.3.1设备端软件
设备端软件主要负责与Arduino控制单元交互,实现数据采集和设备控制功能的模块包括:
- 传感器数据采集模块: 负责与连接的DHT11温湿度传感器、MQ-2烟雾传感器和TCR红外传感器通信,实时获取环境数据。
- 数据传输模块: 将采集到的数据通过适当的通信协议传输到服务器端,确保数据可靠性和实时性。
- 设备控制模块: 接收来自服务器端或本地控制端的指令,执行对LED灯、蜂鸣器等设备的开关控制操作。
图 2 设备端运行图
3.3.2服务器端软件
服务器端软件作为系统的核心,负责接收、处理和展示数据,主要模块包括:
- 数据接收模块: 接收来自设备端和远控端的数据传输,确保数据完整性和安全性。
- 数据处理模块: 对接收到的数据进行解析、存储和分析,支持实时监控和历史数据查询。
- 数据展示模块: 提供用户界面和API,用于展示实时环境数据、历史数据图表和设备状态信息。
图 3 服务器端运行图
3.3.3远控端软件
远控端软件允许用户远程监控和控制智能家居系统,主要模块包括:
- 数据获取模块: 通过TCP连接获取服务器端实时数据和设备状态信息。
- 用户界面模块: 提供直观友好的用户界面,显示实时数据曲线和设备控制按钮。
- 设备控制模块: 允许用户通过远程控制界面对LED灯、蜂鸣器等设备进行远程控制操作。
图 4 远控端运行图及温湿度实时监测曲线
3.3.4手机端软件
手机端软件为用户提供便捷的移动端控制和监控功能,主要模块包括:
- 数据获取模块: 通过安卓应用程序获取服务器端实时数据和设备状态信息。
- 设备控制模块: 允许用户通过手机界面对LED灯、蜂鸣器等设备进行控制操作,实现远程智能家居控制。
图 5 Android Studio手机端运行图
3.3.5DB数据库软件
数据库软件用于管理系统的数据存储和查询,主要包括:
- 数据存储模块: 负责将设备端传来的实时环境数据、历史数据以及用户操作记录等存储在数据库中,确保数据的持久化和可靠性。
图 6 数据库数据一览
4 详细设计
4.1 Arduino端软件设计
#include <dht11.h>
#include <MQUnifiedsensor.h>//MQ2
#define DHT11PIN 4 //温湿度传感器接D4脚
dht11 DHT11; //创建一个温湿度传感器
#define Sensor_AO A0//MQ-2
#define Sensor_DO A2//MQ-2
int beep = 5; //蜂鸣器引脚
int ledPin = 10; //定义数字接口10接LED
int pin = 2; //定义数字检测接口D2
int val;//定义变量
unsigned int sensorValue = 0;
void setup() {
pinMode(pin, INPUT); // 红外寻迹连接引脚D2,并设置为输入模式
pinMode(ledPin, OUTPUT); //设定数字接口10为输出接口
pinMode(beep, OUTPUT); //设定数字接口5为输出接口
Serial.begin(9600);
Serial.setTimeout(10);
pinMode(Sensor_DO, INPUT);//MQ-2
pinMode(DHT11PIN,INPUT); //DHT11PIN设置为输入
pinMode(13,OUTPUT);
digitalWrite(beep, HIGH); // 打开蜂鸣器
delay(1000); // 等待1秒
digitalWrite(beep, LOW); // 关闭蜂鸣器
}
void loop() {
val = digitalRead(pin); //读取数字接口的值
if (val == 1) //如果Pin2检测的值为高电平,点亮LED
{
digitalWrite(beep, HIGH);
digitalWrite(ledPin, LOW);
}
else //如果为低电平熄灭LED
{
digitalWrite(beep, LOW);
digitalWrite(ledPin, HIGH);
}
if (digitalRead(Sensor_DO) == LOW)
{
Serial.println("Alarm!");
}
if(Serial.available())
{
String a=Serial.readString();
if(a.startsWith("command=arduino1"))
{
digitalWrite(13,HIGH);//开灯
Serial.println("command=arduino1;light=on;");
}
if(a.startsWith("command=arduino2"))
{
digitalWrite(13,LOW);//开灯
Serial.println("command=arduino2;light=off;");
}
if(a.startsWith("command=arduino3"))
{
int chk = DHT11.read(DHT11PIN); //读取温湿度
int temp=(int)DHT11.temperature;//串口显示温度
char buf[100];
sprintf(buf,"command=arduino3;temp=%d;",temp);
Serial.println(buf);
}
if(a.startsWith("command=arduino4"))
{
int chk = DHT11.read(DHT11PIN); //读取温湿度
int humi=(int)DHT11.humidity;//串口显示温度
char buf[100];
sprintf(buf,"command=arduino4;humi=%d;",humi);
Serial.println(buf);
}
if (a.startsWith("command=arduino5"))
{
sensorValue = analogRead(Sensor_AO);//AD读取数值
char buf[100];
sprintf(buf,"command=arduino5;CO2=%d;",sensorValue);
Serial.println(buf);
}
if (a.startsWith("command=arduino6"))
{
val = digitalRead(pin); //读取数字接口的值
//Serial.println(val);//输出输出接口的值
char buf[100];
sprintf(buf,"command=arduino6;HW=%d;",val);
Serial.println(buf);
}
if (a.startsWith("command=arduino7"))
{
digitalWrite(beep, LOW);
delay(1000);
char buf[100];
sprintf(buf,"command=arduino7;beep=on;");
Serial.println(buf);
}
if (a.startsWith("command=arduino8"))
{
digitalWrite(beep, HIGH);
char buf[100];
sprintf(buf,"command=arduino8;beep=off;");
Serial.println(buf);
}
}
}
4.2 设备端软件设计
import time
from tkinter import *
import serial
import threading
from socket import *
global deviceID
deviceID = "100001"
ser = serial.Serial("COM4", 9600)
top = Tk()
top.geometry("800x600+100+100")
def cmd1():
ser.write("command=arduino1".encode('utf-8'))
def cmd2():
ser.write("command=arduino2".encode('utf-8'))
def cmd3():
ser.write("command=arduino3".encode('utf-8'))
def cmd4():
ser.write("command=arduino4".encode('utf-8'))
def cmd5():
ser.write("command=arduino5".encode('utf-8'))
def cmd6():
ser.write("command=arduino6".encode('utf-8'))
def cmd7():
ser.write("command=arduino7".encode('utf-8'))
def cmd8():
ser.write("command=arduino8".encode('utf-8'))
b1 = Button(top, text="开灯", command=cmd1)
b1.place(x=100, y=100)
l1 = Label(top, text="label1")
l1.place(x=200, y=100)
b2 = Button(top, text="关灯", command=cmd2)
b2.place(x=100, y=200)
l2 = Label(top, text="label2")
l2.place(x=200, y=200)
b3 = Button(top, text="显示温度", command=cmd3)
b3.place(x=100, y=300)
l3 = Label(top, text="label3")
l3.place(x=200, y=300)
b4 = Button(top, text="显示湿度", command=cmd4)
b4.place(x=100, y=400)
l4 = Label(top, text="label4")
l4.place(x=200, y=400)
b5 = Button(top, text="显示CO2值", command=cmd5)
b5.place(x=100, y=500)
l5 = Label(top, text="label5")
l5.place(x=200, y=500)
b6 = Button(top, text="检测物品", command=cmd6)
b6.place(x=300, y=100)
l6 = Label(top, text="label6")
l6.place(x=400, y=100)
b7 = Button(top, text="打开蜂鸣器", command=cmd7)
b7.place(x=300, y=200)
l7 = Label(top, text="label7")
l7.place(x=400, y=200)
b8 = Button(top, text="关闭蜂鸣器", command=cmd8)
b8.place(x=300, y=300)
def send_to_server(s):
client_socket = socket(AF_INET, SOCK_STREAM)
server_ip_port = ("47.99.36.139", 8888)
client_socket.connect(server_ip_port)
send_data = s
client_socket.send(send_data.encode('utf-8'))
recv_data = client_socket.recv(1024)
print("客户端接收到的服务器消息为:", recv_data.decode('utf-8'))
client_socket.close()
def receive():
while True:
try:
c = ser.readline().decode('utf-8')
print(c)
if c.startswith("command=arduino1"):
l1["text"] = "灯已开"
send_to_server("command=device1;light=on;device={};".format(deviceID))
if c.startswith("command=arduino2"):
l1["text"] = "灯已关"
send_to_server("command=device2;light=off;device={};".format(deviceID))
if c.startswith("command=arduino3"):
tt = c.split(";")[1].split('=')[1]
print("温度为", tt)
l3["text"] = tt
tt = tt.strip()
send_to_server("command=device3;temp={};device={}".format(tt, deviceID))
if c.startswith("command=arduino4"):
hu = c.split(";")[1].split('=')[1]
print("湿度为", hu)
l4["text"] = hu
hu = hu.strip()
send_to_server("command=device4;humi={};device={}".format(hu, deviceID))
if c.startswith("command=arduino5"):
AD = c.split(";")[1].split('=')[1]
print("CO2为", AD)
l5["text"] = AD
AD = AD.strip()
send_to_server("command=device5;CO2={};device={}".format(AD, deviceID))
if c.startswith("command=arduino6"):
hw = c.split(";")[1].split('=')[1]
print("HW为", hw)
if hw.strip() == "0":
l6["text"] = "检测到物品,警报开启"
else:
l6["text"] = hw
hw = hw.strip()
send_to_server("command=device6;hw={};device={}".format(hw, deviceID))
if c.startswith("command=arduino7"):
l7["text"] = "蜂鸣器已开"
send_to_server("command=device7;beep=on;device={}".format(deviceID))
if c.startswith("command=arduino8"):
l7["text"] = "蜂鸣器已关"
send_to_server("command=device8;beep=off;device={}".format(deviceID))
except Exception as e:
print(e)
send_to_server("command=device0;create;device={};".format(deviceID))
send_to_server("command=devicev;create;device={};".format(deviceID))
thread1 = threading.Thread(target=receive)
thread1.start()
def light():
while True:
try:
client_socket = socket(AF_INET, SOCK_STREAM)
server_ip_port = ("47.99.36.139", 8888)
client_socket.connect(server_ip_port)
send_data = "command=device9;light=?;device={}".format(deviceID)
client_socket.send(send_data.encode('utf-8'))
recv_data = client_socket.recv(1024).decode('utf-8')
print("客户端接收到的服务器消息为:", recv_data)
client_socket.close()
status = recv_data.split(";")[1].split('=')[1]
if(status == "on"):
cmd1()
l1["text"] = "灯已开"
elif(status == "off"):
cmd2()
l1["text"] = "灯已关"
time.sleep(3)
except Exception as e:
print(e)
thread2 = threading.Thread(target=light)
thread2.start()
def beep():
while True:
try:
client_socket = socket(AF_INET, SOCK_STREAM)
server_ip_port = ("47.99.36.139", 8888)
client_socket.connect(server_ip_port)
send_data = "command=devicex;beep=?;device={}".format(deviceID)
client_socket.send(send_data.encode('utf-8'))
recv_data = client_socket.recv(1024).decode('utf-8')
print("客户端接收到的服务器消息为:", recv_data)
client_socket.close()
bp = recv_data.split(";")[1].split('=')[1]
if(bp == "on"):
cmd7()
l7["text"] = "蜂鸣器已开"
elif(bp == "off"):
cmd8()
l7["text"] = "蜂鸣器已关"
time.sleep(3)
except Exception as e:
print(e)
thread3 = threading.Thread(target=beep)
thread3.start()
def publish_hw_data():
while True:
cmd6()
time.sleep(1)
thread4 = threading.Thread(target=publish_hw_data)
thread4.start()
def publish_env_data():
while True:
cmd3() # 发布温度数据
time.sleep(1)
cmd4() # 发布湿度数据
time.sleep(1)
cmd5() # 发布CO2数据
time.sleep(1)
thread5 = threading.Thread(target=publish_env_data)
thread5.start()
top.mainloop()
4.3服务器端软件设计
import threading
from socket import *
import datetime
# 设备发给服务器的命令
# command=device0;create;device=100001;
# command=device3;temp=35;device=100001;
# command=device4;humi=64;device=100001;
import sqlite3
sem = threading.Semaphore(1)
conn = sqlite3.connect('equipment.db')
cursor = conn.cursor()
try:
cursor.execute('create table light (devID varchar(20) primary key, status varchar(20))')
except Exception as e:
print(e)
try:
cursor.execute('create table tt (devID varchar(20), temp varchar(20),t varchar(20))')
except Exception as e:
print(e)
try:
cursor.execute('create table hh (devID varchar(20), humi varchar(20),t varchar(20))')
except Exception as e:
print(e)
try:
cursor.execute('create table AD (devID varchar(20), CO2 varchar(20),t varchar(20))')
except Exception as e:
print(e)
try:
cursor.execute('create table HW (devID varchar(20), human varchar(20),t varchar(20))')
except Exception as e:
print(e)
try:
cursor.execute('create table beep (devID varchar(20) primary key, bp varchar(20))')
except Exception as e:
print(e)
print(cursor.rowcount)
cursor.close()
conn.commit()
conn.close()
server_socket = socket(AF_INET, SOCK_STREAM)
host_port = ("172.31.163.166", 8888)
server_socket.bind(host_port)
server_socket.listen(5)
def client_handler(client_socket, client_address):
try:
data = client_socket.recv(1024).decode('utf-8')
print("服务器接收到的数据是:", data)
if (data.startswith("command=device0")):
deviceID = data.split(";")[2].split("=")[1]
status = "off"
sem.acquire()
conn = sqlite3.connect('equipment.db')
cursor = conn.cursor()
try:
cursor.execute('insert into light (devID, status) values\
(?,?)', (deviceID, status))
except Exception as e:
print(e)
print(cursor.rowcount)
cursor.close()
conn.commit()
conn.close()
sem.release()
client_socket.send("device 0 OK".encode("utf-8"))
client_socket.close()
if (data.startswith("command=device1")):
deviceID = data.split(";")[2].split("=")[1]
status = data.split(";")[1].split("=")[1]
sem.acquire()
conn = sqlite3.connect('equipment.db')
cursor = conn.cursor()
try:
cursor.execute('update light set devID=?,status=?' \
, (deviceID, status))
except Exception as e:
print(e)
print(cursor.rowcount)
cursor.close()
conn.commit()
conn.close()
sem.release()
client_socket.send("device 1 OK".encode("utf-8"))
client_socket.close()
if (data.startswith("command=device2")):
deviceID = data.split(";")[2].split("=")[1]
status = data.split(";")[1].split("=")[1]
sem.acquire()
conn = sqlite3.connect('equipment.db')
cursor = conn.cursor()
try:
cursor.execute('update light set devID=?,status=?' \
, (deviceID, status))
except Exception as e:
print(e)
print(cursor.rowcount)
cursor.close()
conn.commit()
conn.close()
sem.release()
client_socket.send("device 2 OK".encode("utf-8"))
client_socket.close()
if (data.startswith("command=device3")):
deviceID = data.split(";")[2].split("=")[1]
temp = data.split(";")[1].split("=")[1]
t = datetime.datetime.now()
sem.acquire()
conn = sqlite3.connect('equipment.db')
cursor = conn.cursor()
try:
cursor.execute('insert into tt (devID,temp,t) values (?,?,?)' \
, (deviceID, temp, t))
except Exception as e:
print(e)
print(cursor.rowcount)
cursor.close()
conn.commit()
conn.close()
sem.release()
client_socket.send("device 3 OK".encode("utf-8"))
client_socket.close()
if (data.startswith("command=device4")):
deviceID = data.split(";")[2].split("=")[1]
humi = data.split(";")[1].split("=")[1]
t = datetime.datetime.now()
sem.acquire()
conn = sqlite3.connect('equipment.db')
cursor = conn.cursor()
try:
cursor.execute('insert into hh (devID,humi,t) values (?,?,?)' \
, (deviceID, humi, t))
except Exception as e:
print(e)
print(cursor.rowcount)
cursor.close()
conn.commit()
conn.close()
sem.release()
client_socket.send("device 4 OK".encode("utf-8"))
client_socket.close()
if (data.startswith("command=device5")):
deviceID = data.split(";")[2].split("=")[1]
CO2 = data.split(";")[1].split("=")[1]
t = datetime.datetime.now()
sem.acquire()
conn = sqlite3.connect('equipment.db')
cursor = conn.cursor()
try:
cursor.execute('insert into AD (devID,CO2,t) values (?,?,?)' \
, (deviceID, CO2, t))
except Exception as e:
print(e)
print(cursor.rowcount)
cursor.close()
conn.commit()
conn.close()
sem.release()
client_socket.send("device 5 OK".encode("utf-8"))
client_socket.close()
if (data.startswith("command=device6")):
deviceID = data.split(";")[2].split("=")[1]
hw = data.split(";")[1].split("=")[1]
t = datetime.datetime.now()
sem.acquire()
conn = sqlite3.connect('equipment.db')
cursor = conn.cursor()
try:
cursor.execute('insert into HW (devID,human,t) values (?,?,?)' \
, (deviceID, hw, t))
except Exception as e:
print(e)
print(cursor.rowcount)
cursor.close()
conn.commit()
conn.close()
sem.release()
client_socket.send("device 6 OK".encode("utf-8"))
client_socket.close()
if (data.startswith("command=devicev")):
device = data.split(";")[2].split("=")[1]
bp = "off"
sem.acquire()
conn = sqlite3.connect('equipment.db')
cursor = conn.cursor()
try:
cursor.execute('insert into beep (devID, bp) values\
(?,?)', (device, bp))
except Exception as e:
print(e)
print(cursor.rowcount)
cursor.close()
conn.commit()
conn.close()
sem.release()
client_socket.send("device v OK".encode("utf-8"))
client_socket.close()
if (data.startswith("command=device7")):
device = data.split(";")[2].split("=")[1]
bp = data.split(";")[1].split("=")[1]
sem.acquire()
conn = sqlite3.connect('equipment.db')
cursor = conn.cursor()
try:
cursor.execute('update beep set devID=?,bp=?' \
, (device, bp))
except Exception as e:
print(e)
print(cursor.rowcount)
cursor.close()
conn.commit()
conn.close()
sem.release()
client_socket.send("device 7 OK".encode("utf-8"))
client_socket.close()
if (data.startswith("command=device8")):
device = data.split(";")[2].split("=")[1]
bp = data.split(";")[1].split("=")[1]
sem.acquire()
conn = sqlite3.connect('equipment.db')
cursor = conn.cursor()
try:
cursor.execute('update beep set devID=?,bp=?' \
, (device, bp))
except Exception as e:
print(e)
print(cursor.rowcount)
cursor.close()
conn.commit()
conn.close()
sem.release()
client_socket.send("device 8 OK".encode("utf-8"))
client_socket.close()
if (data.startswith("command=device9")):
device = data.split(";")[2].split("=")[1]
sem.acquire()
conn = sqlite3.connect('equipment.db')
cursor = conn.cursor()
try:
cursor.execute('select * from light where devID=?' \
, (device,))
except Exception as e:
print(e)
result = cursor.fetchone()
stat = result[1]
conn.commit()
conn.close()
sem.release()
cmd = "command=device9;light=%s;device=%s" % (stat, device)
client_socket.send(cmd.encode("utf-8"))
client_socket.close()
if (data.startswith("command=devicex")):
device = data.split(";")[2].split("=")[1]
sem.acquire()
conn = sqlite3.connect('equipment.db')
cursor = conn.cursor()
try:
cursor.execute('select * from beep where devID=?' \
, (device,))
except Exception as e:
print(e)
result = cursor.fetchone()
stat = result[1]
conn.commit()
conn.close()
sem.release()
cmd = "command=devicex;beep=%s;device=%s" % (stat, device)
client_socket.send(cmd.encode("utf-8"))
client_socket.close()
if (data.startswith("command=PC1")): # 远控端的命令,查询温度
deviceID = data.split(";")[2].split("=")[1]
sem.acquire()
conn = sqlite3.connect('equipment.db')
cursor = conn.cursor()
try:
cursor.execute('update light set status=? where devID=?' \
, ('on', deviceID))
except Exception as e:
print(e)
cursor.close()
conn.commit()
conn.close()
sem.release()
returndata = "command=PC1;light=on;deviceID=%s;" % (deviceID,)
client_socket.send(returndata.encode("utf-8"))
client_socket.close()
if (data.startswith("command=PC2")): # 远控端的命令,查询温度
deviceID = data.split(";")[2].split("=")[1]
sem.acquire()
conn = sqlite3.connect('equipment.db')
cursor = conn.cursor()
try:
cursor.execute('update light set status=? where devID=?' \
, ('off', deviceID))
except Exception as e:
print(e)
cursor.close()
conn.commit()
conn.close()
sem.release()
returndata = "command=PC2;light=off;deviceID=%s;" % (deviceID,)
client_socket.send(returndata.encode("utf-8"))
client_socket.close()
if (data.startswith("command=PC3")): # 远控端的命令,查询温度
# 查询温度command=PC1;temp=?;deviceID=100001;
# 服务器返回command=PC1;temp=35;deviceID=100001;
deviceID = data.split(";")[2].split("=")[1]
sem.acquire()
conn = sqlite3.connect('equipment.db')
cursor = conn.cursor()
try:
cursor.execute('select * from tt where devID=? order by t desc' \
, (deviceID,))
except Exception as e:
print(e)
result = cursor.fetchone()
temp = result[1]
print(temp)
cursor.close()
conn.commit()
conn.close()
sem.release()
returndata = "command=PC3;temp=%s;deviceID=100001;" % (temp,)
client_socket.send(returndata.encode("utf-8"))
client_socket.close()
if (data.startswith("command=PC4")): # 远控端的命令,查询温度
# 查询温度command=PC2;humi=?;deviceID=100001;
# 服务器返回command=PC2;humi=67;deviceID=100001;
deviceID = data.split(";")[2].split("=")[1]
sem.acquire()
conn = sqlite3.connect('equipment.db')
cursor = conn.cursor()
try:
cursor.execute('select * from hh where devID=? order by t desc' \
, (deviceID,))
except Exception as e:
print(e)
result = cursor.fetchone()
humi = result[1]
cursor.close()
conn.commit()
conn.close()
sem.release()
returndata = "command=PC4;humi=%s;deviceID=100001;" % (humi,)
client_socket.send(returndata.encode("utf-8"))
client_socket.close()
if (data.startswith("command=PC5")): # 远控端的命令,查询温度
# 查询温度command=PC2;humi=?;deviceID=100001;
# 服务器返回command=PC2;humi=67;deviceID=100001;
deviceID = data.split(";")[2].split("=")[1]
sem.acquire()
conn = sqlite3.connect('equipment.db')
cursor = conn.cursor()
try:
cursor.execute('select * from AD where devID=? order by t desc' \
, (deviceID,))
except Exception as e:
print(e)
result = cursor.fetchone()
CO2 = result[1]
cursor.close()
conn.commit()
conn.close()
sem.release()
returndata = "command=PC5;CO2=%s;deviceID=100001;" % (CO2,)
client_socket.send(returndata.encode("utf-8"))
client_socket.close()
if (data.startswith("command=PC6")): # 远控端的命令,查询温度
# 查询温度command=PC2;humi=?;deviceID=100001;
# 服务器返回command=PC2;humi=67;deviceID=100001;
deviceID = data.split(";")[2].split("=")[1]
sem.acquire()
conn = sqlite3.connect('equipment.db')
cursor = conn.cursor()
try:
cursor.execute('select * from HW where devID=? order by t desc' \
, (deviceID,))
except Exception as e:
print(e)
result = cursor.fetchone()
hw = result[1]
cursor.close()
conn.commit()
conn.close()
sem.release()
returndata = "command=PC6;hw=%s;deviceID=100001;" % (hw,)
client_socket.send(returndata.encode("utf-8"))
client_socket.close()
if (data.startswith("command=PC7")): # 远控端的命令,查询温度
deviceID = data.split(";")[2].split("=")[1]
sem.acquire()
conn = sqlite3.connect('equipment.db')
cursor = conn.cursor()
try:
cursor.execute('update beep set bp=? where devID=?' \
, ('on', deviceID))
except Exception as e:
print(e)
cursor.close()
conn.commit()
conn.close()
sem.release()
returndata = "command=PC7;beep=on;deviceID=%s;" % (deviceID,)
client_socket.send(returndata.encode("utf-8"))
client_socket.close()
if (data.startswith("command=PC8")): # 远控端的命令,查询温度
deviceID = data.split(";")[2].split("=")[1]
sem.acquire()
conn = sqlite3.connect('equipment.db')
cursor = conn.cursor()
try:
cursor.execute('update beep set bp=? where devID=?' \
, ('off', deviceID))
except Exception as e:
print(e)
cursor.close()
conn.commit()
conn.close()
sem.release()
returndata = "command=PC8;beep=off;deviceID=%s;" % (deviceID,)
client_socket.send(returndata.encode("utf-8"))
client_socket.close()
if (data.startswith("command=mobile3")): # 手机端的命令,查询温度
# 查询温度command=mobile3;temp=?;deviceID=100001;
# 服务器返回command=mobile3;temp=35;deviceID=100001;
device = data.split(";")[2].split("=")[1]
sem.acquire()
conn = sqlite3.connect('equipment.db')
cursor = conn.cursor()
try:
cursor.execute('select * from tt where devID=? order by t desc' \
, (device,))
except Exception as e:
print(e)
result = cursor.fetchone()
temp = result[1]
print(temp)
cursor.close()
conn.commit()
conn.close()
sem.release()
returndata = "command=mobile3;temp=%s;deviceID=100001;" % (temp,)
client_socket.send(returndata.encode("utf-8"))
client_socket.close()
if (data.startswith("command=mobile4")): # 手机端的命令,查询湿度
# 查询温度command=mobile4;humi=?;deviceID=100001;
# 服务器返回command=mobile4;humi=67;deviceID=100001;
device = data.split(";")[2].split("=")[1]
sem.acquire()
conn = sqlite3.connect('equipment.db')
cursor = conn.cursor()
try:
cursor.execute('select * from hh where devID=? order by t desc' \
, (device,))
except Exception as e:
print(e)
result = cursor.fetchone()
humi = result[1]
cursor.close()
conn.commit()
conn.close()
sem.release()
returndata = "command=mobile4;humi=%s;deviceID=100001;" % (humi,)
client_socket.send(returndata.encode("utf-8"))
client_socket.close()
if (data.startswith("command=mobile5")): # 手机端的命令,查询湿度
# 查询温度command=mobile4;humi=?;deviceID=100001;
# 服务器返回command=mobile4;humi=67;deviceID=100001;
device = data.split(";")[2].split("=")[1]
sem.acquire()
conn = sqlite3.connect('equipment.db')
cursor = conn.cursor()
try:
cursor.execute('select * from AD where devID=? order by t desc' \
, (device,))
except Exception as e:
print(e)
result = cursor.fetchone()
CO2 = result[1]
cursor.close()
conn.commit()
conn.close()
sem.release()
returndata = "command=mobile5;CO2=%s;deviceID=100001;" % (CO2,)
client_socket.send(returndata.encode("utf-8"))
client_socket.close()
if (data.startswith("command=mobile6")): # 手机端的命令,查询湿度
# 查询温度command=mobile4;humi=?;deviceID=100001;
# 服务器返回command=mobile4;humi=67;deviceID=100001;
device = data.split(";")[2].split("=")[1]
sem.acquire()
conn = sqlite3.connect('equipment.db')
cursor = conn.cursor()
try:
cursor.execute('select * from HW where devID=? order by t desc' \
, (device,))
except Exception as e:
print(e)
result = cursor.fetchone()
hw = result[1]
cursor.close()
conn.commit()
conn.close()
sem.release()
returndata = "command=mobile6;hw=%s;deviceID=100001;" % (hw,)
client_socket.send(returndata.encode("utf-8"))
client_socket.close()
if (data.startswith("command=mobile1")): # 手机端命令,开灯
# 查询温度command=mobile1;light=on;deviceID=100001;
# 服务器返回command=mobile1;light=on;deviceID=100001;
device = data.split(";")[2].split("=")[1]
sem.acquire()
conn = sqlite3.connect('equipment.db')
cursor = conn.cursor()
try:
cursor.execute('update light set status=? where devID=?' \
, ('on', device))
except Exception as e:
print(e)
cursor.close()
conn.commit()
conn.close()
sem.release()
returndata = "command=mobile1;light=on;deviceID=%s;" % (device,)
client_socket.send(returndata.encode("utf-8"))
client_socket.close()
if (data.startswith("command=mobile2")): # 手机端的命令,关灯
# 查询温度command=mobile2;light=off;deviceID=100001;
# 服务器返回command=mobile2;light=off;deviceID=100001;
device = data.split(";")[2].split("=")[1]
sem.acquire()
conn = sqlite3.connect('equipment.db')
cursor = conn.cursor()
try:
cursor.execute('update light set status=? where devID=?' \
, ('off', device))
except Exception as e:
print(e)
cursor.close()
conn.commit()
conn.close()
sem.release()
returndata = "command=mobile2;light=off;deviceID=%s;" % (device,)
client_socket.send(returndata.encode("utf-8"))
client_socket.close()
if (data.startswith("command=mobile7")): # 手机端命令,开灯
# 查询温度command=mobile1;light=on;deviceID=100001;
# 服务器返回command=mobile1;light=on;deviceID=100001;
device = data.split(";")[2].split("=")[1]
sem.acquire()
conn = sqlite3.connect('equipment.db')
cursor = conn.cursor()
try:
cursor.execute('update beep set bp=? where devID=?' \
, ('on', device))
except Exception as e:
print(e)
cursor.close()
conn.commit()
conn.close()
sem.release()
returndata = "command=mobile7;beep=on;deviceID=%s;" % (device,)
client_socket.send(returndata.encode("utf-8"))
client_socket.close()
if (data.startswith("command=mobile8")): # 手机端的命令,关灯
# 查询温度command=mobile2;light=off;deviceID=100001;
# 服务器返回command=mobile2;light=off;deviceID=100001;
device = data.split(";")[2].split("=")[1]
sem.acquire()
conn = sqlite3.connect('equipment.db')
cursor = conn.cursor()
try:
cursor.execute('update beep set bp=? where devID=?' \
, ('off', device))
except Exception as e:
print(e)
cursor.close()
conn.commit()
conn.close()
sem.release()
returndata = "command=mobile8;beep=off;deviceID=%s;" % (device,)
client_socket.send(returndata.encode("utf-8"))
client_socket.close()
except Exception as e:
print(e)
while True:
try:
# print("主线程[{}]:服务器正在运行,等待客户端连接...".format(threading.currentThread().name))
new_socket, client_addr = server_socket.accept()
print("主线程[{}]:客户端{}已连接!".format(threading.currentThread().name, client_addr))
client = threading.Thread(target=client_handler, args=(new_socket, client_addr))
client.start()
except Exception as e:
print(e)
server_socket.close()
4.4 远控端和手机端软件设计
远控端:
from tkinter import *
from socket import *
import threading
import matplotlib.pyplot as plt
from collections import deque
import time
global deviceID
deviceID = "100001"
top = Tk()
top.geometry("800x600+100+100")
top.title("远控端")
# 初始化温度和湿度数据队列
data_queue = {
'temperature': deque(maxlen=100), # 存储温度数据的队列,最多存储100个数据点
'humidity': deque(maxlen=100), # 存储湿度数据的队列,最多存储100个数据点
}
def cmd1():
cmd = "command=PC1;light=on;deviceID=%s;" % (deviceID,)
a = send_to_server(cmd)
print(a)
l1['text'] = "灯已开"
def cmd2():
cmd = "command=PC2;light=off;deviceID=%s;" % (deviceID,)
a = send_to_server(cmd)
print(a)
l1['text'] = "灯已关"
def cmd3():
cmd = "command=PC3;temp=?;deviceID=%s;" % (deviceID,)
a = send_to_server(cmd)
print(a)
temp = float(a.split(";")[1].split("=")[1])
l3['text'] = str(temp)
data_queue['temperature'].append(temp) # 将温度数据添加到队列中
def cmd4():
cmd = "command=PC4;humi=?;deviceID=%s;" % (deviceID,)
a = send_to_server(cmd)
print(a)
humi = float(a.split(";")[1].split("=")[1])
l4['text'] = str(humi)
data_queue['humidity'].append(humi) # 将湿度数据添加到队列中
def cmd5():
cmd = "command=PC5;CO2=?;deviceID=%s;" % (deviceID,)
a = send_to_server(cmd)
print("a", a)
CO2 = a.split(";")[1].split("=")[1]
l5['text'] = CO2
def cmd6():
cmd = "command=PC6;hw=?;deviceID=%s;" % (deviceID,)
a = send_to_server(cmd)
print("a", a)
hw = a.split(";")[1].split("=")[1]
if hw.strip() == "0":
l6['text'] = "检测到物品,警报开启"
else:
l6['text'] = "" # 清空 Label 内容
l6['text'] = hw # 设置新的文本
def cmd7():
cmd = "command=PC7;beep=on;deviceID=%s;" % (deviceID,)
a = send_to_server(cmd)
print(a)
l7['text'] = "蜂鸣器已开"
def cmd8():
cmd = "command=PC8;beep=off;deviceID=%s;" % (deviceID,)
a = send_to_server(cmd)
print(a)
l7['text'] = "蜂鸣器关闭"
b1 = Button(top, text="开灯", command=cmd1)
b1.place(x=100, y=100)
l1 = Label(top, text="label1")
l1.place(x=200, y=100)
b2 = Button(top, text="关灯", command=cmd2)
b2.place(x=100, y=200)
l2 = Label(top, text="label2")
l2.place(x=200, y=200)
b3 = Button(top, text="显示温度", command=cmd3)
b3.place(x=100, y=300)
l3 = Label(top, text="label3")
l3.place(x=200, y=300)
b4 = Button(top, text="显示湿度", command=cmd4)
b4.place(x=100, y=400)
l4 = Label(top, text="label4")
l4.place(x=200, y=400)
b5 = Button(top, text="显示CO2值", command=cmd5)
b5.place(x=100, y=500)
l5 = Label(top, text="label5")
l5.place(x=200, y=500)
b6 = Button(top, text="检测物品", command=cmd6)
b6.place(x=300, y=100)
l6 = Label(top, text="label6")
l6.place(x=400, y=100)
b7 = Button(top, text="打开蜂鸣器", command=cmd7)
b7.place(x=300, y=200)
l7 = Label(top, text="label7")
l7.place(x=400, y=200)
b8 = Button(top, text="关闭蜂鸣器", command=cmd8)
b8.place(x=300, y=300)
l8 = Label(top, text="label8")
l8.place(x=400, y=300)
def send_to_server(s):
client_socket = socket(AF_INET, SOCK_STREAM)
server_ip_port = ("47.99.36.139", 8888)
client_socket.connect(server_ip_port)
send_data = s
client_socket.send(send_data.encode('utf-8'))
recv_data = client_socket.recv(1024)
print("客户端接收到的服务器消息为:", recv_data.decode('utf-8'))
ret = recv_data.decode('utf-8')
client_socket.close()
return ret
# 更新曲线的函数
def update_plot():
if data_queue['temperature'] and data_queue['humidity']:
plt.clf() # 清除之前的图形
plt.plot(data_queue['temperature'], label='Temperature (℃)')
plt.plot(data_queue['humidity'], label='Humidity (%)')
plt.xlabel('Time')
plt.ylabel('Value')
plt.title('Temperature and Humidity')
plt.legend()
plt.tight_layout()
plt.draw() # 更新图形
# 定时更新温度、湿度数据的函数
def update_data():
cmd3() # 发布温度数据
cmd4() # 发布湿度数据
update_plot() # 更新图形
top.after(1000, update_data) # 每隔1秒更新一次数据
def update_CO2():
while True:
cmd5() # 发布CO2数据
time.sleep(1)
def update_hw():
while True:
cmd6() # 检测物品数据
time.sleep(1)
thread_hw = threading.Thread(target=update_hw)
thread_hw.start()
thread_CO2 = threading.Thread(target=update_CO2)
thread_CO2.start()
plt.ion() # 打开交互模式,允许实时更新图形
plt.show() # 显示图形界面
top.after(0, update_data) # 开始定时更新数据
top.mainloop()
4.5手机端(Android Studio):
package com.example.mylighthumiandtemp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
public class MainActivity extends AppCompatActivity {
Button open;
Button close;
Button openbeep;
Button closebeep;
TextView lightstatus;
TextView beepbp;
TextView tempTextView;
TextView humiTextView;
TextView coTextView;
TextView hwTextView;
String IPAdress = "47.99.36.139";
String Port = "8888";
EditText receiveText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
open = findViewById(R.id.button);
openbeep = findViewById(R.id.button6);
close = findViewById(R.id.button2);
closebeep = findViewById(R.id.button7);
lightstatus = findViewById(R.id.textView);
beepbp = findViewById(R.id.textView5);
tempTextView = findViewById(R.id.tempTextView);
humiTextView = findViewById(R.id.humiTextView);
coTextView = findViewById(R.id.coTextView);
hwTextView = findViewById(R.id.hwTextView);
receiveText = findViewById(R.id.editTextTextMultiLine);
}
public void OpenLight(View v) {
try {
openThread senth = new openThread();
senth.start();
} catch (Exception e) {
e.printStackTrace();
}
}
class openThread extends Thread {
public void run() {
try {
String cmd = "command=mobile1;light=on;device=100001";
InetAddress ipAddress = InetAddress.getByName(IPAdress);
int port = Integer.parseInt(Port);
Socket socket = new Socket(ipAddress, port);
OutputStream output = socket.getOutputStream();
InputStream inputStream = socket.getInputStream();
output.write(cmd.getBytes());
System.out.println("222");
final byte[] buffer = new byte[1024];
final int len = inputStream.read(buffer);
if (len != -1) {
runOnUiThread(() -> {
receiveText.append(new String(buffer, 0, len));
lightstatus.setText("灯已开");
});
}
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void CloseLight(View v) {
try {
closeThread senth = new closeThread();
senth.start();
} catch (Exception e) {
e.printStackTrace();
}
}
class closeThread extends Thread {
public void run() {
try {
String cmd = "command=mobile2;light=off;device=100001";
InetAddress ipAddress = InetAddress.getByName(IPAdress);
int port = Integer.parseInt(Port);
Socket socket = new Socket(ipAddress, port);
OutputStream output = socket.getOutputStream();
InputStream inputStream = socket.getInputStream();
output.write(cmd.getBytes());
System.out.println("222");
final byte[] buffer = new byte[1024];
final int len = inputStream.read(buffer);
if (len != -1) {
runOnUiThread(() -> {
receiveText.append(new String(buffer, 0, len));
lightstatus.setText("灯已关");
});
}
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void OpenBeep(View v) {
try {
openThread1 senth = new openThread1();
senth.start();
} catch (Exception e) {
e.printStackTrace();
}
}
class openThread1 extends Thread {
public void run() {
try {
String cmd = "command=mobile7;beep=on;device=100001";
InetAddress ipAddress = InetAddress.getByName(IPAdress);
int port = Integer.parseInt(Port);
Socket socket = new Socket(ipAddress, port);
OutputStream output = socket.getOutputStream();
InputStream inputStream = socket.getInputStream();
output.write(cmd.getBytes());
System.out.println("222");
final byte[] buffer = new byte[1024];
final int len = inputStream.read(buffer);
if (len != -1) {
runOnUiThread(() -> {
receiveText.append(new String(buffer, 0, len));
beepbp.setText("蜂鸣器已开");
});
}
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void CloseBeep(View v) {
try {
closeThread1 senth = new closeThread1();
senth.start();
} catch (Exception e) {
e.printStackTrace();
}
}
class closeThread1 extends Thread {
public void run() {
try {
String cmd = "command=mobile8;beep=off;device=100001";
InetAddress ipAddress = InetAddress.getByName(IPAdress);
int port = Integer.parseInt(Port);
Socket socket = new Socket(ipAddress, port);
OutputStream output = socket.getOutputStream();
InputStream inputStream = socket.getInputStream();
output.write(cmd.getBytes());
System.out.println("222");
final byte[] buffer = new byte[1024];
final int len = inputStream.read(buffer);
if (len != -1) {
runOnUiThread(() -> {
receiveText.append(new String(buffer, 0, len));
beepbp.setText("蜂鸣器已关");
});
}
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void NeedTemp(View v) {
try {
NeedTemp senth = new NeedTemp();
senth.start();
} catch (Exception e) {
e.printStackTrace();
}
}
class NeedTemp extends Thread {
public void run() {
try {
String cmd = "command=mobile3;temp=?;device=100001";
InetAddress ipAddress = InetAddress.getByName(IPAdress);
int port = Integer.parseInt(Port);
Socket socket = new Socket(ipAddress, port);
OutputStream output = socket.getOutputStream();
InputStream inputStream = socket.getInputStream();
output.write(cmd.getBytes());
System.out.println("222");
final byte[] buffer = new byte[1024];
final int len = inputStream.read(buffer);
if (len != -1) {
runOnUiThread(() -> {
String response = new String(buffer, 0, len);
receiveText.append(response);
tempTextView.setText("温度:" + parseTemperature(response));
});
}
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void NeedHumi(View v) {
try {
NeedHumi senth = new NeedHumi();
senth.start();
} catch (Exception e) {
e.printStackTrace();
}
}
class NeedHumi extends Thread {
public void run() {
try {
String cmd = "command=mobile4;humi=?;device=100001";
InetAddress ipAddress = InetAddress.getByName(IPAdress);
int port = Integer.parseInt(Port);
Socket socket = new Socket(ipAddress, port);
OutputStream output = socket.getOutputStream();
InputStream inputStream = socket.getInputStream();
output.write(cmd.getBytes());
System.out.println("222");
final byte[] buffer = new byte[1024];
final int len = inputStream.read(buffer);
if (len != -1) {
runOnUiThread(() -> {
String response = new String(buffer, 0, len);
receiveText.append(response);
humiTextView.setText("湿度:" + parseHumidity(response));
});
}
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void NeedCo(View v) {
try {
NeedCo senth = new NeedCo();
senth.start();
} catch (Exception e) {
e.printStackTrace();
}
}
class NeedCo extends Thread {
public void run() {
try {
String cmd = "command=mobile5;CO2=?;device=100001";
InetAddress ipAddress = InetAddress.getByName(IPAdress);
int port = Integer.parseInt(Port);
Socket socket = new Socket(ipAddress, port);
OutputStream output = socket.getOutputStream();
InputStream inputStream = socket.getInputStream();
output.write(cmd.getBytes());
System.out.println("222");
final byte[] buffer = new byte[1024];
final int len = inputStream.read(buffer);
if (len != -1) {
runOnUiThread(() -> {
String response = new String(buffer, 0, len);
receiveText.append(response);
coTextView.setText("CO2含量:" + parseCodioxide(response));
});
}
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void NeedHW(View v) {
try {
NeedHW senth = new NeedHW();
senth.start();
} catch (Exception e) {
e.printStackTrace();
}
}
class NeedHW extends Thread {
public void run() {
try {
String cmd = "command=mobile6;hw=?;device=100001";
InetAddress ipAddress = InetAddress.getByName(IPAdress);
int port = Integer.parseInt(Port);
Socket socket = new Socket(ipAddress, port);
OutputStream output = socket.getOutputStream();
InputStream inputStream = socket.getInputStream();
output.write(cmd.getBytes());
System.out.println("222");
final byte[] buffer = new byte[1024];
final int len = inputStream.read(buffer);
if (len != -1) {
runOnUiThread(() -> {
String response = new String(buffer, 0, len);
receiveText.append(response);
hwTextView.setText("是否有物体:" + parseHumad(response));
});
}
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
private String parseTemperature(String response) {
// 假设返回的响应字符串包含 "temp=xx.xx" 格式的数据
String[] parts = response.split(";");
for (String part : parts) {
if (part.startsWith("temp=")) {
return part.split("=")[1];
}
}
return "未知";
}
private String parseHumidity(String response) {
// 假设返回的响应字符串包含 "humi=xx.xx" 格式的数据
String[] parts = response.split(";");
for (String part : parts) {
if (part.startsWith("humi=")) {
return part.split("=")[1];
}
}
return "未知";
}
private String parseCodioxide(String response) {
// 假设返回的响应字符串包含 "co2=xx,xx,xx" 格式的数据
String[] parts = response.split(";");
for (String part : parts) {
if (part.startsWith("CO2=")) {
return part.split("=")[1];
}
}
return "未知";
}
private String parseHumad(String response) {
// 假设返回的响应字符串包含 "co2=xx,xx,xx" 格式的数据
String[] parts = response.split(";");
for (String part : parts) {
if (part.startsWith("hw=")) {
return part.split("=")[1];
}
}
return "未知";
}
}
5 系统测试
系统测试旨在验证物联网智能家居系统在各个层面和整体上的功能完整性、性能稳定性和用户体验。
5.1单元测试
单元测试针对系统的各个组成部分进行测试,具体包括以下方面:
- 传感器模块测试: 确保各传感器(如DHT11温湿度传感器、MQ-2烟雾传感器、TCR红外传感器)的数据采集精度和稳定性,验证其在不同环境条件下的准确性。
- 执行器模块测试: 验证LED灯和蜂鸣器等执行器的控制功能,确保能够按照指令准确地开启、关闭或响应警报。
- 数据传输模块测试: 验证数据传输过程中数据包的格式是否符合标准,以及传输的可靠性和稳定性,包括对丢包率和传输延迟的测试。
5.2集成测试
集成测试主要验证系统不同模块之间的交互和协作,具体包括以下内容:
- 设备端和服务器端的数据交互验证: 确保设备端采集的数据能够成功传输到服务器端,并且服务器端能够正确接收、处理和存储数据。
- 远控端和手机端的功能验证: 验证远控端和手机端能够准确获取服务器端的实时数据,并能够通过界面实现对设备的远程控制操作。
- 各模块的协同工作测试: 测试不同模块之间的协同工作,包括数据流动、指令传递和状态同步,以确保系统各部分能够协调一致地运行。
5.3系统测试
系统测试是对整个物联网智能家居系统的全面测试,具体包括以下方面:
- 模拟环境下的实时监测和控制功能测试: 在模拟的真实环境条件下,测试系统的温湿度实时监测、CO2浓度监测和设备控制功能,确保系统能够准确响应和反馈。
- 异常情况下的恢复能力测试: 模拟各种可能的异常情况,如网络中断、传感器故障或服务器端故障,验证系统的自动恢复能力和异常处理机制。
- 用户界面的友好性测试: 测试客户端、远控端和手机端的用户界面,确保界面设计简洁直观,用户能够轻松操作和理解系统的各项功能。
通过以上系统测试,可以全面评估物联网智能家居系统的稳定性、可靠性和用户体验,确保系统能够满足设计和用户需求。
6 创新能力
项目在多个方面展示了创新能力,从多传感器集成到实时数据传输、数据可视化和智能控制策略,都为智能家居系统的功能和用户体验带来了显著提升。
6.1多传感器集成
本项目集成了多种传感器,能够全面监测家庭环境。不同传感器之间通过协同工作,实现了更加智能化的家居控制。例如,基于温湿度和红外传感器的数据联动,系统可以智能地控制家中设备的运行和响应,从而提高了系统的响应速度和环境适应能力。
6.2实时数据传输与远程控制
通过TCP/IP协议实现了设备端与服务器端的实时数据传输,用户可以通过网页或手机APP随时随地实时查看和控制家中的设备。这种实时数据传输和远程控制功能,极大地增强了用户对家庭环境的实时监控和管理能力,提升了家居智能化水平。
6.3数据可视化与历史记录
系统提供了强大的数据可视化功能,用户可以直观地查看实时数据和历史记录。通过可视化界面,用户能够更好地了解家庭环境的变化趋势和数据分布,从而科学合理地管理家庭生活。这种数据驱动的管理方式,不仅提高了用户对环境的感知能力,还为决策提供了有力支持。
6.4智能控制策略
系统实现了一系列智能控制策略,如基于红外传感器数据的自动控制照明设备功能。这些智能控制策略不仅提升了家庭生活的便利性和舒适性,还能有效节约能源,符合节能减排的现代生活理念。通过智能化的控制策略,系统能够根据实时环境数据智能调整设备的运行状态,以达到最佳的用户体验和能效表现。
这些创新点使得该智能家居系统在功能丰富性、用户体验和能效管理方面都处于领先地位,为现代家庭生活带来了极大的便利和智能化体验。