Location>code7788 >text

Hongmeng NEXT Development Case: Light Intensity Meter

Popularity:21 ℃/2024-11-13 16:53:41

 

[Introduction]

In this paper, we will introduce how to develop a simple light intensity meter application using the Hongmeng NEXT framework, which is able to monitor the ambient light intensity in real time and give corresponding scene descriptions and activity suggestions.

[Environmental Preparation]

Computer system: windows 10

Development Tools: DevEco Studio NEXT Beta1 Build Version: 5.0.3.806

Engineering version: API 12

The real one: mate60 pro

Languages: ArkTS, ArkUI

[Function realization

1. Project structure

The project consists of the following main components:

  • LightIntensityItem Class: Used to define the light intensity range and its associated information, including the light intensity start value, end value, type, description, and suggested activities. These attributes are initialized through the constructor for subsequent use.
  • LightIntensityMeter Component: This is the core of the light intensity meter and contains functions such as state management, sensor initialization and light intensity update. Component Usage@State Decorator to manage the current light intensity value and type and get the list of sensors when the component is about to appear.
  • Sensor Data Processing: By listening to the data from the ambient light sensor, the current light intensity value is updated in real time and the current type is updated according to the light intensity range. This process ensures that the user has access to the latest ambient light information.

2. Interface layout

The user interface of the Light Intensity Meter utilizes the layout components of the Hongmeng system, which includeColumn cap (a poem)Row. The interface presents the current light intensity value and type and visualizes the light intensity through the meter component. Users can clearly see the changes in light intensity and get corresponding scene descriptions and activity suggestions.

  • Instrumentation components: Used to display the current light intensity value, which is dynamically updated to ensure that the user can see the change in light intensity in real time.
  • Information Display: Shows light intensity ranges, descriptions, and suggested activities for each type by traversing the light intensity range list. This section provides users with practical information to help them make appropriate decisions based on ambient light conditions.

3. Summary

Through this case, developers can learn how to build a fully functional light intensity meter application using sensor services and componentized development approach in Hongmeng system. The application not only monitors light intensity in real time, but also provides practical suggestions based on different light intensity ranges to enhance the user experience.

[complete code]

import { sensor } from '@'; // Importing the Sensor Service Suite
import { BusinessError } from '@'; // Import the business error class

// Define a light intensity item class to store information about different light intensity ranges
class LightIntensityItem {
  luxStart: number; // Starting point of the light intensity range
  luxEnd: number; // Light intensity range endpoints
  type: string; // Type
  description: string; // Scene description
  recommendation: string; // Suggested activities

  // Constructor to initialize object properties
  constructor(luxStart: number, luxEnd: number, type: string, description: string, recommendation: string) {
     = luxStart;
     = luxEnd;
     = type;
     = description;
     = recommendation;
  }
}

// Use the decorator to define the component, which is the light intensity meter
@Entry
@Component
struct LightIntensityMeter {
  @State currentType: string = ""; // Current light intensity type
  @State currentIntensity: number = 0; // Current light intensity value
  @State lightIntensityList: LightIntensityItem[] = [// List of different light intensity ranges
    new LightIntensityItem(0, 1, 'Extreme Darkness', 'Outdoors at night, with almost no light sources.', 'Not suitable for any activity, suitable for complete rest.'),
    new LightIntensityItem(1, 10, 'It's dark', 'Indoors at night, with only a faint light or moonlight.', 'For sleeping only, avoid electronic devices.'),
    new LightIntensityItem(10, 50, 'Dark', 'Early in the morning or late in the evening, when natural light is weak.', 'Easy and casual, avoiding long reads and suitable for relaxation.'),
    new LightIntensityItem(50, 100, 'Darker', 'The day is cloudy and the room is softly lit.', 'Everyday life, short readings for light activities.'),
    new LightIntensityItem(100, 300, 'Moderate', 'Cloudy during the day and moderately light indoors.', 'Work-study, moderate reading, suitable for most indoor activities.'),
    new LightIntensityItem(300, 500, 'Brighter', 'The day is clear and the room is well lit.', 'Normal work and study, long hours of reading, suitable for most activities.'),
    new LightIntensityItem(500, 1000, 'Bright', 'Outside on a cloudy day with more natural light.', 'Outdoor activities, take care of the sun, suitable for outdoor recreation.'),
    new LightIntensityItem(1000, 100000, 'Bursting the meter', 'Direct sunlight at midday in summer and extremely strong natural light.',
      'Avoid looking directly into the sun if possible, wear sunglasses for outdoor activities and take care of sun protection.'),
  ];

  // Methods called when a component is about to appear
  aboutToAppear(): void {
    ((error: BusinessError) => { // Get a list of sensors
      if (error) { // If there is an error
        ('Failed to get sensor list', error); // Print the error message
        return;
      }
      (); // start listening for light intensity changes if there are no errors
    });
  }

  // Start listening to the ambient light sensor
  private startLightIntensityUpdates(): void {
    (.AMBIENT_LIGHT, (data) => { // Listen to the ambient light sensor
      (`: ${}`); // Print the light intensity value
       = ; // Update the current light intensity value
      for (const item of ) { // Iterate through the list of light intensities
        if ( >=  &&  <= ) { // Determine in which range the current light intensity falls
           = ; // Update current light intensity type
          break;
        }
      }
    }, { interval: 10000000 }); // Set sensor update interval in nanoseconds (10,000,000 nanoseconds = 1 second)
  }

  // Component building methods
  build() {
    Column() { // Create a vertical layout container
      Text("Light Intensity Meter")// Display title
        .width('100%')// Set the width to 100%
        .height(44)// Set the height to 44
        .backgroundColor("#fe9900")// set the background color
        .textAlign()// Set text alignment to center
        .fontColor(); // Set the font color to white

      Row() { // Create a horizontal layout container
        Gauge({
          // Create a gauge component
          value:  > 1000 ? 1000 : , // Setting the meter value
          min: 0, // Minimum value
          max: 1000 // Maximum value
        }) { // Layout of the instrument interior
          Column() { // Create a vertical layout container
            Text(`${()}`)// Displays the current light intensity value
              .fontSize(25)// Setting the font size
              .fontWeight()// Set the font thickness
              .fontColor("#323232")// Setting the font color
              .height('30%')// Set the height to 30% of the parent container
              .textAlign()// Set text alignment to center
              .margin({ top: '22.2%' })// Set the top margin
              .textOverflow({ overflow:  })// Set up text overflow handling
              .maxLines(1); // Set the maximum number of rows to 1

            Text(`${}`)// Displays the current light intensity type
              .fontSize(16)// Setting the font size
              .fontColor("#848484")// set the font color
              .fontWeight()// Set the font thickness
              .width('47.4%')// set the width to 47.4% of the parent container
              .height('15%')// Set the height to 15% of the parent container
              .textAlign()// Set text alignment to center
              .backgroundColor("#e4e4e4")// set the background color
              .borderRadius(5); // Set the radius of the fillet
          }.width('100%'); // Set the column width to 100%
        }
        .startAngle(225) // Set the instrument start angle
        .endAngle(135) // Setting the meter end angle
        .height(250) // Set the meter height
        .strokeWidth(18) // Set the gauge border width
        .description(null) // Set the description to null
        .trackShadow({ radius: 7, offsetX: 7, offsetY: 7 }) // Setting up shadow effects
        .padding({ top: 30 }); // Setting the inner margins
      }.width('100%').justifyContent(); // Set the row width to 100% and center it.

      Column() { // Create a vertical layout container
        ForEach(, (item: LightIntensityItem, index: number) => { // Traverse the array of light intensity types
          Row() { // Create a horizontal layout container
            Text(`${}~${}Lux `)// Displays the range of light intensities for each type
              .fontSize('25lpx')// Setting the font size
              .textAlign()// Set text alignment to left justified
              .fontColor("#3d3d3d3d")// set the font color
              .width('220lpx') // Set the width

            Text(`${}\n${}`)// Show descriptions and suggested activities for each type
              .fontSize('23lpx')// Setting the font size
              .textAlign()// Set text alignment to left justified
              .fontColor("#3d3d3d3d")// set the font color
              .layoutWeight(1) // Setting Layout Weights
          }.width('660lpx') // Set the row width
          .padding({ bottom: 10, top: 10 }) // Set the top and bottom inner margins
          .borderWidth({ bottom: 1 }) // Set the width of the bottom border
          .borderColor("#737977"); // set the lower border color
        });
      }.width('100%'); // Set the column width to 100%
    }
    .height('100%') // Set the container height to 100%
    .width('100%'); // Set the container width to 100%
  }
}