Published 2 months ago

HarmonyOS Next Smart Home Panel: A Developer's Guide

Software Development
HarmonyOS Next Smart Home Panel: A Developer's Guide

HarmonyOS Next Smart Home Control Panel Development Guide

Building a smart home control panel compatible with various devices and offering intuitive user interaction is crucial in today's rapidly evolving smart home landscape. HarmonyOS Next's powerful capabilities provide the perfect foundation for creating a control panel boasting rich features, a visually appealing interface, and streamlined operation. This guide delves into the development process step-by-step.

UI Design Considerations for Smart Home Applications

Core Function Decomposition: Device Control, Scene Management, Data Display

A smart home control panel's core functionality centers around device control, scene management, and data display. Device control allows users to manage smart devices (lights, sockets, air conditioners, etc.) directly from the panel. Scene management enables users to preset coordinated device actions for various situations (e.g., "Homecoming Mode," "Sleep Mode"). Data display provides real-time information on device status and environmental data (temperature, humidity).

UI Adaptation for Different Screen Sizes: Mobile Phones, Tablets, and Smart Screens

UI design should adapt to the varying screen sizes and interaction methods of different devices.

  • Mobile Phones: Given their smaller screens and touch-based interaction, the UI should be simple and focused on core functions. A bottom tab navigation is ideal for one-handed use, separating functions like Device Control, Scene Management, and Data Display into distinct tabs.
  • Tablets: Tablets' larger screens and greater operating space lend themselves to a dual-column layout. This could display a device list on one side and selected device details on the other.
  • Smart Screens: Large smart screens (often used in living rooms) benefit from a three-column layout: a sidebar for navigation, a central area displaying devices as larger cards, and a right-hand panel for detailed control of selected devices.

Implementing Dynamic Layouts with SideBarContainer, Navigation, and Grid

Large-Screen Devices: Three-Column Mode (Sidebar + Device List + Device Details)

For large screens, a SideBarContainer creates the sidebar, Navigation manages page switching, and Grid arranges the device list. The following code illustrates this:

@Entry
@Component
struct BigScreenPanel {
    @State selectedDevice: string = ''
    @State deviceList: string[] = ['Socket', 'Light', 'Air Conditioner']
    @State deviceDetails: { [key: string]: string } = {
        'Socket': 'Socket Status: On',
        'Light': 'Light Brightness: 50%',
        'Air Conditioner': 'Temperature: 26℃'
    }
    build() {
        SideBarContainer(SideBarContainerType.Embed) {
            // Sidebar
            Column() {
                ForEach(['Device Control', 'Scene Management', 'Data Display'], (item) => {
                    Text(item).fontSize(20).onClick(() => {
                        // Click logic for the sidebar
                    })
                })
            }
              .width('20%')
              .backgroundColor('#F1F3F5')
            Column() {
                // Device List
                GridRow() {
                    ForEach(this.deviceList, (device) => {
                        GridCol({ span: 4 }) {
                            Column() {
                                Text(device).fontSize(18).onClick(() => {
                                    this.selectedDevice = device
                                })
                            }
                              .padding(10)
                              .backgroundColor('#FFFFFF')
                              .borderRadius(10)
                        }
                    })
                }
                // Device Details
                Column() {
                    Text(this.deviceDetails[this.selectedDevice] || '').fontSize(16).padding(10)
                }
            }
              .width('80%')
        }
          .sideBarWidth('20%')
          .showSideBar(true)
    }
}

Small-Screen Devices: Dual-column Mode (Bottom Tab Switching + Device Details Page)

On smaller screens, bottom tabs handle page switching. Navigation manages page transitions, and Grid structures the device details page.

@Entry
@Component
struct SmallScreenPanel {
    @State currentTab: number = 0
    @State selectedDevice: string = ''
    @State deviceList: string[] = ['Socket', 'Light', 'Air Conditioner']
    @State deviceDetails: { [key: string]: string } = {
        'Socket': 'Socket Status: On',
        'Light': 'Light Brightness: 50%',
        'Air Conditioner': 'Temperature: 26℃'
    }
    build() {
        Column() {
            if (this.currentTab === 0) {
                // Device List Page
                GridRow() {
                    ForEach(this.deviceList, (device) => {
                        GridCol({ span: 12 }) {
                            Column() {
                                Text(device).fontSize(18).onClick(() => {
                                    this.selectedDevice = device
                                })
                            }
                              .padding(10)
                              .backgroundColor('#FFFFFF')
                              .borderRadius(10)
                        }
                    })
                }
            } else {
                // Device Details Page
                Column() {
                    Text(this.deviceDetails[this.selectedDevice] || '').fontSize(16).padding(10)
                }
            }
            Tabs({ barPosition: BarPosition.End }) {
                TabContent() {
                    // Device Control Page
                }
                .tabBar(
                    Column() {
                        Image($r('app.media.device_control_icon')).width(24).height(24)
                        Text('Device Control').fontSize(12)
                    }
                  .justifyContent(FlexAlign.Center).height('100%').width('100%')
                )
                TabContent() {
                    // Scene Management Page
                }
                .tabBar(
                    Column() {
                        Image($r('app.media.scene_management_icon')).width(24).height(24)
                        Text('Scene Management').fontSize(12)
                    }
                  .justifyContent(FlexAlign.Center).height('100%').width('100%')
                )
                TabContent() {
                    // Data Display Page
                }
                .tabBar(
                    Column() {
                        Image($r('app.media.data_display_icon')).width(24).height(24)
                        Text('Data Display').fontSize(12)
                    }
                  .justifyContent(FlexAlign.Center).height('100%').width('100%')
                )
            }
              .barMode(BarMode.Fixed)
              .barWidth('100%')
              .barHeight(56)
              .onChange((index: number) => {
                    this.currentTab = index
                })
        }
    }
}

Dynamic Device Card Arrangement with Grid Layout

The Grid layout dynamically adjusts device card arrangement based on screen size. By manipulating the span property of GridCol, different layouts are achieved across breakpoints.

@Entry
@Component
struct GridLayoutForDevices {
    @State currentBreakpoint: string ='sm'
    @State deviceList: string[] = ['Socket', 'Light', 'Air Conditioner']
    build() {
        GridRow({ breakpoints: { value: ['600vp', '840vp'], reference: BreakpointsReference.WindowSize } }) {
            ForEach(this.deviceList, (device) => {
                GridCol({ span: { xs: 12, sm: 12, md: 6, lg: 4 } }) {
                    Column() {
                        Text(device).fontSize(18)
                    }
                      .padding(10)
                      .backgroundColor('#FFFFFF')
                      .borderRadius(10)
                }
            })
        }
          .onBreakpointChange((breakpoint: string) => {
                this.currentBreakpoint = breakpoint
            })
    }
}

This code displays devices in a single column on mobile phones (xs, sm), two columns on tablets (md), and three columns on smart screens (lg).

Optimizing Device Control Interaction

Responsive Breakpoints for Adaptive Window Sizing

Responsive breakpoints and window size listeners ensure optimal layout across various screen sizes. The breakpoints property and onBreakpointChange event of the GridRow component manage this dynamic adjustment.

@Entry
@Component
struct ResponsivePanel {
    @State currentBreakpoint: string ='sm'
    build() {
        GridRow({ breakpoints: { value: ['600vp', '840vp'], reference: BreakpointsReference.WindowSize } }) {
            // Layout content
        }
          .onBreakpointChange((breakpoint: string) => {
                this.currentBreakpoint = breakpoint
            })
    }
}

Component-Based Design for Reusable Smart Device UI

Encapsulating smart device UI components (lights, sockets, etc.) improves efficiency and maintainability. Here's a LightComponent example:

@Component
struct LightComponent {
    @Prop isOn: boolean
    @Prop brightness: number
    @State isEditing: boolean = false
    build() {
        Column() {
            Text('Light').fontSize(18)
            if (this.isEditing) {
                // Editing mode, brightness can be adjusted
                Slider({ value: this.brightness * 100, min: 0, max: 100, style: SliderStyle.OutSet })
                  .blockColor(Color.White)
                  .width('80%')
                  .onChange((value: number) => {
                        // Logic to update brightness
                    })
            } else {
                // Normal mode, display status
                Text(this.isOn? 'On' : 'Off').fontSize(16)
                Text("`Brightness: "+this.brightness * 100+"%").fontSize(14)
            }
            Button(this.isEditing? 'Done' : 'Edit').onClick(() => {
                this.isEditing =!this.isEditing
            })
        }
          .padding(10)
          .backgroundColor('#FFFFFF')
          .borderRadius(10)
    }
}

This component is then easily used in the main panel:

@Entry
@Component
struct MainPanel {
    @State lightIsOn: boolean = true
    @State lightBrightness: number = 0.5
    build() {
        Column() {
            LightComponent({ isOn: this.lightIsOn, brightness: this.lightBrightness })
        }
    }
}

Enhanced Gesture and Remote Control: Sliding, Clicking, and Voice Control

Touch event listeners enable sliding brightness adjustments and click-based on/off switching. HarmonyOS Next's voice recognition capabilities integrate voice control.

@Component
struct InteractiveLightComponent {
    @Prop isOn: boolean
    @Prop brightness: number
    @State isEditing: boolean = false
    build() {
        Column() {
            Text('Light').fontSize(18)
            if (this.isEditing) {
                Slider({ value: this.brightness * 100, min: 0, max: 100, style: SliderStyle.OutSet })
                  .blockColor(Color.White)
                  .width('80%')
                  .onChange((value: number) => {
                        // Logic to update brightness
                    })
            } else {
                Text(this.isOn? 'On' : 'Off').fontSize(16)
                Text("`Brightness: "+this.brightness * 100+"%").fontSize(14)
            }
            Button(this.isEditing? 'Done' : 'Edit').onClick(() => {
                this.isEditing =!this.isEditing
            })
        }
          .padding(10)
          .backgroundColor('#FFFFFF')
          .borderRadius(10)
          .onTouch((event) => {
                if (event.type === TouchType.Swipe) {
                    // Logic to adjust brightness according to the sliding direction
                } else if (event.type === TouchType.Click) {
                    // Logic to switch on/off by clicking
                }
            })
    }
}
import { speech } from '@ohos.speech';

@Entry
@Component
struct VoiceControlledPanel {
    @State lightIsOn: boolean = true
    @State lightBrightness: number = 0.5
    aboutToAppear() {
        speech.init({
            onResult: (result) => {
                if (result.includes('Turn on the light')) {
                    this.lightIsOn = true
                } else if (result.includes('Turn off the light')) {
                    this.lightIsOn = false
                } else if (result.includes('Brighten the light')) {
                    this.lightBrightness = Math.min(1, this.lightBrightness + 0.1)
                } else if (result.includes('Dim the light')) {
                    this.lightBrightness = Math.max(0, this.lightBrightness - 0.1)
                }
            },
            onError: (error) => {
                console.error('Voice recognition error:', error)
            }
        })
        speech.start()
    }
    aboutToDisappear() {
        speech.stop()
    }
    build() {
        Column() {
            InteractiveLightComponent({ isOn: this.lightIsOn, brightness: this.lightBrightness })
        }
    }
}

This approach enables a feature-rich, user-friendly smart home control panel leveraging HarmonyOS Next's capabilities.

Hashtags: #HarmonyOS # SmartHome # UI # Development # ResponsiveDesign # ComponentBased # VoiceControl # GestureControl # Next # Panel

Related Articles

thumb_nail_Unveiling the Haiku License: A Fair Code Revolution

Software Development

Unveiling the Haiku License: A Fair Code Revolution

Dive into the innovative Haiku License, a game-changer in open-source licensing that balances open access with fair compensation for developers. Learn about its features, challenges, and potential to reshape the software development landscape. Explore now!

Read More
thumb_nail_Leetcode - 1. Two Sum

Software Development

Leetcode - 1. Two Sum

Master LeetCode's Two Sum problem! Learn two efficient JavaScript solutions: the optimal hash map approach and a practical two-pointer technique. Improve your coding skills today!

Read More
thumb_nail_The Future of Digital Credentials in 2025: Trends, Challenges, and Opportunities

Business, Software Development

The Future of Digital Credentials in 2025: Trends, Challenges, and Opportunities

Digital credentials are transforming industries in 2025! Learn about blockchain's role, industry adoption trends, privacy enhancements, and the challenges and opportunities shaping this exciting field. Discover how AI and emerging technologies are revolutionizing identity verification and workforce management. Explore the future of digital credentials today!

Read More
Your Job, Your Community
logo
© All rights reserved 2024