本文目录导读:

我来为您设计一个完整的Java智能家居系统案例,涵盖核心功能、架构设计和代码实现。
系统架构设计
graph TB
subgraph 表现层
UI[Web管理界面]
Mobile[移动端APP]
Voice[语音助手]
end
subgraph 应用层
Control[设备控制中心]
Scene[场景联动引擎]
Alarm[报警系统]
Report[能耗报表]
end
subgraph 服务层
Device[设备管理服务]
Auth[认证授权服务]
Data[数据分析服务]
MQTT[MQTT消息服务]
end
subgraph 设备层
Light[智能灯光]
AC[空调系统]
Curtain[智能窗帘]
Sensor[传感器集群]
Camera[监控摄像头]
end
核心代码实现
设备基类设计
// 设备基类
public abstract class SmartDevice {
protected String deviceId;
protected String deviceName;
protected DeviceType type;
protected DeviceStatus status;
protected String location;
protected LocalDateTime lastUpdateTime;
// 抽象方法:设备控制
public abstract boolean turnOn();
public abstract boolean turnOff();
public abstract String getDeviceInfo();
// 设备状态上报
public void reportStatus() {
DeviceMessage message = new DeviceMessage(
this.deviceId,
this.status,
this.lastUpdateTime
);
MQTTService.publish("home/device/" + deviceId + "/status", message);
}
}
// 设备类型枚举
public enum DeviceType {
LIGHT("灯光"),
AIR_CONDITIONER("空调"),
CURTAIN("窗帘"),
SENSOR("传感器"),
CAMERA("摄像头"),
SWITCH("插座");
private String desc;
DeviceType(String desc) {
this.desc = desc;
}
}
// 设备状态枚举
public enum DeviceStatus {
ONLINE("在线"),
OFFLINE("离线"),
FAULT("故障"),
RUNNING("运行中"),
STANDBY("待机");
}
具体设备实现-智能灯光
public class SmartLight extends SmartDevice {
private int brightness; // 亮度 0-100
private String colorTemp; // 色温
private String color; // 颜色RGB
public SmartLight(String deviceId, String name, String location) {
this.deviceId = deviceId;
this.deviceName = name;
this.location = location;
this.type = DeviceType.LIGHT;
this.status = DeviceStatus.STANDBY;
this.brightness = 50;
this.colorTemp = "4000K";
this.color = "#FFFFFF";
this.lastUpdateTime = LocalDateTime.now();
}
@Override
public boolean turnOn() {
this.status = DeviceStatus.RUNNING;
this.lastUpdateTime = LocalDateTime.now();
System.out.println("灯光【" + deviceName + "】已开启,亮度:" + brightness + "%");
reportStatus();
return true;
}
@Override
public boolean turnOff() {
this.status = DeviceStatus.STANDBY;
this.lastUpdateTime = LocalDateTime.now();
System.out.println("灯光【" + deviceName + "】已关闭");
reportStatus();
return true;
}
// 调节亮度
public void setBrightness(int brightness) {
if (brightness >= 0 && brightness <= 100) {
this.brightness = brightness;
this.lastUpdateTime = LocalDateTime.now();
System.out.println("灯光【" + deviceName + "】亮度调至:" + brightness + "%");
// 亮度变化触发自动调节
triggerAutoLighting();
}
}
// 自动亮度调节
private void triggerAutoLighting() {
if (brightness < 20) {
System.out.println("亮度偏低,自动开启补充照明");
}
}
@Override
public String getDeviceInfo() {
return String.format("灯光设备|ID:%s|名称:%s|位置:%s|亮度:%d%%|色温:%s",
deviceId, deviceName, location, brightness, colorTemp);
}
}
设备管理服务
@Service
public class DeviceManagerService {
@Autowired
private DeviceRepository deviceRepository;
private Map<String, SmartDevice> deviceMap = new ConcurrentHashMap<>();
private Map<String, DeviceHook> deviceHooks = new ConcurrentHashMap<>();
/**
* 注册设备
*/
public void registerDevice(SmartDevice device) {
deviceMap.put(device.getDeviceId(), device);
deviceRepository.save(device);
// 注册Mqtt监听
String topic = "home/device/" + device.getDeviceId() + "/command";
MQTTService.subscribe(topic, (message) -> {
handleDeviceCommand(device.getDeviceId(), message);
});
log.info("设备注册成功: {}", device.getDeviceId());
}
/**
* 设备控制
*/
public boolean controlDevice(String deviceId, CommandType command, Object... params) {
SmartDevice device = deviceMap.get(deviceId);
if (device == null) {
throw new DeviceNotFoundException("设备不存在: " + deviceId);
}
switch (command) {
case TURN_ON:
return device.turnOn();
case TURN_OFF:
return device.turnOff();
case SET_BRIGHTNESS:
if (device instanceof SmartLight) {
((SmartLight) device).setBrightness((Integer) params[0]);
return true;
}
break;
// 其他命令处理
default:
throw new UnsupportedOperationException("不支持的命令: " + command);
}
return false;
}
/**
* 设备状态查询
*/
public DeviceStatus getDeviceStatus(String deviceId) {
SmartDevice device = deviceMap.get(deviceId);
return device != null ? device.getStatus() : DeviceStatus.OFFLINE;
}
/**
* 设备事件钩子
*/
public void addDeviceHook(String deviceId, DeviceHook hook) {
deviceHooks.put(deviceId, hook);
}
}
// 命令类型枚举
public enum CommandType {
TURN_ON("开启"),
TURN_OFF("关闭"),
SET_BRIGHTNESS("设置亮度"),
SET_TEMPERATURE("设置温度"),
SET_MODE("设置模式"),
GET_STATUS("获取状态");
private String desc;
CommandType(String desc) { this.desc = desc; }
}
场景联动引擎
@Component
public class SceneEngine {
private Map<String, Scene> sceneMap = new ConcurrentHashMap<>();
private List<SceneRule> rules = new CopyOnWriteArrayList<>();
@Autowired
private DeviceManagerService deviceService;
/**
* 创建场景(如:回家模式、离家模式、观影模式)
*/
public void createScene(String sceneName, List<SceneAction> actions) {
Scene scene = new Scene(sceneName, actions);
sceneMap.put(sceneName, scene);
log.info("创建场景成功: {}", sceneName);
}
/**
* 激活场景
*/
public void activateScene(String sceneName) {
Scene scene = sceneMap.get(sceneName);
if (scene == null) {
throw new SceneNotFoundException("场景不存在: " + sceneName);
}
// 按顺序执行场景动作
for (SceneAction action : scene.getActions()) {
deviceService.controlDevice(
action.getDeviceId(),
action.getCommandType(),
action.getParams()
);
// 场景动作执行延迟(设备响应间隔)
try {
Thread.sleep(200);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
log.info("场景激活成功: {}", sceneName);
}
/**
* 添加自动触发规则
*/
public void addAutomationRule(TriggerCondition condition, String sceneName) {
SceneRule rule = new SceneRule(condition, sceneName);
rules.add(rule);
}
/**
* 检查并触发自动规则
*/
@EventListener
public void onDeviceEvent(DeviceEvent event) {
for (SceneRule rule : rules) {
if (rule.matches(event)) {
log.info("触发自动规则: {}", rule.getSceneName());
activateScene(rule.getSceneName());
}
}
}
}
// 场景数据类
@Data
public class Scene {
private String sceneName;
private List<SceneAction> actions;
private Priority priority;
private LocalDateTime createTime;
// 场景动作
@Data
public static class SceneAction {
private String deviceId;
private CommandType commandType;
private Object[] params;
private int executeOrder;
}
// 触发条件
@Data
public static class TriggerCondition {
private DeviceType deviceType;
private String property; // 属性(如温度、湿度、光感)
private String operator; // 操作符(>、<、=)
private Object threshold; // 阈值
private String period; // 时间段(如:白天、晚上)
}
}
MQTT消息服务
@Component
public class MQTTService {
private MqttClient client;
private MqttConnectOptions options;
@Value("${mqtt.broker}")
private String brokerHost;
@Value("${mqtt.clientId}")
private String clientId;
/**
* 发布消息
*/
public static void publish(String topic, Object message) {
try {
String payload = JSON.toJSONString(message);
MqttMessage mqttMessage = new MqttMessage(payload.getBytes());
mqttMessage.setQos(1);
mqttMessage.setRetained(true);
// client.publish(topic, mqttMessage);
System.out.println("MQTT发布消息到 " + topic + ": " + payload);
} catch (Exception e) {
log.error("MQTT发布消息失败", e);
}
}
/**
* 订阅主题
*/
public static void subscribe(String topic, MessageCallback callback) {
System.out.println("订阅主题: " + topic);
// 实际项目中注册回调
}
/**
* 消息回调接口
*/
public interface MessageCallback {
void onMessage(String topic, String payload);
}
}
能耗监控模块
@Component
public class EnergyMonitorService {
@Autowired
private EnergyDataMapper energyMapper;
private Map<String, EnergyConsumption> deviceEnergyMap = new ConcurrentHashMap<>();
/**
* 记录设备能耗
*/
public void recordEnergy(String deviceId, double powerWatt, long duration) {
double energyKwh = (powerWatt * duration) / (1000 * 3600);
EnergyConsumption consumption = deviceEnergyMap.computeIfAbsent(
deviceId, k -> new EnergyConsumption(deviceId)
);
consumption.addEnergy(energyKwh);
// 异步存储到数据库
CompletableFuture.runAsync(() -> {
energyMapper.insert(consumption);
});
}
/**
* 生成能耗报表
*/
public EnergyReport getDailyReport(String location, LocalDate date) {
double totalEnergy = 0;
Map<String, Double> deviceEnergy = new HashMap<>();
// 查询当日数据,统计分析
for (EnergyConsumption ec : deviceEnergyMap.values()) {
if (ec.getLocation().equals(location)) {
totalEnergy += ec.getTotalEnergy();
deviceEnergy.put(ec.getDeviceName(), ec.getTotalEnergy());
}
}
// 智能节能建议
List<EnergySuggestion> suggestions = new ArrayList<>();
if (totalEnergy > 15.0) {
suggestions.add(new EnergySuggestion(
"能耗超标",
"今日能耗较高,建议关闭不必要的设备",
Severity.HIGH
));
}
return new EnergyReport(date, totalEnergy, deviceEnergy, suggestions);
}
/**
* 能耗预警
*/
public void checkEnergyAlarm() {
for (EnergyConsumption ec : deviceEnergyMap.values()) {
if (ec.getTotalEnergy() > ec.getWarningThreshold()) {
// 发送警报通知
NotificationService.sendAlert(
"能耗异常",
ec.getDeviceName() + " 本月能耗已超阈值"
);
}
}
}
}
WebSocket实时通信
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new DeviceWebSocketHandler(), "/ws/device")
.setAllowedOrigins("*");
}
}
public class DeviceWebSocketHandler extends TextWebSocketHandler {
private static final Set<WebSocketSession> sessions =
new ConcurrentHashMap<>().newKeySet();
@Override
public void afterConnectionEstablished(WebSocketSession session) {
sessions.add(session);
System.out.println("WebSocket连接建立: " + session.getId());
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) {
String payload = message.getPayload();
System.out.println("收到消息: " + payload);
// 广播给所有客户端
for (WebSocketSession s : sessions) {
if (s.isOpen()) {
s.sendMessage(new TextMessage("设备状态更新: " + payload));
}
}
}
}
智能安防监控
@Service
public class SecurityService {
@Autowired
private NotificationService notificationService;
private Map<String, AlarmRecord> alarmRecordMap = new ConcurrentHashMap<>();
/**
* 监控设备数据分析
*/
public void analyzeSecurityData(String location, SensorData data) {
SecurityLevel level = evaluateRisk(data);
if (level == SecurityLevel.HIGH) {
alertSecurityEvent(location, data.getEventType(), level);
} else {
log.info("安全分析通过: {} 级别:{}", location, level);
}
}
/**
* 风险评级
*/
private SecurityLevel evaluateRisk(SensorData data) {
int riskScore = 0;
// 移动检测
if (data.isMotionDetected()) riskScore += 3;
// 门窗状态
if (!data.isDoorLocked()) riskScore += 2;
// 烟雾检测
if (data.getSmokeLevel() > 50) riskScore += 5;
// 异常温度
if (data.getTemperature() > 60) riskScore += 3;
if (riskScore >= 8) return SecurityLevel.HIGH;
if (riskScore >= 4) return SecurityLevel.MEDIUM;
return SecurityLevel.LOW;
}
/**
* 安全事件警报
*/
private void alertSecurityEvent(String location, String eventType, SecurityLevel level) {
AlarmRecord record = new AlarmRecord(
UUID.randomUUID().toString(),
location,
eventType,
level,
LocalDateTime.now()
);
alarmRecordMap.put(record.getRecordId(), record);
// 发送多通道通知
notificationService.sendSMS("安全警报: " + eventType + " 位置: " + location);
notificationService.sendAppNotification("安全警报",
"【" + location + "】检测到" + eventType + "事件,级别:" + level);
// 自动联动
if (level == SecurityLevel.HIGH) {
// 自动开启灯光、启动摄像头录像、锁门等
deviceService.controlDevice("camera_001", CommandType.START_RECORD);
deviceService.controlDevice("door_001", CommandType.LOCK);
// 触发报警场景
sceneEngine.activateScene("安全报警场景");
}
log.warn("安全事件: {}", record);
}
}
// 安全级别
public enum SecurityLevel {
LOW("低风险"),
MEDIUM("中风险"),
HIGH("高风险");
private String desc;
SecurityLevel(String desc) { this.desc = desc; }
}
数据可视化服务
@RestController
@RequestMapping("/api/smart-home")
public class SmartHomeController {
@Autowired
private DeviceManagerService deviceService;
@Autowired
private SceneEngine sceneEngine;
@Autowired
private EnergyMonitorService energyService;
/**
* 获取所有设备状态
*/
@GetMapping("/devices")
public Result<List<DeviceInfo>> getAllDevices() {
// 返回设备列表及状态
return Result.success();
}
/**
* 控制设备
*/
@PostMapping("/device/{deviceId}/control")
public Result<Boolean> controlDevice(@PathVariable String deviceId,
@RequestBody ControlRequest request) {
boolean success = deviceService.controlDevice(
deviceId,
request.getCommand(),
request.getParams()
);
return Result.success(success);
}
/**
* 激活场景
*/
@PostMapping("/scene/{sceneName}/activate")
public Result<Void> activateScene(@PathVariable String sceneName) {
sceneEngine.activateScene(sceneName);
return Result.success();
}
/**
* 获取能耗报表
*/
@GetMapping("/energy/report")
public Result<EnergyReport> getEnergyReport(@RequestParam String location,
@RequestParam String date) {
EnergyReport report = energyService.getDailyReport(
location,
LocalDate.parse(date)
);
return Result.success(report);
}
/**
* 获取环境数据
*/
@GetMapping("/sensors/data")
public Result<EnvironmentData> getSensorData(@RequestParam String location) {
// 返回实时环境数据(温度、湿度、空气质量等)
return Result.success();
}
}
数据库配置
# application.yml
spring:
datasource:
url: jdbc:mysql://localhost:3306/smart_home?useSSL=false&characterEncoding=utf8
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
redis:
host: localhost
port: 6379
# 用于缓存设备状态、会话管理等
mqtt:
broker: tcp://localhost:1883
client-id: smart-home-server
username: admin
password: admin123
webSocket:
end-point: /ws/device
系统运行演示
public class SmartHomeDemo {
public static void main(String[] args) {
// 初始化Spring容器
ApplicationContext context = new ClassPathXmlApplicationContext(
"applicationContext.xml"
);
DeviceManagerService deviceService =
context.getBean(DeviceManagerService.class);
SceneEngine sceneEngine =
context.getBean(SceneEngine.class);
// 1. 创建设备
SmartLight livingRoomLight = new SmartLight(
"L001", "客厅主灯", "客厅"
);
SmartLight bedroomLight = new SmartLight(
"L002", "卧室床头灯", "卧室"
);
SmartAC ac = new SmartAC("AC001", "中央空调", "客厅");
SmartCurtain curtain = new SmartCurtain("C001", "客厅窗帘", "客厅");
// 2. 注册设备
deviceService.registerDevice(livingRoomLight);
deviceService.registerDevice(bedroomLight);
deviceService.registerDevice(ac);
deviceService.registerDevice(curtain);
// 3. 创建场景
List<SceneAction> homeActions = Arrays.asList(
new SceneAction("L001", CommandType.TURN_ON, new Object[]{60}),
new SceneAction("AC001", CommandType.SET_TEMPERATURE, new Object[]{24}),
new SceneAction("C001", CommandType.TURN_ON, null),
new SceneAction("L002", CommandType.TURN_ON, new Object[]{30})
);
sceneEngine.createScene("回家模式", homeActions);
// 4. 执行场景
sceneEngine.activateScene("回家模式");
// 5. 设备联动测试
System.out.println("--- 测试智能联动 ---");
// 开灯后自动调节场景
deviceService.controlDevice("L001", CommandType.SET_BRIGHTNESS, 80);
// 6. 自动触发规则测试
try {
Thread.sleep(1000);
// 模拟温度升高
SensorData data = new SensorData(28.5, 65, false, true, 10);
SecurityService securityService =
context.getBean(SecurityService.class);
securityService.analyzeSecurityData("客厅", data);
} catch (Exception e) {
e.printStackTrace();
}
// 7. 查询设备信息
System.out.println("--- 设备信息查询 ---");
System.out.println(livingRoomLight.getDeviceInfo());
System.out.println(bedroomLight.getDeviceInfo());
// 8. 能耗统计
EnergyMonitorService energyService =
context.getBean(EnergyMonitorService.class);
energyService.recordEnergy("L001", 20.0, 3600); // 20W运行1小时
energyService.recordEnergy("AC001", 2500.0, 1800); // 2500W运行0.5小时
EnergyReport report = energyService.getDailyReport("客厅", LocalDate.now());
System.out.println("今日能耗: " + report.getTotalEnergy() + " kWh");
}
}
系统特点
核心特性:
- 设备抽象:对不同设备类型实现统一接口
- 场景联动:支持多设备协同工作
- 智能联动:基于传感器数据自动触发场景
- 实时监控:通过WebSocket/MQTT实现双向通信
- 能耗管理:统计和分析设备能耗,提供节能建议
- 安全防护:实时监控异常,自动警报
扩展建议:
- 接入第三方语音助手(Alexa、小爱同学)
- 增加机器学习模块,优化场景推荐
- 支持多用户权限管理
- 添加设备固件升级功能
- 集成天气API,实现室外环境联动
这个案例提供了一个完整的智能家居系统框架,可以根据实际需求进行功能扩展和优化。