鸿蒙语音控制智能灯泡系统开发指南
·
鸿蒙语音控制智能灯泡系统开发指南
一、系统架构设计
基于HarmonyOS的语音交互和分布式能力,我们设计了一套语音控制智能灯泡系统,主要功能包括:
- 语音识别:通过语音指令控制灯泡
- 设备控制:连接并控制智能灯泡设备
- 多设备协同:跨设备同步语音指令和灯泡状态
- 场景模式:支持预设灯光场景
- 定时控制:设置定时开关灯
https://example.com/harmony-smart-light-arch.png
二、核心代码实现
1. 语音交互服务
// VoiceControlService.ets
import voiceInteraction from '@ohos.ai.voiceInteraction';
class VoiceControlService {
private static instance: VoiceControlService;
private voiceAssistant: voiceInteraction.VoiceAssistant;
private isListening: boolean = false;
private constructor() {
this.voiceAssistant = voiceInteraction.createVoiceAssistant();
}
public static getInstance(): VoiceControlService {
if (!VoiceControlService.instance) {
VoiceControlService.instance = new VoiceControlService();
}
return VoiceControlService.instance;
}
public async initVoiceControl(): Promise<void> {
const result = await this.voiceAssistant.init();
if (result !== voiceInteraction.ResultCode.SUCCESS) {
throw new Error('语音助手初始化失败');
}
// 注册语音指令
await this.registerVoiceCommands();
}
private async registerVoiceCommands(): Promise<void> {
const commands = [
{
name: 'turn_on_light',
patterns: ['打开灯', '开灯', '亮灯'],
action: 'turn_on'
},
{
name: 'turn_off_light',
patterns: ['关闭灯', '关灯', '熄灯'],
action: 'turn_off'
},
{
name: 'adjust_brightness',
patterns: ['调亮一点', '调暗一点', '亮度调到50%'],
action: 'adjust_brightness'
},
{
name: 'change_color',
patterns: ['切换颜色', '变成红色', '蓝色灯光'],
action: 'change_color'
}
];
await this.voiceAssistant.setCommands(commands);
// 设置语音回调
this.voiceAssistant.on('command', (command) => {
this.handleVoiceCommand(command);
});
}
public startListening(): void {
if (this.isListening) return;
this.voiceAssistant.startListening();
this.isListening = true;
}
public stopListening(): void {
if (!this.isListening) return;
this.voiceAssistant.stopListening();
this.isListening = false;
}
private handleVoiceCommand(command: voiceInteraction.VoiceCommand): void {
switch (command.action) {
case 'turn_on':
lightControlService.turnOn();
break;
case 'turn_off':
lightControlService.turnOff();
break;
case 'adjust_brightness':
this.handleBrightnessCommand(command.text);
break;
case 'change_color':
this.handleColorCommand(command.text);
break;
default:
console.warn('未知语音指令:', command);
}
// 同步指令到其他设备
voiceSyncService.syncVoiceCommand(command);
}
private handleBrightnessCommand(text: string): void {
let brightness = 50; // 默认值
if (text.includes('亮一点')) {
brightness = lightControlService.getBrightness() + 20;
} else if (text.includes('暗一点')) {
brightness = lightControlService.getBrightness() - 20;
} else {
const match = text.match(/亮度调到(\d+)%/);
if (match) {
brightness = parseInt(match[1]);
}
}
brightness = Math.max(0, Math.min(100, brightness));
lightControlService.setBrightness(brightness);
}
private handleColorCommand(text: string): void {
const colorMap: Record<string, number> = {
'红色': 0xFF0000,
'绿色': 0x00FF00,
'蓝色': 0x0000FF,
'黄色': 0xFFFF00,
'紫色': 0xFF00FF,
'白色': 0xFFFFFF
};
for (const [name, value] of Object.entries(colorMap)) {
if (text.includes(name)) {
lightControlService.setColor(value);
return;
}
}
// 默认切换颜色
lightControlService.nextColor();
}
}
export const voiceControlService = VoiceControlService.getInstance();
2. 灯光控制服务
// LightControlService.ets
import distributedHardware from '@ohos.distributedHardware';
class LightControlService {
private static instance: LightControlService;
private deviceManager: distributedHardware.DeviceManager;
private lightDevice: distributedHardware.Device | null = null;
private lightState: LightState = {
on: false,
brightness: 50,
color: 0xFFFFFF,
mode: 'normal'
};
private constructor() {
this.deviceManager = distributedHardware.createDeviceManager();
}
public static getInstance(): LightControlService {
if (!LightControlService.instance) {
LightControlService.instance = new LightControlService();
}
return LightControlService.instance;
}
public async connectToLight(deviceId: string): Promise<void> {
const devices = await this.deviceManager.getTrustedDeviceList();
const device = devices.find(d => d.deviceId === deviceId);
if (!device) {
throw new Error('设备未找到');
}
this.lightDevice = device;
await this.syncLightState();
}
public turnOn(): void {
this.lightState.on = true;
this.updateLightState();
}
public turnOff(): void {
this.lightState.on = false;
this.updateLightState();
}
public toggle(): void {
this.lightState.on = !this.lightState.on;
this.updateLightState();
}
public setBrightness(value: number): void {
this.lightState.brightness = Math.max(0, Math.min(100, value));
this.updateLightState();
}
public setColor(color: number): void {
this.lightState.color = color;
this.updateLightState();
}
public nextColor(): void {
const colors = [0xFF0000, 0x00FF00, 0x0000FF, 0xFFFF00, 0xFF00FF, 0xFFFFFF];
const currentIndex = colors.indexOf(this.lightState.color);
const nextIndex = (currentIndex + 1) % colors.length;
this.setColor(colors[nextIndex]);
}
public setMode(mode: LightMode): void {
this.lightState.mode = mode;
this.updateLightState();
}
public getState(): LightState {
return { ...this.lightState };
}
private async updateLightState(): Promise<void> {
if (!this.lightDevice) return;
const ability = await featureAbility.startAbility({
bundleName: 'com.example.smartLight',
abilityName: 'LightControlAbility',
deviceId: this.lightDevice.deviceId
});
await ability.call({
method: 'updateLightState',
parameters: [this.lightState]
});
// 同步状态到其他设备
lightSyncService.syncLightState(this.lightState);
}
private async syncLightState(): Promise<void> {
if (!this.lightDevice) return;
const ability = await featureAbility.startAbility({
bundleName: 'com.example.smartLight',
abilityName: 'LightStateAbility',
deviceId: this.lightDevice.deviceId
});
const state = await ability.call({
method: 'getLightState',
parameters: []
});
this.lightState = JSON.parse(state);
}
}
export const lightControlService = LightControlService.getInstance();
3. 多设备同步服务
// LightSyncService.ets
import distributedData from '@ohos.data.distributedData';
class LightSyncService {
private static instance: LightSyncService;
private kvManager: distributedData.KVManager;
private kvStore: distributedData.KVStore;
private constructor() {
this.initKVStore();
}
private async initKVStore(): Promise<void> {
const config = {
bundleName: 'com.example.smartLight',
userInfo: { userId: 'currentUser' }
};
this.kvManager = distributedData.createKVManager(config);
this.kvStore = await this.kvManager.getKVStore('light_sync', {
createIfMissing: true
});
this.kvStore.on('dataChange', (data) => {
this.handleRemoteUpdate(data);
});
}
public static getInstance(): LightSyncService {
if (!LightSyncService.instance) {
LightSyncService.instance = new LightSyncService();
}
return LightSyncService.instance;
}
public async syncLightState(state: LightState): Promise<void> {
await this.kvStore.put('light_state', JSON.stringify(state));
}
public async getLightState(): Promise<LightState | null> {
const value = await this.kvStore.get('light_state');
return value ? JSON.parse(value) : null;
}
public async syncVoiceCommand(command: VoiceCommand): Promise<void> {
await this.kvStore.put(`command_${Date.now()}`, JSON.stringify(command));
}
public async getRecentCommands(): Promise<VoiceCommand[]> {
const entries = await this.kvStore.getEntries('command_');
return Array.from(entries)
.map(([_, value]) => JSON.parse(value))
.sort((a, b) => b.timestamp - a.timestamp);
}
private handleRemoteUpdate(data: distributedData.ChangeInfo): void {
if (data.deviceId === deviceInfo.deviceId) return;
const key = data.key as string;
if (key === 'light_state') {
const state = JSON.parse(data.value);
EventBus.emit('lightStateUpdated', state);
} else if (key.startsWith('command_')) {
const command = JSON.parse(data.value);
EventBus.emit('voiceCommandReceived', command);
}
}
}
export const lightSyncService = LightSyncService.getInstance();
三、主界面实现
1. 灯光控制界面
// LightControlView.ets
@Component
struct LightControlView {
@State lightState: LightState = {
on: false,
brightness: 50,
color: 0xFFFFFF,
mode: 'normal'
};
@State isListening: boolean = false;
@State recentCommands: VoiceCommand[] = [];
aboutToAppear() {
this.loadLightState();
EventBus.on('lightStateUpdated', (state) => {
this.lightState = state;
});
EventBus.on('voiceCommandReceived', (command) => {
this.recentCommands.unshift(command);
});
}
build() {
Column() {
// 灯光状态
Row() {
Text(this.lightState.on ? '开' : '关')
.fontSize(24)
.fontColor(this.lightState.on ? '#4CAF50' : '#F44336')
Text(`亮度: ${this.lightState.brightness}%`)
.fontSize(16)
.margin({ left: 16 })
}
.margin({ top: 16 })
// 灯光颜色预览
Circle()
.width(100)
.height(100)
.backgroundColor(this.getColorHex())
.margin({ top: 16 })
// 控制按钮
Row() {
Button(this.lightState.on ? '关闭' : '打开')
.onClick(() => this.toggleLight())
.width(100)
Button('语音控制')
.onClick(() => this.toggleVoiceControl())
.width(100)
.margin({ left: 16 })
}
.margin({ top: 16 })
// 亮度调节
Text('亮度调节')
.fontSize(16)
.margin({ top: 24 })
Slider({
value: this.lightState.brightness,
min: 0,
max: 100,
step: 1,
style: SliderStyle.SLIDER_OUTSET
})
.onChange((value: number) => this.setBrightness(value))
.width('80%')
.margin({ top: 8 })
// 颜色选择
Text('颜色选择')
.fontSize(16)
.margin({ top: 16 })
Scroll({ scrollable: ScrollDirection.Horizontal }) {
Row() {
ForEach(this.getColorOptions(), (color) => {
Circle()
.width(40)
.height(40)
.backgroundColor(color.hex)
.margin({ right: 8 })
.onClick(() => this.setColor(color.value))
})
}
.padding(8)
}
.height(60)
.margin({ top: 8 })
// 语音指令记录
if (this.recentCommands.length > 0) {
Text('最近指令')
.fontSize(16)
.margin({ top: 24 })
Column() {
ForEach(this.recentCommands.slice(0, 3), (command) => {
Text(`"${command.text}"`)
.fontSize(14)
.padding(8)
.backgroundColor('#F5F5F5')
.borderRadius(4)
.margin({ top: 4 })
})
}
}
// 语音控制状态
if (this.isListening) {
Text('正在聆听...')
.fontSize(14)
.fontColor('#2196F3')
.margin({ top: 8 })
}
}
.padding(16)
}
private async loadLightState(): Promise<void> {
const state = await lightSyncService.getLightState();
if (state) {
this.lightState = state;
}
this.recentCommands = await lightSyncService.getRecentCommands();
}
private toggleLight(): void {
if (this.lightState.on) {
lightControlService.turnOff();
} else {
lightControlService.turnOn();
}
}
private toggleVoiceControl(): void {
if (this.isListening) {
voiceControlService.stopListening();
} else {
voiceControlService.startListening();
}
this.isListening = !this.isListening;
}
private setBrightness(value: number): void {
lightControlService.setBrightness(value);
}
private setColor(color: number): void {
lightControlService.setColor(color);
}
private getColorHex(): string {
const hex = this.lightState.color.toString(16).padStart(6, '0');
return `#${hex}`;
}
private getColorOptions(): { value: number; hex: string }[] {
return [
{ value: 0xFF0000, hex: '#FF0000' },
{ value: 0x00FF00, hex: '#00FF00' },
{ value: 0x0000FF, hex: '#0000FF' },
{ value: 0xFFFF00, hex: '#FFFF00' },
{ value: 0xFF00FF, hex: '#FF00FF' },
{ value: 0xFFFFFF, hex: '#FFFFFF' }
];
}
}
2. 设备管理界面
// DeviceManagementView.ets
@Component
struct DeviceManagementView {
@State devices: SmartDevice[] = [];
@State connectedDevice: SmartDevice | null = null;
aboutToAppear() {
this.loadDevices();
}
build() {
Column() {
Text('设备管理')
.fontSize(24)
.fontWeight(FontWeight.Bold)
.margin({ top: 16 })
if (this.connectedDevice) {
Row() {
Image(this.connectedDevice.icon)
.width(40)
.height(40)
Column() {
Text(this.connectedDevice.name)
.fontSize(18)
Text('已连接')
.fontSize(14)
.fontColor('#4CAF50')
.margin({ top: 4 })
}
.margin({ left: 8 })
}
.alignSelf(ItemAlign.Start)
.margin({ top: 16 })
Button('断开连接')
.onClick(() => this.disconnectDevice())
.margin({ top: 16 })
} else {
Text('未连接设备')
.fontSize(16)
.margin({ top: 32 })
}
Divider()
.margin({ top: 16 })
Text('可用设备')
.fontSize(20)
.margin({ top: 16 })
if (this.devices.length === 0) {
Text('搜索中...')
.fontSize(16)
.margin({ top: 32 })
} else {
List({ space: 10 }) {
ForEach(this.devices, (device) => {
ListItem() {
DeviceItem({ device })
.onClick(() => this.connectDevice(device))
}
})
}
.layoutWeight(1)
}
}
.padding(16)
}
private async loadDevices(): Promise<void> {
this.devices = await deviceService.discoverDevices();
}
private async connectDevice(device: SmartDevice): Promise<void> {
try {
await lightControlService.connectToLight(device.id);
this.connectedDevice = device;
} catch (error) {
console.error('连接设备失败:', error);
}
}
private disconnectDevice(): void {
lightControlService.disconnect();
this.connectedDevice = null;
}
}
@Component
struct DeviceItem {
private device: SmartDevice;
build() {
Row() {
Image(device.icon)
.width(40)
.height(40)
Column() {
Text(device.name)
.fontSize(16)
Text(device.type)
.fontSize(14)
.fontColor('#666666')
.margin({ top: 4 })
}
.margin({ left: 8 })
.layoutWeight(1)
Image('resources/connect.png')
.width(24)
.height(24)
}
.padding(12)
}
}
3. 场景模式界面
// SceneModeView.ets
@Component
struct SceneModeView {
@State scenes: LightScene[] = [];
@State activeScene: string | null = null;
aboutToAppear() {
this.loadScenes();
}
build() {
Column() {
Text('场景模式')
.fontSize(24)
.fontWeight(FontWeight.Bold)
.margin({ top: 16 })
if (this.scenes.length === 0) {
Text('加载中...')
.fontSize(16)
.margin({ top: 32 })
} else {
Grid() {
ForEach(this.scenes, (scene) => {
GridItem() {
SceneItem({
scene,
isActive: this.activeScene === scene.id
})
}
})
}
.columnsTemplate('1fr 1fr')
.rowsGap(16)
.columnsGap(16)
.margin({ top: 16 })
}
}
.padding(16)
}
private async loadScenes(): Promise<void> {
this.scenes = await sceneService.getScenes();
this.activeScene = await sceneService.getActiveScene();
}
private async activateScene(sceneId: string): Promise<void> {
await sceneService.activateScene(sceneId);
this.activeScene = sceneId;
}
}
@Component
struct SceneItem {
private scene: LightScene;
private isActive: boolean;
build() {
Column() {
Image(scene.icon)
.width(60)
.height(60)
Text(scene.name)
.fontSize(16)
.margin({ top: 8 })
if (this.isActive) {
Text('已激活')
.fontSize(12)
.fontColor('#4CAF50')
.margin({ top: 4 })
}
}
.padding(16)
.backgroundColor(this.isActive ? '#E8F5E9' : '#FAFAFA')
.borderRadius(8)
.onClick(() => {
if (!this.isActive) {
sceneService.activateScene(this.scene.id);
}
})
}
}
四、高级功能实现
1. 语音指令同步服务
// VoiceSyncService.ets
import deviceManager from '@ohos.distributedHardware.deviceManager';
class VoiceSyncService {
private static instance: VoiceSyncService;
private constructor() {}
public static getInstance(): VoiceSyncService {
if (!VoiceSyncService.instance) {
VoiceSyncService.instance = new VoiceSyncService();
}
return VoiceSyncService.instance;
}
public async syncVoiceCommandToDevice(deviceId: string, command: VoiceCommand): Promise<void> {
const ability = await featureAbility.startAbility({
bundleName: 'com.example.smartLight',
abilityName: 'VoiceCommandAbility',
deviceId
});
await ability.call({
method: 'receiveVoiceCommand',
parameters: [command]
});
}
public async broadcastVoiceCommand(command: VoiceCommand): Promise<void> {
const devices = await deviceManager.getTrustedDeviceList();
await Promise.all(devices.map(device =>
this.syncVoiceCommandToDevice(device.deviceId, command)
));
}
public async syncAllCommandsToNewDevice(deviceId: string): Promise<void> {
const commands = await lightSyncService.getRecentCommands();
const ability = await featureAbility.startAbility({
bundleName: 'com.example.smartLight',
abilityName: 'CommandSyncAbility',
deviceId
});
await ability.call({
method: 'receiveMultipleCommands',
parameters: [commands]
});
}
}
export const voiceSyncService = VoiceSyncService.getInstance();
2. 定时任务服务
// ScheduleService.ets
import reminderAgent from '@ohos.reminderAgent';
class ScheduleService {
private static instance: ScheduleService;
private constructor() {}
public static getInstance(): ScheduleService {
if (!ScheduleService.instance) {
ScheduleService.instance = new ScheduleService();
}
return ScheduleService.instance;
}
public async scheduleTurnOn(time: string): Promise<void> {
const [hours, minutes] = time.split(':').map(Number);
const now = new Date();
const triggerTime = new Date(
now.getFullYear(),
now.getMonth(),
now.getDate(),
hours,
minutes
);
// 如果时间已过,设置为明天
if (triggerTime.getTime() <= now.getTime()) {
triggerTime.setDate(triggerTime.getDate() + 1);
}
const reminderRequest: reminderAgent.ReminderRequest = {
reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER,
actionButton: [{ title: '取消' }],
wantAgent: {
pkgName: 'com.example.smartLight',
abilityName: 'ScheduleTurnOnAbility'
},
triggerTime: triggerTime.getTime(),
repeatInterval: 24 * 60 * 60 * 1000, // 每天重复
title: '定时开灯',
content: `将在${time}打开灯光`,
expiredContent: "定时任务已执行"
};
await reminderAgent.publishReminder(reminderRequest);
}
public async scheduleTurnOff(time: string): Promise<void> {
const [hours, minutes] = time.split(':').map(Number);
const now = new Date();
const triggerTime = new Date(
now.getFullYear(),
now.getMonth(),
now.getDate(),
hours,
minutes
);
// 如果时间已过,设置为明天
if (triggerTime.getTime() <= now.getTime()) {
triggerTime.setDate(triggerTime.getDate() + 1);
}
const reminderRequest: reminderAgent.ReminderRequest = {
reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER,
actionButton: [{ title: '取消' }],
wantAgent: {
pkgName: 'com.example.smartLight',
abilityName: 'ScheduleTurnOffAbility'
},
triggerTime: triggerTime.getTime(),
repeatInterval: 24 * 60 * 60 * 1000, // 每天重复
title: '定时关灯',
content: `将在${time}关闭灯光`,
expiredContent: "定时任务已执行"
};
await reminderAgent.publishReminder(reminderRequest);
}
public async cancelAllSchedules(): Promise<void> {
const reminders = await reminderAgent.getValidReminders();
await Promise.all(reminders.map(rem =>
reminderAgent.cancelReminder(rem.id)
));
}
public async getScheduledTasks(): Promise<ScheduledTask[]> {
const reminders = await reminderAgent.getValidReminders();
return reminders.map(rem => ({
id: rem.id,
type: rem.title.includes('开灯') ? 'turn_on' : 'turn_off',
time: this.getTimeFromTimestamp(rem.triggerTime),
title: rem.title,
content: rem.content
}));
}
private getTimeFromTimestamp(timestamp: number): string {
const date = new Date(timestamp);
return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
}
}
export const scheduleService = ScheduleService.getInstance();
3. 智能场景服务
// SmartSceneService.ets
class SmartSceneService {
private static instance: SmartSceneService;
private constructor() {}
public static getInstance(): SmartSceneService {
if (!SmartSceneService.instance) {
SmartSceneService.instance = new SmartSceneService();
}
return SmartSceneService.instance;
}
public getDefaultScenes(): LightScene[] {
return [
{
id: 'reading',
name: '阅读模式',
description: '适合阅读的灯光设置',
icon: 'scene_reading.png',
settings: {
brightness: 70,
color: 0xFFFFFF,
mode: 'steady'
}
},
{
id: 'relax',
name: '放松模式',
description: '温馨放松的灯光氛围',
icon: 'scene_relax.png',
settings: {
brightness: 40,
color: 0xFFD700,
mode: 'warm'
}
},
{
id: 'party',
name: '派对模式',
description: '多彩变化的灯光效果',
icon: 'scene_party.png',
settings: {
brightness: 90,
color: 0xFF00FF,
mode: 'dynamic'
}
},
{
id: 'sleep',
name: '睡眠模式',
description: '助眠的柔和灯光',
icon: 'scene_sleep.png',
settings: {
brightness: 10,
color: 0x0000FF,
mode: 'dim'
}
}
];
}
public async activateScene(sceneId: string): Promise<void> {
const scenes = this.getDefaultScenes();
const scene = scenes.find(s => s.id === sceneId);
if (scene) {
await lightControlService.setBrightness(scene.settings.brightness);
await lightControlService.setColor(scene.settings.color);
await lightControlService.setMode(scene.settings.mode);
// 同步场景状态
await sceneStateService.setActiveScene(sceneId);
}
}
public async getActiveScene(): Promise<string | null> {
return sceneStateService.getActiveScene();
}
public async createCustomScene(scene: CustomScene): Promise<void> {
await sceneStateService.saveCustomScene(scene);
}
public async getCustomScenes(): Promise<CustomScene[]> {
return sceneStateService.getCustomScenes();
}
public async deleteCustomScene(sceneId: string): Promise<void> {
await sceneStateService.deleteCustomScene(sceneId);
}
}
export const sceneService = SmartSceneService.getInstance();
五、总结
本语音控制智能灯泡系统实现了以下核心价值:
- 语音控制:支持自然语言指令控制灯光
- 多设备协同:跨设备同步灯光状态和语音指令
- 智能场景:一键切换预设灯光场景
- 定时任务:设置自动开关灯时间
- 远程控制:通过分布式能力远程控制灯泡
扩展方向:
- 增加更多智能家居设备支持
- 开发手势控制功能
- 集成环境光传感器自动调节
- 增加能耗统计功能
注意事项:
1. 需要申请ohos.permission.MICROPHONE权限
2. 语音识别准确率受环境噪音影响
3. 设备连接需在同一局域网
4. 定时任务需保持应用后台运行
5. 首次使用建议完成设备配对更多推荐

所有评论(0)