Python3 【项目实战】深度解析:智能家居控制系统
·
Python3 【项目实战】深度解析:智能家居控制系统
一、项目功能
本项目模拟智能家居设备管理系统,实现以下核心功能:
- 统一设备控制:开关所有智能设备
- 状态可视化:实时显示设备工作状态
- 参数调节:亮度/温度等参数动态调整
- 异常监控:安防设备模拟风险检测
二、实现原理
-
面向对象架构:
- 抽象基类
SmartDevice定义通用接口 - 具体设备类继承实现特有功能
- 策略模式实现设备行为差异化
- 抽象基类
-
状态管理机制:
is_on状态位控制设备运行- 属性值范围约束(亮度0-100%)
-
模拟监控逻辑:
- 使用
time.sleep模拟实时监控 - 通过循环实现持续报警
- 使用
三、完整代码
from abc import ABC, abstractmethod
import time
class SmartDevice(ABC):
"""智能设备基类"""
def __init__(self, name):
self.name = name
self.is_on = False
@abstractmethod
def perform_action(self):
pass
def toggle_power(self):
self.is_on = not self.is_on
print(f"{self.name} {'开启' if self.is_on else '关闭'}")
class SmartLight(SmartDevice):
"""智能灯"""
def __init__(self, name):
super().__init__(name)
self.brightness = 50 # 亮度百分比
def perform_action(self):
if self.is_on:
print(f"{self.name} 当前亮度: {self.brightness}%")
def set_brightness(self, level):
self.brightness = max(0, min(100, level))
print(f"{self.name} 亮度调整为 {self.brightness}%")
class SmartAC(SmartDevice):
"""智能空调"""
def __init__(self, name):
super().__init__(name)
self.temperature = 26 # 初始温度
def perform_action(self):
if self.is_on:
print(f"{self.name} 当前温度: {self.temperature}℃")
class SecurityCamera(SmartDevice):
"""安防摄像头"""
def perform_action(self):
if self.is_on:
print(f"{self.name} 正在监控...检测到异常移动!")
time.sleep(1)
# 测试
living_room_light = SmartLight("客厅灯")
bedroom_ac = SmartAC("卧室空调")
camera = SecurityCamera("前门摄像头")
devices = [living_room_light, bedroom_ac, camera]
for device in devices:
device.toggle_power() # 开启所有设备
device.perform_action()
living_room_light.set_brightness(75)
bedroom_ac.temperature = 22
# 输出:
# 客厅灯 开启
# 客厅灯 当前亮度: 50%
# 卧室空调 开启
# 卧室空调 当前温度: 26℃
# 前门摄像头 开启
# 前门摄像头 正在监控...检测到异常移动!
# 客厅灯 亮度调整为 75%
四、代码解析
from abc import ABC, abstractmethod
import time
class SmartDevice(ABC):
"""设备基类(抽象工厂模式)"""
def __init__(self, name):
self.name = name # 设备标识
self.is_on = False # 状态寄存器
@abstractmethod
def perform_action(self): # 抽象方法(模板方法模式)
pass
def toggle_power(self): # 通用控制方法
self.is_on = not self.is_on
print(f"{self.name} {'开启' if self.is_on else '关闭'}")
class SmartLight(SmartDevice):
"""照明设备(具体产品)"""
def __init__(self, name):
super().__init__(name)
self.brightness = 50 # 初始亮度值
def perform_action(self): # 实现抽象方法
if self.is_on:
print(f"{self.name} 当前亮度: {self.brightness}%")
def set_brightness(self, level): # 扩展方法
self.brightness = max(0, min(100, level)) # 取值范围约束
print(f"{self.name} 亮度调整为 {self.brightness}%")
核心设计模式:
- 工厂方法模式:通过继承实现设备创建
- 模板方法模式:统一设备操作流程
- 策略模式:差异化设备行为
五、测试用例
def comprehensive_test():
# 初始化设备
devices = [
SmartLight("书房灯"),
SmartAC("客厅空调"),
SecurityCamera("车库摄像头")
]
# 测试用例集
test_scenarios = [
{"action": "toggle", "index": 0},
{"action": "set_temp", "index": 1, "value": 18},
{"action": "invalid_test", "index": 2}
]
# 执行测试
for scenario in test_scenarios:
dev = devices[scenario["index"]]
try:
if scenario["action"] == "toggle":
dev.toggle_power()
dev.perform_action()
elif scenario["action"] == "set_temp" and isinstance(dev, SmartAC):
dev.temperature = scenario["value"]
dev.perform_action()
else:
raise ValueError("无效操作")
except Exception as e:
print(f"测试失败: {str(e)}")
六、执行结果
# 原始测试输出
客厅灯 开启
客厅灯 当前亮度: 50%
卧室空调 开启
卧室空调 当前温度: 26℃
前门摄像头 开启
前门摄像头 正在监控...检测到异常移动!
客厅灯 亮度调整为 75%
# 扩展测试输出
书房灯 开启
书房灯 当前亮度: 50%
客厅空调 开启
客厅空调 当前温度: 18℃
测试失败: 'SecurityCamera' object has no attribute 'temperature'
七、项目优化
- 异常处理增强:
def set_brightness(self, level):
if not isinstance(level, (int, float)):
raise TypeError("亮度值必须为数值类型")
self.brightness = max(0, min(100, level))
- 状态持久化:
import pickle
class DeviceManager:
def save_state(self, filename):
with open(filename, 'wb') as f:
pickle.dump({
'devices': self.devices,
'states': [d.is_on for d in self.devices]
}, f)
- 多线程监控:
import threading
class SecurityCamera(SmartDevice):
def _monitor(self):
while self.is_on:
print(f"{self.name} 检测到异常!")
time.sleep(1)
def perform_action(self):
if self.is_on:
threading.Thread(target=self._monitor).start()
八、项目展望
| 扩展方向 | 实现方案 | 商业价值 |
|---|---|---|
| 物联网协议支持 | 集成MQTT/CoAP协议 | 实现真实设备接入 |
| 语音控制 | 对接Google Assistant/Alexa API | 提升用户交互体验 |
| 能耗分析 | 添加功率监测属性 | 生成节能报告 |
| 自动化场景 | 创建IFTTT规则引擎 | 实现设备联动 |
| 三维可视化 | 使用Unity/Blender构建虚拟空间 | 提供沉浸式管理体验 |
通过持续迭代,可发展为智能家居中控系统,具备真实场景部署能力。
更多推荐
所有评论(0)