# Zepp OS API Reference --- > Complete API reference for Zepp OS development. This file is optimized for AI/LLM consumption. --- > For the interactive version, visit https://docs.zepp.com/docs/ --- # @zos/alarm ## Constants | Constant | Description | API_LEVEL | |----------|-------------|-----------| | `REPEAT_ONCE` | Repeat once | 3.0 | | `REPEAT_MINUTE` | Specify the repetition period as minute | 3.0 | | `REPEAT_HOUR` | Specify the repetition period as hour | 3.0 | | `REPEAT_DAY` | Specify the repetition period as day | 3.0 | | `REPEAT_WEEK` | Specify the repetition period as week | 3.0 | | `REPEAT_MONTH` | Specify the repetition period as month | 3.0 | | `REPEAT_YEAR` | Specify the repetition period as year | 3.0 | | `WEEK_MON` | Monday | 3.0 | | `WEEK_TUE` | Tuesday | 3.0 | | `WEEK_WED` | Wednesday | 3.0 | | `WEEK_THU` | Thursday | 3.0 | | `WEEK_FRI` | Friday | 3.0 | | `WEEK_SAT` | Saturday | 3.0 | | `WEEK_SUN` | Sunday | 3.0 | ## cancel ### Import ```js import { cancel } from '@zos/alarm' ``` ### Typings - Description: Cancels the set timer, if the timer is set to persist and also cancels the persistence - API_LEVEL: 3.0 - Permission: `device:os.alarm` - Example: ```js import { cancel } from '@zos/alarm' cancel(id) ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Cancels the set timer, if the timer is set to persist and also cancels the persistence. > **ℹ️ Info** > > permission code: `device:os.alarm` ## Type ```ts function cancel(option: Option): Result ``` ### Simplified calling method ```ts function cancel(id: number): Result ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | ------------------- | -------- | ------------ | ------------------------------------- | --------- | | id | `number` | Y | - | Vertical axis coordinates of the page | 3.0 | ### Result | Type | Description | | ------------------- | ---------------------------------------- | | `number` | If `0` is returned, success is indicated | ## Example ```js cancel(id) ``` --- ## getAllAlarms ### Import ```js import { getAllAlarms } from '@zos/alarm' ``` ### Typings - Description: Get an array of all created timers alarmId for the current Mini Program, including timers that support persistence - API_LEVEL: 3.0 - Permission: `device:os.alarm` - Example: ```js import { getAllAlarms } from '@zos/alarm' getAllAlarms() ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Get an array of all created timers alarmId for the current Mini Program, including timers that support persistence. > **ℹ️ Info** > > permission code: `device:os.alarm` ## Type ```ts function getAllAlarms(): Array ``` ## Example ```js getAllAlarms() ``` --- ## set ### Import ```js import { set, REPEAT_DAY } from '@zos/alarm' ``` ### Typings - Description: Support for persistent timers to wake up pages of Mini Program - API_LEVEL: 3.0 - Permission: `device:os.alarm` - Constants: `alarm_repeat`, `alarm_week` - Example: ```js // At a certain time each day import { set, REPEAT_DAY } from '@zos/alarm' const option = { url: 'pages/index.js', time: 12345678, repeat_type: REPEAT_DAY } const id = set(option) // Every Monday and Wednesday import { set, REPEAT_WEEK, WEEK_MON, WEEK_WED } from '@zos/alarm' const option = { url: 'pages/index.js', time: 12345678, repeat_type: REPEAT_WEEK, week_days: WEEK_MON| WEEK_WED } const id = set(option) // Reminder every 21 days import { set, REPEAT_DAY } from '@zos/alarm' const option = { url: 'pages/index.js', time: 12345678, repeat_type: REPEAT_DAY, repeat_period: 20, repeat_duration: 1, } const id = set(option) ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Support for persistent timers to wake up pages of Mini Program. > **ℹ️ Info** > > permission code: `device:os.alarm` ## Type ```ts function set(option: Option): Result ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | --------------- | -------------------- | -------- | -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | | appid | `number` | N | - | App ID of the Mini Program, default current Mini Program ID | 3.0 | | url | `string` | Y | - | File path to wake up Mini Program, supporting App Service | 3.0 | | time | `number` | N | - | Timer execution time, UTC timestamp, in seconds, this field has higher priority than `delay`, each call must pass one of the `time` and `delay` parameter | 3.0 | | delay | `number` | N | - | How many seconds of delay based on the current time after the execution, in seconds. Each call must pass one of the `time` and `delay` parameter | 3.0 | | param | `string` | N | - | The argument passed to the app.js lifecycle `onCreate` | 3.0 | | store | `boolean` | N | `false` | Does the timer need persistent storage (can still be executed successfully after device reboot) | 3.0 | | repeat_type | `number` | N | - | Timer repetition type, refer to timer periodic repetition constants | 3.0 | | repeat_period | `number` | N | `REPEAT_MINUTE` | Effective when `repeat_type` is set to `REPEAT_MINUTE`, `REPEAT_HOUR`, `REPEAT_DAY`, used in conjunction with repeat_duration to set a repeat period, one repeat period in the current `repeat_type`, containing `repeat_period` times, and `repeat_duration` times before the reminder | 3.0 | | repeat_duration | `number` | N | `1` | When `repeat_type` is set to `REPEAT_MINUTE`, `REPEAT_HOUR`, `REPEAT_DAY`, the number of reminders in a period of the timer, used with `repeat_duration`, a period of the current `repeat_type`, including repeat_period times, `repeat_duration` times before the reminder | 3.0 | | week_days | `number` | N | - | Effective when `repeat_type` is `REPEAT_WEEK`, you can customize which days of the week are repeated, refer to the timer week constants | 3.0 | | start_time | `number` | N | - | The time when the repeat reminder starts, in UTC seconds, and the repeat reminder only takes effect during the repeat time period | 3.0 | | end_time | `number` | N | - | The time when the repeat reminder ends, in UTC seconds, and the repeat reminder only takes effect during the repeat time period | 3.0 | ### Result | Type | Description | | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `number` | The id returned by the timer creation, `0` is an invalid ID, which means the timer creation failed, and the ID remains the same after the system restart for timers that support persistence | ## Constants ### Timer repeats constants | Constant | Description | API_LEVEL | | --------------- | --------------------------------------- | --------- | | `REPEAT_ONCE` | Repeat once | 3.0 | | `REPEAT_MINUTE` | Specify the repetition period as minute | 3.0 | | `REPEAT_HOUR` | Specify the repetition period as hour | 3.0 | | `REPEAT_DAY` | Specify the repetition period as day | 3.0 | | `REPEAT_WEEK` | Specify the repetition period as week | 3.0 | | `REPEAT_MONTH` | Specify the repetition period as month | 3.0 | | `REPEAT_YEAR` | Specify the repetition period as year | 3.0 | ### Timer weekly constants | Constant | Description | API_LEVEL | | ---------- | ----------- | --------- | | `WEEK_MON` | Monday | 3.0 | | `WEEK_TUE` | Tuesday | 3.0 | | `WEEK_WED` | Wednesday | 3.0 | | `WEEK_THU` | Thursday | 3.0 | | `WEEK_FRI` | Friday | 3.0 | | `WEEK_SAT` | Saturday | 3.0 | | `WEEK_SUN` | Sunday | 3.0 | ## Example ```js // At a certain time each day const option = { url: 'pages/index.js', time: 12345678, repeat_type: REPEAT_DAY, } const id = set(option) // Every Monday and Wednesday const option = { url: 'pages/index.js', time: 12345678, repeat_type: REPEAT_WEEK, week_days: WEEK_MON | WEEK_WED, } const id = set(option) // Reminder every 21 days const option = { url: 'pages/index.js', time: 12345678, repeat_type: REPEAT_DAY, repeat_period: 20, repeat_duration: 1, } const id = set(option) ``` --- --- # @zos/app-access ## getSportData ### Import ```js import { getSportData } from '@zos/app-access' ``` ### Typings - Description: By default, the system will off the screen in one page of the Mini Program, and the system will exit the Mini Program after 10s, and enter the dial page when the watch is woken up again. If `relaunch` is set to `true`, the Mini Program will reopen and enter the corresponding page when the watch is woken up again - API_LEVEL: 3.6 - Permission: `data:user.hd.workout` - Example: ```js import { getSportData } from '@zos/app-access' const result = getSportData({ type: 'distance', }, (callbackResult) => { const { code, data } = callbackResult if (code === 0) { const [{ distance }] = JSON.parse(data) console.log(distance) } }) ``` > Start from API_LEVEL `3.6` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). By default, the system will off the screen in one page of the Mini Program, and the system will exit the Mini Program after 10s, and enter the dial page when the watch is woken up again. If `relaunch` is set to `true`, the Mini Program will reopen and enter the corresponding page when the watch is woken up again. > **ℹ️ Info** > > permission code: `data:user.hd.workout` ## Type ```ts function getSportData(options: Options, callback: (callbackResult: CallbackResult) => void): Result ``` ## Parameters ### Options | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | ------------------- | -------- | ------------ | ---------------------------------------------- | --------- | | type | `string` | Y | - | Sports type, refer to the value of `SportType` | 3.6 | ### CallbackResult | Property | Type | Description | API_LEVEL | | -------- | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | | code | `number` | Result status code, `0` means success, non- `0` means failure | 3.6 | | data | `string` | Sports data, return value type is string, needs to be parsed using `JSON.parse`, the parsed type is `Array`, the specific type of `object` can be referred to the `SportType` type description below, and the return value corresponding to each `type` is different | 3.6 | ### Result | Type | Description | | -------------------- | --------------------------------------------------------------------------------- | | `boolean` | If it returns `true`, it means the call was successful, otherwise the call failed | ### SportType | Value | Type | Description | API_LEVEL | | ----------------------- | ------------------- | --------------------------------------------------------------------------------------------------------------------------- | --------- | | speed | `object` | Speed, example return value `{"speed": "9.99", "name": "Speed"}` | 3.6 | | avg_speed | `object` | Average speed, example return value `{"avg_speed": "9.99", "name": "Average Speed"}` | 3.6 | | pace | `object` | Pace, example return value `{"avg_pace": "1' 12" "," name ":" Average Pace "}` | 3.6 | | avg_pace | `object` | Average pace, example return value `{"avg_pace": "1'12'", "name": "Average Pace"}` | 3.6 | | distance | `object` | Distance, example return value `{"distance": "9.99", "name": "Distance"}` | 3.6 | | duration | `object` | Time duration of workout, example return value `{"duration":"1:15:15", "name": "Duration"}` | 3.6 | | calories | `object` | Consumption, example return value `{"calories": "9.99", "name": "Calories"}` | 3.6 | | cadence | `object` | Cadence/cadence, example return value `{"cadence": "9.99", "name": "Cadence"}` | 3.6 | | avg_cadence | `object` | Average cadence, example return value `{"avg_cadence": "9.99", "name": "Average Cadence"}` | 3.6 | | altitude | `object` | Altitude, example return value `{"altitude": "9.99", "name": "Elevation"}` | 3.6 | | total_up_altitude | `object` | Accumulated elevation, example return value `{"total_up_altitude": "9.99", "name": "Total Ascent"}` | 3.6 | | total_count | `object` | Total count, example return value `{"total_count": "9.99", "name": "Total count"}` | 3.6 | | vertical_speed | `object` | Vertical Speed, example return value `{"vertical_speed": "9.99", "name": "Vertical Speed"}` | 3.6 | | downhill_count | `object` | Number of downhills, example return value `{"downhill_count": "9.99", "name": "Downhills"}` | 3.6 | | total_downhill_distance | `object` | Cumulative downhill distance, example return value `{"total_downhill_distance": "9.99", "name": "Total Downhill Distance"}` | 3.6 | ## Example ```js const result = getSportData( { type: 'distance', }, (callbackResult) => { const { code, data } = callbackResult if (code === 0) { const [{ distance }] = JSON.parse(data) console.log(distance) } }, ) ``` --- --- # @zos/app-service ## exit ### Import ```js import { exit } from '@zos/app-service' ``` ### Typings - Description: Called in The App Service, it will exit the service and will not affect the foreground page - API_LEVEL: 3.0 - Permission: `device:os.bg_service` - Example: ```js import { exit } from '@zos/app-service' exit() ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Called in The App Service, it will exit the service and will not affect the foreground page. > **ℹ️ Info** > > permission code: `device:os.bg_service` ## Type ```ts function exit(): void ``` ## Example ```js exit() ``` --- ## getAllAppServices ### Import ```js import { getAllAppServices } from '@zos/app-service' ``` ### Typings - Description: Get the list of running App services, used to query the service status - API_LEVEL: 3.0 - Permission: `device:os.bg_service` - Example: ```js import { getAllAppServices } from '@zos/app-service' const serviceList = getAllAppServices() console.log(serviceList) ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Get the list of running App services, used to query the service status. > **ℹ️ Info** > > permission code: `device:os.bg_service` ## Type ```ts function getAllAppServices(): Result ``` ## Parameters ### Result | Type | Description | | ---------------------------------- | ---------------------------------------------- | | `Array` | Get the list of currently running App services | ## Example ```js const serviceList = getAllAppServices() console.log(serviceList) ``` --- ## start ### Import ```js import { start } from '@zos/app-service' ``` ### Typings - Description: Start the specified App service, return the result through the callback function - API_LEVEL: 3.0 - Permission: `device:os.bg_service` - Example: ```js import { start } from '@zos/app-service' ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Start the specified App service, return the result through the callback function. > **ℹ️ Info** > > permission code: `device:os.bg_service` ## Type ```ts function start(option: Option): Result ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | ------------- | --------------------------------------------------------- | -------- | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | | file | `string` | Y | - | The App Service js file must be the one configured in the module app-service in app.json | 3.0 | | param | `string` | N | - | Parameters passed in when the js file is loaded by the backend service | 3.0 | | complete_func | `(callbackOption: CallbackOption) => void` | Y | - | Callback function for the completion of the backend service start | 3.0 | | reload | `boolean` | N | `true` | Whether to persist and automatically restart following system running state changes. System state changes include: system restart, power saving mode entry/exit, system language changes, Mini Program updates, etc. | 4.0 | ### CallbackOption | Property | Type | Description | API_LEVEL | | -------- | -------------------- | --------------------------------------------------------------------- | --------- | | file | `string` | App service js file, same as `start` incoming parameters | 3.0 | | result | `boolean` | App service start result, `true` means success, `false` means failure | 3.0 | ### Result | Type | Description | | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `boolean` | If the return value is `0`, it indicates that the device application service has been successfully started; for the meanings of other values, refer to ERROR_CODE | ### ERROR_CODE | Value | Type | Description | API_LEVEL | | ----- | ------------------- | --------------------------------------------------- | --------- | | 0 | `number` | Success | 3.0 | | 1 | `number` | Parameter error | 3.0 | | 2 | `number` | Service Status Error | 3.0 | | 3 | `number` | No Permission | 3.0 | | 4 | `number` | Out Of Memory | 3.0 | | 5 | `number` | Not Supported | 3.0 | | 6 | `number` | Prohibited | 3.0 | | 7 | `number` | The number of services has reached the system limit | 3.0 | | 255 | `number` | Unknown Error | 3.0 | ## Example ```js ``` --- ## stop ### Import ```js import { stop } from '@zos/app-service' ``` ### Typings - Description: Shutdown the specified backend service, called asynchronously, with the shutdown result returned via a callback function - API_LEVEL: 3.0 - Permission: `device:os.bg_service` - Example: ```js import { stop } from '@zos/app-service' ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Shutdown the specified backend service, called asynchronously, with the shutdown result returned via a callback function. > **ℹ️ Info** > > permission code: `device:os.bg_service` ## Type ```ts function stop(option: Option): Result ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | ------------- | --------------------------------------------------------- | -------- | ------------ | ------------------------------------------------------------------------------------ | --------- | | file | `string` | Y | - | The App Service js file must be the one configured in the service module in app.json | 3.0 | | complete_func | `(callbackOption: CallbackOption) => void` | Y | - | Callback function for the completion of the backend service stop | 3.0 | ### CallbackOption | Property | Type | Description | API_LEVEL | | -------- | -------------------- | -------------------------------------------------------------------- | --------- | | file | `string` | App service js file, same as `stop` incoming parameters | 3.0 | | result | `boolean` | App service stop result, `true` means success, `false` means failure | 3.0 | ### Result | Type | Description | | -------------------- | ---------------------------------------------------------- | | `boolean` | If `0` is returned, The App Service is closed successfully | ## Example ```js ``` --- --- # @zos/app ## Constants | Constant | Description | API_LEVEL | |----------|-------------|-----------| | `SCENE_APP` | In Mini Program | — | | `SCENE_WATCHFACE` | In watchface interface | — | | `SCENE_SETTINGS` | In the Mini Program configuration or dial edit page | — | | `SCENE_AOD` | In the rest screen screen | — | ## emitCustomSystemEvent ### Import ```js import { emitCustomSystemEvent } from '@zos/app' ``` ### Typings - Description: The Mini Program can customize the system events and can actively dispatch the custom system events - API_LEVEL: 3.0 - Example: ```js import { emitCustomSystemEvent } from '@zos/app' emitCustomSystemEvent({ eventName: 'event:customize.test', eventParam: 'eventName=event:customize.test&type=0' }) ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). The Mini Program can customize the system events and can actively dispatch the custom system events. ## Type ```ts function emitCustomSystemEvent(option: Option): void ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | ---------- | ------------------- | -------- | ------------ | -------------------------------------------------------------------------------------------------------------------- | --------- | | eventName | `string` | Y | - | Customize event names that meet the naming convention of `event:customize.${event}` | 3.0 | | eventParam | `string` | Y | - | Custom event parameters, this parameter is passed to the `onInit` lifecycle function of the `AppService` constructor | 3.0 | ## Example ```js emitCustomSystemEvent({ eventName: 'event:customize.test', eventParam: 'eventName=event:customize.test&type=0', }) ``` --- ## getPackageInfo ### Import ```js import { getPackageInfo } from '@zos/app' ``` ### Typings - Description: Get some of the fields in the Mini Program configuration `app.json` - Example: ```js import { getPackageInfo } from '@zos/app' const packageInfo = getPackageInfo() console.log(packageInfo.name) ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Get some of the fields in the Mini Program configuration `app.json`. ## Type ```ts function getPackageInfo(): Result ``` ## Parameters ### Result | Type | Description | | ------------------- | ---------------------------------------------------- | | `object` | Please see the fields in `app.json` for more details | ## Example ```js const packageInfo = getPackageInfo() console.log(packageInfo.name) ``` --- ## getPackageInfoById ### Import ```js import { getPackageInfoById } from '@zos/app' ``` ### Typings - Description: Get some of the fields in the Mini Program configuration `app.json` by app ID - API_LEVEL: 4.0 - Example: ```js import { getPackageInfoById } from '@zos/app' const packageInfo = getPackageInfoById({ appId: 1001 }) console.log(packageInfo.name) ``` > Start from API_LEVEL `4.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Get some of the fields in the Mini Program configuration `app.json` by app ID. ## Type ```ts function getPackageInfoById(option: Option): Result ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | ------------------- | -------- | ------------ | --------------- | --------- | | appId | `number` | Y | - | Mini Program ID | 4.0 | ### Result | Type | Description | | ------------------- | ---------------------------------------------------- | | `object` | Please see the fields in `app.json` for more details | ## Example ```js const packageInfo = getPackageInfoById({ appId: 1001 }) console.log(packageInfo.name) ``` --- ## getPerformance ### Import ```js import { getPerformance } from '@zos/app' ``` ### Typings - Description: Get Mini Program performance statistics, including memory usage and loading performance metrics - API_LEVEL: 4.0 - Example: ```js import { getPerformance } from '@zos/app' // Get memory info only const memoryProfile = getPerformance('memory') // Get both memory and performance info const fullProfile = getPerformance('memory', 'perf') ``` > Start from API_LEVEL `4.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Get Mini Program performance statistics, including memory usage and loading performance metrics. ## Type ```ts function getPerformance(...args: Array<'memory' | 'perf'>): Result ``` ## Parameters ### Result | Property | Type | Description | API_LEVEL | | -------- | ------------------- | ---------------------- | --------- | | memory | `Memory` | Memory statistics | 4.0 | | perf | `Perf` | Performance statistics | 4.0 | ### Memory | Property | Type | Description | API_LEVEL | | -------- | ----------------------------------------- | ----------------------------------- | --------- | | system | `SystemMemory` | system memory information | 4.0 | | app | `Array` | Application memory information list | 4.0 | | leaking | `Array` | Unreleased memory information list | 4.0 | ### SystemMemory | Property | Type | Description | API_LEVEL | | -------- | ------------------- | -------------------- | --------- | | used | `number` | Used memory (bytes) | 4.0 | | total | `number` | Total memory (bytes) | 4.0 | ### AppMemory | Property | Type | Description | API_LEVEL | | -------- | ---------------------------------------- | ------------------------- | --------- | | appid | `number` | Mini Program ID | 4.0 | | used | `number` | Memory usage (bytes) | 4.0 | | peak | `number` | Peak memory usage (bytes) | 4.0 | | modules | `Array` | Module memory information | 4.0 | ### LeakingMemory | Property | Type | Description | API_LEVEL | | -------- | ---------------------------------------- | ------------------------- | --------- | | appid | `number` | Mini Program ID | 4.0 | | used | `number` | Memory usage (bytes) | 4.0 | | modules | `Array` | Module memory information | 4.0 | ### MemoryModule | Property | Type | Description | API_LEVEL | | -------- | ------------------- | ------------------------- | --------- | | file | `string` | File path | 4.0 | | used | `number` | Memory usage (bytes) | 4.0 | | peak | `number` | Peak memory usage (bytes) | 4.0 | ### Perf | Property | Type | Description | API_LEVEL | | -------- | -------------------------------------- | ----------------------------------- | --------- | | appid | `number` | Mini Program ID | 4.0 | | modules | `Array` | Module performance information list | 4.0 | ### PerfModule | Property | Type | Description | API_LEVEL | | ---------- | ------------------- | ------------------------------------------------------------------ | --------- | | file | `string` | File name | 4.0 | | evalTime | `number` | File reading and running time (excluding lifecycle execution time) | 4.0 | | createTime | `number` | onCreate lifecycle execution time | 4.0 | | initTime | `number` | onInit lifecycle execution time | 4.0 | | buildTime | `number` | build lifecycle execution time | 4.0 | ## Example ```js // Get memory info only const memoryProfile = getPerformance('memory') // Get both memory and performance info const fullProfile = getPerformance('memory', 'perf') ``` --- ## getScene ### Import ```js import { getScene, SCENE_APP } from '@zos/app' ``` ### Typings - Description: Get the current scene where the Mini Program is running - Constants: `scene` - Example: ```js import { getScene, SCENE_APP } from '@zos/app' const result = getScene() if (result === SCENE_APP) { console.log('in Mini Program') } ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Get the current scene where the Mini Program is running. ## Type ```ts function getScene(): Result ``` ## Parameters ### Result | Type | Description | | ------------------- | --------------------------------------------------------------------------------------- | | `number` | The current scene in which the Mini Program is running, value reference scene constants | ## Constants ### Current scene running Mini Program constants | Constant | Description | API_LEVEL | | ----------------- | --------------------------------------------------- | --------- | | `SCENE_APP` | In Mini Program | 2.0 | | `SCENE_WATCHFACE` | In watchface interface | 2.0 | | `SCENE_SETTINGS` | In the Mini Program configuration or dial edit page | 2.0 | | `SCENE_AOD` | In the rest screen screen | 2.0 | ## Example ```js const result = getScene() if (result === SCENE_APP) { console.log('in Mini Program') } ``` --- ## queryPermission ### Import ```js import { queryPermission } from '@zos/app' ``` ### Typings - Description: Check the authorization status of Mini Program permissions - API_LEVEL: 3.0 - Example: ```js import { queryPermission } from '@zos/app' const result = queryPermission() console.log(result) ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Check the authorization status of Mini Program permissions. ## Type ```ts function queryPermission(option: Option): Result ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | ----------- | ---------------------------------- | -------- | ------------ | -------------------------------------------------------------------- | --------- | | permissions | `Array` | Y | - | An array of permission strings, with an array length of at least `1` | 3.0 | ### Result | Type | Description | | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | | `Array` | Permissions query result array, corresponding to the order of `permissions` array, `0`: not authorized, `1`: unknown permissions, `2`: authorized | ## Example ```js const result = queryPermission() console.log(result) ``` --- ## requestPermission ### Import ```js import { requestPermission } from '@zos/app' ``` ### Typings - Description: Dynamic permission application, when querying a dynamic permission has not been authorized, you can use this interface to apply for the relevant permission. Generally, before using the system-related functional interface (such as the interface to enable app services), do the relevant permission check and application, otherwise the functional interface will not be allowed to execute due to the permission issue - API_LEVEL: 3.0 - Example: ```js import { requestPermission } from '@zos/app' const result = requestPermission({ permissions: ['device:os.bg_service'], callback: (result) => { console.log(result) } }) console.log(result) ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Dynamic permission application, when querying a dynamic permission has not been authorized, you can use this interface to apply for the relevant permission. Generally, before using the system-related functional interface (such as the interface to enable app services), do the relevant permission check and application, otherwise the functional interface will not be allowed to execute due to the permission issue. ## Type ```ts function requestPermission(option: Option): Result ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | ----------- | -------------------------------------------------------- | -------- | ------------ | -------------------------------------------------------------------- | --------- | | permissions | `Array` | Y | - | An array of permission strings, with an array length of at least `1` | 3.0 | | callback | `(result: Array) => void` | Y | - | Permission request result callback function | 3.0 | ### Result | Type | Description | | ------------------- | --------------------------------------------------- | | `number` | Method result value. See 'result' for a description | ### result | Value | Type | Description | API_LEVEL | | ----- | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | | 0 | `number` | In authorization processing, user interaction will be triggered, and the user will be informed of the authorization result in the callback function | 3.0 | | 1 | `number` | There are no authorization requests that can be made | 3.0 | | 2 | `number` | The requested interface is authorized and can be called immediately | 3.0 | ## Example ```js const result = requestPermission({ permissions: ['device:os.bg_service'], callback: (result) => { console.log(result) }, }) console.log(result) ``` --- --- # @zos/ble ## addListener ### Import ```js import { addListener } from '@zos/ble' ``` ### Typings - Description: Registering connection status listening callback function - Example: ```js import { addListener } from '@zos/ble' // ... ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Registering connection status listening callback function. ## Type ```ts function addListener(callback: Callback): void ``` ## Parameters ### Callback | Type | Description | | ------------------------------------------- | -------------------------------------------------------- | | `(status?: boolean) => void` | Connection callback function, `status` Connection status | ## Example ```js // ... ``` --- ## connectStatus ### Import ```js import { connectStatus } from '@zos/ble' ``` ### Typings - Description: Query connection status, `true` means connected, `false` means not connected - Example: ```js import { connectStatus } from '@zos/ble' // ... ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Query connection status, `true` means connected, `false` means not connected. ## Type ```ts function connectStatus(): boolean ``` ## Example ```js // ... ``` --- ## createConnect ### Import ```js import { createConnect } from '@zos/ble' ``` ### Typings - Description: Create connection - Example: ```js import { createConnect } from '@zos/ble' // ... ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Create connection. ## Type ```ts function createConnect(callback: Callback): void ``` ## Parameters ### Callback | Type | Description | | ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | | `(index?: number, data?: object, size?: number) => void` | Connection callback function, `index` packet number, `data` data, `size` data length | ## Example ```js // ... ``` --- ## disConnect ### Import ```js import { disConnect } from '@zos/ble' ``` ### Typings - Description: Disconnect - Example: ```js import { disConnect } from '@zos/ble' // ... ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Disconnect. ## Type ```ts function disConnect(): void ``` ## Example ```js // ... ``` --- ## mstBuildProfile ### Import ```js import { mstBuildProfile } from '@zos/ble' ``` ### Typings - Description: Creating a Profile connection - API_LEVEL: 3.0 - Example: ```js import { mstBuildProfile } from '@zos/ble' // ... ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Creating a Profile connection. ## Type ```ts function mstBuildProfile(profile: ProfileObj): Result ``` ## Parameters ### ProfileObj | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | --------------------------------------- | -------- | ------------ | ------------------------------------------------------------- | --------- | | pair | `boolean` | Y | - | Whether to pair automatically | 3.0 | | id | `number` | Y | - | Connection ID | 3.0 | | profile | `string` | Y | - | Profile Name | 3.0 | | dev | `ArrayBuffer` | Y | - | Device MAC address, 6 bytes long, Uint8Array view recommended | 3.0 | | len | `number` | Y | - | `list` array length | 3.0 | | list | `Array` | Y | - | Services list array | 3.0 | ### ServicesObj | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | -------------------------------------- | -------- | ------------ | ------------------- | --------- | | len | `number` | Y | - | `list` array length | 3.0 | | list | `Array` | Y | - | Service array | 3.0 | ### ServiceObj | Property | Type | Required | DefaultValue | Description | API_LEVEL | | ---------- | --------------------------------------------- | -------- | -------------- | ------------------------------------------ | --------- | | uuid | `string` | Y | - | Service UUID | 3.0 | | permission | `number` | N | `0` | Permission control, default `0` No control | 3.0 | | len1 | `number` | Y | - | Characteristic array length | 3.0 | | list | `Array` | Y | - | Characteristic length | 3.0 | ### CharacteristicObj | Property | Type | Required | DefaultValue | Description | API_LEVEL | | ---------- | ----------------------------------------- | -------- | -------------- | ------------------------------------------ | --------- | | uuid | `string` | Y | - | Characteristic UUID | 3.0 | | permission | `number` | N | `0` | Permission control, default `0` No control | 3.0 | | len | `number` | Y | - | Descriptor array length | 3.0 | | list | `Array` | Y | - | Descriptor array | 3.0 | ### DescriptorObj | Property | Type | Required | DefaultValue | Description | API_LEVEL | | ---------- | ------------------- | -------- | -------------- | ------------------------------------------ | --------- | | uuid | `string` | Y | - | Descriptor UUID | 3.0 | | permission | `number` | N | `0` | Permission control, default `0` No control | 3.0 | ### Result | Type | Description | | -------------------- | ---------------------------------------------------------------------------- | | `boolean` | The result of the function call, `true` means success, `false` means failure | ## Example ```js // ... ``` --- ## mstConnect ### Import ```js import { mstConnect } from '@zos/ble' ``` ### Typings - Description: Connecting Devices - API_LEVEL: 3.0 - Example: ```js import { mstConnect } from '@zos/ble' // ... ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Connecting Devices. ## Type ```ts function mstConnect(deviceAddress: DeviceAddress, callback: Callback): Result ``` ## Parameters ### DeviceAddress | Type | Description | | ------------------------ | ------------------------------------------------------------- | | `ArrayBuffer` | Device MAC address, 6 bytes long, Uint8Array view recommended | ### Callback | Type | Description | | ------------------------------------------------ | ----------------------------------- | | `(result: ConnectResult) => void` | Connection result callback function | ### ConnectResult | Property | Type | Description | API_LEVEL | | ---------- | ------------------------ | ------------------------------------------------------------------------------------------- | --------- | | connected | `number` | Connection status, `0` - successful connection, `1` - failed connection, `2` - disconnected | 3.0 | | connect_id | `number` | The ID of the connection is returned when the connection is successful | 3.0 | | dev_addr | `ArrayBuffer` | Device MAC address, 6 bytes long, Uint8Array view recommended | 3.0 | ### Result | Type | Description | | -------------------- | ---------------------------------------------------------------------------- | | `boolean` | The result of the function call, `true` means success, `false` means failure | ## Example ```js // ... ``` --- ## mstDestroyProfileInstance ### Import ```js import { mstDestroyProfileInstance } from '@zos/ble' ``` ### Typings - Description: Destroy Profile - API_LEVEL: 3.0 - Example: ```js import { mstDestroyProfileInstance } from '@zos/ble' mstDestroyProfileInstance() ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Destroy Profile. ## Type ```ts function mstDestroyProfileInstance(profile: Profile): void ``` ## Parameters ### Profile | Type | Description | | ------------------- | --------------- | | `number` | Profile pointer | ## Example ```js mstDestroyProfileInstance() ``` --- ## mstDisconnect ### Import ```js import { mstDisconnect } from '@zos/ble' ``` ### Typings - Description: Disconnecting devices - API_LEVEL: 3.0 - Example: ```js import { mstDisconnect } from '@zos/ble' // ... ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Disconnecting devices. ## Type ```ts function mstDisconnect(connectId: ConnectId): Result ``` ## Parameters ### ConnectId | Type | Description | | ------------------- | --------------------------------------------------------------------------------------- | | `number` | The connection ID returned when the connection is successful using the `mstConnect` API | ### Result | Type | Description | | -------------------- | ---------------------------------------------------------------------------- | | `boolean` | The result of the function call, `true` means success, `false` means failure | ## Example ```js // ... ``` --- ## mstGetConnIdByRemoteAddr ### Import ```js import { mstGetConnIdByRemoteAddr } from '@zos/ble' ``` ### Typings - Description: Look up the connection Id based on the Peripheral MAC address - API_LEVEL: 3.0 - Example: ```js import { mstGetConnIdByRemoteAddr } from '@zos/ble' // ... ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Look up the connection Id based on the Peripheral MAC address. ## Type ```ts function mstGetConnIdByRemoteAddr(deviceAddress: DeviceAddress): Result ``` ## Parameters ### DeviceAddress | Type | Description | | ------------------------ | ------------------------------------------------------------- | | `ArrayBuffer` | Device MAC address, 6 bytes long, Uint8Array view recommended | ### Result | Type | Description | | ---------------------------------- | -------------------------------------------------------------------------------------------------------------- | | `number|undefined` | The result of the function call returns `connectId` for a successful query and `undefined` for a failed query. | ## Example ```js // ... ``` --- ## mstGetProfileInstance ### Import ```js import { mstGetProfileInstance } from '@zos/ble' ``` ### Typings - Description: Query Profile pointer based on Profile name and connection ID - API_LEVEL: 3.0 - Example: ```js import { mstGetProfileInstance } from '@zos/ble' // ... ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Query Profile pointer based on Profile name and connection ID. ## Type ```ts function mstGetProfileInstance(profileName: ProfileName, connectId: ConnectId): Result ``` ## Parameters ### ProfileName | Type | Description | | ------------------- | ------------ | | `string` | Profile name | ### ConnectId | Type | Description | | ------------------- | ------------------------------------------ | | `number` | The ID returned on a successful connection | ### Result | Type | Description | | ---------------------------------- | ------------------------------------------------------------------------------------ | | `number|undefined` | A successful search returns the Profile pointer, a failed search returns `undefined` | ## Example ```js // ... ``` --- ## mstOffAllCb ### Import ```js import { mstOffAllCb } from '@zos/ble' ``` ### Typings - Description: Unregister of all registered Bluetooth-related callback functions - API_LEVEL: 3.0 - Example: ```js import { mstOffAllCb } from '@zos/ble' mstOffAllCb() ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Unregister of all registered Bluetooth-related callback functions. ## Type ```ts function mstOffAllCb(): void ``` ## Example ```js mstOffAllCb() ``` --- ## mstOnCharaNotification ### Import ```js import { mstOnCharaNotification } from '@zos/ble' ``` ### Typings - Description: Register Characteristic Notification to reach the callback function - API_LEVEL: 3.0 - Example: ```js import { mstOnCharaNotification } from '@zos/ble' // ... ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Register Characteristic Notification to reach the callback function. ## Type ```ts function mstOnCharaNotification(callback: Callback): Result ``` ## Parameters ### Callback | Type | Description | | ----------------------------------------------------------------------------------- | ------------------------------------------------------------ | | `(profile: Profile, uuid: UUID, data: Data, length: Length) => void` | Characteristic Notification arrives at the callback function | ### Profile | Type | Description | | ------------------- | --------------- | | `number` | Profile pointer | ### UUID | Type | Description | | ------------------- | -------------------------- | | `string` | Characteristic UUID string | ### Data | Type | Description | | ------------------------ | ------------------------------------------------------------- | | `ArrayBuffer` | It is recommended to use the Uint8Array view to read the data | ### Length | Type | Description | | ------------------- | ----------- | | `number` | Data length | ### Result | Type | Description | | -------------------- | ---------------------------------------------------------------------------- | | `boolean` | The result of the function call, `true` means success, `false` means failure | ## Example ```js // ... ``` --- ## mstOnCharaReadComplete ### Import ```js import { mstOnCharaReadComplete } from '@zos/ble' ``` ### Typings - Description: Register the read Characteristic completion callback function - API_LEVEL: 3.0 - Example: ```js import { mstOnCharaReadComplete } from '@zos/ble' // ... ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Register the read Characteristic completion callback function. ## Type ```ts function mstOnCharaReadComplete(callback: Callback): Result ``` ## Parameters ### Callback | Type | Description | | ----------------------------------------------------------------------- | ------------------------------------------------ | | `(profile: Profile, uuid: UUID, status: Status) => void` | Read Characteristic Completion Callback Function | ### Profile | Type | Description | | ------------------- | --------------- | | `number` | Profile pointer | ### UUID | Type | Description | | ------------------- | -------------------------- | | `string` | Characteristic UUID string | ### Status | Type | Description | | ------------------- | ----------------------------- | | `number` | Status, `0` indicates success | ### Result | Type | Description | | -------------------- | ---------------------------------------------------------------------------- | | `boolean` | The result of the function call, `true` means success, `false` means failure | ## Example ```js // ... ``` --- ## mstOnCharaValueArrived ### Import ```js import { mstOnCharaValueArrived } from '@zos/ble' ``` ### Typings - Description: Register to read Characteristic data to the callback function - API_LEVEL: 3.0 - Example: ```js import { mstOnCharaValueArrived } from '@zos/ble' // ... ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Register to read Characteristic data to the callback function. ## Type ```ts function mstOnCharaValueArrived(callback: Callback): Result ``` ## Parameters ### Callback | Type | Description | | ----------------------------------------------------------------------------------- | ------------------------------------------------- | | `(profile: Profile, uuid: UUID, data: Data, status: Status) => void` | Read Characteristic data to the callback function | ### Profile | Type | Description | | ------------------- | --------------- | | `number` | Profile pointer | ### UUID | Type | Description | | ------------------- | -------------------------- | | `string` | Characteristic UUID string | ### Data | Type | Description | | ------------------------ | ---------------------------------------- | | `ArrayBuffer` | Reads the data using the Uint8Array view | ### Status | Type | Description | | ------------------- | ----------------------------- | | `number` | Status, `0` indicates success | ### Result | Type | Description | | -------------------- | ---------------------------------------------------------------------------- | | `boolean` | The result of the function call, `true` means success, `false` means failure | ## Example ```js // ... ``` --- ## mstOnCharaWriteComplete ### Import ```js import { mstOnCharaWriteComplete } from '@zos/ble' ``` ### Typings - Description: Register the Write Characteristic data completion callback function - API_LEVEL: 3.0 - Example: ```js import { mstOnCharaWriteComplete } from '@zos/ble' // ... ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Register the Write Characteristic data completion callback function. ## Type ```ts function mstOnCharaWriteComplete(callback: Callback): Result ``` ## Parameters ### Callback | Type | Description | | ----------------------------------------------------------------------- | ------------------------------------------------------ | | `(profile: Profile, uuid: UUID, status: Status) => void` | Write Characteristic Data Completion Callback Function | ### Profile | Type | Description | | ------------------- | --------------- | | `number` | Profile pointer | ### UUID | Type | Description | | ------------------- | -------------------------- | | `string` | Characteristic UUID string | ### Status | Type | Description | | ------------------- | ----------------------------- | | `number` | Status, `0` indicates success | ### Result | Type | Description | | -------------------- | ---------------------------------------------------------------------------- | | `boolean` | The result of the function call, `true` means success, `false` means failure | ## Example ```js // ... ``` --- ## mstOnDescValueArrived ### Import ```js import { mstOnDescValueArrived } from '@zos/ble' ``` ### Typings - Description: Register the Read Descriptor data arrival callback function - API_LEVEL: 3.0 - Example: ```js import { mstOnDescValueArrived } from '@zos/ble' // ... ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Register the Read Descriptor data arrival callback function. ## Type ```ts function mstOnDescValueArrived(callback: Callback): Result ``` ## Parameters ### Callback | Type | Description | | ---------------------------------------------------------------------------------------------------------- | --------------------------------------------- | | `( profile: Profile, uuid: UUID, descUUID: DescUUID, data: Data, status: Status, ) => void` | Read Descriptor data to the callback function | ### Profile | Type | Description | | ------------------- | --------------- | | `number` | Profile pointer | ### UUID | Type | Description | | ------------------- | -------------------------- | | `string` | Characteristic UUID string | ### DescUUID | Type | Description | | ------------------- | ---------------------- | | `string` | Descriptor UUID string | ### Data | Type | Description | | ------------------------ | ---------------------------------------- | | `ArrayBuffer` | Reads the data using the Uint8Array view | ### Status | Type | Description | | ------------------- | ----------------------------- | | `number` | Status, `0` indicates success | ### Result | Type | Description | | -------------------- | ---------------------------------------------------------------------------- | | `boolean` | The result of the function call, `true` means success, `false` means failure | ## Example ```js // ... ``` --- ## mstOnDescWriteComplete ### Import ```js import { mstOnDescWriteComplete } from '@zos/ble' ``` ### Typings - Description: Register Descriptor data write completion callback function - API_LEVEL: 3.0 - Example: ```js import { mstOnDescWriteComplete } from '@zos/ble' // ... ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Register Descriptor data write completion callback function. ## Type ```ts function mstOnDescWriteComplete(callback: Callback): Result ``` ## Parameters ### Callback | Type | Description | | ------------------------------------------------------------------------------------------- | -------------------------------------------------- | | `(profile: Profile, uuid: UUID, descUUID: DescUUID, status: Status) => void` | Descriptor Data write completion callback function | ### Profile | Type | Description | | ------------------- | --------------- | | `number` | Profile pointer | ### UUID | Type | Description | | ------------------- | -------------------------- | | `string` | Characteristic UUID string | ### DescUUID | Type | Description | | ------------------- | ---------------------- | | `string` | Descriptor UUID string | ### Status | Type | Description | | ------------------- | ----------------------------- | | `number` | Status, `0` indicates success | ### Result | Type | Description | | -------------------- | ---------------------------------------------------------------------------- | | `boolean` | The result of the function call, `true` means success, `false` means failure | ## Example ```js // ... ``` --- ## mstOnPrepare ### Import ```js import { mstOnPrepare } from '@zos/ble' ``` ### Typings - Description: Register the prepare operation callback function - API_LEVEL: 3.0 - Example: ```js import { mstOnPrepare } from '@zos/ble' // ... ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Register the prepare operation callback function. ## Type ```ts function mstOnPrepare(callback: Callback): Result ``` ## Parameters ### Callback | Type | Description | | ----------------------------------------------------------- | ------------------------------------------------ | | `(profile: Profile, status: Status) => void` | Listening to the prepare event callback function | ### Profile | Type | Description | | ------------------- | --------------- | | `number` | Profile pointer | ### Status | Type | Description | | ------------------- | ----------------------------- | | `number` | Status, `0` indicates success | ### Result | Type | Description | | -------------------- | ---------------------------------------------------------------------------- | | `boolean` | The result of the function call, `true` means success, `false` means failure | ## Example ```js // ... ``` --- ## mstOnServiceChangeBegin ### Import ```js import { mstOnServiceChangeBegin } from '@zos/ble' ``` ### Typings - Description: Register the Service start change callback function - API_LEVEL: 3.0 - Example: ```js import { mstOnServiceChangeBegin } from '@zos/ble' // ... ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Register the Service start change callback function. ## Type ```ts function mstOnServiceChangeBegin(callback: Callback): Result ``` ## Parameters ### Callback | Type | Description | | ------------------------------------------- | -------------------------------------- | | `(profile: Profile) => void` | Service start change callback function | ### Profile | Type | Description | | ------------------- | --------------- | | `number` | Profile pointer | ### Result | Type | Description | | -------------------- | ---------------------------------------------------------------------------- | | `boolean` | The result of the function call, `true` means success, `false` means failure | ## Example ```js // ... ``` --- ## mstOnServiceChangeEnd ### Import ```js import { mstOnServiceChangeEnd } from '@zos/ble' ``` ### Typings - Description: Register the Service change end callback function - API_LEVEL: 3.0 - Example: ```js import { mstOnServiceChangeEnd } from '@zos/ble' // ... ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Register the Service change end callback function. ## Type ```ts function mstOnServiceChangeEnd(callback: Callback): Result ``` ## Parameters ### Callback | Type | Description | | ------------------------------------------- | ------------------------------------ | | `(profile: Profile) => void` | Service change end callback function | ### Profile | Type | Description | | ------------------- | --------------- | | `number` | Profile pointer | ### Result | Type | Description | | -------------------- | ---------------------------------------------------------------------------- | | `boolean` | The result of the function call, `true` means success, `false` means failure | ## Example ```js // ... ``` --- ## mstPair ### Import ```js import { mstPair } from '@zos/ble' ``` ### Typings - Description: Pairing with devices via `connectId` - API_LEVEL: 3.0 - Example: ```js import { mstPair } from '@zos/ble' // ... ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Pairing with devices via `connectId`. ## Type ```ts function mstPair(connectId: ConnectId): Result ``` ## Parameters ### ConnectId | Type | Description | | ------------------- | --------------------------------------------------------------------------------------- | | `number` | The connection ID returned when the connection is successful using the `mstConnect` API | ### Result | Type | Description | | -------------------- | ---------------------------------------------------------------------------- | | `boolean` | The result of the function call, `true` means success, `false` means failure | ## Example ```js // ... ``` --- ## mstPrepare ### Import ```js import { mstPrepare } from '@zos/ble' ``` ### Typings - Description: prepare interface - API_LEVEL: 3.0 - Example: ```js import { mstPrepare } from '@zos/ble' // ... ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). prepare interface. ## Type ```ts function mstPrepare(profile: Profile): void ``` ## Parameters ### Profile | Type | Description | | ------------------- | --------------------------------------------------- | | `number` | The `profile` pointer returned by `mstBuildProfile` | ## Example ```js // ... ``` --- ## mstReadCharacteristic ### Import ```js import { mstReadCharacteristic } from '@zos/ble' ``` ### Typings - Description: Read Characteristic information - API_LEVEL: 3.0 - Example: ```js import { mstReadCharacteristic } from '@zos/ble' // ... ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Read Characteristic information. ## Type ```ts function mstReadCharacteristic(profile: Profile, uuid: UUID): void ``` ## Parameters ### Profile | Type | Description | | ------------------- | --------------- | | `number` | Profile pointer | ### UUID | Type | Description | | ------------------- | -------------------------- | | `string` | Characteristic UUID string | ## Example ```js // ... ``` --- ## mstReadDescriptor ### Import ```js import { mstReadDescriptor } from '@zos/ble' ``` ### Typings - Description: Write characteristic information - API_LEVEL: 3.0 - Example: ```js import { mstReadDescriptor } from '@zos/ble' // ... ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Write characteristic information. ## Type ```ts function mstReadDescriptor(profile: Profile, uuid: UUID, descUUID: DescUUID): void ``` ## Parameters ### Profile | Type | Description | | ------------------- | --------------- | | `number` | Profile pointer | ### UUID | Type | Description | | ------------------- | -------------------------- | | `string` | Characteristic UUID string | ### DescUUID | Type | Description | | ------------------- | ---------------------- | | `string` | Descriptor UUID string | ## Example ```js // ... ``` --- ## mstStartScan ### Import ```js import { mstStartScan } from '@zos/ble' ``` ### Typings - Description: Scan and discover Bluetooth peripherals, which can be filtered according to filter conditions - API_LEVEL: 3.0 - Example: ```js import { mstStartScan } from '@zos/ble' // ... ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Scan and discover Bluetooth peripherals, which can be filtered according to filter conditions. ## Type ```ts function mstStartScan(callback: Callback, filter?: Filter): Result ``` ## Parameters ### Callback | Type | Description | | --------------------------------------------------------------------------------- | -------------------------------------------- | | `(result: ScanResult, filter?: Filter, timeout?: Timeout) => void` | Callback function for receiving scan results | ### ScanResult | Property | Type | Description | API_LEVEL | | ------------------ | --------------------------------------- | ------------------------------------------------------------- | --------- | | dev_name | `string` | Device name | 3.0 | | dev_addr | `ArrayBuffer` | Device MAC address, 6 bytes long, Uint8Array view recommended | 3.0 | | rssi | `number` | RSSI Signal Strength | 3.0 | | service_uuid_array | `Array` | Service UUID array in broadcast data | 3.0 | | service_data_array | `Array` | Array of Service Data Objects in Broadcast Data | 3.0 | ### ServiceData | Property | Type | Description | API_LEVEL | | ------------ | ------------------------ | ------------ | --------- | | uuid | `string` | Service UUID | 3.0 | | service_data | `ArrayBuffer` | Service data | 3.0 | ### Filter | Property | Type | Required | DefaultValue | Description | API_LEVEL | | ----------------- | ------------------- | -------- | ------------ | -------------------------------------------------- | --------- | | device_name | `string` | N | - | Device name | 3.0 | | fuzzy_mode | `string` | N | - | Whether to use fuzzy mode for device name matching | 3.0 | | service_uuid | `string` | N | - | Service UUID | 3.0 | | service_data_uuid | `string` | N | - | Service data UUID | 3.0 | | manufacturer_id | `number` | N | - | Manufacturer ID | 3.0 | ### Timeout | Property | Type | Required | DefaultValue | Description | API_LEVEL | | ---------- | --------------------------- | -------- | ------------ | ---------------------------------------------------------------------------------------------- | --------- | | duration | `number` | N | - | Scanning duration, in seconds. Scanning automatically stops when the given duration is reached | 3.0 | | on_timeout | `() => void` | N | - | Callback function after scanning stops | 3.0 | ### Result | Type | Description | | -------------------- | ---------------------------------------------------------------------------- | | `boolean` | The result of the function call, `true` means success, `false` means failure | ## Example ```js // ... ``` --- ## mstStopScan ### Import ```js import { mstStopScan } from '@zos/ble' ``` ### Typings - Description: Stop device scanning, used in conjunction with `mstStartScan` - API_LEVEL: 3.0 - Example: ```js import { mstStopScan } from '@zos/ble' mstStopScan() ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Stop device scanning, used in conjunction with `mstStartScan`. ## Type ```ts function mstStopScan(): Result ``` ## Parameters ### Result | Type | Description | | -------------------- | ---------------------------------------------------------------------------- | | `boolean` | The result of the function call, `true` means success, `false` means failure | ## Example ```js mstStopScan() ``` --- ## mstWriteCharacteristic ### Import ```js import { mstWriteCharacteristic } from '@zos/ble' ``` ### Typings - Description: Write Characteristic information - API_LEVEL: 3.0 - Example: ```js import { mstWriteCharacteristic } from '@zos/ble' // ... ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Write Characteristic information. ## Type ```ts function mstWriteCharacteristic(profile: Profile, uuid: UUID, data: Data, length: Length): void ``` ## Parameters ### Profile | Type | Description | | ------------------- | --------------- | | `number` | Profile pointer | ### UUID | Type | Description | | ------------------- | -------------------------- | | `string` | Characteristic UUID string | ### Data | Type | Description | | ------------------------ | ---------------------------------------- | | `ArrayBuffer` | Reads the data using the Uint8Array view | ### Length | Type | Description | | ------------------- | ----------- | | `number` | Data length | ## Example ```js // ... ``` --- ## mstWriteDescriptor ### Import ```js import { mstWriteDescriptor } from '@zos/ble' ``` ### Typings - Description: Register the Characteristic notification arrival callback function - API_LEVEL: 3.0 - Example: ```js import { mstWriteDescriptor } from '@zos/ble' // ... ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Register the Characteristic notification arrival callback function. ## Type ```ts function mstWriteDescriptor( profile: Profile, uuid: UUID, descUUID: DescUUID, data: Data, length: Length, ): Result ``` ## Parameters ### Profile | Type | Description | | ------------------- | --------------- | | `number` | Profile pointer | ### UUID | Type | Description | | ------------------- | -------------------------- | | `string` | Characteristic UUID string | ### DescUUID | Type | Description | | ------------------- | ---------------------- | | `string` | Descriptor UUID string | ### Data | Type | Description | | ------------------------ | ---------------------------------------- | | `ArrayBuffer` | Reads the data using the Uint8Array view | ### Length | Type | Description | | ------------------- | ----------- | | `number` | Data length | ### Result | Type | Description | | -------------------- | ---------------------------------------------------------------------------- | | `boolean` | The result of the function call, `true` means success, `false` means failure | ## Example ```js // ... ``` --- ## removeListener ### Import ```js import { removeListener } from '@zos/ble' ``` ### Typings - Description: Cancel connection status listening callback function - Example: ```js import { removeListener } from '@zos/ble' // ... ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Cancel connection status listening callback function. ## Type ```ts function removeListener(): void ``` ## Example ```js // ... ``` --- ## send ### Import ```js import { send } from '@zos/ble' ``` ### Typings - Description: Send message, `data` data to be sent, `size` length of data to be sent - Example: ```js import { send } from '@zos/ble' // ... ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Send message, `data` data to be sent, `size` length of data to be sent. ## Type ```ts function send(data: object, size: number): void ``` ## Example ```js // ... ``` --- --- # @zos/crypto ## Constants | Constant | Description | API_LEVEL | |----------|-------------|-----------| | `alg` | Supported encryption, signature, digest, and checksum algorithms | — | | `ecp_dp` | ECDSA elliptic curve parameters | — | ## AESCrypto ### Import ```js import { alg, createCrypto } from '@zos/crypto' ``` ## createCrypto Create an AES-CBC symmetric encryption instance. Plaintext length must be a multiple of 16 bytes. | algorithmId | Description | API_LEVEL | | ------------- | ---------------------------- | --------- | --- | | `alg.AES_CBC` | AES-CBC symmetric encryption | `3.0` | . | ### Type ```ts function createCrypto(algorithmId: typeof alg.AES_CBC, option: AESOptions): AESCrypto | undefined ``` ### Parameters #### AESData | Type | Description | | ------------------------------------------------------ | --------------- | | `number[]|ArrayBuffer|Uint8Array` | Data to process | #### AESOptions | Property | Type | Required | DefaultValue | Description | | -------------- | -------------------------------- | -------- | ------------ | ------------------------------------------------------------ | | key_bit_length | `number` | Y | - | Key length in bits; AES-CBC uses 128 | | key_encrypt | `boolean|number` | N | - | Whether the key is encrypted again by the hardware key | | private_key | `AESData` | N | - | Existing private key; use it instead of generating a new key | ## AESCrypto AES-CBC symmetric encryption instance. ### Methods #### createChiper Create or return the AES private key; returns `undefined` on failure ```ts createChiper(): AESKeyResult | undefined ``` ##### AESKeyResult | Property | Type | Description | | ------------------ | ------------------------ | ------------------ | | private_key_length | `number` | Private key length | | private_key | `ArrayBuffer` | Private key data | #### encrypt Encrypt data whose length is a multiple of 16 bytes ```ts encrypt(data: createCrypto.AESData): AESCipherResult | undefined ``` ##### AESCipherResult | Property | Type | Description | | -------- | ------------------------ | -------------- | | data | `ArrayBuffer` | Encrypted data | | length | `number` | Data length | #### decrypt Decrypt AES-CBC data ```ts decrypt(data: createCrypto.AESData): AESCipherResult | undefined ``` ##### AESCipherResult | Property | Type | Description | | -------- | ------------------------ | -------------- | | data | `ArrayBuffer` | Decrypted data | | length | `number` | Data length | ### Example ```js const plainData = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]) const aes = createCrypto(alg.AES_CBC, { key_bit_length: 128, key_encrypt: 1, }) if (!aes) throw new Error('Failed to create AES-CBC instance') const keyInfo = aes.createChiper() if (!keyInfo) throw new Error('Failed to create AES key') const encrypted = aes.encrypt(plainData) if (!encrypted) throw new Error('Failed to encrypt data') const decrypted = aes.decrypt(encrypted.data) if (!decrypted) throw new Error('Failed to decrypt data') console.log(new Uint8Array(decrypted.data)) // Create another AES-CBC instance with an existing private key const existingKey = new Uint8Array(keyInfo.private_key) const aesWithExistingKey = createCrypto(alg.AES_CBC, { key_bit_length: 128, private_key: existingKey, key_encrypt: 1, }) if (!aesWithExistingKey) throw new Error('Failed to reuse AES key') const encryptedAgain = aesWithExistingKey.encrypt(plainData) const decryptedAgain = encryptedAgain ? aesWithExistingKey.decrypt(encryptedAgain.data) : undefined ``` --- ## CRCCrypto ### Import ```js import { alg, createCrypto } from '@zos/crypto' ``` ## createCrypto Create a CRC checksum instance. The result uses little-endian byte order. | algorithmId | Description | API_LEVEL | | ----------- | -------------- | --------- | --- | | `alg.CRC16` | CRC16 checksum | `3.0` | | `alg.CRC32` | CRC32 checksum | `3.0` | . | ### Type ```ts function createCrypto(algorithmId: typeof alg.CRC16 | typeof alg.CRC32): CRCCrypto | undefined ``` ### Parameters #### CRCData | Type | Description | | ------------------------------------------------------ | ---------------- | | `number[]|ArrayBuffer|Uint8Array` | Data to checksum | ## CRCCrypto CRC16/CRC32 checksum instance supporting only `encrypt()`. ### Methods #### encrypt Calculate a CRC checksum in little-endian form ```ts encrypt(data: createCrypto.CRCData): CRCResult | undefined ``` ##### CRCResult | Property | Type | Description | | -------- | ------------------------ | ---------------------------------- | | data | `ArrayBuffer` | CRC checksum in little-endian form | | length | `number` | Data length | ### Example ```js const crc16 = createCrypto(alg.CRC16) if (!crc16) throw new Error('Failed to create CRC16 instance') const crc16Result = crc16.encrypt([1, 2, 3]) const crc32 = createCrypto(alg.CRC32) if (!crc32) throw new Error('Failed to create CRC32 instance') const crc32Result = crc32.encrypt(new Uint8Array([1, 2, 3])) ``` --- ## DigestCrypto ### Import ```js import { alg, createCrypto } from '@zos/crypto' ``` ## createCrypto Create a digest instance. Pass the HMAC key through `private_key`. | algorithmId | Description | API_LEVEL | | ------------------ | ------------------- | --------- | --- | | `alg.MD5` | MD5 digest | `3.0` | | `alg.HMACMD5` | HMAC-MD5 digest | `3.0` | | `alg.SHA_256` | SHA-256 digest | `3.0` | | `alg.HMAC_SHA_256` | HMAC-SHA-256 digest | `3.0` | | `alg.SHA_1` | SHA-1 digest | `3.0` | | `alg.HMAC_SHA_1` | HMAC-SHA-1 digest | `3.0` | . | ### Type ```ts function createCrypto( algorithmId: typeof alg.MD5 | typeof alg.SHA_256 | typeof alg.SHA_1, option?: DigestOptions, ): DigestCrypto | undefined function createCrypto( algorithmId: typeof alg.HMACMD5 | typeof alg.HMAC_SHA_256 | typeof alg.HMAC_SHA_1, option: HMACOptions, ): DigestCrypto | undefined ``` ### Parameters #### DigestData | Type | Description | | ------------------------------------------------------ | -------------- | | `number[]|ArrayBuffer|Uint8Array` | Data to digest | #### DigestOptions | Property | Type | Required | DefaultValue | Description | | ----------- | -------------------------------- | -------- | ------------ | ------------------------------------------------------ | | key_encrypt | `boolean|number` | N | - | Whether the key is encrypted again by the hardware key | #### HMACOptions | Property | Type | Required | DefaultValue | Description | | ----------- | -------------------------------- | -------- | ------------ | ------------------------------------------------------ | | private_key | `DigestData` | Y | - | Key used by HMAC algorithms | | key_encrypt | `boolean|number` | N | - | Whether the key is encrypted again by the hardware key | ## DigestCrypto MD5, SHA, and HMAC digest instance supporting one-shot and streaming calculation. ### Methods #### encrypt Calculate a digest in one call ```ts encrypt(data: createCrypto.DigestData): DigestResult | undefined ``` ##### DigestResult | Property | Type | Description | | ---------- | ------------------------ | ------------- | | md_content | `ArrayBuffer` | Digest data | | length | `number` | Digest length | #### start Start streaming digest calculation ```ts start(): void ``` #### update Append a data chunk ```ts update(data: createCrypto.DigestData): void ``` #### finish Finish streaming calculation and return the digest ```ts finish(): DigestResult | undefined ``` ##### DigestResult | Property | Type | Description | | ---------- | ------------------------ | ------------- | | md_content | `ArrayBuffer` | Digest data | | length | `number` | Digest length | ### Example ```js const digest = createCrypto(alg.HMAC_SHA_256, { private_key: [1, 2, 3] }) if (!digest) throw new Error('Failed to create digest instance') const oneShot = digest.encrypt([65, 66, 67]) digest.start() digest.update([65]) digest.update([66, 67]) const streamed = digest.finish() ``` --- ## ECDSACrypto ### Import ```js import { alg, createCrypto, ecp_dp } from '@zos/crypto' ``` ## createCrypto Create an ECDSA digital signature instance. The default curve is `ecp_dp.SECP256K1`. | Value | Description | API_LEVEL | | ------------------ | --------------------------------- | --------- | --- | | `alg.ECDSA` | ECDSA digital signature | `3.0` | | `ecp_dp.SECP192K1` | SECP192K1 elliptic curve | `3.0` | | `ecp_dp.SECP224K1` | SECP224K1 elliptic curve | `3.0` | | `ecp_dp.SECP256K1` | SECP256K1 elliptic curve; default | `3.0` | . | ### Type ```ts function createCrypto(algorithmId: typeof alg.ECDSA, option?: ECDSAOptions): ECDSACrypto | undefined ``` ### Parameters #### ECDSAData | Type | Description | | ------------------------------------------------------ | --------------- | | `number[]|ArrayBuffer|Uint8Array` | Data to process | #### ECDSAOptions | Property | Type | Required | DefaultValue | Description | | ----------- | ---------------------------------------------------------------------------------------------- | -------- | ------------ | -------------------------------------------------------- | | ecp_dp_mode | `typeof ecp_dp.SECP192K1|typeof ecp_dp.SECP224K1|typeof ecp_dp.SECP256K1` | N | - | Elliptic curve parameter; defaults to `ecp_dp.SECP256K1` | | key_encrypt | `boolean|number` | N | - | Whether the key is encrypted again by the hardware key | | private_key | `ECDSAData` | N | - | Existing private key | | pub_key | `ECDSAData` | N | - | Existing public key | ## ECDSACrypto ECDSA instance for key-pair creation, signing, and signature verification. ### Methods #### createChiper Create an ECDSA public/private key pair; returns `undefined` on failure ```ts createChiper(): ECDSAKeyResult | undefined ``` ##### ECDSAKeyResult | Property | Type | Description | | ------------------ | ------------------------ | ------------------ | | private_key_length | `number` | Private key length | | private_key | `ArrayBuffer` | Private key data | | pub_key_length | `number` | Public key length | | pub_key | `ArrayBuffer` | Public key data | #### encrypt Generate a digital signature for data ```ts encrypt( data: createCrypto.ECDSAData, option: Options, ): ECDSACipherResult | undefined ``` ##### Options | Property | Type | Required | DefaultValue | Description | | ----------- | --------------------------------------------------- | -------- | ------------ | ------------------------------------------------------ | | digest_type | `typeof alg.MD5|typeof alg.HMACMD5` | Y | - | Digest algorithm; supports `alg.MD5` and `alg.HMACMD5` | ##### ECDSACipherResult | Property | Type | Description | | -------- | ------------------------ | ---------------------- | | data | `ArrayBuffer` | Digital signature data | | length | `number` | Data length | #### decrypt Verify source data with signature data ```ts decrypt( data: createCrypto.ECDSAData, option: Options, ): ECDSACipherResult | undefined ``` ##### Options | Property | Type | Required | DefaultValue | Description | | -------- | ----------------------------------- | -------- | ------------ | --------------------------- | | sig_data | `createCrypto.ECDSAData` | Y | - | Digital signature to verify | ##### ECDSACipherResult | Property | Type | Description | | -------- | ------------------------ | ---------------------------------- | | data | `ArrayBuffer` | Signature verification result data | | length | `number` | Data length | ### Example ```js const source = new Uint8Array([1, 2, 3]) const ecdsa = createCrypto(alg.ECDSA, { ecp_dp_mode: ecp_dp.SECP256K1 }) if (!ecdsa) throw new Error('Failed to create ECDSA instance') const keys = ecdsa.createChiper() const signature = ecdsa.encrypt(source, { digest_type: alg.MD5 }) if (signature) { const verified = ecdsa.decrypt(source, { sig_data: signature.data }) } ``` --- ## encryptKey ### Import ```js import { encryptKey } from '@zos/crypto' ``` ### Typings - Description: Encrypt data with the firmware PUF hardware module using AES. Input length must be a multiple of 16 bytes; returns `undefined` on failure - API_LEVEL: 3.0 - Example: ```js import { encryptKey } from '@zos/crypto' const key = new Uint8Array(16) const encryptedKey = encryptKey(key) ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Encrypt data with the firmware PUF hardware module using AES. Input length must be a multiple of 16 bytes; returns `undefined` on failure. ## Type ```ts function encryptKey(data: CryptoData): ArrayBuffer | undefined ``` ## Parameters ### CryptoData | Type | Description | | ------------------------------------------------------ | --------------- | | `number[]|ArrayBuffer|Uint8Array` | Data to encrypt | ## Example ```js const key = new Uint8Array(16) const encryptedKey = encryptKey(key) ``` --- --- # @zos/device ## Constants | Constant | Description | API_LEVEL | |----------|-------------|-----------| | `SCREEN_SHAPE_SQUARE` | Square Screen | — | | `SCREEN_SHAPE_ROUND` | Round Screen | — | ## getDeviceInfo ### Import ```js import { getDeviceInfo, SCREEN_SHAPE_SQUARE } from '@zos/device' ``` ### Typings - Description: Gets device information - Permission: `data:os.device.info` - Constants: `screenShape` - Example: ```js import { getDeviceInfo, SCREEN_SHAPE_SQUARE } from '@zos/device' const { width, screenShape } = getDeviceInfo() console.log(width) if (screenShape === SCREEN_SHAPE_SQUARE) { console.log('Square Screen') } ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Gets device information. > **ℹ️ Info** > > permission code: `data:os.device.info` ## Type ```ts function getDeviceInfo(): Result ``` ## Parameters ### Result | Property | Type | Description | API_LEVEL | | ------------ | ------------------- | --------------------------------------------------- | --------- | | width | `number` | Device screen width | 2.0 | | height | `number` | Device screen height | 2.0 | | screenShape | `number` | Screen shape, value refer to screen shape constants | 2.0 | | deviceName | `number` | Device name | 2.0 | | keyNumber | `number` | Number of keys | 2.0 | | deviceSource | `number` | Device Plain Numeric Designators | 2.0 | | keyType | `string` | Device physical button type | 2.0 | | deviceColor | `number` | Device color identification | 2.0 | | uuid | `string` | Device unique identifier, 32 bytes in length | 4.2 | ## Constants ### Screen shape | Constant | Description | API_LEVEL | | --------------------- | ------------- | --------- | | `SCREEN_SHAPE_SQUARE` | Square Screen | 2.0 | | `SCREEN_SHAPE_ROUND` | Round Screen | 2.0 | ## Example ```js const { width, screenShape } = getDeviceInfo() console.log(width) if (screenShape === SCREEN_SHAPE_SQUARE) { console.log('Square Screen') } ``` --- ## getDiskInfo ### Import ```js import { getDiskInfo } from '@zos/device' ``` ### Typings - Description: Gets disk information - Example: ```js import { getDiskInfo } from '@zos/device' const { total } = getDiskInfo() console.log(total) ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Gets disk information. ## Type ```ts function getDiskInfo(): Result ``` ## Parameters ### Result | Property | Type | Description | API_LEVEL | | --------- | ------------------- | ---------------------------------------- | --------- | | total | `number` | Total Space in bytes | 2.0 | | free | `number` | Available Space in bytes | 2.0 | | app | `number` | Space occupied by Mini Programs in bytes | 2.0 | | watchface | `number` | Space occupied by watchfaces in bytes | 2.0 | | music | `number` | Space occupied by musics in bytes | 2.0 | | system | `number` | Space occupied by system in bytes | 2.0 | ## Example ```js const { total } = getDiskInfo() console.log(total) ``` --- --- # @zos/display ## getAutoBrightness ### Import ```js import { getAutoBrightness } from '@zos/display' ``` ### Typings - Description: Get whether to turn on the screen auto brightness setting - Example: ```js import { getAutoBrightness } from '@zos/display' const result = getAutoBrightness() if (result) { console.log('Auto brightness setting is turned on') } ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Get whether to turn on the screen auto brightness setting. ## Type ```ts function getAutoBrightness(): Result ``` ## Parameters ### Result | Type | Description | | -------------------- | ------------------------------------------------------------------------------ | | `boolean` | `true` - auto-brightness is set to on, `false` - auto-brightness is set to off | ## Example ```js const result = getAutoBrightness() if (result) { console.log('Auto brightness setting is turned on') } ``` --- ## getBrightness ### Import ```js import { getBrightness } from '@zos/display' ``` ### Typings - Description: Get the screen brightness of the current device - Example: ```js import { getBrightness } from '@zos/display' const result = getBrightness() console.log(`current brightness ${result}`) ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Get the screen brightness of the current device. ## Type ```ts function getBrightness(): Result ``` ## Parameters ### Result | Type | Description | | ------------------- | -------------------------------------- | | `number` | Screen brightness value, range 0 - 100 | ## Example ```js const result = getBrightness() console.log(`current brightness ${result}`) ``` --- ## getSettings ### Import ```js import { getSettings } from '@zos/display' ``` ### Typings - Description: Get system display related information - API_LEVEL: 3.0 - Example: ```js import { getSettings } from '@zos/display' console.log(getSettings()) ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Get system display related information. ## Type ```ts function getSettings(): Result ``` ## Parameters ### Result | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | ----------------------- | -------- | ------------ | ------------------------------- | --------- | | screen | `ScreenObj` | Y | - | Screen Status | 3.0 | | wrist | `WristObj` | Y | - | Lift wrist to view info setting | 3.0 | | standby | `StandbyObj` | Y | - | Rest screen display settings | 3.0 | ### ScreenObj | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | ------------------- | -------- | ------------ | ---------------------------------------- | --------- | | status | `number` | Y | - | Current screen status, `1`: On, `2`: Off | 3.0 | | duration | `number` | Y | - | Screen light-up time, in seconds | 3.0 | ### WristObj | Property | Type | Required | DefaultValue | Description | API_LEVEL | | --------- | ------------------- | -------- | ------------ | ------------------------------------------------------------- | --------- | | speed | `number` | Y | - | Response speed | 3.0 | | model | `number` | Y | - | Mode, see `model` for value | 3.0 | | startTime | `number` | Y | - | Start time, based on the number of minutes at 0:00 of the day | 3.0 | | endTime | `number` | Y | - | End time, based on the number of minutes at 0:00 of the day | 3.0 | ### StandbyObj | Property | Type | Required | DefaultValue | Description | API_LEVEL | | --------- | ------------------- | -------- | ------------ | ------------------------------------------------------------------------------ | --------- | | style | `number` | Y | - | Rest screen Watchface style, `0`: system default, `1`: follow the current dial | 3.0 | | model | `number` | Y | - | Mode, see `model` for value | 3.0 | | startTime | `number` | Y | - | Start time, based on the number of minutes at 0:00 of the day | 3.0 | | endTime | `number` | Y | - | End time, based on the number of minutes at 0:00 of the day | 3.0 | ### mode | Value | Type | Description | API_LEVEL | | ----- | ------------------- | ------------------- | --------- | | 0 | `number` | Measurement invalid | 3.0 | | 1 | `number` | Measurement invalid | 3.0 | | 2 | `number` | Measurement invalid | 3.0 | | 3 | `number` | Measurement invalid | 3.0 | ## Example ```js console.log(getSettings()) ``` --- ## pauseDropWristScreenOff ### Import ```js import { pauseDropWristScreenOff } from '@zos/display' ``` ### Typings - Description: Suspension of wrist resting behavior - API_LEVEL: 2.1 - Example: ```js import { pauseDropWristScreenOff } from '@zos/display' pauseDropWristScreenOff({ duration: 60000 }) ``` > Start from API_LEVEL `2.1` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Suspension of wrist resting behavior. ## Type ```ts function pauseDropWristScreenOff(option: Option): Result ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | ------------------- | -------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------- | --------- | | duration | `number` | N | `30000` | Duration (milliseconds), if `0` is passed, the wrist rest behavior will be suspended until `resetPalmScreenOff` is called | 2.1 | ### Result | Type | Description | | ------------------- | ---------------------------------------- | | `number` | If `0` is returned, success is indicated | ## Example ```js pauseDropWristScreenOff({ duration: 60000, }) ``` --- ## pausePalmScreenOff ### Import ```js import { pausePalmScreenOff } from '@zos/display' ``` ### Typings - Description: Suspension of overlapping palm resting screen behavior - API_LEVEL: 2.1 - Example: ```js import { pausePalmScreenOff } from '@zos/display' pausePalmScreenOff({ duration: 60000 }) ``` > Start from API_LEVEL `2.1` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Suspension of overlapping palm resting screen behavior. ## Type ```ts function pausePalmScreenOff(option: Option): Result ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | ------------------- | -------- | ------------------ | ------------------------------------------------------------------------------------------------------------------- | --------- | | duration | `number` | N | `30000` | Duration (milliseconds), if `0` is passed, the palm rest behavior is suspended until `resetPalmScreenOff` is called | 2.1 | ### Result | Type | Description | | ------------------- | ---------------------------------------- | | `number` | If `0` is returned, success is indicated | ## Example ```js pausePalmScreenOff({ duration: 60000, }) ``` --- ## resetDropWristScreenOff ### Import ```js import { pauseDropWristScreenOff, resetDropWristScreenOff } from '@zos/display' ``` ### Typings - Description: Resume wrist drop resting behavior - API_LEVEL: 2.1 - Example: ```js import { pauseDropWristScreenOff, resetDropWristScreenOff } from '@zos/display' pauseDropWristScreenOff({ duration: 0 }) setTimeout(() => { resetDropWristScreenOff() }, 3000) ``` > Start from API_LEVEL `2.1` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Resume wrist drop resting behavior. ## Type ```ts function resetDropWristScreenOff(): Result ``` ## Parameters ### Result | Type | Description | | ------------------- | ---------------------------------------- | | `number` | If `0` is returned, success is indicated | ## Example ```js pauseDropWristScreenOff({ duration: 0, }) setTimeout(() => { resetDropWristScreenOff() }, 3000) ``` --- ## resetPageBrightTime ### Import ```js import { setPageBrightTime, resetPageBrightTime } from '@zos/display' ``` ### Typings - Description: Cancel the bright time set by `setPageBrightTime` - Example: ```js import { setPageBrightTime, resetPageBrightTime } from '@zos/display' setPageBrightTime({ brightTime: 60000 }) const result = resetPageBrightTime() ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Cancel the bright time set by `setPageBrightTime`. ## Type ```ts function resetPageBrightTime(): Result ``` ## Parameters ### Result | Type | Description | | ------------------- | ---------------------------------------- | | `number` | If `0` is returned, success is indicated | ## Example ```js setPageBrightTime({ brightTime: 60000, }) const result = resetPageBrightTime() ``` --- ## resetPalmScreenOff ### Import ```js import { pausePalmScreenOff, resetPalmScreenOff } from '@zos/display' ``` ### Typings - Description: Recovery of overlapping palm resting screen behavior - API_LEVEL: 2.1 - Example: ```js import { pausePalmScreenOff, resetPalmScreenOff } from '@zos/display' pausePalmScreenOff({ duration: 0 }) setTimeout(() => { resetPalmScreenOff() }, 3000) ``` > Start from API_LEVEL `2.1` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Recovery of overlapping palm resting screen behavior. ## Type ```ts function resetPalmScreenOff(): Result ``` ## Parameters ### Result | Type | Description | | ------------------- | ---------------------------------------- | | `number` | If `0` is returned, success is indicated | ## Example ```js pausePalmScreenOff({ duration: 0, }) setTimeout(() => { resetPalmScreenOff() }, 3000) ``` --- ## setAutoBrightness ### Import ```js import { setAutoBrightness } from '@zos/display' ``` ### Typings - Description: Set whether to turn on auto-brightness, if it is on, then the screen brightness will be controlled by the light sensor and the `setBrightness` will be disabled - Example: ```js import { setAutoBrightness } from '@zos/display' setAutoBrightness({ autoBright: true }) ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Set whether to turn on auto-brightness, if it is on, then the screen brightness will be controlled by the light sensor and the `setBrightness` will be disabled. ## Type ```ts function setAutoBrightness(option: Option): void ``` ### Simplified calling method ```ts function setAutoBrightness(autoBright: boolean): void ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | ---------- | -------------------- | -------- | ------------ | ---------------------------------------- | --------- | | autoBright | `boolean` | Y | - | Whether to open the automatic brightness | 2.0 | ## Example ```js setAutoBrightness({ autoBright: true, }) ``` --- ## setBrightness ### Import ```js import { setBrightness } from '@zos/display' ``` ### Typings - Description: Set the screen brightness of the current device. If the auto brightness setting is currently turned on, the brightness is automatically adjusted by the light sensor, calling `setBrightness` will not take effect at this time, you need to use `setAutoBrightness` to turn off the auto brightness and then set it again. Note: If you exit the current page, you need to consider whether you need to set the brightness back to the original brightness - Example: ```js import { setBrightness } from '@zos/display' const result = setBrightness({ brightness: 50 }) if (result === 0) { console.log('setBrightness success') } ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Set the screen brightness of the current device. If the auto brightness setting is currently turned on, the brightness is automatically adjusted by the light sensor, calling `setBrightness` will not take effect at this time, you need to use `setAutoBrightness` to turn off the auto brightness and then set it again. Note: If you exit the current page, you need to consider whether you need to set the brightness back to the original brightness. ## Type ```ts function setBrightness(option: Option): Result ``` ### Simplified calling method ```ts function setBrightness(brightness: number): Result ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | ---------- | ------------------- | -------- | ------------ | -------------------------------------- | --------- | | brightness | `number` | Y | - | Screen brightness value, range 0 - 100 | 2.0 | ### Result | Type | Description | | ------------------- | ---------------------------------------- | | `number` | If `0` is returned, success is indicated | ## Example ```js const result = setBrightness({ brightness: 50, }) if (result === 0) { console.log('setBrightness success') } ``` --- ## setPageBrightTime ### Import ```js import { setPageBrightTime } from '@zos/display' ``` ### Typings - Description: Set the current page screen lighting time, this setting will follow the page destruction to do reset - Example: ```js import { setPageBrightTime } from '@zos/display' const result = setPageBrightTime({ brightTime: 60000 }) if (result === 0) { console.log('setPageBrightTime success') } ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Set the current page screen lighting time, this setting will follow the page destruction to do reset. ## Type ```ts function setPageBrightTime(option: Option): Result ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | ---------- | ------------------- | -------- | ------------------ | -------------------------------------------------------------- | --------- | | brightTime | `number` | N | `10000` | Screen lighting time (milliseconds), range [1000 - 2147483000] | 2.0 | ### Result | Type | Description | | ------------------- | ---------------------------------------- | | `number` | If `0` is returned, success is indicated | ## Example ```js const result = setPageBrightTime({ brightTime: 60000, }) if (result === 0) { console.log('setPageBrightTime success') } ``` --- ## setScreenOff ### Import ```js import { setScreenOff } from '@zos/display' ``` ### Typings - Description: Set the screen to rest - Example: ```js import { setScreenOff } from '@zos/display' const result = setScreenOff() if (result === 0) { console.log('setScreenOff success') } ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Set the screen to rest. ## Type ```ts function setScreenOff(): Result ``` ## Parameters ### Result | Type | Description | | ------------------- | ---------------------------------------- | | `number` | If `0` is returned, success is indicated | ## Example ```js const result = setScreenOff() if (result === 0) { console.log('setScreenOff success') } ``` --- ## setWakeUpRelaunch ### Import ```js import { setWakeUpRelaunch } from '@zos/display' ``` ### Typings - Description: By default, the system will off the screen in one page of the Mini Program, and the system will exit the Mini Program after 10s, and enter the dial page when the watch is woken up again. If `relaunch` is set to `true`, the Mini Program will reopen and enter the corresponding page when the watch is woken up again - Example: ```js import { setWakeUpRelaunch } from '@zos/display' setWakeUpRelaunch({ relaunch: true }) ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). By default, the system will off the screen in one page of the Mini Program, and the system will exit the Mini Program after 10s, and enter the dial page when the watch is woken up again. If `relaunch` is set to `true`, the Mini Program will reopen and enter the corresponding page when the watch is woken up again. ## Type ```ts function setWakeUpRelaunch(option: Option): void ``` ### Simplified calling method ```ts function setWakeUpRelaunch(relaunch: boolean): void ``` ## Parameters ### Option | Type | Description | | --------------------------------- | ------------------------------------------------------------------------------ | | `Options|boolean` | `true` - auto-brightness is set to on, `false` - auto-brightness is set to off | ### Options | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | -------------------- | -------- | ------------ | --------------------------------------------------------------------------------------- | --------- | | relaunch | `boolean` | Y | - | Whether to reopen the Mini Program after waking up the watch again after a screen break | 2.0 | ## Example ```js setWakeUpRelaunch({ relaunch: true, }) ``` --- --- # @zos/fs ## Constants | Constant | Description | API_LEVEL | |----------|-------------|-----------| | `O_RDONLY` | Flag indicating to open a file for read-only access | — | | `O_WRONLY` | Flag indicating to open a file for write-only access | — | | `O_RDWR` | Flag indicating to open a file for read-write access | — | | `O_APPEND` | Flag indicating that data will be appended to the end of the file | — | | `O_CREAT` | Flag indicating to create the file if it does not already exist | — | | `O_EXCL` | Flag indicating that opening a file should fail if the `O_CREAT` flag is set and the file already exists | — | | `O_TRUNC` | Flag indicating that if the file exists and the file is opened successfully for write access, its length shall be truncated to zero | — | ## closeSync ### Import ```js import { openSync, closeSync, O_RDONLY } from '@zos/fs' ``` ### Typings - Description: Close the file handle synchronously - Example: ```js import { openSync, closeSync, O_RDONLY } from '@zos/fs' const fd = openSync({ path: 'test.txt', flag: O_RDONLY }) const result = closeSync({ fd }) if (result === 0) { console.log('file descriptor closed') } ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Close the file handle synchronously. ## Type ```ts function closeSync(option: Option): Result ``` ### Simplified calling method ```ts function closeSync(fd: number): Result ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | ------------------- | -------- | ------------ | ------------------------------------------------------------------------ | --------- | | fd | `number` | Y | - | File handle, returned by the `openSync`, `openAssetsSync` and other APIs | 2.0 | ### Result | Type | Description | | ------------------- | ---------------------------------------- | | `number` | If `0` is returned, success is indicated | ## Example ```js const fd = openSync({ path: 'test.txt', flag: O_RDONLY, }) const result = closeSync({ fd, }) if (result === 0) { console.log('file descriptor closed') } ``` --- ## mkdirSync ### Import ```js import { mkdirSync } from '@zos/fs' ``` ### Typings - Description: Synchronously create a directory in the `/data` directory of the Mini Program - Example: ```js import { mkdirSync } from '@zos/fs' const result = mkdirSync({ path: 'content', }) if (result === 0) { console.log('mkdirSync success') } ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Synchronously create a directory in the `/data` directory of the Mini Program. ## Type ```ts function mkdirSync(option: Option): Result ``` ### Simplified calling method ```ts function mkdirSync(path: string): Result ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | ------------------- | -------- | ------------ | -------------- | --------- | | path | `string` | Y | - | Directory path | 2.0 | ### Result | Type | Description | | ------------------- | ---------------------------------------- | | `number` | If `0` is returned, success is indicated | ## Example ```js const result = mkdirSync({ path: 'content', }) if (result === 0) { console.log('mkdirSync success') } ``` --- ## openAssetsSync ### Import ```js import { openSync, O_RDONLY } from '@zos/fs' ``` ### Typings - Description: Open the file in the `/assets` directory of the Mini Program synchronously and get the file handle - Constants: `open` - Example: ```js import { openSync, O_RDONLY } from '@zos/fs' const fd = openAssetsSync({ path: 'test.txt', flag: O_RDONLY }) ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Open the file in the `/assets` directory of the Mini Program synchronously and get the file handle. ## Type ```ts function openAssetsSync(option: Option): Result ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | ------------------- | -------- | --------------------- | ---------------------------------- | --------- | | path | `string` | Y | - | path | 2.0 | | flag | `number` | N | `O_RDONLY` | Value refer to file open constants | 2.0 | ### Result | Type | Description | | ------------------- | --------------------------- | | `number` | The numeric file descriptor | ## Constants ### file open constants | Constant | Description | API_LEVEL | | ---------- | ----------------------------------------------------------------------------------------------------------------------------------- | --------- | | `O_RDONLY` | Flag indicating to open a file for read-only access | 2.0 | | `O_WRONLY` | Flag indicating to open a file for write-only access | 2.0 | | `O_RDWR` | Flag indicating to open a file for read-write access | 2.0 | | `O_APPEND` | Flag indicating that data will be appended to the end of the file | 2.0 | | `O_CREAT` | Flag indicating to create the file if it does not already exist | 2.0 | | `O_EXCL` | Flag indicating that opening a file should fail if the `O_CREAT` flag is set and the file already exists | 2.0 | | `O_TRUNC` | Flag indicating that if the file exists and the file is opened successfully for write access, its length shall be truncated to zero | 2.0 | ## Example ```js const fd = openAssetsSync({ path: 'test.txt', flag: O_RDONLY, }) ``` --- ## openSync ### Import ```js import { openSync, O_RDONLY } from '@zos/fs' ``` ### Typings - Description: Open the file in the `/data` directory of the Mini Program synchronously and get the file handle - Constants: `open` - Example: ```js import { openSync, O_RDONLY } from '@zos/fs' const fd = openSync({ path: 'test.txt', flag: O_RDONLY }) ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Open the file in the `/data` directory of the Mini Program synchronously and get the file handle. ## Type ```ts function openSync(option: Option): Result ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | -------------------- | -------- | --------------------- | ---------------------------------- | --------- | | path | `string` | Y | - | path | 2.0 | | flag | `number` | N | `O_RDONLY` | Value refer to file open constants | 2.0 | | options | `Options` | N | - | Other Options | 3.0 | ### Options | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | ------------------- | -------- | ------------ | ------------------------------------------------------------------------------------------------------------- | --------- | | appId | `number` | N | - | Mini Program ID, you can open the file in the `/data` directory of the Mini Program with the corresponding ID | 3.0 | ### Result | Type | Description | | ------------------- | --------------------------- | | `number` | The numeric file descriptor | ## Constants ### file open constants | Constant | Description | API_LEVEL | | ---------- | ----------------------------------------------------------------------------------------------------------------------------------- | --------- | | `O_RDONLY` | Flag indicating to open a file for read-only access | 2.0 | | `O_WRONLY` | Flag indicating to open a file for write-only access | 2.0 | | `O_RDWR` | Flag indicating to open a file for read-write access | 2.0 | | `O_APPEND` | Flag indicating that data will be appended to the end of the file | 2.0 | | `O_CREAT` | Flag indicating to create the file if it does not already exist | 2.0 | | `O_EXCL` | Flag indicating that opening a file should fail if the `O_CREAT` flag is set and the file already exists | 2.0 | | `O_TRUNC` | Flag indicating that if the file exists and the file is opened successfully for write access, its length shall be truncated to zero | 2.0 | ## Example ```js const fd = openSync({ path: 'test.txt', flag: O_RDONLY, }) ``` --- ## readFileSync ### Import ```js import { readFileSync } from '@zos/fs' ``` ### Typings - Description: Returns the entire contents of the specified file in the `/data` directory of the Mini Program - Example: ```js import { readFileSync } from '@zos/fs' const contentBuffer = readFileSync({ path: 'test.txt', }) const contentString = readFileSync({ path: 'test.txt', options: { encoding: 'utf8' } }) ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Returns the entire contents of the specified file in the `/data` directory of the Mini Program. ## Type ```ts function readFileSync(option: Option): Result ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | -------------------- | -------- | ------------ | ------------- | --------- | | path | `string` | Y | - | path | 2.0 | | options | `Options` | N | - | Other Options | 2.0 | ### Options | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | ------------------- | -------- | ------------ | ----------------------------------------------------------------------------- | --------- | | encoding | `string` | N | - | When the encoding method is specified, the API returns `string` as the result | 2.0 | ### Result | Type | Description | | --------------------------------------------------- | -------------------------------------------------------------------- | | `ArrayBuffer|string|undefined` | File content. If `undefined` is returned, the file failed to be read | ## Example ```js const contentBuffer = readFileSync({ path: 'test.txt', }) const contentString = readFileSync({ path: 'test.txt', options: { encoding: 'utf8', }, }) ``` --- ## readSync ### Import ```js import { openSync, readSync, O_RDONLY } from '@zos/fs' ``` ### Typings - Description: Synchronously reads the content from the file specified by the file handle into the given `ArrayBuffer`. - Example: ```js import { openSync, readSync, O_RDONLY } from '@zos/fs' const fd = openSync({ path: 'test.txt', flag: O_RDONLY }) const buffer = new ArrayBuffer(4) const result = readSync({ fd, buffer }) ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Synchronously reads the content from the file specified by the file handle into the given `ArrayBuffer`.. ## Type ```ts function readSync(option: Option): Result ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | ------------------------ | -------- | ------------ | ------------------------------------------------------------------------ | --------- | | fd | `number` | Y | - | File handle, returned by the `openSync`, `openAssetsSync` and other APIs | 2.0 | | buffer | `ArrayBuffer` | Y | - | The ArrayBuffer that the data will be written to | 2.0 | | options | `Options` | N | - | Other Options | 2.0 | ### Options | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | ----------------------------- | -------- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | | offset | `number` | N | `0` | The position in buffer to write the data to | 2.0 | | length | `number` | N | `buffer.byteLength` | The number of bytes to read, the default is the number of bytes passed into the buffer | 2.0 | | position | `number|null` | N | `null` | Specifies the position from which to start reading from the file. If `position` is `null`, the data will be read from the current file position and the file position will be updated | 2.0 | ### Result | Type | Description | | ------------------- | ------------------------ | | `number` | The number of bytes read | ## Example ```js const fd = openSync({ path: 'test.txt', flag: O_RDONLY, }) const buffer = new ArrayBuffer(4) const result = readSync({ fd, buffer, }) ``` --- ## readdirSync ### Import ```js import { readdirSync } from '@zos/fs' ``` ### Typings - Description: Read the directory under the `/data` directory of the Mini Program synchronously - Example: ```js import { readdirSync } from '@zos/fs' const result = readdirSync({ path: 'content', }) ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Read the directory under the `/data` directory of the Mini Program synchronously. ## Type ```ts function readdirSync(option: Option): Result ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | ------------------- | -------- | ------------ | -------------- | --------- | | path | `string` | Y | - | Directory path | 2.0 | ### Result | Type | Description | | ------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | | `Array|undefined` | If `undefined` is returned, the directory does not exist, otherwise an array of filenames is returned | ## Example ```js const result = readdirSync({ path: 'content', }) ``` --- ## renameSync ### Import ```js import { renameSync } from '@zos/fs' ``` ### Typings - Description: Rename the files in the `/data` directory of the Mini Program, renaming the files from `oldPath` to `newPath` - Example: ```js import { renameSync } from '@zos/fs' const result = renameSync({ oldPath: 'test.txt', newPath: 'new_test.txt' }) if (result === 0) { console.log('renameSync success') } ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Rename the files in the `/data` directory of the Mini Program, renaming the files from `oldPath` to `newPath`. ## Type ```ts function renameSync(option: Option): Result ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | ------------------- | -------- | ------------ | ----------- | --------- | | oldPath | `string` | Y | - | Old path | 2.0 | | newPath | `string` | Y | - | New path | 2.0 | ### Result | Type | Description | | ------------------- | ---------------------------------------- | | `number` | If `0` is returned, success is indicated | ## Example ```js const result = renameSync({ oldPath: 'test.txt', newPath: 'new_test.txt', }) if (result === 0) { console.log('renameSync success') } ``` --- ## rmSync ### Import ```js import { rmSync } from '@zos/fs' ``` ### Typings - Description: Synchronously delete files in the `/data` directory of the Mini Program - Example: ```js import { rmSync } from '@zos/fs' const result = rmSync({ path: 'test.txt', }) if (result === 0) { console.log('rmSync success') } ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Synchronously delete files in the `/data` directory of the Mini Program. ## Type ```ts function rmSync(option: Option): Result ``` ### Simplified calling method ```ts function rmSync(path: string): Result ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | ------------------- | -------- | ------------ | ----------- | --------- | | path | `string` | Y | - | path | 2.0 | ### Result | Type | Description | | ------------------- | ---------------------------------------- | | `number` | If `0` is returned, success is indicated | ## Example ```js const result = rmSync({ path: 'test.txt', }) if (result === 0) { console.log('rmSync success') } ``` --- ## statAssetsSync ### Import ```js import { statAssetsSync } from '@zos/fs' ``` ### Typings - Description: Synchronously gets information about the files in the Mini Program `/assets` directory - Example: ```js import { statAssetsSync } from '@zos/fs' const result = statAssetsSync({ path: 'test.txt', }) if (result) { const { size } = result console.log(size) } ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Synchronously gets information about the files in the Mini Program `/assets` directory. ## Type ```ts function statAssetsSync(option: Option): Result ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | ------------------- | -------- | ------------ | ----------- | --------- | | path | `string` | Y | - | path | 2.0 | ### Result | Type | Description | | ---------------------------------- | ------------------------------------------------------------------------------------------------------------- | | `FSStat|undefined` | If `undefined` is returned, the target file does not exist, otherwise the file information object is returned | ### FSStat | Property | Type | Description | API_LEVEL | | -------- | ------------------- | ----------------------------- | --------- | | size | `number` | The size of the file in bytes | 2.0 | ## Example ```js const result = statAssetsSync({ path: 'test.txt', }) if (result) { const { size } = result console.log(size) } ``` --- ## statSync ### Import ```js import { statSync } from '@zos/fs' ``` ### Typings - Description: Get information about the files in the `/data` directory of the Mini Program synchronously - Example: ```js import { statSync } from '@zos/fs' const result = statSync({ path: 'test.txt', }) if (result) { const { size } = result console.log(size) } ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Get information about the files in the `/data` directory of the Mini Program synchronously. ## Type ```ts function statSync(option: Option): Result ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | ------------------- | -------- | ------------ | ----------- | --------- | | path | `string` | Y | - | path | 2.0 | ### Result | Type | Description | | ---------------------------------- | ------------------------------------------------------------------------------------------------------------- | | `FSStat|undefined` | If `undefined` is returned, the target file does not exist, otherwise the file information object is returned | ### FSStat | Property | Type | Description | API_LEVEL | | -------- | ------------------- | ----------------------------- | --------- | | size | `number` | The size of the file in bytes | 2.0 | ## Example ```js const result = statSync({ path: 'test.txt', }) if (result) { const { size } = result console.log(size) } ``` --- ## writeFileSync ### Import ```js import { writeFileSync } from '@zos/fs' ``` ### Typings - Description: Synchronously write data to a file in the `/data` directory of the Mini Program, replacing the file if it already exists, or creating a new file if it doesn't - Example: ```js import { writeFileSync } from '@zos/fs' const buffer = new ArrayBuffer(4) writeFileSync({ path: 'test.txt', data: buffer }) writeFileSync({ path: 'content.txt', data: 'some content...', options: { encoding: 'utf8' } }) ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Synchronously write data to a file in the `/data` directory of the Mini Program, replacing the file if it already exists, or creating a new file if it doesn't. ## Type ```ts function writeFileSync(option: Option): void ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | -------------------------------------------------- | -------- | ------------ | ------------------------------------- | --------- | | path | `string|number` | Y | - | File path or file descriptor | 2.0 | | data | `ArrayBuffer|string|DataView` | Y | - | Data to be written to the target file | 2.0 | | options | `Options` | N | - | Other Options | 2.0 | ### Options | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | ------------------- | -------- | ----------------- | ------------------------------------------------------------------------- | --------- | | encoding | `string` | N | `utf8` | If the `data` format is `string`, you need to specify the encoding method | 2.0 | ## Example ```js const buffer = new ArrayBuffer(4) writeFileSync({ path: 'test.txt', data: buffer, }) writeFileSync({ path: 'content.txt', data: 'some content...', options: { encoding: 'utf8', }, }) ``` --- ## writeSync ### Import ```js import { openSync, writeSync, O_RDWR, O_CREAT } from '@zos/fs' ``` ### Typings - Description: Synchronously write ArrayBuffer to the file specified by fd - Example: ```js import { openSync, writeSync, O_RDWR, O_CREAT } from '@zos/fs' const fd = openSync({ path: 'test.txt', flag: O_RDWR | O_CREAT }) const buffer = new ArrayBuffer(4) const result = writeSync({ fd, buffer }) ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Synchronously write ArrayBuffer to the file specified by fd. ## Type ```ts function writeSync(option: Option): Result ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | ------------------------ | -------- | ------------ | ------------------------------------------------------------------------ | --------- | | fd | `number` | Y | - | File handle, returned by the `openSync`, `openAssetsSync` and other APIs | 2.0 | | buffer | `ArrayBuffer` | Y | - | The buffer that the data will be written to | 2.0 | | options | `Options` | N | - | Other Options | 2.0 | ### Options | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | ----------------------------- | -------- | ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | | offset | `number` | N | `0` | Based on first address offset in ArrayBuffer to write the data | 2.0 | | length | `number` | N | `buffer.byteLength` | The number of bytes to write, the default is the length of the incoming buffer | 2.0 | | position | `number|null` | N | `null` | Position refers to the offset from the beginning of the file where this data should be written. If position is 'null', the data will be written at the and the file position will be updated | 2.0 | ### Result | Type | Description | | ------------------- | --------------------------- | | `number` | The number of bytes written | ## Example ```js const fd = openSync({ path: 'test.txt', flag: O_RDWR | O_CREAT, }) const buffer = new ArrayBuffer(4) const result = writeSync({ fd, buffer, }) ``` --- --- # @zos/global ## App > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Register the Mini Program, specifying the Mini Program's lifecycle callbacks, etc. `App()` must be called in `app.js`, and can only be called once. ## Type ```ts function App(option: Option): Result ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | ---------- | ------------------------------------------ | -------- | ------------ | ---------------------------------------------------------------------------------------------------- | --------- | | globalData | `object` | N | - | Mounted data objects on App instances that can be used to store the global state of the Mini Program | 2.0 | | onCreate | `(params?: string) => void` | N | - | Mounted data objects on App instances that can be used to store the global state of the Mini Program | 2.0 | | onDestroy | `() => void` | N | - | The `onDestroy` lifecycle function is triggered when the Mini Program is destroyed | 2.0 | ### Result | Type | Description | | -------------------- | ------------ | | `unknown` | App instance | ## Example ```js title="app.js" App({ globalData: { text: 'Hello Zepp OS', }, onCreate() { console.log('onCreate') console.log(this.globalData.text) }, onDestroy() { console.log('onDestroy') }, }) ``` --- ## AppService > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Register an App Service in the Mini Program, specify the lifecycle callback for the current App Service, etc. Each App Service file must call the `AppService()` constructor only once. > **ℹ️ Info** > > permission code: `device:os.bg_service` ## Type ```ts function AppService(option: Option): Result ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | --------- | ------------------------------------------ | -------- | ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | | state | `object` | N | - | A data object mounted on the appService instance that can be used to store the current state of the service | 3.0 | | onInit | `(params?: string) => void` | N | - | This function is triggered when the service is started. If the service is started with params, the params string can be obtained in the onInit method | 3.0 | | onDestroy | `() => void` | N | - | The `onDestroy` lifecycle function is triggered when the service is destroyed | 3.0 | ### Result | Type | Description | | -------------------- | ------------------- | | `unknown` | AppService instance | ## Example ```js title="appService.js" AppService({ state: { text: 'Hello Zepp OS', }, onInit() { console.log('onInit') }, }) ``` --- ## AppWidget > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Register AppWidget, specify the lifecycle callback for the current AppWidget, etc. Each AppWidget file must call the `AppWidget()` constructor only once. ## Type ```ts function AppWidget(option: Option): Result ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | --------- | ------------------------------------------ | -------- | ------------ | ---------------------------------------------------------------------------------------------------------- | --------- | | state | `object` | N | - | A data object mounted on a AppWidget instance that can be used to store the state of the current AppWidget | 2.0 | | onInit | `(params?: string) => void` | N | - | It is triggered once per AppWidget and can be used to initialize the AppWidget state | 2.0 | | build | `(params?: string) => void` | N | - | Triggered after `onInit` execution completes, recommended for UI drawing in the `build` lifecycle | 2.0 | | onResume | `() => void` | N | - | Triggered when the screen focus is on this AppWidget | 2.0 | | onPause | `() => void` | N | - | Triggered when the screen focus leaves this AppWidget | 2.0 | | onDestroy | `() => void` | N | - | The `onDestroy` lifecycle function is triggered when the AppWidget is destroyed | 2.0 | ### Result | Type | Description | | -------------------- | ------------------ | | `unknown` | AppWidget instance | ## Example ```js title="appWidget.js" AppWidget({ state: { text: 'Hello Zepp OS', }, onInit() { console.log('onInit') }, build() { console.log('build') console.log(this.state.text) }, }) ``` --- ## Buffer > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Buffer, Reference Node.js https://nodejs.org/dist/latest-v16.x/docs/api/buffer.html. ## Example ```js Buffer.from('Hello Zepp OS') ``` --- ## DataWidget > Start from API_LEVEL `3.6` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Register DataWidget, specify the lifecycle callback for the current DataWidget, etc. Each DataWidget file must call the `DataWidget()` constructor only once. ## Type ```ts function DataWidget(option: Option): Result ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | --------- | ------------------------------------------ | -------- | ------------ | ------------------------------------------------------------------------------------------------------------ | --------- | | state | `object` | N | - | A data object mounted on a DataWidget instance that can be used to store the state of the current DataWidget | 3.6 | | onInit | `(params?: string) => void` | N | - | It is triggered once per DataWidget and can be used to initialize the DataWidget state | 3.6 | | build | `(params?: string) => void` | N | - | Triggered after `onInit` execution completes, recommended for UI drawing in the `build` lifecycle | 3.6 | | onResume | `() => void` | N | - | Triggered when the screen focus is on this DataWidget | 3.6 | | onPause | `() => void` | N | - | Triggered when the screen focus leaves this DataWidget | 3.6 | | onDestroy | `() => void` | N | - | The `onDestroy` lifecycle function is triggered when the DataWidget is destroyed | 3.6 | ### Result | Type | Description | | ------------------- | ------------------- | | `object` | DataWidget instance | ## Example ```js title="DataWidget.js" DataWidget({ state: { text: 'Hello Zepp OS', }, onInit() { console.log('onInit') }, build() { console.log('build') console.log(this.state.text) }, }) ``` --- ## Page > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Register a page in the Mini Program, specify the lifecycle callback for the current page, etc. Each page file must call the `Page()` constructor only once. ## Type ```ts function Page(option: Option): Result ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | --------- | ------------------------------------------ | -------- | ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | | state | `object` | N | - | A data object mounted on a page instance that can be used to store the state of the current page | 2.0 | | onInit | `(params?: string) => void` | N | - | It is triggered once per page and can be used to initialize the page state. If the page is opened by the relevant method in the router module with params parameters, the params string can be retrieved in the onInit method | 2.0 | | build | `(params?: string) => void` | N | - | Triggered after `onInit` execution completes, recommended for UI drawing in the `build` lifecycle | 2.0 | | onDestroy | `() => void` | N | - | The `onDestroy` lifecycle function is triggered when the page is destroyed | 2.0 | ### Result | Type | Description | | -------------------- | ------------- | | `unknown` | Page instance | ## Example ```js title="page.js" Page({ state: { text: 'Hello Zepp OS', }, onInit() { console.log('onInit') }, build() { console.log('build') console.log(this.state.text) }, }) ``` --- ## SecondaryWidget > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Register SecondaryWidget, specify the lifecycle callback for the current SecondaryWidget, etc. Each SecondaryWidget file must call the `SecondaryWidget()` constructor only once. ## Type ```ts function SecondaryWidget(option: Option): Result ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | --------- | ------------------------------------------ | -------- | ------------ | ---------------------------------------------------------------------------------------------------------------------- | --------- | | state | `object` | N | - | A data object mounted on a SecondaryWidget instance that can be used to store the state of the current SecondaryWidget | 2.0 | | onInit | `(params?: string) => void` | N | - | It is triggered once per SecondaryWidget and can be used to initialize the SecondaryWidget state | 2.0 | | build | `(params?: string) => void` | N | - | Triggered after `onInit` execution completes, recommended for UI drawing in the `build` lifecycle | 2.0 | | onResume | `() => void` | N | - | Triggered when the screen focus is on this SecondaryWidget | 2.0 | | onPause | `() => void` | N | - | Triggered when the screen focus leaves this SecondaryWidget | 2.0 | | onDestroy | `() => void` | N | - | The `onDestroy` lifecycle function is triggered when the SecondaryWidget is destroyed | 2.0 | ### Result | Type | Description | | -------------------- | ------------------------ | | `unknown` | SecondaryWidget instance | ## Example ```js title="secondaryWidget.js" SecondaryWidget({ state: { text: 'Hello Zepp OS', }, onInit() { console.log('onInit') }, build() { console.log('build') console.log(this.state.text) }, }) ``` --- ## clearInterval > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Cancel the timer registered by `setInterval`. ## Type ```ts function clearInterval(intervalID: IntervalID): void ``` ## Parameters ### IntervalID | Type | Description | | ------------------- | ------------ | | `number` | Timer number | ## Example ```js const intervalID = setInterval(() => { console.log('Hello Zepp OS') }, 1000) clearInterval(intervalID) ``` --- ## clearTimeout > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Cancel the timer registered by `setTimeout`. ## Type ```ts function clearTimeout(timeoutID: TimeoutID): void ``` ## Parameters ### TimeoutID | Type | Description | | ------------------- | ------------ | | `number` | Timer number | ## Example ```js const timeoutID = setTimeout(() => { console.log('Hello Zepp OS') }, 1000) clearTimeout(timeoutID) ``` --- ## console > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Console Print Log. ## Methods ### log Print log level logs with any number of parameters. Each log is limited in length and will be truncated if it is exceeded. To print the full content, the developer needs to print the content in multiple times ```ts log(...data: any[]): void ``` ## Example ```js console.log('Hello Zepp OS') ``` --- ## getApp > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Get the app instance object. ## Type ```ts function getApp(): Result ``` ## Parameters ### Result | Property | Type | Description | API_LEVEL | | --------- | -------------------- | --------------------- | --------- | | \_options | `Options` | app instance property | 2.0 | ### Options | Property | Type | Description | API_LEVEL | | ---------- | ------------------- | ------------------------------------- | --------- | | globalData | `object` | mounted data objects on app instances | 2.0 | ## Example ```js App({ globalData: { text: 'Hello Zepp OS', }, onCreate() { console.log('onCreate') console.log(this.globalData.text) }, onDestroy() { console.log('onDestroy') }, }) const app = getApp() console.log(app._options.globalData.text) ``` --- ## getCurrentPage > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Get the page instance object. ## Type ```ts function getCurrentPage(): Result ``` ## Parameters ### Result | Property | Type | Description | API_LEVEL | | --------- | -------------------- | ---------------------- | --------- | | \_options | `Options` | page instance property | 2.0 | ### Options | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | ------------------- | -------- | ------------ | -------------------------------------- | --------- | | state | `object` | N | - | mounted data objects on page instances | 2.0 | ## Example ```js title="page.js" Page({ state: { text: 'Hello Zepp OS', }, onInit() { console.log('onInit') }, build() { console.log('build') console.log(this.state.text) }, }) const page = getCurrentPage() console.log(page._options.state.text) ``` --- ## setInterval > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Repeatedly call a function with a fixed time interval between each call. ## Type ```ts function setInterval(callback: Callback, delay: Delay): IntervalID ``` ## Parameters ### Callback | Type | Description | | ------------------------------ | ------------------------------------ | | `() => unknown` | Repeatedly called callback functions | ### Delay | Type | Description | | ------------------- | ------------------------------------------------- | | `number` | Time interval between each callback function call | ### IntervalID | Type | Description | | ------------------- | ------------ | | `number` | Timer number | ## Example ```js setInterval(() => { console.log('Hello Zepp OS') }, 1000) ``` --- ## setTimeout > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Set a timer and execute the registered callback function after the timer expires. ## Type ```ts function setTimeout(callback: Callback, delay?: Delay): TimeoutID ``` ## Parameters ### Callback | Type | Description | | ------------------------------ | --------------------------------------------------- | | `() => unknown` | Callback functions executed after the timer expires | ### Delay | Type | Description | | ------------------- | ------------------------------------------------------------- | | `number` | The number of milliseconds to delay the function, default 1ms | ### TimeoutID | Type | Description | | ------------------- | ------------ | | `number` | Timer number | ## Example ```js setTimeout(() => { console.log('Hello Zepp OS') }, 1000) ``` --- --- # @zos/i18n ## getText ### Import ```js import { getText } from '@zos/i18n' ``` ### Typings - Description: Get the corresponding string from the internationalization resource file (.po) based on the internationalization key - Example: ```js import { getText } from '@zos/i18n' getText('name') ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Get the corresponding string from the internationalization resource file (.po) based on the internationalization key. ## Type ```ts function getText(key: Key): Result ``` ## Parameters ### Key | Type | Description | | ------------------- | ------------------------ | | `string` | Internationalization key | ### Result | Type | Description | | ------------------- | ----------------------------------------------------- | | `string` | The string corresponding to the internationalized key | ## Example ```js getText('name') ``` --- --- # @zos/interaction ## Constants | Constant | Description | API_LEVEL | |----------|-------------|-----------| | `GESTURE_UP` | Gesture up slide | — | | `GESTURE_DOWN` | Gesture down slide | — | | `GESTURE_LEFT` | Gesture left slide | — | | `GESTURE_RIGHT` | Gesture right slide | — | | `KEY_BACK` | BACK KEY | — | | `KEY_SELECT` | SELECT KEY | — | | `KEY_HOME` | HOME KEY | — | | `KEY_UP` | UP KEY | — | | `KEY_DOWN` | SHORTCUT KEY | — | | `KEY_SHORTCUT` | SHORTCUT KEY | — | | `KEY_EVENT_CLICK` | Key click event | — | | `KEY_EVENT_LONG_PRESS` | Key long-press event | — | | `KEY_EVENT_DOUBLE_CLICK` | Key double-click event | — | | `KEY_EVENT_PRESS` | Key press event | — | | `KEY_EVENT_RELEASE` | Key release event | — | | `MODAL_CONFIRM` | Modal Confirm button | — | | `MODAL_CANCEL` | Modal Cancel button | — | | `WRIST_MOTION_LIFT` | Wrist lift | — | | `WRIST_MOTION_LOWER` | Wrist down | — | | `WRIST_MOTION_FLIP` | Flip wrist movement | — | ## createModal ### Import ```js import { createModal, MODAL_CONFIRM } from '@zos/interaction' ``` ### Typings - Description: Create Modal prompt box - Constants: `modalKey` - Example: ```js import { createModal, MODAL_CONFIRM } from '@zos/interaction' const dialog = createModal({ content: 'hello world', autoHide: false, onClick: (keyObj) => { const { type } = keyObj if (type === MODAL_CONFIRM) { console.log('confirm') } else { dialog.show(false) } } }) dialog.show(true) ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). [Image: createModal_image] Create Modal prompt box. ## Type ```ts function createModal(option: Option): Modal ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | ------------- | ----------------------------------------- | -------- | --------------------- | ------------------------------------------------------------------------------------------------------- | --------- | | content | `string` | Y | - | title of Modal | 2.0 | | title | `string` | N | - | Modal dialog box title, alias for `content` | 3.6 | | show | `boolean` | N | `true` | Whether to display Modal immediately after the creation is completed | 2.0 | | onClick | `(keyObj: KeyObj) => void` | N | - | Whether to display Modal immediately | 2.0 | | autoHide | `boolean` | N | `true` | Whether to automatically close the Modal dialog after clicking the Confirm or Cancel button | 2.0 | | subtitle | `string` | N | - | subtitle | 3.6 | | src | `string` | N | - | Icon icon path | 3.6 | | text | `string` | N | - | text content | 3.6 | | textColor | `number` | N | `0xFFFFFF` | text color | 3.6 | | textAlpha | `number` | N | `255` | Text transparency, transparency [0-255], 0 is full transparency | 3.6 | | okButton | `string` | N | - | The icon path of the confirmation button | 3.6 | | cancelButton | `string` | N | - | Cancel button icon icon path | 3.6 | | capsuleButton | `Array` | N | - | Capsule button configuration, as a string array, click `type` in the returned KeyObj starting from `10` | 3.6 | ### KeyObj | Property | Type | Description | API_LEVEL | | -------- | ------------------- | -------------------------------------------------------- | --------- | | type | `number` | Modal key name, value reference Modal key name constants | 2.0 | ### Modal | Property | Type | Description | API_LEVEL | | -------- | ------------------------------------------ | ------------------ | --------- | | show | `(isShow: boolean) => void` | Show or hide Modal | 2.0 | ## Constants ### Modal key name constants | Constant | Description | API_LEVEL | | --------------- | -------------------- | --------- | | `MODAL_CONFIRM` | Modal Confirm button | 2.0 | | `MODAL_CANCEL` | Modal Cancel button | 2.0 | ## Example ```js const dialog = createModal({ content: 'hello world', autoHide: false, onClick: (keyObj) => { const { type } = keyObj if (type === MODAL_CONFIRM) { console.log('confirm') } else { dialog.show(false) } }, }) dialog.show(true) ``` --- ## offDigitalCrown ### Import ```js import { onDigitalCrown, offDigitalCrown, KEY_HOME } from '@zos/interaction' ``` ### Typings - Description: Cancel the `onDigitalCrown` registration to listen for digital crown rotation events - Example: ```js import { onDigitalCrown, offDigitalCrown, KEY_HOME } from '@zos/interaction' const callback = (key, degree) => { if (key === KEY_HOME) { console.log(degree) } } onDigitalCrown({ callback }) offDigitalCrown() ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Cancel the `onDigitalCrown` registration to listen for digital crown rotation events. ## Type ```ts function offDigitalCrown(): void ``` ## Example ```js const callback = (key, degree) => { if (key === KEY_HOME) { console.log(degree) } } onDigitalCrown({ callback, }) offDigitalCrown() ``` --- ## offGesture ### Import ```js import { onGesture, offGesture, GESTURE_UP } from '@zos/interaction' ``` ### Typings - Description: Cancel the `onGesture` registration to listen for user gesture events - Example: ```js import { onGesture, offGesture, GESTURE_UP } from '@zos/interaction' const gestureCallback = (event) => { if (event === GESTURE_UP) { console.log('up') } return true } onGesture({ callback: gestureCallback }) offGesture() ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Cancel the `onGesture` registration to listen for user gesture events. ## Type ```ts function offGesture(): void ``` ## Example ```js const gestureCallback = (event) => { if (event === GESTURE_UP) { console.log('up') } return true } onGesture({ callback: gestureCallback, }) offGesture() ``` --- ## offKey ### Import ```js import { onKey, offKey, KEY_UP, KEY_EVENT_CLICK } from '@zos/interaction' ``` ### Typings - Description: Cancel the keystroke event registered by `onKey`. - Example: ```js import { onKey, offKey, KEY_UP, KEY_EVENT_CLICK } from '@zos/interaction' const keyCallback = (key, keyEvent) => { if (key === KEY_UP && keyEvent === KEY_EVENT_CLICK) { console.log('up click') } return true } onKey({ callback: keyCallback }) offKey() ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Cancel the keystroke event registered by `onKey`.. ## Type ```ts function offKey(): void ``` ## Example ```js const keyCallback = (key, keyEvent) => { if (key === KEY_UP && keyEvent === KEY_EVENT_CLICK) { console.log('up click') } return true } onKey({ callback: keyCallback, }) offKey() ``` --- ## onDigitalCrown ### Import ```js import { onDigitalCrown, KEY_HOME } from '@zos/interaction' ``` ### Typings - Description: Listen to the digital crown rotation event, only one event is allowed to be registered, if multiple registrations will cause the last registered event to fail - Constants: `key` - Example: ```js import { onDigitalCrown, KEY_HOME } from '@zos/interaction' onDigitalCrown({ callback: (key, degree) => { if (key === KEY_HOME) { console.log(degree) } } }) ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Listen to the digital crown rotation event, only one event is allowed to be registered, if multiple registrations will cause the last registered event to fail. ## Type ```ts function onDigitalCrown(option: Option): void ``` ### Simplified calling method ```ts function onDigitalCrown(callback: (key: Key, degree: Degree) => void): void ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | --------------------------------------------------- | -------- | ------------ | ---------------------------------------------- | --------- | | callback | `(key: Key, degree: Degree) => void` | Y | - | Digital crown rotation event callback function | 2.0 | ### Key | Type | Description | | ------------------- | ------------------------------------------------------------------------------------ | | `number` | Key name, value reference key name constants, currently only `KEY_HOME` is supported | ### Degree | Type | Description | | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `number` | The rotation angle, positive number is counterclockwise rotation, negative number is clockwise rotation. The value is the angle of rotation, the faster the rotation speed, the larger the absolute value | ## Constants ### Key name constants | Constant | Description | API_LEVEL | | -------------- | ------------ | --------- | | `KEY_BACK` | BACK KEY | 2.0 | | `KEY_SELECT` | SELECT KEY | 2.0 | | `KEY_HOME` | HOME KEY | 2.0 | | `KEY_UP` | UP KEY | 2.0 | | `KEY_DOWN` | SHORTCUT KEY | 2.0 | | `KEY_SHORTCUT` | SHORTCUT KEY | 2.0 | ## Example ```js onDigitalCrown({ callback: (key, degree) => { if (key === KEY_HOME) { console.log(degree) } }, }) ``` --- ## onGesture ### Import ```js import { onGesture, GESTURE_UP } from '@zos/interaction' ``` ### Typings - Description: Listen to user gesture events, only one event is allowed to be registered, if multiple registrations will cause the last registered event to fail - Constants: `gestureEvent` - Example: ```js import { onGesture, GESTURE_UP } from '@zos/interaction' onGesture({ callback: (event) => { if (event === GESTURE_UP) { console.log('up') } return true } }) ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Listen to user gesture events, only one event is allowed to be registered, if multiple registrations will cause the last registered event to fail. ## Type ```ts function onGesture(option: Option): void ``` ### Simplified calling method ```ts function onGesture(callback: (event: GestureEvent) => PreventDefault): void ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | -------------------------------------------------------- | -------- | ------------ | ------------------------------- | --------- | | callback | `(event: GestureEvent) => PreventDefault` | Y | - | Gesture event callback function | 2.0 | ### GestureEvent | Type | Description | | ------------------- | ----------------------------------------------------------- | | `number` | Gesture event name, value reference gesture event constants | ### PreventDefault | Type | Description | | -------------------- | --------------------------------------------------------------------------------- | | `boolean` | Whether to skip the default gesture behavior, `true` - skip, `false` - don't skip | ## Constants ### Gesture event constants | Constant | Description | API_LEVEL | | --------------- | ------------------- | --------- | | `GESTURE_UP` | Gesture up slide | 2.0 | | `GESTURE_DOWN` | Gesture down slide | 2.0 | | `GESTURE_LEFT` | Gesture left slide | 2.0 | | `GESTURE_RIGHT` | Gesture right slide | 2.0 | ## Example ```js onGesture({ callback: (event) => { if (event === GESTURE_UP) { console.log('up') } return true }, }) ``` --- ## onKey ### Import ```js import { onKey, KEY_UP, KEY_EVENT_CLICK } from '@zos/interaction' ``` ### Typings - Description: Listen to key events, only one event is allowed to be registered, if multiple registrations will cause the last registered event to fail - Constants: `key`, `keyEvent` - Example: ```js import { onKey, KEY_UP, KEY_EVENT_CLICK } from '@zos/interaction' onKey({ callback: (key, keyEvent) => { if (key === KEY_UP && keyEvent === KEY_EVENT_CLICK) { console.log('up click') } return true } }) ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Listen to key events, only one event is allowed to be registered, if multiple registrations will cause the last registered event to fail. ## Type ```ts function onKey(option: Option): void ``` ### Simplified calling method ```ts function onKey(callback: (key: Key, event: KeyEvent) => PreventDefault): void ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | -------------------------------------------------------------- | -------- | ------------ | --------------------------- | --------- | | callback | `(key: Key, event: KeyEvent) => PreventDefault` | Y | - | Key event callback function | 2.0 | ### Key | Type | Description | | ------------------- | -------------------------------------------- | | `number` | Key name, value reference key name constants | ### KeyEvent | Type | Description | | ------------------- | --------------------------------------------------- | | `number` | Key event name, value reference key event constants | ### PreventDefault | Type | Description | | -------------------- | ----------------------------------------------------------------------------- | | `boolean` | Whether to skip the default key behavior, `true` - skip, `false` - don't skip | ## Constants ### Key name constants | Constant | Description | API_LEVEL | | -------------- | ------------ | --------- | | `KEY_BACK` | BACK KEY | 2.0 | | `KEY_SELECT` | SELECT KEY | 2.0 | | `KEY_HOME` | HOME KEY | 2.0 | | `KEY_UP` | UP KEY | 2.0 | | `KEY_DOWN` | SHORTCUT KEY | 2.0 | | `KEY_SHORTCUT` | SHORTCUT KEY | 2.0 | ### Key event constants | Constant | Description | API_LEVEL | | ------------------------ | ---------------------- | --------- | | `KEY_EVENT_CLICK` | Key click event | 2.0 | | `KEY_EVENT_LONG_PRESS` | Key long-press event | 2.0 | | `KEY_EVENT_DOUBLE_CLICK` | Key double-click event | 2.0 | | `KEY_EVENT_PRESS` | Key press event | 2.0 | | `KEY_EVENT_RELEASE` | Key release event | 2.0 | ## Example ```js onKey({ callback: (key, keyEvent) => { if (key === KEY_UP && keyEvent === KEY_EVENT_CLICK) { console.log('up click') } return true }, }) ``` --- ## onWristMotion ### Import ```js import { onWristMotion, WRIST_MOTION_LIFT } from '@zos/interaction' ``` ### Typings - Description: Monitoring hand movement events - API_LEVEL: 3.0 - Constants: `motion` - Example: ```js import { onWristMotion, WRIST_MOTION_LIFT } from '@zos/interaction' onWristMotion({ callback: (result) => { const { type, motion } = result if (type === 3) { console.log(motion === WRIST_MOTION_LIFT) } } }) ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Monitoring hand movement events. ## Type ```ts function onWristMotion(option: Option): void ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | ----------------------------------------- | -------- | ------------ | ---------------------------------------------- | --------- | | callback | `(params: Params) => void` | Y | - | Digital crown rotation event callback function | 3.0 | ### Params | Property | Type | Description | API_LEVEL | | -------- | ------------------- | ------------------------------------------------- | --------- | | type | `number` | Action type, 0 - palm covering, 3 - wrist event | 3.6 | | motion | `number` | Action code, value reference hand motion constant | 3.0 | ## Constants ### Hand motion constant | Constant | Description | API_LEVEL | | -------------------- | ------------------- | --------- | | `WRIST_MOTION_LIFT` | Wrist lift | 2.0 | | `WRIST_MOTION_LOWER` | Wrist down | 2.0 | | `WRIST_MOTION_FLIP` | Flip wrist movement | 2.0 | ## Example ```js onWristMotion({ callback: (result) => { const { type, motion } = result if (type === 3) { console.log(motion === WRIST_MOTION_LIFT) } }, }) ``` --- ## showToast ### Import ```js import { showToast } from '@zos/interaction' ``` ### Typings - Description: Display Message Prompt Box - Example: ```js import { showToast } from '@zos/interaction' showToast({ content: 'hello world' }) ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). [Image: showToast_image] Display Message Prompt Box. ## Type ```ts function showToast(option: Option): void ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | ------------------- | -------- | ------------ | --------------------- | --------- | | content | `string` | Y | - | Content of the prompt | 2.0 | ## Example ```js showToast({ content: 'hello world', }) ``` --- --- # @zos/media ## Constants | Constant | Description | API_LEVEL | |----------|-------------|-----------| | `codec` | Media audio codec types | 3.0 | ## Player ### Import ```js import { create, id } from '@zos/media' ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). [Image: Player_image] The media player controller sets audio sources, prepares playback resources, controls playback, and reads media information.. ## Properties ### source | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | ------------------- | -------- | ------------ | --------------------------- | --------- | | FILE | `number` | Y | - | Play a specified audio file | 3.0 | ### event | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | ------------------- | -------- | ------------ | ------------------------------------ | --------- | | PREPARE | `number` | Y | - | Asynchronous result of `prepare()` | 3.0 | | COMPLETE | `number` | Y | - | Audio playback completed | 3.0 | | PLAY | `number` | Y | - | Result after `start()` or `resume()` | 3.0 | | STOP | `number` | Y | - | Playback stopped | 3.0 | | PAUSE | `number` | Y | - | Playback paused | 3.0 | | PROGRESS | `number` | Y | - | Playback progress updated | 3.0 | ### state | Property | Type | Required | DefaultValue | Description | API_LEVEL | | ----------- | ------------------- | -------- | ------------ | ---------------------------- | --------- | | IDLE | `number` | Y | - | Initial state | 3.0 | | INITIALIZED | `number` | Y | - | State after `setSource()` | 3.0 | | PREPARING | `number` | Y | - | Intermediate preparing state | 3.0 | | PREPARED | `number` | Y | - | Resources prepared | 3.0 | | STARTING | `number` | Y | - | Intermediate starting state | 3.0 | | PLAY | `number` | Y | - | Playback in progress | 3.0 | | PAUSING | `number` | Y | - | Intermediate pausing state | 3.0 | | PAUSED | `number` | Y | - | Playback paused | 3.0 | | RESUMING | `number` | Y | - | Intermediate resuming state | 3.0 | ## Methods ### setSource Set playback parameters and specify the audio file path before playback starts. `player.source.FILE` supports MP3 files and OPUS files recorded with the audio API. `options.file` is relative to the mini program `assets` directory by default; use `data://` to access the `data` directory. ```ts setSource(source: Player['source']['FILE'], options: { file: string }): void ``` ### prepare Prepare the player by checking the path, file format, and supported bitrate. On success, the player changes state and starts buffering media data; use the event listener to get the result. ```ts prepare(): void ``` ### start Start playback ```ts start(): void ``` ### pause Pause playback ```ts pause(): void ``` ### resume Resume playback; has the same effect as calling `start()` ```ts resume(): void ``` ### stop Stop playback ```ts stop(): void ``` ### seek > Start from API_LEVEL `4.2` Set the playback position as a percentage of the total duration. `percentage` must be in [0 - 100]; the return value indicates whether the position was set successfully. - In `PREPARED`, playback starts automatically after `seek()` - In `PAUSED` or `PLAY`, the current state is preserved after `seek()` ```ts seek(percentage: number): boolean ``` ### seekTo > Start from API_LEVEL `4.3` Set the playback position in seconds; equivalent to `seek()` ```ts seekTo(seconds: number): boolean ``` ### getDuration Get the total duration of the current media file in seconds. A return value of `0` is invalid; the player must be in `PREPARED` to get the duration ```ts getDuration(): number ``` ### getVolume Get the current system volume in the range [0 - 100] ```ts getVolume(): number ``` ### setVolume Set the system volume in the range [0 - 100]. The return value indicates whether the setting succeeded; `true` means success ```ts setVolume(volume: number): boolean ``` ### getTitle Get the title of the current media file; returns `undefined` on failure ```ts getTitle(): string | undefined ``` ### getArtist Get the artist of the current media file; returns `undefined` on failure ```ts getArtist(): string | undefined ``` ### getMediaInfo Get the title, artist, and duration of the current media file. `title` and `artist` are available after `setSource()`; `duration` requires the player to be in `PREPARED` ```ts getMediaInfo(): { title: string | undefined artist: string | undefined duration: number } ``` ### getStatus Get the player state; see `player.state` for the meanings ```ts getStatus(): number ``` ### addEventListener Listen for playback state changes; `callback` is triggered when the state changes ```ts addEventListener(event: number, callback: (result: boolean | number | undefined) => void): void ``` ## Example ```js const player = create(id.PLAYER) player.addEventListener(player.event.PREPARE, (result) => { if (result) player.start() }) player.addEventListener(player.event.COMPLETE, () => { player.stop() }) player.setSource(player.source.FILE, { file: 'data://music.opus' }) const info = player.getMediaInfo() console.log(info.title, info.artist, info.duration) player.prepare() player.pause() player.resume() player.stop() ``` --- ## Recorder ### Import ```js import { codec, create, id } from '@zos/media' ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). The media recorder controller records audio to a file in the mini program `data` directory.. ## Properties ### event | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | ------------------- | -------- | ------------ | -------------------------------------- | --------- | | START | `number` | Y | - | Result reported after recording starts | 3.0 | | STOP | `number` | Y | - | Recording stopped | 3.0 | ### state | Property | Type | Required | DefaultValue | Description | API_LEVEL | | --------- | ------------------- | -------- | ------------ | ------------------------------ | --------- | | IDLE | `number` | Y | - | Initial state | 3.0 | | PREPARING | `number` | Y | - | Requesting recording resources | 3.0 | | STARTING | `number` | Y | - | Starting recording | 3.0 | | RECORDING | `number` | Y | - | Recording in progress | 3.0 | ## Methods ### setFormat Set the recording format and output file. Use a value from `codec`; `codec.OPUS` is currently supported. `options.target_file` specifies the output path in the mini program `data` directory, for example `data://record_file.opus` ```ts setFormat(codecValue: typeof codec.OPUS, options: { target_file: string }): void ``` ### start Start recording ```ts start(): void ``` ### stop Stop recording ```ts stop(): void ``` ### getStatus Get the recorder state; see `recorder.state` for the meanings ```ts getStatus(): number ``` ### addEventListener Listen for recorder state changes; `callback` is triggered when the state changes ```ts addEventListener(event: number, callback: (result: boolean | undefined) => void): void ``` ## Example ```js const recorder = create(id.RECORDER) recorder.addEventListener(recorder.event.START, (result) => { if (result) console.log('recording started') }) recorder.addEventListener(recorder.event.STOP, () => { console.log('recording stopped') }) recorder.setFormat(codec.OPUS, { target_file: 'data://record.opus', }) recorder.start() recorder.getStatus() recorder.stop() ``` --- ## create ### Import ```js import { codec, create, id } from '@zos/media' ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Create a media player or recorder. ## Type ```ts function create(controllerId: typeof id.PLAYER): Player function create(controllerId: typeof id.RECORDER): Recorder ``` ## Example ```js const player = create(id.PLAYER) player.setSource(player.source.FILE, { file: 'data://music.opus' }) player.prepare() const recorder = create(id.RECORDER) recorder.setFormat(codec.OPUS, { target_file: 'data://record.opus' }) recorder.start() recorder.stop() ``` --- --- # @zos/notification ## cancel ### Import ```js import { cancel } from '@zos/notification' ``` ### Typings - Description: Delete the notification message identified by the specified ID in the notification center - API_LEVEL: 3.0 - Permission: `device:os.notification` - Example: ```js import { cancel } from '@zos/notification' cancel(alarmID) ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Delete the notification message identified by the specified ID in the notification center. > **ℹ️ Info** > > permission code: `device:os.notification` ## Type ```ts function cancel(alarmId: number | Array): void ``` ## Example ```js cancel(alarmID) ``` --- ## getAllNotifications ### Import ```js import { getAllNotifications } from '@zos/notification' ``` ### Typings - Description: Get the notification IDs that have been sent by the current app and are still in the notification center - API_LEVEL: 3.0 - Permission: `device:os.notification` - Example: ```js import { getAllNotifications } from '@zos/notification' getAllNotifications() ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Get the notification IDs that have been sent by the current app and are still in the notification center. > **ℹ️ Info** > > permission code: `device:os.notification` ## Type ```ts function getAllNotifications(): Array ``` ## Example ```js getAllNotifications() ``` --- ## notify ### Import ```js import { notify } from '@zos/notification' ``` ### Typings - Description: Send notifications to the Watch Notification Center - API_LEVEL: 3.0 - Permission: `device:os.notification` - Example: ```js import { notify } from '@zos/notification' ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Send notifications to the Watch Notification Center. > **ℹ️ Info** > > permission code: `device:os.notification` ## Type ```ts function notify(option: Option): Result ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | ---------------------------------- | -------- | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | | title | `string` | Y | - | Notice title text | 3.0 | | content | `string` | Y | - | Text of the notice | 3.0 | | actions | `Array` | Y | - | Custom button arrays | 3.0 | | vibrate | `number` | N | `0` | Specify the vibration effect when the notification center pops up, 0 - default, 1 - beep, 2 - birdsong, 3 - drumbeat, 4 - gentle, 5 - buzz, Only effective for linear motors | 3.0 | ### Action | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | ------------------- | -------- | ------------ | ---------------------------------------- | --------- | | text | `string` | Y | - | Button Text | 3.0 | | file | `string` | Y | - | The App Service file to be started | 3.0 | | param | `string` | N | - | Parameters passed in during file loading | 3.0 | ### Result | Type | Description | | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | | `number` | The result of the notification delivery, returns `0` for delivery failure, the rest of the result indicates the ID of the notification | ## Example ```js ``` --- --- # @zos/page ## Constants | Constant | Description | API_LEVEL | |----------|-------------|-----------| | `SCROLL_MODE_FREE` | Free scrolling mode, system default scrolling mode | — | | `SCROLL_MODE_SWIPER` | Swiper mode, vertical rotating map, walking lights, by configuring the height and number of individual pages can achieve the whole screen scrolling effect | — | | `SCROLL_MODE_SWIPER_HORIZONTAL` | Swiper mode, horizontal rotating map, walking lights, by configuring the width and number of individual pages can achieve the whole screen scrolling effect | 2.1 | | `SCROLL_ANIMATION_SMOOTH` | Scroll smoothly to the corresponding position | — | | `SCROLL_ANIMATION_NONE` | No animation, scroll directly to the corresponding position | — | ## getScrollTop ### Import ```js import { getScrollTop } from '@zos/page' ``` ### Typings - Description: Get the vertical coordinate of the current scroll position of the page - Example: ```js import { getScrollTop } from '@zos/page' const top = getScrollTop() console.log(top) ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Get the vertical coordinate of the current scroll position of the page. ## Type ```ts function getScrollTop(): Result ``` ## Parameters ### Result | Type | Description | | ------------------- | ------------------------------------------------------------------ | | `number` | The vertical coordinate of the current scroll position of the page | ## Example ```js const top = getScrollTop() console.log(top) ``` --- ## getSwiperIndex ### Import ```js import { setScrollMode, swipeToIndex, getSwiperIndex, SCROLL_MODE_SWIPER } from '@zos/page' ``` ### Typings - Description: Get the scroll position of the current page, only if the page scroll mode is `SCROLL_MODE_SWIPER` or `SCROLL_MODE_SWIPER_HORIZONTAL` return the index of the current item (starting from `1`), otherwise return `undefined` - Example: ```js import { setScrollMode, swipeToIndex, getSwiperIndex, SCROLL_MODE_SWIPER } from '@zos/page' setScrollMode({ mode: SCROLL_MODE_SWIPER, options: { height: 480, count: 10 } }) swipeToIndex({ index: 5 }) const currentIndex = getSwiperIndex() console.log(currentIndex) ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Get the scroll position of the current page, only if the page scroll mode is `SCROLL_MODE_SWIPER` or `SCROLL_MODE_SWIPER_HORIZONTAL` return the index of the current item (starting from `1`), otherwise return `undefined`. ## Type ```ts function getSwiperIndex(): Result ``` ## Parameters ### Result | Type | Description | | ---------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `number|undefined` | If the page scroll mode is `SCROLL_MODE_SWIPER` or `SCROLL_MODE_SWIPER_HORIZONTAL`, the value is the index of the current item (starting from `1`). Otherwise, it is `undefined`. | ## Example ```js setScrollMode({ mode: SCROLL_MODE_SWIPER, options: { height: 480, count: 10, }, }) swipeToIndex({ index: 5, }) const currentIndex = getSwiperIndex() console.log(currentIndex) ``` --- ## scrollTo ### Import ```js import { scrollTo } from '@zos/page' ``` ### Typings - Description: Scroll the page to the specified position - Example: ```js import { scrollTo } from '@zos/page' scrollTo({ y: -200 }) ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Scroll the page to the specified position. ## Type ```ts function scrollTo(option: Option): void ``` ### Simplified calling method ```ts function scrollTo(y: number): void ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | ---------- | ----------------------- | -------- | ------------ | ---------------------------------------------------------------------------------------------------------------------------- | --------- | | y | `number` | Y | - | The vertical axis coordinates of the page, the 12 o'clock direction of the watch is positive, and scrolling down is negative | 2.0 | | animConfig | `animConfig` | N | - | Scroll animation configuration | 3.6 | ### animConfig | Property | Type | Required | DefaultValue | Description | API_LEVEL | | ------------------ | --------------------------- | -------- | --------------- | --------------------------------------------------------------------------------------------------------------------------------- | --------- | | anim_rate | `string` | N | - | Animation curve, optional values `linear`, `easein`, `easeout`, `easeinout` refer to [https://easings.net/](https://easings.net/) | 3.6 | | anim_duration | `number` | N | - | Animation duration, in milliseconds | 3.6 | | anim_fps | `number` | N | `25` | Animation frame rate | 3.6 | | anim_complete_func | `() => void` | N | - | End of animation callback function | 3.6 | ## Example ```js scrollTo({ y: -200, }) ``` --- ## setScrollLock ### Import ```js import { setScrollLock } from '@zos/page' ``` ### Typings - Description: Set the current page scrolling position to be locked, i.e. the screen position will not change with the gesture swipe. After calling this API to perform the unlock operation, the page scrolling mode will be set to free scrolling mode - Example: ```js import { setScrollLock } from '@zos/page' setScrollLock({ lock: true }) ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Set the current page scrolling position to be locked, i.e. the screen position will not change with the gesture swipe. After calling this API to perform the unlock operation, the page scrolling mode will be set to free scrolling mode. ## Type ```ts function setScrollLock(option: Option): void ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | -------------------- | -------- | ----------------- | ------------------------------------------------ | --------- | | lock | `boolean` | N | `true` | Whether to lock the current page scroll position | 2.0 | ## Example ```js setScrollLock({ lock: true, }) ``` --- ## setScrollMode ### Import ```js import { setScrollMode, SCROLL_MODE_SWIPER } from '@zos/page' ``` ### Typings - Description: Set the scroll mode of the page - Constants: `scrollMode` - Example: ```js import { setScrollMode, SCROLL_MODE_SWIPER } from '@zos/page' setScrollMode({ mode: SCROLL_MODE_SWIPER, options: { height: 480, count: 10 } }) ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Set the scroll mode of the page. ## Type ```ts function setScrollMode(option: Option): Result ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | -------------------- | -------- | ------------ | ------------------------------------------------------------ | --------- | | mode | `string` | Y | - | Page scroll mode, value reference page scroll mode constants | 2.0 | | options | `Options` | N | - | Other Options | 2.0 | ### Options | Property | Type | Required | DefaultValue | Description | API_LEVEL | | ---------- | ------------------------------------------------ | -------- | ------------ | --------------------------------------------------------------------------------------------------------------------------------------- | --------- | | height | `number` | N | - | Specify the height of a single item in Swiper, effective only if the scroll mode is `SCROLL_MODE_SWIPER` | 2.0 | | count | `number` | N | - | Specify the number of items in the Swiper, effective only if the scroll mode is `SCROLL_MODE_SWIPER` or `SCROLL_MODE_SWIPER_HORIZONTAL` | 2.0 | | width | `number` | N | - | Specify the width of a single item in Swiper, effective only if the scroll mode is `SCROLL_MODE_SWIPER_HORIZONTAL` | 2.1 | | modeParams | `FreeModeParams|SwipeModeParams` | N | - | Parameters for the scroll mode | 3.0 | ### FreeModeParams | Property | Type | Description | API_LEVEL | | -------------------- | -------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | | scroll_frame_func | `(params: ScrollObj) => void` | The callback function for each frame during scrolling | 3.0 | | scroll_complete_func | `(params: ScrollObj) => void` | The end of the scroll callback function | 3.0 | | bounce | `boolean` | Control whether the page rebound effect is turned on. When the page content exceeds one screen, it is turned on by default. If the page content is less than one screen, it is turned off by default. This parameter needs to be passed in the `build` lifecycle to take effect. | 3.6 | ### ScrollObj | Property | Type | Description | API_LEVEL | | -------- | ------------------- | -------------------------- | --------- | | type | `number` | Todo | 3.0 | | yoffset | `number` | Pixel offset on the y axis | 3.0 | ### SwipeModeParams | Property | Type | Description | API_LEVEL | | ------------ | -------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | --------- | | on_page | `(pageIndex: number) => void` | Callback function after page flipping, `pageIndex` is the page index after page flipping, and the index starts from `0` | 3.0 | | crown_enable | `boolean` | Whether to respond to crown events, the default response, you can use the crown to control page turning | 3.0 | ### Result | Type | Description | | ------------------- | ------------------------------------------- | | `number` | If `true` is returned, success is indicated | ## Constants ### Page scroll mode constants | Constant | Description | API_LEVEL | | ------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | | `SCROLL_MODE_FREE` | Free scrolling mode, system default scrolling mode | 2.0 | | `SCROLL_MODE_SWIPER` | Swiper mode, vertical rotating map, walking lights, by configuring the height and number of individual pages can achieve the whole screen scrolling effect | 2.0 | | `SCROLL_MODE_SWIPER_HORIZONTAL` | Swiper mode, horizontal rotating map, walking lights, by configuring the width and number of individual pages can achieve the whole screen scrolling effect | 2.1 | ## Example ```js setScrollMode({ mode: SCROLL_MODE_SWIPER, options: { height: 480, count: 10, }, }) ``` --- ## swipeToIndex ### Import ```js import { setScrollMode, swipeToIndex, SCROLL_MODE_SWIPER } from '@zos/page' ``` ### Typings - Description: Scrolls the page to the Swiper's target item, only if the current page scroll mode is `SCROLL_MODE_SWIPER` - Constants: `scrollAnimation` - Example: ```js import { setScrollMode, swipeToIndex, SCROLL_MODE_SWIPER } from '@zos/page' setScrollMode({ mode: SCROLL_MODE_SWIPER, options: { height: 480, count: 10 } }) swipeToIndex({ index: 5 }) ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Scrolls the page to the Swiper's target item, only if the current page scroll mode is `SCROLL_MODE_SWIPER`. ## Type ```ts function swipeToIndex(option: Option): void ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | --------- | ------------------- | -------- | -------------------------------------- | ----------------------------------------------------------------------- | --------- | | index | `number` | Y | - | Index of the target project, starting from 0 | 2.0 | | animation | `string` | N | ``SCROLL_ANIMATION_SMOOTH`` | Scrolling animation, value reference page scrolling animation constants | 2.0 | ## Constants ### Page scroll mode constants | Constant | Description | API_LEVEL | | ------------------------- | ----------------------------------------------------------- | --------- | | `SCROLL_ANIMATION_SMOOTH` | Scroll smoothly to the corresponding position | 2.0 | | `SCROLL_ANIMATION_NONE` | No animation, scroll directly to the corresponding position | 2.0 | ## Example ```js setScrollMode({ mode: SCROLL_MODE_SWIPER, options: { height: 480, count: 10, }, }) swipeToIndex({ index: 5, }) ``` --- --- # @zos/router ## Constants | Constant | Description | API_LEVEL | |----------|-------------|-----------| | `SYSTEM_APP_STATUS` | Activity | 3.0 | | `SYSTEM_APP_HR` | Heart Rate | 3.0 | | `SYSTEM_APP_SPORT` | Workout | 3.0 | | `SYSTEM_APP_WEATHER` | Weather | 3.0 | | `SYSTEM_APP_ALARM` | Alarm | 3.0 | | `SYSTEM_APP_CAMERA` | Camera Remote | 3.0 | | `SYSTEM_APP_MUSIC` | Music | 3.0 | | `SYSTEM_APP_STOPWATCH` | Stopwatch | 3.0 | | `SYSTEM_APP_COUNTDOWN` | Timer | 3.0 | | `SYSTEM_APP_FINE_PHONE` | Find My Phone | 3.0 | | `SYSTEM_APP_CARD` | Cards | 3.0 | | `SYSTEM_APP_ALIPAY` | Alipay | 3.0 | | `SYSTEM_APP_SETTING` | Settings | 3.0 | | `SYSTEM_APP_SPORT_HISTORY` | Workout History | 3.0 | | `SYSTEM_APP_COMPASS` | Compass | 3.0 | | `SYSTEM_APP_PAI` | PAI | 3.0 | | `SYSTEM_APP_WORLD_CLOCK` | World Clock | 3.0 | | `SYSTEM_APP_PRESSURE` | Stress | 3.0 | | `SYSTEM_APP_MENSTRUAL` | Cycle Tracking | 3.0 | | `SYSTEM_APP_SPORT_STATUS` | Workout Status | 3.0 | | `SYSTEM_APP_CALENDAR` | Calendar | 3.0 | | `SYSTEM_APP_SLEEP` | Sleep | 3.0 | | `SYSTEM_APP_SPO2` | Blood Oxygen | 3.0 | | `SYSTEM_APP_PHONE` | Phone | 3.0 | | `SYSTEM_APP_NETEASE_MUSIC` | NetEase Music | 3.0 | | `SYSTEM_APP_WEPAY` | Weixin Pay | 3.0 | | `SYSTEM_APP_BREATH` | Breathe | 3.0 | | `SYSTEM_APP_POMODORO` | Pomodoro Timer | 3.0 | | `SYSTEM_APP_ALEAX` | Alexa | 3.0 | | `SYSTEM_APP_THERMOMETER` | Thermometer | 3.0 | | `SYSTEM_APP_TODO_LIST` | To Do | 3.0 | | `SYSTEM_APP_ALTIMETER` | Barometer | 3.0 | | `SYSTEM_APP_VOICE_MEMO` | Voice Memos | 3.0 | | `SYSTEM_APP_SUN_AND_MOON` | Sun & Moon | 3.0 | | `SYSTEM_APP_MEASUREMENT` | One-tap Measuring | 3.0 | | `SYSTEM_APP_ZEPP_COACH` | Zepp Coach | 3.0 | | `SYSTEM_APP_CLUB_CARD` | Membership Card | 3.0 | | `SYSTEM_APP_BODY_COMPOSITION` | Body Composition | 3.0 | | `SYSTEM_APP_READINESS` | Readiness | 3.0 | ## back ### Import ```js import { back } from '@zos/router' ``` ### Typings - Description: Closes the current page to return to the previous page - Example: ```js import { back } from '@zos/router' back() ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Closes the current page to return to the previous page. ## Type ```ts function back(): void ``` ## Example ```js back() ``` --- ## checkSystemApp ### Import ```js import { checkSystemApp, SYSTEM_APP_STATUS } from '@zos/router' ``` ### Typings - Description: Check if the system application supports jumping - API_LEVEL: 3.0 - Constants: `system_app` - Example: ```js import { checkSystemApp, SYSTEM_APP_STATUS } from '@zos/router' checkSystemApp({ appId: SYSTEM_APP_STATUS }) ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Check if the system application supports jumping. ## Type ```ts function checkSystemApp(option: Option): void ``` ### Simplified calling method ```ts function checkSystemApp(appId: number): void ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | ------------------- | -------- | ------------ | -------------------------------------------------------------------------------- | --------- | | appId | `number` | Y | - | ID of the system App to be jumped to, value refers to the system App ID constant | 3.0 | ## Constants ### System App ID constants | Constant | Description | API_LEVEL | | ----------------------------- | ----------------- | --------- | | `SYSTEM_APP_STATUS` | Activity | 3.0 | | `SYSTEM_APP_HR` | Heart Rate | 3.0 | | `SYSTEM_APP_SPORT` | Workout | 3.0 | | `SYSTEM_APP_WEATHER` | Weather | 3.0 | | `SYSTEM_APP_ALARM` | Alarm | 3.0 | | `SYSTEM_APP_CAMERA` | Camera Remote | 3.0 | | `SYSTEM_APP_MUSIC` | Music | 3.0 | | `SYSTEM_APP_STOPWATCH` | Stopwatch | 3.0 | | `SYSTEM_APP_COUNTDOWN` | Timer | 3.0 | | `SYSTEM_APP_FINE_PHONE` | Find My Phone | 3.0 | | `SYSTEM_APP_CARD` | Cards | 3.0 | | `SYSTEM_APP_ALIPAY` | Alipay | 3.0 | | `SYSTEM_APP_SETTING` | Settings | 3.0 | | `SYSTEM_APP_SPORT_HISTORY` | Workout History | 3.0 | | `SYSTEM_APP_COMPASS` | Compass | 3.0 | | `SYSTEM_APP_PAI` | PAI | 3.0 | | `SYSTEM_APP_WORLD_CLOCK` | World Clock | 3.0 | | `SYSTEM_APP_PRESSURE` | Stress | 3.0 | | `SYSTEM_APP_MENSTRUAL` | Cycle Tracking | 3.0 | | `SYSTEM_APP_SPORT_STATUS` | Workout Status | 3.0 | | `SYSTEM_APP_CALENDAR` | Calendar | 3.0 | | `SYSTEM_APP_SLEEP` | Sleep | 3.0 | | `SYSTEM_APP_SPO2` | Blood Oxygen | 3.0 | | `SYSTEM_APP_PHONE` | Phone | 3.0 | | `SYSTEM_APP_NETEASE_MUSIC` | NetEase Music | 3.0 | | `SYSTEM_APP_WEPAY` | Weixin Pay | 3.0 | | `SYSTEM_APP_BREATH` | Breathe | 3.0 | | `SYSTEM_APP_POMODORO` | Pomodoro Timer | 3.0 | | `SYSTEM_APP_ALEAX` | Alexa | 3.0 | | `SYSTEM_APP_THERMOMETER` | Thermometer | 3.0 | | `SYSTEM_APP_TODO_LIST` | To Do | 3.0 | | `SYSTEM_APP_ALTIMETER` | Barometer | 3.0 | | `SYSTEM_APP_VOICE_MEMO` | Voice Memos | 3.0 | | `SYSTEM_APP_SUN_AND_MOON` | Sun & Moon | 3.0 | | `SYSTEM_APP_MEASUREMENT` | One-tap Measuring | 3.0 | | `SYSTEM_APP_ZEPP_COACH` | Zepp Coach | 3.0 | | `SYSTEM_APP_CLUB_CARD` | Membership Card | 3.0 | | `SYSTEM_APP_BODY_COMPOSITION` | Body Composition | 3.0 | | `SYSTEM_APP_READINESS` | Readiness | 3.0 | ## Example ```js checkSystemApp({ appId: SYSTEM_APP_STATUS, }) ``` --- ## clearLaunchAppTimeout ### Import ```js import { setLaunchAppTimeout, clearLaunchAppTimeout } from '@zos/router' ``` ### Typings - Description: Cancel the wakeup Mini Program timer created by `setLaunchAppTimeout` - Example: ```js import { setLaunchAppTimeout, clearLaunchAppTimeout } from '@zos/router' const timeoutId = setLaunchAppTimeout({ url: 'pages/js_widget_sample', appId: 1000001, delay: 10000 }) clearLaunchAppTimeout({ timeoutId }) ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Cancel the wakeup Mini Program timer created by `setLaunchAppTimeout`. ## Type ```ts function clearLaunchAppTimeout(option: Option): void ``` ### Simplified calling method ```ts function clearLaunchAppTimeout(timeoutId: number): void ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | --------- | ------------------- | -------- | ------------ | --------------------------------------------------------------------------------------------------------------------------- | --------- | | timeoutId | `number` | Y | - | The identifier of the timeout you want to cancel. This ID was returned by the corresponding call to `setLaunchAppTimeout`() | 2.0 | ### Result | Type | Description | | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `number` | The returned value is a positive integer value which identifies the timer created by the call to `setLaunchAppTimeout`. This value can be passed to `clearLaunchAppTimeout` to cancel the timeout | ## Example ```js const timeoutId = setLaunchAppTimeout({ url: 'pages/js_widget_sample', appId: 1000001, delay: 10000, }) clearLaunchAppTimeout({ timeoutId, }) ``` --- ## exit ### Import ```js import { exit } from '@zos/router' ``` ### Typings - Description: Exit the Mini Program and return to the applist page - Example: ```js import { exit } from '@zos/router' exit() ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Exit the Mini Program and return to the applist page. ## Type ```ts function exit(): void ``` ## Example ```js exit() ``` --- ## getAppIdByName ### Import ```js import { getAppIdByName } from '@zos/router' ``` ### Typings - Description: Fuzzy match the English name of installed Mini Programs on the device by name - API_LEVEL: 3.6 - Example: ```js import { getAppIdByName } from '@zos/router' const appId = getAppIdByName('calculator') console.log(appId) ``` > Start from API_LEVEL `3.6` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Fuzzy match the English name of installed Mini Programs on the device by name. ## Type ```ts function getAppIdByName(name: string): Result ``` ## Parameters ### Result | Type | Description | | ------------------- | ------------------------------------------------------------ | | `number` | Matched Mini Program ID, returns invalid ID when match fails | ## Example ```js const appId = getAppIdByName('calculator') console.log(appId) ``` --- ## home ### Import ```js import { home } from '@zos/router' ``` ### Typings - Description: Exit the Mini Program and return to the watchface page - Example: ```js import { home } from '@zos/router' home() ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Exit the Mini Program and return to the watchface page. ## Type ```ts function home(): void ``` ## Example ```js home() ``` --- ## launchApp ### Import ```js import { launchApp, SYSTEM_APP_HR } from '@zos/router' ``` ### Typings - Description: Open Mini Program - Constants: `system_app` - Example: ```js import { launchApp, SYSTEM_APP_HR } from '@zos/router' // Jump to Mini Program launchApp({ appId: 1000001, url: 'pages/js_widget_sample', params: { type: 1 } }) // Jump to system App Heart Rate launchApp({ appId: SYSTEM_APP_HR, native: true }) ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Open Mini Program. ## Type ```ts function launchApp(option: Option): void ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | ------------------------------- | -------- | ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | | appId | `number` | Y | - | Mini Program ID or System App ID (API_LEVEL 3.0 support, value reference System App ID constant) | 2.0 | | url | `string` | Y | - | path | 2.0 | | native | `boolean` | Y | `false` | Whether to jump to the system App | 3.0 | | params | `string|object` | N | - | The argument passed to the app.js lifecycle `onCreate` supports either a string or a standard JSON object. If a standard JSON object is passed, the method internally converts it to a string | 2.0 | ## Constants ### System App ID constants | Constant | Description | API_LEVEL | | ----------------------------- | ----------------- | --------- | | `SYSTEM_APP_STATUS` | Activity | 3.0 | | `SYSTEM_APP_HR` | Heart Rate | 3.0 | | `SYSTEM_APP_SPORT` | Workout | 3.0 | | `SYSTEM_APP_WEATHER` | Weather | 3.0 | | `SYSTEM_APP_ALARM` | Alarm | 3.0 | | `SYSTEM_APP_CAMERA` | Camera Remote | 3.0 | | `SYSTEM_APP_MUSIC` | Music | 3.0 | | `SYSTEM_APP_STOPWATCH` | Stopwatch | 3.0 | | `SYSTEM_APP_COUNTDOWN` | Timer | 3.0 | | `SYSTEM_APP_FINE_PHONE` | Find My Phone | 3.0 | | `SYSTEM_APP_CARD` | Cards | 3.0 | | `SYSTEM_APP_ALIPAY` | Alipay | 3.0 | | `SYSTEM_APP_SETTING` | Settings | 3.0 | | `SYSTEM_APP_SPORT_HISTORY` | Workout History | 3.0 | | `SYSTEM_APP_COMPASS` | Compass | 3.0 | | `SYSTEM_APP_PAI` | PAI | 3.0 | | `SYSTEM_APP_WORLD_CLOCK` | World Clock | 3.0 | | `SYSTEM_APP_PRESSURE` | Stress | 3.0 | | `SYSTEM_APP_MENSTRUAL` | Cycle Tracking | 3.0 | | `SYSTEM_APP_SPORT_STATUS` | Workout Status | 3.0 | | `SYSTEM_APP_CALENDAR` | Calendar | 3.0 | | `SYSTEM_APP_SLEEP` | Sleep | 3.0 | | `SYSTEM_APP_SPO2` | Blood Oxygen | 3.0 | | `SYSTEM_APP_PHONE` | Phone | 3.0 | | `SYSTEM_APP_NETEASE_MUSIC` | NetEase Music | 3.0 | | `SYSTEM_APP_WEPAY` | Weixin Pay | 3.0 | | `SYSTEM_APP_BREATH` | Breathe | 3.0 | | `SYSTEM_APP_POMODORO` | Pomodoro Timer | 3.0 | | `SYSTEM_APP_ALEAX` | Alexa | 3.0 | | `SYSTEM_APP_THERMOMETER` | Thermometer | 3.0 | | `SYSTEM_APP_TODO_LIST` | To Do | 3.0 | | `SYSTEM_APP_ALTIMETER` | Barometer | 3.0 | | `SYSTEM_APP_VOICE_MEMO` | Voice Memos | 3.0 | | `SYSTEM_APP_SUN_AND_MOON` | Sun & Moon | 3.0 | | `SYSTEM_APP_MEASUREMENT` | One-tap Measuring | 3.0 | | `SYSTEM_APP_ZEPP_COACH` | Zepp Coach | 3.0 | | `SYSTEM_APP_CLUB_CARD` | Membership Card | 3.0 | | `SYSTEM_APP_BODY_COMPOSITION` | Body Composition | 3.0 | | `SYSTEM_APP_READINESS` | Readiness | 3.0 | ## Example ```js // Jump to Mini Program launchApp({ appId: 1000001, url: 'pages/js_widget_sample', params: { type: 1, }, }) // Jump to system App Heart Rate launchApp({ appId: SYSTEM_APP_HR, native: true, }) ``` --- ## push ### Import ```js import { push } from '@zos/router' ``` ### Typings - Description: Navigate to a page within the Mini Program. Use the `back` method to go back to the original page - Example: ```js import { push } from '@zos/router' push({ url: 'page/index', params: 'type=1' }) ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Navigate to a page within the Mini Program. Use the `back` method to go back to the original page. ## Type ```ts function push(option: Option): void ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | ------------------------------- | -------- | ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | | url | `string` | Y | - | path | 2.0 | | params | `string|object` | N | - | Parameters passed to the page `onInit` lifecycle, supporting strings or standard JSON object. If a standard JSON object is passed, the method internally converts it to a string | 2.0 | ## Example ```js push({ url: 'page/index', params: 'type=1', }) ``` --- ## replace ### Import ```js import { replace } from '@zos/router' ``` ### Typings - Description: Close the current page and jump to a page within the app - Example: ```js import { replace } from '@zos/router' replace({ url: 'page/index', params: 'type=1' }) ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Close the current page and jump to a page within the app. ## Type ```ts function replace(option: Option): void ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | ------------------------------- | -------- | ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | | url | `string` | Y | - | path | 2.0 | | params | `string|object` | N | - | Parameters passed to the page `onCreate` lifecycle, supporting strings or standard JSON objects. If a standard JSON object is passed, the method internally converts it to a string | 2.0 | ## Example ```js replace({ url: 'page/index', params: 'type=1', }) ``` --- ## setLaunchAppTimeout ### Import ```js import { setLaunchAppTimeout, clearLaunchAppTimeout } from '@zos/router' ``` ### Typings - Description: Register a timer to launch the Mini Program at a given time - Example: ```js import { setLaunchAppTimeout, clearLaunchAppTimeout } from '@zos/router' const timeoutId = setLaunchAppTimeout({ url: 'pages/js_widget_sample', appId: 1000001, delay: 1000 }) clearLaunchAppTimeout({ timeoutId }) ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Register a timer to launch the Mini Program at a given time. ## Type ```ts function setLaunchAppTimeout(option: Option): Result ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | ------------------------------- | -------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | | appId | `number` | Y | - | Mini Program ID | 2.0 | | url | `string` | Y | - | path | 2.0 | | utc | `number` | N | - | utc timestamp(milliseconds),the priority is higher than `delay`, and when set at the same time as the `delay` field, only the `utc` field takes effect | 2.0 | | delay | `number` | N | `0` | The time, in milliseconds that the timer should wait before the Mini Program is waked. | 3.0 | | params | `string|object` | N | - | The argument passed to the app.js lifecycle `onCreate` supports either a string or a standard JSON object. If a standard JSON object is passed, the method internally converts it to a string | 2.0 | ### Result | Type | Description | | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `number` | The returned value is a positive integer value which identifies the timer created by the call to `setLaunchAppTimeout`. This value can be passed to `clearLaunchAppTimeout` to cancel the timeout. | ## Example ```js const timeoutId = setLaunchAppTimeout({ url: 'pages/js_widget_sample', appId: 1000001, delay: 1000, }) clearLaunchAppTimeout({ timeoutId, }) ``` --- --- # @zos/sensor ## Constants | Constant | Description | API_LEVEL | |----------|-------------|-----------| | `VIBRATOR_SCENE_SHORT_LIGHT` | Light vibration intensity and short time (20ms) | — | | `VIBRATOR_SCENE_SHORT_MIDDLE` | Medium vibration intensity, short time (20ms) | — | | `VIBRATOR_SCENE_SHORT_STRONG` | High vibration intensity and short time (20ms) | — | | `VIBRATOR_SCENE_DURATION` | High vibration intensity, lasting 600ms | — | | `VIBRATOR_SCENE_DURATION_LONG` | High vibration intensity, lasting 1000ms | — | | `VIBRATOR_SCENE_STRONG_REMINDER` | High vibration intensity, four vibrations in 1200ms, can be used for stronger reminders | — | | `VIBRATOR_SCENE_NOTIFICATION` | Two short, continuous vibrations, consistent with the watch message notification vibration feedback | — | | `VIBRATOR_SCENE_CALL` | High vibration intensity, single vibration twice in 500ms, continuous vibration, need to manually `stop`, consistent with the watch call vibration feedback | — | | `VIBRATOR_SCENE_TIMER` | High vibration intensity, single long vibration 500ms, continuous vibration, need to manually `stop`, consistent with the watch alarm clock, countdown vibration feedback | — | | `TIME_HOUR_FORMAT_12` | 12-hour format | 2.1 | | `TIME_HOUR_FORMAT_24` | 24-hour format | 2.1 | | `FREQ_MODE_LOW` | Low power mode with low trigger frequency | 3.0 | | `FREQ_MODE_NORMAL` | Normal power consumption mode, medium trigger frequency | 3.0 | | `FREQ_MODE_HIGH` | High power consumption mode with high trigger frequency | 3.0 | ## Accelerometer ### Import ```js import { Accelerometer, FREQ_MODE_NORMAL } from '@zos/sensor' ``` ### Typings - Description: accelerometer. Measure the acceleration of the device along three orthogonal axes (x, y, z). The x and y axes are parallel to the screen, with the positive direction referring to the diagram. The z-axis is perpendicular to the device's screen, with the positive direction pointing upward - API_LEVEL: 3.0 - Permission: `device:os.accelerometer` - Example: ```js import { Accelerometer, FREQ_MODE_NORMAL } from '@zos/sensor' const accelerometer = new Accelerometer() const callback = () => { console.log(accelerometer.getCurrent()) } accelerometer.onChange(callback) accelerometer.setFreqMode(FREQ_MODE_NORMAL) accelerometer.start() // When not needed for use accelerometer.offChange() accelerometer.stop() ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). [Image: Accelerometer_image] accelerometer. Measure the acceleration of the device along three orthogonal axes (x, y, z). The x and y axes are parallel to the screen, with the positive direction referring to the diagram. The z-axis is perpendicular to the device's screen, with the positive direction pointing upward. > **ℹ️ Info** > > permission code: `device:os.accelerometer` ## Methods ### start Start listening to accelerometer data ```ts start(): void ``` ### stop Stop listening to accelerometer data ```ts stop(): void ``` ### getCurrent Get current accelerometer data ```ts getCurrent(): Result ``` #### Result | Property | Type | Description | API_LEVEL | | -------- | ------------------- | -------------------------------- | --------- | | x | `number` | Acceleration of x-axis in cm/s^2 | 3.0 | | y | `number` | Acceleration of y-axis in cm/s^2 | 3.0 | | z | `number` | Acceleration of z-axis in cm/s^2 | 3.0 | ### onChange Register the accelerometer data change event listener callback function ```ts onChange(callback: () => void): void ``` ### offChange Cancel the accelerometer data change event listener callback function ```ts offChange(callback: () => void): void ``` ### setFreqMode > Start from API_LEVEL `3.0` Set the mode of trigger frequency, `mode` value reference frequency mode constant ```ts setFreqMode(mode: number): void ``` #### Constants ##### Frequency Mode | Constant | Description | API_LEVEL | | ------------------ | ------------------------------------------------------- | --------- | | `FREQ_MODE_LOW` | Low power mode with low trigger frequency | 3.0 | | `FREQ_MODE_NORMAL` | Normal power consumption mode, medium trigger frequency | 3.0 | | `FREQ_MODE_HIGH` | High power consumption mode with high trigger frequency | 3.0 | ### getFreqMode > Start from API_LEVEL `3.0` Get the mode of trigger frequency, result value reference frequency mode constant ```ts getFreqMode(): number ``` #### Constants ##### Frequency Mode | Constant | Description | API_LEVEL | | ------------------ | ------------------------------------------------------- | --------- | | `FREQ_MODE_LOW` | Low power mode with low trigger frequency | 3.0 | | `FREQ_MODE_NORMAL` | Normal power consumption mode, medium trigger frequency | 3.0 | | `FREQ_MODE_HIGH` | High power consumption mode with high trigger frequency | 3.0 | ## Example ```js const accelerometer = new Accelerometer() const callback = () => { console.log(accelerometer.getCurrent()) } accelerometer.onChange(callback) accelerometer.setFreqMode(FREQ_MODE_NORMAL) accelerometer.start() // When not needed for use accelerometer.offChange() accelerometer.stop() ``` --- ## Barometer ### Import ```js import { Barometer } from '@zos/sensor' ``` ### Typings - Description: Barometer Sensor - API_LEVEL: 2.1 - Permission: `device:os.barometer` - Example: ```js import { Barometer } from '@zos/sensor' const barometer = new Barometer() const airPressure = barometer.getAirPressure() const altitude = barometer.getAltitude() const callback = () => { console.log(barometer.getAltitude()) } barometer.onChange(callback) // When not needed for use barometer.offChange(callback) ``` > Start from API_LEVEL `2.1` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Barometer Sensor. > **ℹ️ Info** > > permission code: `device:os.barometer` ## Methods ### getAirPressure Get air pressure value in hPa ```ts getAirPressure(): number ``` ### getAltitude Get altitude value in meters ```ts getAltitude(): number ``` ### onChange Register the air pressure and altitude change event callback function ```ts onChange(callback: () => void): void ``` ### offChange Cancel the air pressure and altitude change event callback function ```ts offChange(callback: () => void): void ``` ## Example ```js const barometer = new Barometer() const airPressure = barometer.getAirPressure() const altitude = barometer.getAltitude() const callback = () => { console.log(barometer.getAltitude()) } barometer.onChange(callback) // When not needed for use barometer.offChange(callback) ``` --- ## Battery ### Import ```js import { Battery } from '@zos/sensor' ``` ### Typings - Description: Battery Sensor - Example: ```js import { Battery } from '@zos/sensor' const battery = new Battery() const current = battery.getCurrent() const callback = () => { console.log(battery.getCurrent()) } battery.onChange(callback) // When not needed for use battery.offChange(callback) ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Battery Sensor. ## Methods ### getCurrent Get the current device power percentage, range 0 - 100 ```ts getCurrent(): number ``` ### onChange Register the power change event callback function ```ts onChange(callback: () => void): void ``` ### offChange Cancel the power change event callback function ```ts offChange(callback: () => void): void ``` ## Example ```js const battery = new Battery() const current = battery.getCurrent() const callback = () => { console.log(battery.getCurrent()) } battery.onChange(callback) // When not needed for use battery.offChange(callback) ``` --- ## BloodOxygen ### Import ```js import { BloodOxygen } from '@zos/sensor' ``` ### Typings - Description: Blood oxygen Sensor - Permission: `data:user.hd.spo2` - Example: ```js import { BloodOxygen } from '@zos/sensor' const bloodOxygen = new BloodOxygen() const { value } = bloodOxygen.getCurrent() const lastDay = bloodOxygen.getLastDay() const callback = () => { console.log(bloodOxygen.getCurrent()) } bloodOxygen.onChange(callback) bloodOxygen.stop() bloodOxygen.start() // When not needed for use bloodOxygen.offChange(callback) ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Blood oxygen Sensor. > **ℹ️ Info** > > permission code: `data:user.hd.spo2` ## Methods ### getCurrent Get the current measured blood oxygen result ```ts getCurrent(): Result ``` #### Result | Property | Type | Description | API_LEVEL | | -------- | ------------------- | ----------------------------------------- | --------- | | value | `number` | Blood oxygen measurement values | 2.0 | | time | `number` | Measurement time | 2.0 | | retCode | `number` | Result code, refer to retCode description | 2.0 | #### retCode | Value | Type | Description | API_LEVEL | | ----- | ------------------- | ----------------------- | --------- | | 0 | `number` | Measurement invalid | 2.0 | | 1 | `number` | Continue measuring | 2.0 | | 2 | `number` | Measurement success | 2.0 | | 3 | `number` | Measurement failure | 2.0 | | 4 | `number` | Not wearing | 2.0 | | 5 | `number` | Measurement timeout | 2.0 | | 6 | `number` | Invalid wearing | 2.0 | | 7 | `number` | Invalid signal | 2.0 | | 8 | `number` | Low blood oxygen value | 2.0 | | 9 | `number` | High blood oxygen value | 2.0 | | 10 | `number` | Measurement invalid | 2.0 | ### getLastDay Returns the average blood sample data for the past 24 hours, with an array length of 24 ```ts getLastDay(): Array ``` ### start > Start from API_LEVEL `2.1` Start blood oxygen measurement, it is recommended to call `stop` to stop the last measurement before calling the `start` method ```ts start(): void ``` ### stop > Start from API_LEVEL `2.1` Cancel blood oxygen measurement ```ts stop(): void ``` ### onChange Register a callback function to listen for blood oxygen measurement change events ```ts onChange(callback: () => void): void ``` ### offChange Cancel a callback function to listen for blood oxygen measurement change events ```ts offChange(callback: () => void): void ``` ### getLastFewHour > Start from API_LEVEL `3.0` Obtain blood oxygen measurements for the last `hour` and sort the results in chronological order ```ts getLastFewHour(hour: number): Array ``` #### Data | Property | Type | Description | API_LEVEL | | -------- | ------------------- | --------------------------------------------------------------------- | --------- | | spo2 | `number` | Blood oxygen measurement value | 3.0 | | time | `number` | Time of measurement of blood oxygen values, UTC time stamp in seconds | 3.0 | ## Example ```js const bloodOxygen = new BloodOxygen() const { value } = bloodOxygen.getCurrent() const lastDay = bloodOxygen.getLastDay() const callback = () => { console.log(bloodOxygen.getCurrent()) } bloodOxygen.onChange(callback) bloodOxygen.stop() bloodOxygen.start() // When not needed for use bloodOxygen.offChange(callback) ``` --- ## BodyTemperature ### Import ```js import { BodyTemperature } from '@zos/sensor' ``` ### Typings - Description: Body surface temperature sensor - API_LEVEL: 3.0 - Permission: `data:user.hd.body_temp` - Example: ```js import { BodyTemperature } from '@zos/sensor' const bodyTemperature = new BodyTemperature() bodyTemperature.getCurrent() ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Body surface temperature sensor. > **ℹ️ Info** > > permission code: `data:user.hd.body_temp` ## Methods ### getCurrent Get the latest measurement of body surface temperature ```ts getCurrent(): Result ``` #### Result | Property | Type | Description | API_LEVEL | | -------- | ------------------- | ------------------------------------------------------------------------------------------------------- | --------- | | current | `number` | Sleep stage type, refer to the constants returned by `getStageConstantObj` for the meaning of the value | 3.0 | | time | `number` | Sleep stage type, refer to the constants returned by `getStageConstantObj` for the meaning of the value | 3.0 | ### getToday Get the body surface temperature measurement values for 24 hours a day. The array length is 24 \* 60 / 5 = 288, with an average measurement value every five minutes. The unit is Celsius, such as `35.2`. Data without measurement values is `-1000` ```ts getToday(): Array ``` ## Example ```js const bodyTemperature = new BodyTemperature() bodyTemperature.getCurrent() ``` --- ## Buzzer ### Import ```js import { createWidget, widget, prop, align, text_style } from '@zos/ui' ``` ### Typings - Description: Buzzer - API_LEVEL: 3.6 - Example: ```js import { createWidget, widget, prop, align, text_style } from "@zos/ui"; import { Buzzer } from "@zos/sensor"; import { px } from "@zos/utils"; const sceneList = ['ALARM', 'REMIND_1', 'REMIND_2', 'OPERATE', 'SUCCESS', 'FAILURE'] Page({ state: { pageName: "BUZZER", currentIndex: 0 }, build() { const buzzer = new Buzzer(); const sceneText = createWidget(widget.TEXT, { x: px(0), y: px(120), w: px(480), h: px(46), color: 0xffffff, text_size: px(20), align_h: align.CENTER_H, align_v: align.CENTER_V, text_style: text_style.NONE, text: `${sceneList[this.state.currentIndex]}`, }); const startBuzzer = () => { const alarmType = buzzer.getSourceType()[sceneList[this.state.currentIndex]]; if (buzzer.isEnabled()) { buzzer.start(alarmType); } this.state.currentIndex = (this.state.currentIndex + 1) % sceneList.length sceneText.setProperty(prop.MORE, { text: `BUZZER: ${sceneList[this.state.currentIndex]}`, }); }; createWidget(widget.BUTTON, { x: px(80), y: px(300), w: px(300), h: px(60), radius: px(12), normal_color: 0xfc6950, press_color: 0xfeb4a8, text: "START BUZZER", click_func: startBuzzer, }); }, }); > Start from API_LEVEL `3.6` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Buzzer. ## Methods ### isEnabled Get whether other options in the system buzzer scene settings are turned on, Settings - > Sound & Vibration - > Buzzer Scene - > Other ```ts isEnabled(): boolean ``` ### getSourceType Get buzzer mode ```ts getSourceType(): Type ``` #### Type | Value | Type | Description | API_LEVEL | | -------- | ------------------- | ----------- | --------- | | ALARM | `number` | Alarm clock | 3.6 | | REMIND_1 | `number` | Reminder 1 | 3.6 | | REMIND_2 | `number` | Reminder 2 | 3.6 | | OPERATE | `number` | Operation | 3.6 | | SUCCESS | `number` | Success | 3.6 | | FAILURE | `number` | Failure | 3.6 | ### getStrength Get buzzer strength, '0' - weak, '1' - medium, '2' - high ```ts getStrength(): number ``` ### start Start beeping, you can pass in `type` to specify the built-in beeping mode of the system,`repeatCount` is the number of repetitions, default `0`, do not repeat ```ts start(type: number, repeatCount: 0): void ``` ### stop Stop buzzer ```ts stop(): void ``` ## Example ```js const sceneList = ['ALARM', 'REMIND_1', 'REMIND_2', 'OPERATE', 'SUCCESS', 'FAILURE'] Page({ state: { pageName: 'BUZZER', currentIndex: 0, }, build() { const buzzer = new Buzzer() const sceneText = createWidget(widget.TEXT, { x: px(0), y: px(120), w: px(480), h: px(46), color: 0xffffff, text_size: px(20), align_h: align.CENTER_H, align_v: align.CENTER_V, text_style: text_style.NONE, text: `${sceneList[this.state.currentIndex]}`, }) const startBuzzer = () => { const alarmType = buzzer.getSourceType()[sceneList[this.state.currentIndex]] if (buzzer.isEnabled()) { buzzer.start(alarmType) } this.state.currentIndex = (this.state.currentIndex + 1) % sceneList.length sceneText.setProperty(prop.MORE, { text: `BUZZER: ${sceneList[this.state.currentIndex]}`, }) } createWidget(widget.BUTTON, { x: px(80), y: px(300), w: px(300), h: px(60), radius: px(12), normal_color: 0xfc6950, press_color: 0xfeb4a8, text: 'START BUZZER', click_func: startBuzzer, }) }, }) ``` --- ## Calorie ### Import ```js import { Calorie } from '@zos/sensor' ``` ### Typings - Description: Calorie Sensor - Permission: `data:user.hd.calorie` - Example: ```js import { Calorie } from '@zos/sensor' const calorie = new Calorie() const current = calorie.getCurrent() const target = calorie.getTarget() const callback = () => { console.log(calorie.getCurrent()) } calorie.onChange(callback) // When not needed for use calorie.offChange(callback) ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Calorie Sensor. > **ℹ️ Info** > > permission code: `data:user.hd.calorie` ## Methods ### getCurrent Get the current calorie consumption in kcal ```ts getCurrent(): number ``` ### getTarget Get the target calorie consumption in kcal ```ts getTarget(): number ``` ### onChange Register the calories change event callback function ```ts onChange(callback: () => void): void ``` ### offChange Cancel the calories change event callback function ```ts offChange(callback: () => void): void ``` ## Example ```js const calorie = new Calorie() const current = calorie.getCurrent() const target = calorie.getTarget() const callback = () => { console.log(calorie.getCurrent()) } calorie.onChange(callback) // When not needed for use calorie.offChange(callback) ``` --- ## Compass ### Import ```js import { Compass } from '@zos/sensor' ``` ### Typings - Description: compass - API_LEVEL: 3.0 - Permission: `device:os.compass` - Example: ```js import { Compass } from '@zos/sensor' const compass = new Compass() const callback = () => { if (compass.getStatus()) { console.log(compass.getDirection()) console.log(compass.getDirectionAngle()) } } compass.onChange(callback) compass.start() // When not needed for use compass.offChange() compass.stop() ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). compass. > **ℹ️ Info** > > permission code: `device:os.compass` ## Methods ### start Start listening to compass data ```ts start(): void ``` ### stop Stop listening to compass data ```ts stop(): void ``` ### getStatus Get the compass calibration status, `true` means calibrated ```ts getStatus(): boolean ``` ### getDirection Get the direction of the current watch's 12-point scale, divided into eight directions, refer to `direction` ```ts getDirection(): string ``` #### direction | Value | Type | Description | API_LEVEL | | ----- | ------------------- | ----------- | --------- | | N | `string` | North | 3.0 | | NE | `string` | Northeast | 3.0 | | E | `string` | East | 3.0 | | SE | `string` | Southeast | 3.0 | | S | `string` | South | 3.0 | | SW | `string` | Southwest | 3.0 | | W | `string` | West | 3.0 | | NW | `string` | Northwest | 3.0 | ### getDirectionAngle Get the current direction angle, the clockwise rotation angle of the watch's 12 o'clock scale direction relative to due north, takes the values 0 - 360, if the compass is not calibrated, returns the `INVALID` string ```ts getDirectionAngle(): number | 'INVALID' ``` ### onChange Register the compass direction change event listener callback function ```ts onChange(callback: () => void): void ``` ### offChange Cancel the compass direction change event listener callback function ```ts offChange(callback: () => void): void ``` ### setFreqMode > Start from API_LEVEL `4.0` Set the mode of trigger frequency, `mode` value reference frequency mode constant ```ts setFreqMode(mode: number): void ``` #### Constants ##### Frequency Mode | Constant | Description | API_LEVEL | | ------------------ | ------------------------------------------------------- | --------- | | `FREQ_MODE_LOW` | Low power mode with low trigger frequency | 3.0 | | `FREQ_MODE_NORMAL` | Normal power consumption mode, medium trigger frequency | 3.0 | | `FREQ_MODE_HIGH` | High power consumption mode with high trigger frequency | 3.0 | ### getFreqMode > Start from API_LEVEL `4.0` Get the mode of trigger frequency, result value reference frequency mode constant ```ts getFreqMode(): number ``` #### Constants ##### Frequency Mode | Constant | Description | API_LEVEL | | ------------------ | ------------------------------------------------------- | --------- | | `FREQ_MODE_LOW` | Low power mode with low trigger frequency | 3.0 | | `FREQ_MODE_NORMAL` | Normal power consumption mode, medium trigger frequency | 3.0 | | `FREQ_MODE_HIGH` | High power consumption mode with high trigger frequency | 3.0 | ## Example ```js const compass = new Compass() const callback = () => { if (compass.getStatus()) { console.log(compass.getDirection()) console.log(compass.getDirectionAngle()) } } compass.onChange(callback) compass.start() // When not needed for use compass.offChange() compass.stop() ``` --- ## Distance ### Import ```js import { Distance } from '@zos/sensor' ``` ### Typings - Description: Distance Sensor - Permission: `data:user.hd.distance` - Example: ```js import { Distance } from '@zos/sensor' const distance = new Distance() const current = distance.getCurrent() const callback = () => { console.log(distance.getCurrent()) } distance.onChange(callback) // When not needed for use distance.offChange(callback) ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Distance Sensor. > **ℹ️ Info** > > permission code: `data:user.hd.distance` ## Methods ### getCurrent Get the current distance ```ts getCurrent(): number ``` ### onChange Register the distance change event callback function ```ts onChange(callback: () => void): void ``` ### offChange Cancel the distance change event callback function ```ts offChange(callback: () => void): void ``` ## Example ```js const distance = new Distance() const current = distance.getCurrent() const callback = () => { console.log(distance.getCurrent()) } distance.onChange(callback) // When not needed for use distance.offChange(callback) ``` --- ## FatBurning ### Import ```js import { FatBurning } from '@zos/sensor' ``` ### Typings - Description: FatBurning Sensor - Permission: `data:user.hd.fat_burning` - Example: ```js import { FatBurning } from '@zos/sensor' const fatBurning = new FatBurning() const current = fatBurning.getCurrent() const target = fatBurning.getTarget() const callback = () => { console.log(fatBurning.getCurrent()) } fatBurning.onChange(callback) // When not needed for use fatBurning.offChange(callback) ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). FatBurning Sensor. > **ℹ️ Info** > > permission code: `data:user.hd.fat_burning` ## Methods ### getCurrent Get current fat burning minutes ```ts getCurrent(): number ``` ### getTarget Get current fat burning target minutes ```ts getTarget(): number ``` ### onChange Register a callback function to listen to the fat burning minutes change event ```ts onChange(callback: () => void): void ``` ### offChange Cancel a callback function to listen to the fat burning minutes change event ```ts offChange(callback: () => void): void ``` ## Example ```js const fatBurning = new FatBurning() const current = fatBurning.getCurrent() const target = fatBurning.getTarget() const callback = () => { console.log(fatBurning.getCurrent()) } fatBurning.onChange(callback) // When not needed for use fatBurning.offChange(callback) ``` --- ## Geolocation ### Import ```js import { Geolocation } from '@zos/sensor' ``` ### Typings - Description: Geolocation Sensor - API_LEVEL: 2.1 - Permission: `device:os.geolocation` - Example: ```js import { Geolocation } from '@zos/sensor' const geolocation = new Geolocation() const callback = () => { if (geolocation.getStatus() === 'A') { console.log(geolocation.getLatitude()) console.log(geolocation.getLongitude()) } } geolocation.start() geolocation.onChange(callback) // When not needed for use geolocation.offChange(callback) geolocation.stop() ``` > Start from API_LEVEL `2.1` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Geolocation Sensor. > **ℹ️ Info** > > permission code: `device:os.geolocation` ## Methods ### start Start listening to location data ```ts start(): void ``` ### stop Stop listening to location data ```ts stop(): void ``` ### getStatus Get the positioning status, return `A` for positioning in progress, return `V` for invalid positioning ```ts getStatus(): string ``` ### getLatitude Get Latitude ```ts getLatitude(option: Option): Result ``` #### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | ------------------- | -------- | --------------- | --------------------------------------------------------------------------------------- | --------- | | format | `string` | N | `DD` | Coordinate format, optionally `DD` for decimal or `DMS` in degrees, minutes and seconds | 2.1 | #### Result | Type | Description | | ---------------------------- | ------------------------------------------ | | `number|DMS` | Coordinates, coordinate system type WGS-84 | #### DMS | Property | Type | Description | API_LEVEL | | --------- | ------------------- | --------------------------------------------------------- | --------- | | direction | `string` | Direction, `N` for north latitude, `S` for south latitude | 2.1 | | degrees | `number` | degree | 2.1 | | minutes | `number` | minute | 2.1 | | seconds | `number` | second | 2.1 | ### getLongitude Get Longitude ```ts getLongitude(option: Option): Result ``` #### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | ------------------- | -------- | --------------- | --------------------------------------------------------------------------------------- | --------- | | format | `string` | N | `DD` | Coordinate format, optionally `DD` for decimal or `DMS` in degrees, minutes and seconds | 2.1 | #### Result | Type | Description | | ---------------------------- | ------------------------------------------ | | `number|DMS` | Coordinates, coordinate system type WGS-84 | #### DMS | Property | Type | Description | API_LEVEL | | --------- | ------------------- | --------------------------------------------------------- | --------- | | direction | `string` | Direction, `E` for east longitude, `W` for west longitude | 2.1 | | degrees | `number` | degree | 2.1 | | minutes | `number` | minute | 2.1 | | seconds | `number` | second | 2.1 | ### getSetting > Start from API_LEVEL `3.0` Get the positioning settings ```ts getSetting(): Result ``` #### Result | Property | Type | Description | API_LEVEL | | -------- | ------------------- | ------------------------------------------------------------- | --------- | | mode | `number` | Positioning settings, see `mode` below for value descriptions | 3.0 | #### mode | Value | Type | Description | API_LEVEL | | ----- | ------------------- | ------------------ | --------- | | 0 | `number` | Accuracy | 3.0 | | 1 | `number` | Automation | 3.0 | | 2 | `number` | Balance | 3.0 | | 3 | `number` | Power Saving | 3.0 | | 4 | `number` | Super Power Saving | 3.0 | | 5 | `number` | Custom | 3.0 | ### onChange Register a callback function to listen for location information change events ```ts onChange(callback: () => void): void ``` ### offChange Cancel the callback function for listening to the location information change event ```ts offChange(callback: () => void): void ``` ### onGnssChange > Start from API_LEVEL `3.0` Register a callback function to listen for GNSS information change events ```ts onGnssChange(callback: (info: Info) => void): void ``` #### Info | Property | Type | Description | API_LEVEL | | ------------------ | ------------------------------------------- | -------------------------------------------------------------------------------------- | --------- | | agps_inject_time | `number` | AGPS update time UTC timestamp in milliseconds | 3.0 | | top4_cn_val | `number` | Signal strength value of the positioning satellite | 3.0 | | is_dualband | `number` | Whether dual-band | 3.0 | | nb_valid_satellite | `number` | Number of available satellites | 3.0 | | nb_used_satellite | `number` | Number of satellites used | 3.0 | | elapsed_time | `number` | Time consumed from the start of satellite search to successful positioning, in seconds | 3.0 | | satellite_data | `Array` | Satellite data arrays | 3.0 | #### SatelliteSystem | Property | Type | Description | API_LEVEL | | ------------------ | ------------------------------------- | -------------------------------------------------------- | --------- | | gnss_id | `number` | Satellite ID, see `gnss_id` below for value descriptions | 3.0 | | sub_top4_cn_val | `number` | The strongest signal value of this satellite system | 3.0 | | nb_valid_satellite | `number` | Number of available satellites that can be searched | 3.0 | | gsv_data | `Array` | Single satellite data array, maximum length 32 | 3.6 | #### gnss_id | Value | Type | Description | API_LEVEL | | ----- | ------------------- | ----------- | --------- | | 0 | `number` | GPS | 3.0 | | 1 | `number` | BDS | 3.0 | | 2 | `number` | GLONASS | 3.0 | | 3 | `number` | GALILEO | 3.0 | | 4 | `number` | QZSS | 3.0 | | 5 | `number` | IRNSS | 3.0 | #### Satellite | Property | Type | Description | API_LEVEL | | --------- | ------------------- | --------------------- | --------- | | id | `number` | Satellite ID | 3.6 | | elevation | `number` | Pitch angle | 3.6 | | azimuth | `number` | Azimuth | 3.6 | | snr | `number` | Signal-to-noise ratio | 3.6 | ### offGnssChange > Start from API_LEVEL `3.0` Cancel the callback function for listening to the GNSS information change event ```ts offGnssChange(callback: (info: Geolocation.onGnssChange.Info) => void): void ``` ### getEnabled > Start from API_LEVEL `4.0` Get whether the user allows the Mini Program to use location features ```ts getEnabled(): boolean ``` ### onEnableChange > Start from API_LEVEL `4.0` Register a callback function to listen for user location permission change events ```ts onEnableChange(callback: () => void): void ``` ### offEnableChange > Start from API_LEVEL `4.0` Cancel the callback function for listening to user location permission change events ```ts offEnableChange(callback: () => void): void ``` ## Example ```js const geolocation = new Geolocation() const callback = () => { if (geolocation.getStatus() === 'A') { console.log(geolocation.getLatitude()) console.log(geolocation.getLongitude()) } } geolocation.start() geolocation.onChange(callback) // When not needed for use geolocation.offChange(callback) geolocation.stop() ``` --- ## Gyroscope ### Import ```js import { Gyroscope, FREQ_MODE_LOW } from '@zos/sensor' ``` ### Typings - Description: Gyroscope. Measuring the angular velocity of the device rotating along three orthogonal axes (x, y, z), the x and y axes are parallel to the screen, the positive direction refers to the figure, the z axis is perpendicular to the device's screen, the positive direction points upward, and the direction of the rotational angular velocity is determined using the [Right-hand rule](https://en.wikipedia.org/wiki/Right-hand_rule). The direction of the rotation arrow in the figure is the positive direction - API_LEVEL: 3.0 - Permission: `device:os.gyroscope` - Example: ```js import { Gyroscope, FREQ_MODE_LOW } from '@zos/sensor' const gyroscope = new Gyroscope() const callback = () => { console.log(gyroscope.getCurrent()) } gyroscope.onChange(callback) gyroscope.setFreqMode(FREQ_MODE_LOW) gyroscope.start() // When not needed for use gyroscope.offChange() gyroscope.stop() ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). [Image: Gyroscope_image] Gyroscope. Measuring the angular velocity of the device rotating along three orthogonal axes (x, y, z), the x and y axes are parallel to the screen, the positive direction refers to the figure, the z axis is perpendicular to the device's screen, the positive direction points upward, and the direction of the rotational angular velocity is determined using the [Right-hand rule](https://en.wikipedia.org/wiki/Right-hand_rule). The direction of the rotation arrow in the figure is the positive direction. > **ℹ️ Info** > > permission code: `device:os.gyroscope` ## Methods ### start Start listening to gyroscope data ```ts start(): void ``` ### stop Stop listening to gyroscope data ```ts stop(): void ``` ### getCurrent Get current gyroscope data ```ts getCurrent(): Result ``` #### Result | Property | Type | Description | API_LEVEL | | -------- | ------------------- | ----------------------------------------------------- | --------- | | x | `number` | Angular velocity of x-axis in DPS, degrees per second | 3.0 | | y | `number` | Angular velocity of y-axis in DPS, degrees per second | 3.0 | | z | `number` | Angular velocity of z-axis in DPS, degrees per second | 3.0 | ### onChange Register the gyroscope data change event listener callback function ```ts onChange(callback: () => void): void ``` ### offChange Cancel the gyroscope data change event listener callback function ```ts offChange(callback: () => void): void ``` ### setFreqMode > Start from API_LEVEL `3.0` Set the mode of trigger frequency, `mode` value reference frequency mode constant ```ts setFreqMode(mode: number): void ``` #### Constants ##### Frequency Mode | Constant | Description | API_LEVEL | | ------------------ | ------------------------------------------------------- | --------- | | `FREQ_MODE_LOW` | Low power mode with low trigger frequency | 3.0 | | `FREQ_MODE_NORMAL` | Normal power consumption mode, medium trigger frequency | 3.0 | | `FREQ_MODE_HIGH` | High power consumption mode with high trigger frequency | 3.0 | ### getFreqMode > Start from API_LEVEL `3.0` Get the mode of trigger frequency, result value reference frequency mode constant ```ts getFreqMode(): number ``` #### Constants ##### Frequency Mode | Constant | Description | API_LEVEL | | ------------------ | ------------------------------------------------------- | --------- | | `FREQ_MODE_LOW` | Low power mode with low trigger frequency | 3.0 | | `FREQ_MODE_NORMAL` | Normal power consumption mode, medium trigger frequency | 3.0 | | `FREQ_MODE_HIGH` | High power consumption mode with high trigger frequency | 3.0 | ## Example ```js const gyroscope = new Gyroscope() const callback = () => { console.log(gyroscope.getCurrent()) } gyroscope.onChange(callback) gyroscope.setFreqMode(FREQ_MODE_LOW) gyroscope.start() // When not needed for use gyroscope.offChange() gyroscope.stop() ``` --- ## HeartRate ### Import ```js import { HeartRate } from '@zos/sensor' ``` ### Typings - Description: HeartRate Sensor - Permission: `data:user.hd.heart_rate` - Example: ```js import { HeartRate } from '@zos/sensor' const heartRate = new HeartRate() const lastValue = heartRate.getLast() const callback = () => { console.log(heartRate.getCurrent()) } heartRate.onCurrentChange(callback) // When not needed for use heartRate.offCurrentChange(callback) ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). HeartRate Sensor. > **ℹ️ Info** > > permission code: `data:user.hd.heart_rate` ## Methods ### getCurrent Get the current heart rate measurement, this method needs to be used in the `onCurrentChange` callback function ```ts getCurrent(): number ``` ### getLast Get the most recent heart rate measurement (single measurement or heart rate monitoring measurement, continuous heart rate measurement `onCurrentChange` results are not counted) ```ts getLast(): number ``` ### getToday Get the heart rate measurement data in minutes from 0:00 to the current moment of the day, the longest array is 60\*24 ```ts getToday(): Array ``` ### onCurrentChange > Start from API_LEVEL `2.1` Call this method and start measuring heart rate continuously, call the callback function when there is a measurement result, call the `getCurrent` method in the callback function to get the heart rate measurement value, if you want to stop the heart rate measurement, you need to call the `offCurrentChange` method ```ts onCurrentChange(callback: () => void): void ``` ### offCurrentChange > Start from API_LEVEL `2.1` Cancel continuous heart rate measurement and cancel callback function listeners ```ts offCurrentChange(callback: () => void): void ``` ### onLastChange > Start from API_LEVEL `2.1` Register the heart rate single measurement change event callback function ```ts onLastChange(callback: () => void): void ``` ### offLastChange > Start from API_LEVEL `2.1` Cancel the heart rate single measurement change event callback function ```ts offLastChange(callback: () => void): void ``` ### getDailySummary > Start from API_LEVEL `3.0` Get daily heart rate statistics ```ts getDailySummary(): Result ``` #### Result | Property | Type | Description | API_LEVEL | | -------- | -------------------- | ------------------------------ | --------- | | maximum | `Maximum` | Maximum heart rate information | 3.0 | #### Maximum | Property | Type | Description | API_LEVEL | | -------- | ------------------- | -------------------------------------- | --------- | | hr_value | `number` | Maximum heart rate value | 3.0 | | time | `number` | Measurement time of maximum heart rate | 3.0 | ### getResting > Start from API_LEVEL `3.0` Get current resting heart rate ```ts getResting(): number ``` ### getAFibRecord > Start from API_LEVEL `3.0` Get Atrial Fibrillation Data Array ```ts getAFibRecord(): Result ``` #### Result | Type | Description | | ------------------------------------ | ------------------------------------- | | `Array` | Atrial Fibrillation Information Array | #### AfibInfo | Property | Type | Description | API_LEVEL | | -------- | ------------------- | ------------------------------------------------------------------------------------------------------------ | --------- | | flag | `number` | Atrial fibrillation test results, `0` - normal, `1` - high alert, `2` - low alert, `3` - atrial fibrillation | 3.0 | | val | `number` | Atrial fibrillation data value, integer value 0 - 255 | 3.0 | | maxValue | `number` | Atrial fibrillation data maximum value, integer value 0 - 255 | 3.0 | | minValue | `number` | Atrial fibrillation data minimum value, integer value 0 - 255 | 3.0 | | time | `number` | Time of Atrial fibrillation data acquisition, UTC seconds | 3.0 | | duration | `number` | Duration in seconds | 3.0 | ### onRestingChange > Start from API_LEVEL `3.0` After calling this method, the device starts real-time resting heart rate measurement and registers a callback function, which is called when there is a measurement result, in which the `getResting` method can be called to get the resting heart rate measurement value, and if you need to stop the resting heart rate measurement, you need to call the `offRestingChange` method ```ts onRestingChange(callback: () => void): void ``` ### offRestingChange > Start from API_LEVEL `3.0` Cancel continuous resting heart rate measurement and cancel callback function listeners ```ts offRestingChange(callback: () => void): void ``` ## Example ```js const heartRate = new HeartRate() const lastValue = heartRate.getLast() const callback = () => { console.log(heartRate.getCurrent()) } heartRate.onCurrentChange(callback) // When not needed for use heartRate.offCurrentChange(callback) ``` --- ## Pai ### Import ```js import { Pai } from '@zos/sensor' ``` ### Typings - Description: PAI Sensor - Permission: `data:user.hd.pai` - Example: ```js import { Pai } from '@zos/sensor' const pai = new Pai() const total = pai.getTotal() const today = pai.getToday() const lastWeek = pai.getLastWeek() ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). PAI Sensor. > **ℹ️ Info** > > permission code: `data:user.hd.pai` ## Methods ### getTotal Get the current cumulative PAI value ```ts getTotal(): number ``` ### getToday Get the PAI values obtained today ```ts getToday(): number ``` ### getLastWeek Get the PAI data for the past 7 days, the return value is an array of length `7`, the position of index `0` is the PAI value of today, the position of index `1` is the PAI value of the previous day, and so on ```ts getLastWeek(): Array ``` ## Example ```js const pai = new Pai() const total = pai.getTotal() const today = pai.getToday() const lastWeek = pai.getLastWeek() ``` --- ## Screen ### Import ```js import { Screen } from '@zos/sensor' ``` ### Typings - Description: Screen Status Sensor - API_LEVEL: 3.0 - Example: ```js import { Screen } from '@zos/sensor' const screen = new Screen() const status = screen.getStatus() const callback = () => { console.log(screen.getStatus()) } screen.onChange(callback) // When not needed for use screen.offChange(callback) ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Screen Status Sensor. ## Methods ### getStatus Get the screen status, `1`: On, `2`: Off ```ts getStatus(): number ``` ### getAodMode Whether to turn on the AOD rest screen display function ```ts getAodMode(): boolean ``` ### getLight > Start from API_LEVEL `3.6` Light intensity, unit lux ```ts getLight(): number ``` ### onChange Register a callback function to listen to screen display change events ```ts onChange(callback: (status: number) => void): void ``` ### offChange Cancel a callback function to listen to screen display change events ```ts offChange(callback: (status: number) => void): void ``` ## Example ```js const screen = new Screen() const status = screen.getStatus() const callback = () => { console.log(screen.getStatus()) } screen.onChange(callback) // When not needed for use screen.offChange(callback) ``` --- ## Sleep ### Import ```js import { Sleep } from '@zos/sensor' ``` ### Typings - Description: Sleep Sensor - Permission: `data:user.hd.sleep` - Example: ```js import { Sleep } from '@zos/sensor' const sleep = new Sleep() const { score } = sleep.getInfo() const sleepStageConstants = sleep.getStageConstantObj() const stage = sleep.getStage() stage.forEach((i) => { const { model } = i if (model === sleepStageConstants.WAKE_STAGE) { console.log('This stage is awake stage') } }) ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Sleep Sensor. > **ℹ️ Info** > > permission code: `data:user.hd.sleep` ## Methods ### updateInfo By default, the system updates the sleep data every `30` minutes, the `updateInfo` method is used to actively trigger the update of the sleep data ```ts updateInfo(): void ``` ### getInfo Get sleep information ```ts getInfo(): SleepInfo ``` #### SleepInfo | Property | Type | Description | API_LEVEL | | --------- | ------------------- | ------------------------------------------------------------------- | --------- | | score | `number` | Sleep score | 2.0 | | deepTime | `number` | Deep sleep time (minutes) | 2.0 | | startTime | `number` | Sleep onset time, based on the number of minutes at 0:00 of the day | 2.0 | | endTime | `number` | Sleep end time, based on the number of minutes at 0:00 of the day | 2.0 | | totalTime | `number` | Get total sleep time (minutes) | 2.0 | ### getStageConstantObj Get the constant value of the sleep stage, used to determine the sleep stage in the `getStage` return value ```ts getStageConstantObj(): StageConstants ``` #### StageConstants | Property | Type | Description | API_LEVEL | | ----------- | ------------------- | ------------------------- | --------- | | WAKE_STAGE | `number` | Awake stage | 2.0 | | REM_STAGE | `number` | Deep sleep time (minutes) | 2.0 | | LIGHT_STAGE | `number` | Light Sleep stage | 2.0 | | DEEP_STAGE | `number` | Deep Sleep stage | 2.0 | ### getStage Get Sleep Staging Data ```ts getStage(): Array ``` #### StageInfo | Property | Type | Description | API_LEVEL | | -------- | ------------------- | ------------------------------------------------------------------------------------------------------- | --------- | | model | `number` | Sleep stage type, refer to the constants returned by `getStageConstantObj` for the meaning of the value | 2.0 | | start | `number` | Sleep stage onset time, based on the number of minutes at 0:00 of the day | 2.0 | | stop | `number` | Sleep stage end time, based on the number of minutes at 0:00 of the day | 2.0 | ### getSleepingStatus > Start from API_LEVEL `3.0` Get the current sleep state, 0 'awake, 1' sleeping ```ts getSleepingStatus(): number ``` ### getNap > Start from API_LEVEL `3.0` Get nap data ```ts getNap(): Array ``` #### NapInfo | Property | Type | Description | API_LEVEL | | -------- | ------------------- | ----------------------------------------------------------------- | --------- | | length | `number` | Nap duration (minutes) | 3.0 | | start | `number` | Nap start time, based on the number of minutes at 0:00 of the day | 3.0 | | stop | `number` | Nap end time, based on the number of minutes at 0:00 of the day | 3.0 | ## Example ```js const sleep = new Sleep() const { score } = sleep.getInfo() const sleepStageConstants = sleep.getStageConstantObj() const stage = sleep.getStage() stage.forEach((i) => { const { model } = i if (model === sleepStageConstants.WAKE_STAGE) { console.log('This stage is awake stage') } }) ``` --- ## Stand ### Import ```js import { Stand } from '@zos/sensor' ``` ### Typings - Description: Standing behavior Sensor - Permission: `data:user.hd.stand` - Example: ```js import { Stand } from '@zos/sensor' const stand = new Stand() const current = stand.getCurrent() const target = stand.getTarget() const callback = () => { console.log(stand.getCurrent()) } stand.onChange(callback) // When not needed for use stand.offChange(callback) ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Standing behavior Sensor. > **ℹ️ Info** > > permission code: `data:user.hd.stand` ## Methods ### getCurrent Get the current number of hours with standing behavior ```ts getCurrent(): number ``` ### getTarget Get the number of hours with standing behavior targets ```ts getTarget(): number ``` ### onChange Register a callback function to listen for changes in the number of hours of standing behavior ```ts onChange(callback: () => void): void ``` ### offChange Cancel a callback function to listen for changes in the number of hours of standing behavior ```ts offChange(callback: () => void): void ``` ## Example ```js const stand = new Stand() const current = stand.getCurrent() const target = stand.getTarget() const callback = () => { console.log(stand.getCurrent()) } stand.onChange(callback) // When not needed for use stand.offChange(callback) ``` --- ## Step ### Import ```js import { Step } from '@zos/sensor' ``` ### Typings - Description: Step Sensor - Permission: `data:user.hd.step` - Example: ```js import { Step } from '@zos/sensor' const step = new Step() const current = step.getCurrent() const target = step.getTarget() const callback = () => { console.log(step.getCurrent()) } step.onChange(callback) // When not needed for use step.offChange(callback) ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Step Sensor. > **ℹ️ Info** > > permission code: `data:user.hd.step` ## Methods ### getCurrent Get the current step count ```ts getCurrent(): number ``` ### getTarget Get step goal ```ts getTarget(): number ``` ### onChange Register the step change event callback function ```ts onChange(callback: () => void): void ``` ### offChange Cancel the step change event callback function ```ts offChange(callback: () => void): void ``` ## Example ```js const step = new Step() const current = step.getCurrent() const target = step.getTarget() const callback = () => { console.log(step.getCurrent()) } step.onChange(callback) // When not needed for use step.offChange(callback) ``` --- ## Stress ### Import ```js import { Stress } from '@zos/sensor' ``` ### Typings - Description: Stress Sensor - Permission: `data:user.hd.stress` - Example: ```js import { Stress } from '@zos/sensor' const stress = new Stress() const { value } = stress.getCurrent() const callback = () => { console.log(stress.getCurrent()) } stress.onChange(callback) // When not needed for use stress.offChange(callback) ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Stress Sensor. > **ℹ️ Info** > > permission code: `data:user.hd.stress` ## Methods ### getCurrent Get the current pressure measurement ```ts getCurrent(): Result ``` #### Result | Property | Type | Description | API_LEVEL | | -------- | ------------------- | --------------------------------- | --------- | | value | `number` | Stress measurement values | 2.0 | | time | `number` | Time to obtain the measured value | 2.0 | ### onChange Register a callback function to listen for stress measurement change events ```ts onChange(callback: () => void): void ``` ### offChange Cancel a callback function to listen for stress measurement change events ```ts offChange(callback: () => void): void ``` ### getToday > Start from API_LEVEL `3.0` Get the pressure measurements for the whole day, recorded every minute, the return value is an array of variable length, the maximum length of the array is 24 \* 60 ```ts getToday(): Array ``` #### StressInfo | Property | Type | Description | API_LEVEL | | -------- | ------------------- | ----------------------------------------------------------- | --------- | | second | `number` | Pressure value measurement time, UTC time stamp, in seconds | 3.0 | | stress | `number` | Pressure value, `0` means invalid | 3.0 | ### getTodayByHour > Start from API_LEVEL `3.0` Get the average pressure value for the whole day, the return value is a fixed-length array, the average pressure for each hour, the length of the array is 24 ```ts getTodayByHour(): Array ``` ### getLastWeek > Start from API_LEVEL `3.0` Get the average pressure value for each day of the past 7 days, the return value is a fixed-length array, the average pressure per day, the length of the array is 7, the position of index 0 represents six days ago, the position of index 6 represents today ```ts getLastWeek(): Array ``` ### getLastWeekByHour > Start from API_LEVEL `3.0` Get the hourly pressure average for the past 7 days, the return value is a fixed-length array, the length of the array is 7 \* 24 ```ts getLastWeekByHour(): Array ``` #### StressInfo | Property | Type | Description | API_LEVEL | | -------- | ------------------- | ----------------------------------------------------------- | --------- | | second | `number` | Pressure value measurement time, UTC time stamp, in seconds | 3.0 | | stress | `number` | Pressure value, `0` means invalid | 3.0 | ## Example ```js const stress = new Stress() const { value } = stress.getCurrent() const callback = () => { console.log(stress.getCurrent()) } stress.onChange(callback) // When not needed for use stress.offChange(callback) ``` --- ## SystemSounds ### Import ```js import { SystemSounds } from '@zos/sensor' ``` ### Typings - Description: System Sounds - API_LEVEL: 3.6 - Example: ```js import { SystemSounds } from '@zos/sensor' const systemSounds = new SystemSounds() const alarmType = systemSounds.getSourceType().ALARM if (systemSounds.getEnabled()) { systemSounds.start(alarmType) } ``` > Start from API_LEVEL `3.6` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). System Sounds. ## Methods ### getEnabled Get whether the system ringtone function is turned on, and it can only be played after it is turned on ```ts getEnabled(): boolean ``` ### getSourceType Get built-in system ringtone type ```ts getSourceType(): Type ``` #### Type | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | ------------------- | -------- | ------------ | --------------------------------------------------------- | --------- | | ALARM | `number` | Y | - | Alarm clock reminder | 3.6 | | MESSAGE | `number` | Y | - | Notification sound when receiving text messages or emails | 3.6 | | REGULAR | `number` | Y | - | TingTing sound | 3.6 | | ACHIEVE | `number` | Y | - | Goals achieved | 3.6 | | CAMERA | `number` | Y | - | Camera shutter | 3.6 | | ABN_HIGH | `number` | Y | - | Health data measurement abnormalities (high values) | 3.6 | | ABN_LOW | `number` | Y | - | Health data measurement abnormalities (low values) | 3.6 | | SOS | `number` | Y | - | SOS for help | 3.6 | ### start Start playing the sound, you can pass in `type` to specify the ringtone type, `repeatCount` is the number of audio repetitions, default is `0`, do not repeat playback ```ts start(sourceType: number, repeatCount: 0): void ``` ### stop Stop sound playback ```ts stop(): void ``` ## Example ```js const systemSounds = new SystemSounds() const alarmType = systemSounds.getSourceType().ALARM if (systemSounds.getEnabled()) { systemSounds.start(alarmType) } ``` --- ## Time ### Import ```js import { Time } from '@zos/sensor' ``` ### Typings - Description: Time/Date Sensor - Example: ```js import { Time } from '@zos/sensor' const time = new Time() const currentTime = time.getTime() ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Time/Date Sensor. ## Methods ### getTime Gets the UTC timestamp in milliseconds ```ts getTime(): number ``` ### getFullYear Get the year of the current date ```ts getFullYear(): number ``` ### getMonth Get the month of the current date, range 1 - 12, return `1` for January ```ts getMonth(): number ``` ### getDate Get the number of days of the current date, i.e. the day of the month, in the range 1 - 31 ```ts getDate(): number ``` ### getHours Get the number of hours of the current time ```ts getHours(): number ``` ### getMinutes Get the number of minutes of the current time ```ts getMinutes(): number ``` ### getSeconds Get the number of seconds of the current time ```ts getSeconds(): number ``` ### getDay Get the current time corresponding to the day of the week, range 1 - 7, return `1` for Monday ```ts getDay(): number ``` ### getHourFormat > Start from API_LEVEL `2.1` Get the current system time format, 12-hour format or 24-hour format,value reference hour format constants ```ts getHourFormat(): number ``` #### Constants ##### Hour format constants | Constant | Description | API_LEVEL | | --------------------- | -------------- | --------- | | `TIME_HOUR_FORMAT_12` | 12-hour format | 2.1 | | `TIME_HOUR_FORMAT_24` | 24-hour format | 2.1 | ### getFormatHour > Start from API_LEVEL `2.1` Get the number of hours in the current time format (12-hour format or 24-hour format) ```ts getFormatHour(): number ``` ### onPerMinute > Start from API_LEVEL `2.1` Register end-of-minute event listener callback function ```ts onPerMinute(callback: () => void): void ``` ### onPerDay > Start from API_LEVEL `2.1` Register the end-of-day event listener callback function ```ts onPerDay(callback: () => void): void ``` ### onPerHourEnd > Start from API_LEVEL `3.6` Register the end-of-hour event listener callback function ```ts onPerHourEnd(callback: () => void): void ``` ### getFestival Get gregorian holidays, or return the string `'INVALID'` if there is no holiday ```ts getFestival(): string ``` ### getLunarYear Get Chinese lunar year, only works when system language is set to Chinese ```ts getLunarYear(): number ``` ### getLunarMonth Get Chinese lunar month, only works when system language is set to Chinese ```ts getLunarMonth(): number ``` ### getLunarDay Get Chinese lunar day, only works when system language is set to Chinese ```ts getLunarDay(): number ``` ### getLunarFestival Get Chinese lunar holidays, only works when system language is set to Chinese, or return the string `'INVALID'` if there is no holiday ```ts getLunarFestival(): string ``` ### getSolarTerm Get Traditional Chinese Solar Terms, only works when system language is set to Chinese, or return the string `'INVALID'` if there is no Solar Term ```ts getSolarTerm(): string ``` ### getShowFestival Get the holiday strings displayed on that day, the priority is Gregorian holidays, Chinese lunar holidays, Chinese lunar festivals in that order, only when the system language is set to Chinese ```ts getShowFestival(): string ``` ### getLunarMonthCalendar Get the monthly calendar information of the current month of Chinese lunar calendar, only works when the system language is set to Chinese ```ts getLunarMonthCalendar(): LunarMonthCalendar ``` #### LunarMonthCalendar | Property | Type | Description | API_LEVEL | | ---------------- | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------- | --------- | | day_count | `number` | Number of days in the current month | 2.0 | | lunar_days_array | `Array` | Array of display content for each day of the current month, display content priority for holidays, Solar Term, date | 2.0 | ### onSunrise > Start from API_LEVEL `3.0` Register the Sunrise event listener callback function to take effect only when the device weather information ```ts onSunrise(callback: () => void): void ``` ### onSunset > Start from API_LEVEL `3.0` Register the Sunset event listener callback function to take effect only when the device weather information ```ts onSunset(callback: () => void): void ``` ### onPhoneTimeSetting > Start from API_LEVEL `3.0` Register the phone modify time event listening callback function ```ts onPhoneTimeSetting(callback: () => void): void ``` ## Example ```js const time = new Time() const currentTime = time.getTime() ``` --- ## Vibrator ### Import ```js import { Vibrator, VIBRATOR_SCENE_DURATION } from '@zos/sensor' ``` ### Typings - Description: Vibrator - Example: ```js import { Vibrator, VIBRATOR_SCENE_DURATION } from '@zos/sensor' const vibrator = new Vibrator() vibrator.start() // set scene vibrator.setMode(VIBRATOR_SCENE_DURATION) vibrator.start() ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Vibrator. ## Methods ### start Start vibration, the'option 'parameter passed in only takes effect for this vibration, and supports passing in vibration scene arrays after API_LEVEL 3.6 ```ts start(option?: Option | Array): void ``` #### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | ------------------- | -------- | ---------------------------------------- | ------------------------------------------------------------- | --------- | | mode | `number` | N | `VIBRATOR_SCENE_SHORT_MIDDLE` | Vibration mode, Value refer to Vibration motor mode constants | 2.0 | #### Action | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | ------------------- | -------- | ------------ | --------------------- | --------- | | type | `number` | Y | - | Vibration Scene Type | 3.6 | | duration | `number` | N | - | Duration of vibration | 3.6 | #### Constants ##### Vibration motor mode constants | Constant | Description | API_LEVEL | | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | | `VIBRATOR_SCENE_SHORT_LIGHT` | Light vibration intensity and short time (20ms) | 2.0 | | `VIBRATOR_SCENE_SHORT_MIDDLE` | Medium vibration intensity, short time (20ms) | 2.0 | | `VIBRATOR_SCENE_SHORT_STRONG` | High vibration intensity and short time (20ms) | 2.0 | | `VIBRATOR_SCENE_DURATION` | High vibration intensity, lasting 600ms | 2.0 | | `VIBRATOR_SCENE_DURATION_LONG` | High vibration intensity, lasting 1000ms | 2.0 | | `VIBRATOR_SCENE_STRONG_REMINDER` | High vibration intensity, four vibrations in 1200ms, can be used for stronger reminders | 2.0 | | `VIBRATOR_SCENE_NOTIFICATION` | Two short, continuous vibrations, consistent with the watch message notification vibration feedback | 2.0 | | `VIBRATOR_SCENE_CALL` | High vibration intensity, single vibration twice in 500ms, continuous vibration, need to manually `stop`, consistent with the watch call vibration feedback | 2.0 | | `VIBRATOR_SCENE_TIMER` | High vibration intensity, single long vibration 500ms, continuous vibration, need to manually `stop`, consistent with the watch alarm clock, countdown vibration feedback | 2.0 | ### stop Stop vibration ```ts stop(): void ``` ### setMode Set the vibration mode, call `start()` after successful setting, it will vibrate according to the set mode ```ts setMode(option: Option): void ``` #### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | ------------------- | -------- | ------------ | ------------------------------------------------------------- | --------- | | mode | `number` | Y | - | Vibration mode, Value refer to Vibration motor mode constants | 2.0 | ### getConfig Get Vibration Motor Configuration ```ts getConfig(): Option ``` #### Option | Property | Type | Description | API_LEVEL | | -------- | ------------------- | ------------------------------------------------------------- | --------- | | mode | `number` | Vibration mode, Value refer to Vibration motor mode constants | 2.0 | ### getType > Start from API_LEVEL `3.6` Get Vibration Scene Type ```ts getType(): Type ``` #### Type | Property | Type | Description | API_LEVEL | | -------------- | ------------------- | --------------------------------------------- | --------- | | GENTLE_SHORT | `number` | Vibration scene, light short vibration | 3.6 | | STRONG_SHORT | `number` | Vibration scene, strong and short vibration | 3.6 | | STANDARD_CROWN | `number` | Vibration scene, standard crown vibration | 3.6 | | STRONG_CROWN | `number` | Vibration scene, strong crown vibration | 3.6 | | SPULSE_CROWN | `number` | Vibration scene, single-pulse crown vibration | 3.6 | | DIPULSE_CROWN | `number` | Vibration scene, dual-pulse crown vibration | 3.6 | | KEYCODE_CLICK | `number` | Vibration scene, password button vibration | 3.6 | | URGENT | `number` | Vibration scene, urgent vibration | 3.6 | | CONTINUOUS | `number` | Vibration scene, continuous vibration | 3.6 | | PAUSE | `number` | Vibration scene, stop vibration | 3.6 | ## Example ```js const vibrator = new Vibrator() vibrator.start() // set scene vibrator.setMode(VIBRATOR_SCENE_DURATION) vibrator.start() ``` --- ## Wear ### Import ```js import { Wear } from '@zos/sensor' ``` ### Typings - Description: Wearing status sensor - Example: ```js import { Wear } from '@zos/sensor' const wear = new Wear() const status = wear.getStatus() const callback = () => { console.log(wear.getStatus()) } wear.onChange(callback) // When not needed for use wear.offChange(callback) ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Wearing status sensor. ## Methods ### getStatus Get the current device wearing status, `0`: not wearing, `1`: wearing, `2`: in motion, `3`: not sure ```ts getStatus(): number ``` ### onChange Register the device wear status change event listening callback function ```ts onChange(callback: () => void): void ``` ### offChange Cancel the device wear status change event listening callback function ```ts offChange(callback: () => void): void ``` ## Example ```js const wear = new Wear() const status = wear.getStatus() const callback = () => { console.log(wear.getStatus()) } wear.onChange(callback) // When not needed for use wear.offChange(callback) ``` --- ## Weather ### Import ```js import { Weather } from '@zos/sensor' ``` ### Typings - Description: Weather Forecasts sensor - Example: ```js import { Weather } from '@zos/sensor' const weather = new Weather() const { forecastData, tideData, cityName } = weather.getForecast() console.log(cityName) for (let i = 0; i < forecastData.count; i++) { const element = forecastData.data[i] console.log('Index' + element.index) console.log('Highest temperature' + element.high) console.log('Lowest temperature' + element.low) } for (let i = 0; i < tideData.count; i++) { const element = tideData.data[i] console.log('Sunrise' + element.sunrise.hour + element.sunrise.minute) console.log('Sunset' + element.sunset.hour + element.sunset.minute) } ``` ### Methods | Method | Signature | Description | API_LEVEL | Permission | |--------|-----------|-------------|-----------|------------| | `getForecastWeather` | `getForecastWeather(): Weather.getForecastWeather.ForecastWeather` | Get weather forecast data | — | — | ### Method Details #### getForecastWeather - Signature: `getForecastWeather(): Weather.getForecastWeather.ForecastWeather` - Description: Get weather forecast data - Returns: `Weather.getForecastWeather.ForecastWeather` > **⚠️ Warning** > > This interface has been deprecated, please refer to https://github.com/orgs/zepp-health/discussions/83 > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Weather Forecasts sensor. ## Methods ### getForecastWeather Get weather forecast data ```ts getForecastWeather(): ForecastWeather ``` #### ForecastWeather | Property | Type | Description | API_LEVEL | | ------------ | ------------------------- | ------------------- | --------- | | cityName | `string` | City Name | 2.0 | | forecastData | `ForecastData` | Weather Information | 2.0 | | tideData | `TideData` | Tide Information | 2.0 | #### ForecastData | Property | Type | Description | API_LEVEL | | -------- | -------------------------------------------- | -------------------------------------------------------------- | --------- | | data | `Array` | Weather Information Array, index 0 position represents the day | 2.0 | | count | `number` | The length of Weather Information Array | 2.0 | #### ForecastDataItem | Property | Type | Description | API_LEVEL | | -------- | ------------------- | -------------------------------------------------------------------------------- | --------- | | high | `number` | Maximum temperature | 2.0 | | low | `number` | Lowest temperature | 2.0 | | index | `number` | The index value of the weather, see `index` below for a description of the value | 2.0 | #### index | Value | Type | Description | API_LEVEL | | ----- | ------------------- | -------------------- | --------- | | 0 | `number` | Cloudy | 2.0 | | 1 | `number` | Showers | 2.0 | | 2 | `number` | Snow Showers | 2.0 | | 3 | `number` | Sunny | 2.0 | | 4 | `number` | Overcast | 2.0 | | 5 | `number` | Light Rain | 2.0 | | 6 | `number` | Light Snow | 2.0 | | 7 | `number` | Moderate Rain | 2.0 | | 8 | `number` | Moderate Snow | 2.0 | | 9 | `number` | Heavy Snow | 2.0 | | 10 | `number` | Heavy Rain | 2.0 | | 11 | `number` | Sandstorm | 2.0 | | 12 | `number` | Rain and Snow | 2.0 | | 13 | `number` | Fog | 2.0 | | 14 | `number` | Hazy | 2.0 | | 15 | `number` | T-Storms | 2.0 | | 16 | `number` | Snowstorm | 2.0 | | 17 | `number` | Floating dust | 2.0 | | 18 | `number` | Very Heavy Rainstorm | 2.0 | | 19 | `number` | Rain and Hail | 2.0 | | 20 | `number` | T-Storms and Hail | 2.0 | | 21 | `number` | Heavy Rainstorm | 2.0 | | 22 | `number` | Dust | 2.0 | | 23 | `number` | Heavy sand storm | 2.0 | | 24 | `number` | Rainstorm | 2.0 | | 25 | `number` | Unknown | 2.0 | | 26 | `number` | Cloudy Nighttime | 2.0 | | 27 | `number` | Showers Nighttime | 2.0 | | 28 | `number` | Sunny Nighttime | 2.0 | #### TideData | Property | Type | Description | API_LEVEL | | -------- | ---------------------------------------- | ----------------------------------------------------------- | --------- | | data | `Array` | Tide Information Array, index 0 position represents the day | 2.0 | | count | `number` | The length of Tide Information Array | 2.0 | #### TideDataItem | Property | Type | Description | API_LEVEL | | -------- | -------------------- | ------------ | --------- | | sunrise | `Sunrise` | Sunrise time | 2.0 | | sunset | `Sunset` | Sunset time | 2.0 | #### Sunrise | Property | Type | Description | API_LEVEL | | -------- | ------------------- | --------------------- | --------- | | hour | `number` | Sunrise time - hour | 2.0 | | minute | `number` | Sunrise time - minute | 2.0 | #### Sunset | Property | Type | Description | API_LEVEL | | -------- | ------------------- | --------------------- | --------- | | hour | `number` | Sunrise time - hour | 2.0 | | minute | `number` | Sunrise time - minute | 2.0 | ## Example ```js const weather = new Weather() const { forecastData, tideData, cityName } = weather.getForecast() console.log(cityName) for (let i = 0; i < forecastData.count; i++) { const element = forecastData.data[i] console.log('Index' + element.index) console.log('Highest temperature' + element.high) console.log('Lowest temperature' + element.low) } for (let i = 0; i < tideData.count; i++) { const element = tideData.data[i] console.log('Sunrise' + element.sunrise.hour + element.sunrise.minute) console.log('Sunset' + element.sunset.hour + element.sunset.minute) } ``` --- ## Workout ### Import ```js import { Workout } from '@zos/sensor' ``` ### Typings - Description: Workout Sensor - API_LEVEL: 3.0 - Permission: `data:user.hd.workout` - Example: ```js import { Workout } from '@zos/sensor' const workout = new Workout() const status = workout.getStatus() const history = workout.getHistory() const hrZoneSettings = workout.getUserHrZoneSettings() // {"type":0,"rest":83,"range":[129,138,147,157,166,175]} // {"type":1,"rest":70,"range":[90,108,126,144,162,181]} const trackNavInfo = workout.getWorkoutTrackNavInfo() ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Workout Sensor. > **ℹ️ Info** > > permission code: `data:user.hd.workout` ## Methods ### getStatus Get altitude value in meters ```ts getStatus(): Status ``` #### Status | Property | Type | Description | API_LEVEL | | ---------------- | ------------------- | ------------------ | --------- | | vo2Max | `number` | VO2 Max | 3.0 | | trainingLoad | `number` | Training Load | 3.0 | | fullRecoveryTime | `number` | Full Recovery Time | 3.0 | ### getHistory Get the duration of the workout record ```ts getHistory(): Array ``` #### History | Property | Type | Description | API_LEVEL | | --------- | ------------------- | ------------------------------ | --------- | | startTime | `number` | Workout start time | 3.0 | | duration | `number` | Duration of workout in seconds | 3.0 | ### getUserHrZoneSettings > Start from API_LEVEL `4.2` Get user heart rate zone settings ```ts getUserHrZoneSettings(): HrZoneSettings ``` #### HrZoneSettings | Property | Type | Description | API_LEVEL | | -------- | --------------------- | --------------------------------------------------------------------------------------------------------------------------------- | --------- | | type | `number` | Heart rate zone type, 0: by heart rate reserve, 1: by maximum heart rate | 4.2 | | rest | `number` | Resting heart rate value | 4.2 | | range | `number[]` | Heart rate zone value array with 6 values, corresponding to: Ligit, Intensive, Aerobic, Anaerobic, VO2 max and maximum heart rate | 4.2 | ### getWorkoutTrackNavInfo > Start from API_LEVEL `4.2` Get workout track navigation information, returns navigation info object when navigation is enabled, returns `undefined` when navigation is not enabled ```ts getWorkoutTrackNavInfo(): WorkoutTrackNavInfo | undefined ``` #### WorkoutTrackNavInfo | Property | Type | Description | API_LEVEL | | -------------- | ------------------- | ----------------------------------------------------------------------- | --------- | | update | `number` | Data update status, true: need update, false: no need to update | 4.2 | | isYaw | `number` | Whether off course, true: off course, false: on course | 4.2 | | yawAngle | `number` | Yaw angle | 4.2 | | yawDistance | `number` | Yaw distance in meters | 4.2 | | remainDistance | `number` | Remaining distance in meters | 4.2 | | turnDistance | `number` | Distance to next turn in meters | 4.2 | | turnType | `number` | The direction of the next turn, refer to `TURN_TYPE` for value meanings | 4.2 | #### TURN_TYPE | Value | Type | Description | API_LEVEL | | ----- | ------------------- | ------------------- | --------- | | 1 | `number` | Turn right forward | 4.2 | | 2 | `number` | Turn right | 4.2 | | 3 | `number` | Turn right backward | 4.2 | | 4 | `number` | U-turn to the right | 4.2 | | 5 | `number` | U-turn | 4.2 | | 6 | `number` | U-turn to the left | 4.2 | | 7 | `number` | Turn left backward | 4.2 | | 8 | `number` | Turn left | 4.2 | | 9 | `number` | Turn left forward | 4.2 | ## Example ```js const workout = new Workout() const status = workout.getStatus() const history = workout.getHistory() const hrZoneSettings = workout.getUserHrZoneSettings() // {"type":0,"rest":83,"range":[129,138,147,157,166,175]} // {"type":1,"rest":70,"range":[90,108,126,144,162,181]} const trackNavInfo = workout.getWorkoutTrackNavInfo() ``` --- ## WorldClock ### Import ```js import { WorldClock } from '@zos/sensor' ``` ### Typings - Description: World Clock Sensor - API_LEVEL: 3.0 - Example: ```js import { WorldClock } from '@zos/sensor' const worldClock = new WorldClock() const worldClockCount = worldClock.getCount() for (let i = 0; i < worldClockCount; i++) { const worldClockInfo = worldClock.getInfo(i) console.log(worldClockInfo.city) console.log(worldClockInfo.cityCode) console.log(worldClockInfo.hour) console.log(worldClockInfo.minute) console.log(worldClockInfo.timeZoneHour) console.log(worldClockInfo.timeZoneMinute) } // When not needed for use worldClock.destroy() ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). World Clock Sensor. ## Methods ### getCount Get the number of configured world clocks ```ts getCount(): number ``` ### getInfo Get the configured world clock information according to the index ```ts getInfo(index: number): WorldClockInfo ``` #### WorldClockInfo | Property | Type | Description | API_LEVEL | | -------------- | ------------------- | ----------------------------------- | --------- | | city | `string` | City Name | 3.0 | | cityCode | `string` | City code, e.g. San Francisco `SFO` | 3.0 | | hour | `number` | Hour | 3.0 | | minute | `number` | Minute | 3.0 | | timeZoneHour | `number` | Time Zone hours | 3.0 | | timeZoneMinute | `number` | Time zone minutes | 3.0 | ## Example ```js const worldClock = new WorldClock() const worldClockCount = worldClock.getCount() for (let i = 0; i < worldClockCount; i++) { const worldClockInfo = worldClock.getInfo(i) console.log(worldClockInfo.city) console.log(worldClockInfo.cityCode) console.log(worldClockInfo.hour) console.log(worldClockInfo.minute) console.log(worldClockInfo.timeZoneHour) console.log(worldClockInfo.timeZoneMinute) } // When not needed for use worldClock.destroy() ``` --- ## checkSensor ### Import ```js import { checkSensor, Geolocation } from '@zos/sensor' ``` ### Typings - Description: Check the availability of sensors on the current device - API_LEVEL: 3.0 - Example: ```js import { checkSensor, Geolocation } from '@zos/sensor' const result = checkSensor(Geolocation) let geolocation = null if (result) { geolocation = new Geolocation() } ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Check the availability of sensors on the current device. ## Type ```ts function checkSensor(sensor: Sensor): Result ``` ## Parameters ### Sensor | Type | Description | | ------------------- | ----------------------------------------------------------------------------------------------------------------------- | | `object` | Sensor, such as checking if the positioning sensor is available, pass in the `Geolocation` sensor construction function | ### Result | Type | Description | | -------------------- | ------------------------------------------------------------------------------ | | `boolean` | `true` - auto-brightness is set to on, `false` - auto-brightness is set to off | ## Example ```js const result = checkSensor(Geolocation) let geolocation = null if (result) { geolocation = new Geolocation() } ``` --- --- # @zos/settings ## Constants | Constant | Description | API_LEVEL | |----------|-------------|-----------| | `DATE_FORMAT_YMD` | year-month-day | — | | `DATE_FORMAT_DMY` | day-month-year | — | | `DATE_FORMAT_MDY` | month-day-year | — | | `TIME_FORMAT_12` | 12-hour format | 2.1 | | `TIME_FORMAT_24` | 24-hour format | 2.1 | | `DISTANCE_UNIT_METRIC` | metric system | — | | `DISTANCE_UNIT_IMPERIAL` | imperial system | — | | `WEIGHT_UNIT_KILOGRAM` | Kilogram | — | | `WEIGHT_UNIT_JIN` | Jin | — | | `WEIGHT_UNIT_POUND` | Pound | — | | `WEIGHT_UNIT_STONE` | Stone | — | | `TEMPERATURE_UNIT_CENTIGRADE` | Celsius temperature | — | | `TEMPERATURE_UNIT_FAHRENHEIT` | Fahrenheit temperature | — | ## getDateFormat ### Import ```js import { getDateFormat, DATE_FORMAT_YMD } from '@zos/settings' ``` ### Typings - Description: Get the current system date format - Constants: `dateFormat` - Example: ```js import { getDateFormat, DATE_FORMAT_YMD } from '@zos/settings' const currentDateFormat = getDateFormat() if (currentDateFormat === DATE_FORMAT_YMD) { console.log('date format is YYYY-MM-DD') } ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Get the current system date format. ## Type ```ts function getDateFormat(): Result ``` ## Parameters ### Result | Type | Description | | ------------------- | ------------------------------------------------- | | `number` | Date format, value refer to date format constants | ## Constants ### Date format constants | Constant | Description | API_LEVEL | | ----------------- | -------------- | --------- | | `DATE_FORMAT_YMD` | year-month-day | 2.0 | | `DATE_FORMAT_DMY` | day-month-year | 2.0 | | `DATE_FORMAT_MDY` | month-day-year | 2.0 | ## Example ```js const currentDateFormat = getDateFormat() if (currentDateFormat === DATE_FORMAT_YMD) { console.log('date format is YYYY-MM-DD') } ``` --- ## getDistanceUnit ### Import ```js import { getDistanceUnit, DISTANCE_UNIT_METRIC } from '@zos/settings' ``` ### Typings - Description: Returns whether the current distance unit is metric or imperial. This method is to get the units set by the user, not to represent the units of the data, the data units refer to the interface description of the corresponding data - Constants: `distanceUnit` - Example: ```js import { getDistanceUnit, DISTANCE_UNIT_METRIC } from '@zos/settings' const distanceUnit = getDistanceUnit() if (distanceUnit === DISTANCE_UNIT_METRIC) { console.log('metric') } ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Returns whether the current distance unit is metric or imperial. This method is to get the units set by the user, not to represent the units of the data, the data units refer to the interface description of the corresponding data. ## Type ```ts function getDistanceUnit(): Result ``` ## Parameters ### Result | Type | Description | | ------------------- | ------------------------------------------------------ | | `number` | Distance units, value refer to distance unit constants | ## Constants ### Distance unit constants | Constant | Description | API_LEVEL | | ------------------------ | --------------- | --------- | | `DISTANCE_UNIT_METRIC` | metric system | 2.0 | | `DISTANCE_UNIT_IMPERIAL` | imperial system | 2.0 | ## Example ```js const distanceUnit = getDistanceUnit() if (distanceUnit === DISTANCE_UNIT_METRIC) { console.log('metric') } ``` --- ## getLanguage ### Import ```js import { getLanguage } from '@zos/settings' ``` ### Typings - Description: Get the current system language setting - Example: ```js import { getLanguage } from '@zos/settings' const languageCode = getLanguage() console.log(languageCode) ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Get the current system language setting. ## Type ```ts function getLanguage(): Result ``` ## Parameters ### Result | Type | Description | | ------------------- | ---------------------------------------------------- | | `number` | Please see the Multilingual Mapping for more details | ## Example ```js const languageCode = getLanguage() console.log(languageCode) ``` --- ## getSleepTarget ### Import ```js import { getSleepTarget } from '@zos/settings' ``` ### Typings - Description: Get the sleep target set by the user - Example: ```js import { getSleepTarget } from '@zos/settings' const sleepTarget = getSleepTarget() console.log(sleepTarget) ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Get the sleep target set by the user. ## Type ```ts function getSleepTarget(): Result ``` ## Parameters ### Result | Type | Description | | ------------------- | ------------------------------------------------- | | `number` | User-set sleep target, default is `0`, in minutes | ## Example ```js const sleepTarget = getSleepTarget() console.log(sleepTarget) ``` --- ## getSystemInfo ### Import ```js import { getSystemInfo } from '@zos/settings' ``` ### Typings - Description: Get system related information - API_LEVEL: 2.1 - Example: ```js import { getSystemInfo } from '@zos/settings' const { minAPI } = getSystemInfo() console.log(minAPI) ``` > Start from API_LEVEL `2.1` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Get system related information. ## Type ```ts function getSystemInfo(): Result ``` ## Parameters ### Result | Property | Type | Description | API_LEVEL | | --------------- | ------------------- | ----------------------- | --------- | | osVersion | `string` | Zepp OS System Version | 2.1 | | firmwareVersion | `string` | Device firmware version | 2.1 | | minAPI | `string` | API_LEVEL | 2.1 | ## Example ```js const { minAPI } = getSystemInfo() console.log(minAPI) ``` --- ## getSystemMode ### Import ```js import { getSystemMode } from '@zos/settings' ``` ### Typings - Description: Get the system mode setting information - API_LEVEL: 3.0 - Example: ```js import { getSystemMode } from '@zos/settings' const mode = getSystemMode() console.log(mode) ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Get the system mode setting information. ## Type ```ts function getSystemMode(): Result ``` ## Parameters ### Result | Property | Type | Description | API_LEVEL | | ---------------- | -------------------- | ----------------------------- | --------- | | DND | `boolean` | State of Do Not Disturb Mode | 3.0 | | sleep | `boolean` | State of Sleep Mode | 3.0 | | theater | `boolean` | State of Sleep Mode | 3.0 | | systemLock | `boolean` | State of Screen Lock Mode | 3.0 | | lowTemperature | `boolean` | State of Low Temperature Mode | 3.0 | | powerSaving | `boolean` | State of Power Saving Mode | 3.0 | | ultraPowerSaving | `boolean` | State of Clock Mode | 3.0 | | button | `boolean` | State of Button Mode | 3.0 | | accessibleSwitch | `boolean` | State of Accessible | 3.0 | ## Example ```js const mode = getSystemMode() console.log(mode) ``` --- ## getTemperatureUnit ### Import ```js import { getTemperatureUnit, TEMPERATURE_UNIT_CENTIGRADE } from '@zos/settings' ``` ### Typings - Description: Get the temperature units set by the user - API_LEVEL: 2.1 - Constants: `temperatureUnit` - Example: ```js import { getTemperatureUnit, TEMPERATURE_UNIT_CENTIGRADE } from '@zos/settings' const temperatureUnit = getTemperatureUnit() if (temperatureUnit === TEMPERATURE_UNIT_CENTIGRADE) { console.log('centigrade') } ``` > Start from API_LEVEL `2.1` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Get the temperature units set by the user. ## Type ```ts function getTemperatureUnit(): Result ``` ## Parameters ### Result | Type | Description | | ------------------- | ------------------------------------------------------------- | | `number` | Temperature units, value reference temperature unit constants | ## Constants ### Temperature unit constants | Constant | Description | API_LEVEL | | ----------------------------- | ---------------------- | --------- | | `TEMPERATURE_UNIT_CENTIGRADE` | Celsius temperature | 2.0 | | `TEMPERATURE_UNIT_FAHRENHEIT` | Fahrenheit temperature | 2.0 | ## Example ```js const temperatureUnit = getTemperatureUnit() if (temperatureUnit === TEMPERATURE_UNIT_CENTIGRADE) { console.log('centigrade') } ``` --- ## getTimeFormat ### Import ```js import { getTimeFormat, TIME_FORMAT_24 } from '@zos/settings' ``` ### Typings - Description: Get the current system time format, 12-hour format or 24-hour format - API_LEVEL: 2.1 - Constants: `hourFormat` - Example: ```js import { getTimeFormat, TIME_FORMAT_24 } from '@zos/settings' const timeFormat = getTimeFormat() if (timeFormat === TIME_FORMAT_24) { console.log('time format is 24-hour format') } ``` > Start from API_LEVEL `2.1` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Get the current system time format, 12-hour format or 24-hour format. ## Type ```ts function getTimeFormat(): Result ``` ## Parameters ### Result | Type | Description | | ------------------- | ------------------------------------------------- | | `number` | Hour format, value refer to hour format constants | ## Constants ### Hour format constants | Constant | Description | API_LEVEL | | ---------------- | -------------- | --------- | | `TIME_FORMAT_12` | 12-hour format | 2.1 | | `TIME_FORMAT_24` | 24-hour format | 2.1 | ## Example ```js const timeFormat = getTimeFormat() if (timeFormat === TIME_FORMAT_24) { console.log('time format is 24-hour format') } ``` --- ## getWeightTarget ### Import ```js import { getWeightTarget } from '@zos/settings' ``` ### Typings - Description: Get the weight target set by the user - Example: ```js import { getWeightTarget } from '@zos/settings' const weightTarget = getWeightTarget() console.log(weightTarget) ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Get the weight target set by the user. ## Type ```ts function getWeightTarget(): Result ``` ## Parameters ### Result | Type | Description | | ------------------- | -------------------------------------- | | `number` | User-set weight target, default is `0` | ## Example ```js const weightTarget = getWeightTarget() console.log(weightTarget) ``` --- ## getWeightUnit ### Import ```js import { getWeightUnit, WEIGHT_UNIT_KILOGRAM } from '@zos/settings' ``` ### Typings - Description: Gets the weight unit set by the user - Constants: `weightUnit` - Example: ```js import { getWeightUnit, WEIGHT_UNIT_KILOGRAM } from '@zos/settings' const weightUnit = getWeightUnit() if (weightUnit === WEIGHT_UNIT_KILOGRAM) { console.log('Kilogram') } ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Gets the weight unit set by the user. ## Type ```ts function getWeightUnit(): Result ``` ## Parameters ### Result | Type | Description | | ------------------- | -------------------------------------------------- | | `number` | Weight units, value refer to weight unit constants | ## Constants ### Weight unit constants | Constant | Description | API_LEVEL | | ---------------------- | ----------- | --------- | | `WEIGHT_UNIT_KILOGRAM` | Kilogram | 2.0 | | `WEIGHT_UNIT_JIN` | Jin | 2.0 | | `WEIGHT_UNIT_POUND` | Pound | 2.0 | | `WEIGHT_UNIT_STONE` | Stone | 2.0 | ## Example ```js const weightUnit = getWeightUnit() if (weightUnit === WEIGHT_UNIT_KILOGRAM) { console.log('Kilogram') } ``` --- --- # @zos/share-storage ## FileSystem ### Import ```js import { writeFileSync } from '@zos/fs' ``` ### Typings - Description: Read-only file system across applications. Application B uses application A's appId to inspect, open and read a known file path from application A; this class does not provide write operations - API_LEVEL: 3.0 - Example: ```js // ==================== Application A (data provider) ==================== import { writeFileSync } from '@zos/fs' const path = 'shared.json' writeFileSync({ path, data: JSON.stringify({ theme: 'dark' }), options: { encoding: 'utf8' }, }) // ==================== Application B (data consumer) ==================== import { FileSystem } from '@zos/share-storage' const fs = new FileSystem(100001) // 100001 is application A's appId const stat = fs.statSync({ path }) if (stat && stat.isFile) { const fd = fs.openSync({ path }) const buffer = new ArrayBuffer(stat.size) fs.readSync({ fd, buffer }) fs.closeSync(fd) } const content = fs.readFileSync({ path, options: { encoding: 'utf8' }, }) ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Read-only file system across applications. Application B uses application A's appId to inspect, open and read a known file path from application A; this class does not provide write operations. ## Constructor Create a read-only file system instance for the target application. ```ts constructor(appId: number) ``` ## Methods ### openSync Open a file in read-only mode ```ts openSync(options: { path: string }): number ``` ### closeSync Close a file descriptor ```ts closeSync(fd: number): number ``` ### statSync Get file information, or undefined when the file does not exist ```ts statSync(options: { path: string }): { size: number; mtimeMs: number; isDir: boolean; isFile: boolean } | undefined ``` ### readSync Read file content into a buffer ```ts readSync(options: { fd: number buffer: ArrayBuffer options?: { offset?: number; length?: number; position?: number } }): number ``` ### readFileSync Read an entire file. Returns a string when encoding is specified, otherwise an ArrayBuffer. ```ts readFileSync(options: { path: string options?: { encoding?: string } }): string | ArrayBuffer ``` ## Example ```js // ==================== Application A (data provider) ==================== const path = 'shared.json' writeFileSync({ path, data: JSON.stringify({ theme: 'dark' }), options: { encoding: 'utf8' }, }) // ==================== Application B (data consumer) ==================== const fs = new FileSystem(100001) // 100001 is application A's appId const stat = fs.statSync({ path }) if (stat && stat.isFile) { const fd = fs.openSync({ path }) const buffer = new ArrayBuffer(stat.size) fs.readSync({ fd, buffer }) fs.closeSync(fd) } const content = fs.readFileSync({ path, options: { encoding: 'utf8' }, }) ``` --- ## LocalStorage ### Import ```js import { ShareLocalStorage } from '@zos/storage' ``` ### Typings - Description: Read-only JSON key-value storage across applications. Application A publishes data with `ShareLocalStorage` from `@zos/storage`, and application B reads it with application A's appId. When using a custom storagePath, both applications must use the same path - API_LEVEL: 3.0 - Example: ```js // ==================== Application A (data provider) ==================== import { ShareLocalStorage } from '@zos/storage' const sharedStorage = new ShareLocalStorage('shared-settings.json') sharedStorage.setItem('profile', { name: 'Zepp', theme: 'dark' }) sharedStorage.setItem('lastUpdatedAt', Date.now()) const profile = sharedStorage.getItem('profile', { name: '', theme: 'light' }) sharedStorage.removeItem('legacy-profile') // Clear all shared data when it is no longer needed. // sharedStorage.clear() // ==================== Application B (data consumer) ==================== import { LocalStorage } from '@zos/share-storage' const storage = new LocalStorage(100001, 'shared-settings.json') // 100001 is application A's appId if (storage.isExisted()) { const profile = storage.getItem('profile', { name: '', theme: 'light' }) const lastUpdatedAt = storage.getItem('lastUpdatedAt', 0) } ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Read-only JSON key-value storage across applications. Application A publishes data with `ShareLocalStorage` from `@zos/storage`, and application B reads it with application A's appId. When using a custom storagePath, both applications must use the same path. ## Constructor Create a read-only shared local storage instance for the target application. ```ts constructor(appId: number, storagePath?: string) ``` ## Methods ### getItem Get a value, or return the default value when not found ```ts getItem(key: string, defaultValue?: T): T | undefined ``` ### isExisted Check whether the target shared storage file exists ```ts isExisted(): boolean ``` ## Example ```js // ==================== Application A (data provider) ==================== const sharedStorage = new ShareLocalStorage('shared-settings.json') sharedStorage.setItem('profile', { name: 'Zepp', theme: 'dark' }) sharedStorage.setItem('lastUpdatedAt', Date.now()) const profile = sharedStorage.getItem('profile', { name: '', theme: 'light' }) sharedStorage.removeItem('legacy-profile') // Clear all shared data when it is no longer needed. // sharedStorage.clear() // ==================== Application B (data consumer) ==================== const storage = new LocalStorage(100001, 'shared-settings.json') // 100001 is application A's appId if (storage.isExisted()) { const profile = storage.getItem('profile', { name: '', theme: 'light' }) const lastUpdatedAt = storage.getItem('lastUpdatedAt', 0) } ``` --- ## TypedStorage ### Import ```js import { ShareTypedStorage } from '@zos/storage' ``` ### Typings - Description: Read-only typed key-value storage across applications. Application A publishes system properties with `ShareTypedStorage` from `@zos/storage`, and application B reads them with application A's appId. When using a custom scope, both applications must use the same scope - API_LEVEL: 3.0 - Example: ```js // ==================== Application A (data provider) ==================== import { ShareTypedStorage } from '@zos/storage' const sharedStorage = new ShareTypedStorage('watchface-data') sharedStorage.putBool('enabled', true) sharedStorage.putInt('steps', 6000) sharedStorage.putInt64('lastUpdatedAt', Date.now()) sharedStorage.putDouble('progress', 0.75) sharedStorage.putString('theme', 'dark') if (sharedStorage.has('legacy-theme')) { sharedStorage.remove('legacy-theme') } // Clear all shared typed data when it is no longer needed. // sharedStorage.clear() // ==================== Application B (data consumer) ==================== import { TypedStorage } from '@zos/share-storage' const storage = new TypedStorage(100001, 'watchface-data') // 100001 is application A's appId const enabled = storage.getBool('enabled', false) const steps = storage.getInt('steps', 0) const lastUpdatedAt = storage.getInt64('lastUpdatedAt', 0) const progress = storage.getDouble('progress', 0) const theme = storage.getString('theme', 'light') ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Read-only typed key-value storage across applications. Application A publishes system properties with `ShareTypedStorage` from `@zos/storage`, and application B reads them with application A's appId. When using a custom scope, both applications must use the same scope. ## Constructor Create a read-only typed storage instance for the target application. The scope identifies a key group. When omitted, it reads the framework default shared group; a custom scope must match the publisher. ```ts constructor(appId: number, scope?: string) ``` ## Methods ### getBool Get a boolean value from the target application ```ts getBool(key: string, defaultValue: boolean): boolean ``` ### getInt Get an integer value from the target application ```ts getInt(key: string, defaultValue: number): number ``` ### getInt64 Get a 64-bit integer value from the target application ```ts getInt64(key: string, defaultValue: number): number ``` ### getDouble Get a double value from the target application ```ts getDouble(key: string, defaultValue: number): number ``` ### getString Get a string value from the target application ```ts getString(key: string, defaultValue: string): string ``` ## Example ```js // ==================== Application A (data provider) ==================== const sharedStorage = new ShareTypedStorage('watchface-data') sharedStorage.putBool('enabled', true) sharedStorage.putInt('steps', 6000) sharedStorage.putInt64('lastUpdatedAt', Date.now()) sharedStorage.putDouble('progress', 0.75) sharedStorage.putString('theme', 'dark') if (sharedStorage.has('legacy-theme')) { sharedStorage.remove('legacy-theme') } // Clear all shared typed data when it is no longer needed. // sharedStorage.clear() // ==================== Application B (data consumer) ==================== const storage = new TypedStorage(100001, 'watchface-data') // 100001 is application A's appId const enabled = storage.getBool('enabled', false) const steps = storage.getInt('steps', 0) const lastUpdatedAt = storage.getInt64('lastUpdatedAt', 0) const progress = storage.getDouble('progress', 0) const theme = storage.getString('theme', 'light') ``` --- --- # @zos/storage ## Constants | Constant | Description | API_LEVEL | |----------|-------------|-----------| | `DEFAULT_FILE_PATH` | Default local storage file path | — | | `DEFAULT_SHARE_FILE_PATH` | Default shared local storage file path | — | ## ShareLocalStorage ### Import ```js import { ShareLocalStorage } from '@zos/storage' ``` ### Typings - Description: Shared JSON key-value storage for cross-application scenarios. Application A publishes data with this class, and application B reads it with `LocalStorage` from `@zos/share-storage` and application A's appId. When using a custom storagePath, both applications must use the same path - API_LEVEL: 3.0 - Permission: `device:os.local_storage` - Example: ```js // ==================== Application A (data provider) ==================== import { ShareLocalStorage } from '@zos/storage' const sharedStorage = new ShareLocalStorage('shared-settings.json') sharedStorage.setItem('profile', { name: 'Zepp', theme: 'dark' }) sharedStorage.setItem('lastUpdatedAt', Date.now()) const profile = sharedStorage.getItem('profile', { name: '', theme: 'light' }) sharedStorage.removeItem('legacy-profile') // Clear all shared data when it is no longer needed. // sharedStorage.clear() // ==================== Application B (data consumer) ==================== // This section runs in application B. Use application A's appId and the same storagePath. import { LocalStorage } from '@zos/share-storage' const storage = new LocalStorage(appIdOfApplicationA, 'shared-settings.json') if (storage.isExisted()) { const profile = storage.getItem('profile', { name: '', theme: 'light' }) const lastUpdatedAt = storage.getItem('lastUpdatedAt', 0) } ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Shared JSON key-value storage for cross-application scenarios. Application A publishes data with this class, and application B reads it with `LocalStorage` from `@zos/share-storage` and application A's appId. When using a custom storagePath, both applications must use the same path. > **ℹ️ Info** > > permission code: `device:os.local_storage` ## Constructor Create a shared local storage instance. Uses the shared storage file by default, or a custom file path. ```ts constructor(storagePath?: string) ``` ## Methods ### setItem Set a value ```ts setItem(key: string, value: any): void ``` ### getItem Get a value, or return the default value when not found ```ts getItem(key: string, defaultValue?: T): T | undefined ``` ### removeItem Delete a value by key ```ts removeItem(key: string): boolean ``` ### clear Clear all shared storage data ```ts clear(): void ``` ## Example ```js // ==================== Application A (data provider) ==================== const sharedStorage = new ShareLocalStorage('shared-settings.json') sharedStorage.setItem('profile', { name: 'Zepp', theme: 'dark' }) sharedStorage.setItem('lastUpdatedAt', Date.now()) const profile = sharedStorage.getItem('profile', { name: '', theme: 'light' }) sharedStorage.removeItem('legacy-profile') // Clear all shared data when it is no longer needed. // sharedStorage.clear() // ==================== Application B (data consumer) ==================== // This section runs in application B. Use application A's appId and the same storagePath. const storage = new LocalStorage(appIdOfApplicationA, 'shared-settings.json') if (storage.isExisted()) { const profile = storage.getItem('profile', { name: '', theme: 'light' }) const lastUpdatedAt = storage.getItem('lastUpdatedAt', 0) } ``` --- ## ShareTypedStorage ### Import ```js import { ShareTypedStorage } from '@zos/storage' ``` ### Typings - Description: Shared typed key-value storage for cross-application scenarios. Application A publishes system properties with this class, and application B reads them with `TypedStorage` from `@zos/share-storage` and application A's appId. When using a custom scope, both applications must use the same scope - API_LEVEL: 3.0 - Example: ```js // ==================== Application A (data provider) ==================== import { ShareTypedStorage } from '@zos/storage' const sharedStorage = new ShareTypedStorage('watchface-data') sharedStorage.putBool('enabled', true) sharedStorage.putInt('steps', 6000) sharedStorage.putInt64('lastUpdatedAt', Date.now()) sharedStorage.putDouble('progress', 0.75) sharedStorage.putString('theme', 'dark') if (sharedStorage.has('legacy-theme')) { sharedStorage.remove('legacy-theme') } // Clear all shared typed data when it is no longer needed. // sharedStorage.clear() // ==================== Application B (data consumer) ==================== // This section runs in application B. Use application A's appId and the same scope. import { TypedStorage } from '@zos/share-storage' const storage = new TypedStorage(appIdOfApplicationA, 'watchface-data') const enabled = storage.getBool('enabled', false) const steps = storage.getInt('steps', 0) const lastUpdatedAt = storage.getInt64('lastUpdatedAt', 0) const progress = storage.getDouble('progress', 0) const theme = storage.getString('theme', 'light') ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Shared typed key-value storage for cross-application scenarios. Application A publishes system properties with this class, and application B reads them with `TypedStorage` from `@zos/share-storage` and application A's appId. When using a custom scope, both applications must use the same scope. ## Constructor Create a shared typed storage instance. The scope groups keys. When omitted, the framework default shared group is used; when customized, readers must use the same value. ```ts constructor(scope?: string) ``` ## Methods ### getBool Get a boolean value ```ts getBool(key: string, defaultValue: boolean): boolean ``` ### getInt Get an integer value ```ts getInt(key: string, defaultValue: number): number ``` ### getInt64 Get a 64-bit integer value ```ts getInt64(key: string, defaultValue: number): number ``` ### getDouble Get a double value ```ts getDouble(key: string, defaultValue: number): number ``` ### getString Get a string value ```ts getString(key: string, defaultValue: string): string ``` ### putBool Set a boolean value ```ts putBool(key: string, value: boolean): number ``` ### putInt Set an integer value ```ts putInt(key: string, value: number): number ``` ### putInt64 Set a 64-bit integer value ```ts putInt64(key: string, value: number): number ``` ### putDouble Set a double value ```ts putDouble(key: string, value: number): number ``` ### putString Set a string value ```ts putString(key: string, value: string): number ``` ### has Check whether a key exists ```ts has(key: string): boolean ``` ### clear Clear all shared typed storage data ```ts clear(): void ``` ### remove Delete a value by key ```ts remove(key: string): boolean ``` ## Example ```js // ==================== Application A (data provider) ==================== const sharedStorage = new ShareTypedStorage('watchface-data') sharedStorage.putBool('enabled', true) sharedStorage.putInt('steps', 6000) sharedStorage.putInt64('lastUpdatedAt', Date.now()) sharedStorage.putDouble('progress', 0.75) sharedStorage.putString('theme', 'dark') if (sharedStorage.has('legacy-theme')) { sharedStorage.remove('legacy-theme') } // Clear all shared typed data when it is no longer needed. // sharedStorage.clear() // ==================== Application B (data consumer) ==================== // This section runs in application B. Use application A's appId and the same scope. const storage = new TypedStorage(appIdOfApplicationA, 'watchface-data') const enabled = storage.getBool('enabled', false) const steps = storage.getInt('steps', 0) const lastUpdatedAt = storage.getInt64('lastUpdatedAt', 0) const progress = storage.getDouble('progress', 0) const theme = storage.getString('theme', 'light') ``` --- ## TypedStorage ### Import ```js import { TypedStorage } from '@zos/storage' ``` ### Typings - Description: Typed key-value storage backed by system properties. Suitable for primitive values such as booleans, numbers and strings. - API_LEVEL: 3.0 - Example: ```js import { TypedStorage } from '@zos/storage' const storage = new TypedStorage() storage.putBool('enabled', true) storage.putInt('count', 1) const enabled = storage.getBool('enabled', false) const count = storage.getInt('count', 0) ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Typed key-value storage backed by system properties. Suitable for primitive values such as booleans, numbers and strings.. ## Constructor Create a typed storage instance. The optional scope isolates key names. ```ts constructor(scope?: string) ``` ## Methods ### getBool Get a boolean value ```ts getBool(key: string, defaultValue: boolean): boolean ``` ### getInt Get an integer value ```ts getInt(key: string, defaultValue: number): number ``` ### getInt64 Get a 64-bit integer value ```ts getInt64(key: string, defaultValue: number): number ``` ### getDouble Get a double value ```ts getDouble(key: string, defaultValue: number): number ``` ### getString Get a string value ```ts getString(key: string, defaultValue: string): string ``` ### putBool Set a boolean value ```ts putBool(key: string, value: boolean): number ``` ### putInt Set an integer value ```ts putInt(key: string, value: number): number ``` ### putInt64 Set a 64-bit integer value ```ts putInt64(key: string, value: number): number ``` ### putDouble Set a double value ```ts putDouble(key: string, value: number): number ``` ### putString Set a string value ```ts putString(key: string, value: string): number ``` ### has Check whether a key exists ```ts has(key: string): boolean ``` ### clear Clear all typed storage data ```ts clear(): void ``` ### remove Delete a value by key ```ts remove(key: string): boolean ``` ## Example ```js const storage = new TypedStorage() storage.putBool('enabled', true) storage.putInt('count', 1) const enabled = storage.getBool('enabled', false) const count = storage.getInt('count', 0) ``` --- ## localStorage ### Import ```js import { localStorage } from '@zos/storage' ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Locally stored key-value pairs, data cleared after Mini Program uninstallation. > **ℹ️ Info** > > permission code: `device:os.local_storage` ## Methods ### setItem Save data ```ts setItem(key: string, value: any): void ``` ### getItem Read the data, specify the default value `defaultValue`, and return `defaultValue` if the value on the specified `key` is not retrieved. ```ts getItem(key: string, defaultValue?: T): T | undefined ``` ### removeItem Delete the data of the specified `key` ```ts removeItem(key: string): boolean ``` ### clear Clear all data in localStorage ```ts clear(): void ``` ## Example ```js localStorage.setItem('test', 'test value') const val = localStorage.getItem('test') const defaultValue = localStorage.getItem('none_key', 'defaultValue') localStorage.removeItem('test') localStorage.clear() ``` --- ## LocalStorage ### Import ```js import { LocalStorage } from '@zos/storage' ``` ### Typings - Description: Locally stored key-value pairs, data cleared after Mini Program uninstallation. An instance keeps loaded data in memory, making it suitable for repeated reads and writes by reducing repeated file reads - API_LEVEL: 3.0 - Permission: `device:os.local_storage` - Example: ```js import { LocalStorage } from '@zos/storage' const localStorage = new LocalStorage() localStorage.setItem('test', 'test value') const val = localStorage.getItem('test') const defaultValue = localStorage.getItem('none_key', 'defaultValue') localStorage.removeItem('test') localStorage.clear() ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Locally stored key-value pairs, data cleared after Mini Program uninstallation. An instance keeps loaded data in memory, making it suitable for repeated reads and writes by reducing repeated file reads. > **ℹ️ Info** > > permission code: `device:os.local_storage` ## Constructor Create a local storage instance. Uses the Mini Program local storage file by default, or a custom file path. ```ts constructor(storagePath?: string) ``` ## Methods ### setItem Save data ```ts setItem(key: string, value: any): void ``` ### getItem Read the data, specify the default value `defaultValue`, and return `defaultValue` if the value on the specified `key` is not retrieved. ```ts getItem(key: string, defaultValue?: T): T | undefined ``` ### removeItem Delete the data of the specified `key` ```ts removeItem(key: string): boolean ``` ### clear Clear all data in localStorage ```ts clear(): void ``` ## Example ```js const localStorage = new LocalStorage() localStorage.setItem('test', 'test value') const val = localStorage.getItem('test') const defaultValue = localStorage.getItem('none_key', 'defaultValue') localStorage.removeItem('test') localStorage.clear() ``` --- ## sessionStorage ### Import ```js import { sessionStorage } from '@zos/storage' ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Key-value pairs are stored and data is cleared after exiting the Mini Program. ## Methods ### setItem Save data ```ts setItem(key: string, value: any): void ``` ### getItem Read the data, specify the default value `defaultValue`, and return `defaultValue` if the value on the specified `key` is not retrieved. ```ts getItem(key: string, defaultValue?: T): T | undefined ``` ### removeItem Delete the data of the specified `key` ```ts removeItem(key: string): boolean ``` ### clear Clear all data in sessionStorage ```ts clear(): void ``` ## Example ```js sessionStorage.setItem('test', 'test value') const val = sessionStorage.getItem('test') const defaultValue = sessionStorage.getItem('none_key', 'defaultValue') sessionStorage.removeItem('test') sessionStorage.clear() ``` --- ## SessionStorage ### Import ```js import { SessionStorage } from '@zos/storage' ``` ### Typings - Description: Key-value pairs are stored and data is cleared after exiting the Mini Program. Each instance has independent temporary in-memory storage, suitable for isolated session data - Example: ```js import { SessionStorage } from '@zos/storage' const sessionStorage = new SessionStorage() sessionStorage.setItem('test', 'test value') const val = sessionStorage.getItem('test') const defaultValue = sessionStorage.getItem('none_key', 'defaultValue') sessionStorage.removeItem('test') sessionStorage.clear() ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Key-value pairs are stored and data is cleared after exiting the Mini Program. Each instance has independent temporary in-memory storage, suitable for isolated session data. ## Methods ### setItem Save data ```ts setItem(key: string, value: any): void ``` ### getItem Read the data, specify the default value `defaultValue`, and return `defaultValue` if the value on the specified `key` is not retrieved. ```ts getItem(key: string, defaultValue?: T): T | undefined ``` ### removeItem Delete the data of the specified `key` ```ts removeItem(key: string): boolean ``` ### clear Clear all data in sessionStorage ```ts clear(): void ``` ## Example ```js const sessionStorage = new SessionStorage() sessionStorage.setItem('test', 'test value') const val = sessionStorage.getItem('test') const defaultValue = sessionStorage.getItem('none_key', 'defaultValue') sessionStorage.removeItem('test') sessionStorage.clear() ``` --- --- # @zos/timer ## createSysTimer ### Import ```js import { createSysTimer } from '@zos/timer' ``` ### Typings - Description: A system-level timer that can be registered in device app services and runs regardless of watch screen state - API_LEVEL: 4.0 - Example: ```js import { createSysTimer } from '@zos/timer' // Create a non-periodic timer that executes after 5 seconds const timerId = createSysTimer(false, 5000, (param) => { console.log('timer callback with param:', param) }, 'customParam') // Create a periodic timer that executes every 10 seconds const intervalId = createSysTimer(true, 10000, () => { console.log('interval timer callback') }) ``` > Start from API_LEVEL `4.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). A system-level timer that can be registered in device app services and runs regardless of watch screen state. ## Type ```ts function createSysTimer(periodic: Periodic, period: Period, callback: Callback, arg?: Arg): Result ``` ## Parameters ### Periodic | Type | Description | | -------------------- | ---------------------------------- | | `boolean` | Whether to create a periodic timer | ### Period | Type | Description | | ------------------- | ----------------------------------------------------------------------------------------------------- | | `number` | Timer period (ms). For non-periodic timers, it represents delay duration, 0 means immediate execution | ### Callback | Type | Description | | ---------------------------------------- | ----------------- | | `(arg?: unknown) => void` | Callback function | ### Arg | Type | Description | | -------------------- | ----------------------------------------- | | `unknown` | Parameter passed to the callback function | ### Result | Type | Description | | ------------------- | ------------------------------------------------------------------------ | | `number` | The ID returned by creating a system timer, used to stop the timer later | ## Example ```js // Create a non-periodic timer that executes after 5 seconds const timerId = createSysTimer( false, 5000, (param) => { console.log('timer callback with param:', param) }, 'customParam', ) // Create a periodic timer that executes every 10 seconds const intervalId = createSysTimer(true, 10000, () => { console.log('interval timer callback') }) ``` --- ## stopTimer ### Import ```js import { createSysTimer, stopTimer } from '@zos/timer' ``` ### Typings - Description: Stop the timer created by `createSysTimer` method - API_LEVEL: 4.0 - Example: ```js import { createSysTimer, stopTimer } from '@zos/timer' // Create a periodic timer that executes every 10 seconds const timerId = createSysTimer(true, 10000, () => { console.log('Execute every 10 seconds') }) // Stop the timer after 5 seconds createSysTimer(false, 5000, () => { stopTimer(timerId) console.log('Timer stopped') }) ``` > Start from API_LEVEL `4.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Stop the timer created by `createSysTimer` method. ## Type ```ts function stopTimer(timerId: TimerId): void ``` ## Parameters ### TimerId | Type | Description | | ------------------- | ----------------------------------------------------------- | | `number` | Timer ID to be stopped, returned by `createSysTimer` method | ## Example ```js // Create a periodic timer that executes every 10 seconds const timerId = createSysTimer(true, 10000, () => { console.log('Execute every 10 seconds') }) // Stop the timer after 5 seconds createSysTimer(false, 5000, () => { stopTimer(timerId) console.log('Timer stopped') }) ``` --- --- # @zos/transfer-file ## TransferFile ### Import ```js import TransferFile from "@zos/ble/TransferFile" ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). File Transfer. ## Methods ### getInbox Get the receiving file object ```ts getInbox(): Inbox ``` #### Inbox | Property | Type | Description | API_LEVEL | | ----------- | ------------------------------------------------------------------------------ | ------------------------------------------------------ | --------- | | getNextFile | `() => FileObject` | Return `FileObject` to receive the file object | 3.0 | | on | `(eventName: InboxEventName, callback: () => void) => void` | Listening event, event name reference `InboxEventName` | 3.0 | #### FileObject | Property | Type | Description | API_LEVEL | | ---------- | --------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | --------- | | sessionId | `number` | Session identifier for transferring files | 3.0 | | fileName | `string` | File name | 3.0 | | filePath | `string` | File path | 3.0 | | params | `object` | User passed parameters | 3.0 | | fileSize | `number` | File size | 3.0 | | readyState | `ReceiveFileState` | For the status value of the received file, see 'ReceiveFileState' | 3.0 | | cancel | `() => void` | Cancel a file transfer task | 3.0 | | on | `(eventName: FileEventName, callback: ChangeCallback|ProgressCallback) => void` | Listen to the file transfer task event, event name reference `FileEventName` | 3.0 | #### InboxEventName | Value | Type | Description | API_LEVEL | | ------- | ------------------- | ------------------------------------------- | --------- | | NEWFILE | `string` | The event that just received the file | 3.0 | | FILE | `string` | The event that completed receiving the file | 3.0 | #### ReceiveFileState | Value | Type | Description | API_LEVEL | | ------------ | ------------------- | ------------ | --------- | | pending | `string` | Pending | 3.0 | | transferring | `string` | Transferring | 3.0 | | transferred | `string` | Transferred | 3.0 | | error | `string` | Error | 3.0 | | canceled | `string` | Canceled | 3.0 | #### FileEventName | Value | Type | Description | API_LEVEL | | -------- | ------------------- | ------------------------------------------------------------------------------------------------------------------- | --------- | | change | `string` | The event name that occurs when `readyState` changes state, corresponding to the `ChangeCallback` callback function | 3.0 | | progress | `string` | The event name when the file transfer progress changes, corresponding to the `ProgressCallback` callback function | 3.0 | #### ChangeCallback | Type | Description | | --------------------------------------------- | -------------------------------------------------------- | | `(event: ChangeEvent) => void` | The callback that occurs when `readyState` changes state | #### ChangeEvent | Property | Type | Description | API_LEVEL | | --------- | -------------------------------- | ------------------------------------------------- | --------- | | type | `'readyStateChanged'` | Event type, value is ` readyStateChanged` string | 3.0 | | date | `ChangeEventData` | Event data object, see `ChangeEventData` for type | 3.0 | | timestamp | `number` | UTC timestamp of the event, in milliseconds | 3.0 | #### ChangeEventData | Property | Type | Description | API_LEVEL | | ---------- | ------------------- | ------------------------- | --------- | | readyState | `string` | File transfer task status | 3.0 | #### ProgressCallback | Type | Description | | ----------------------------------------------- | ----------------------------------------------------------- | | `(event: ProgressEvent) => void` | Event callback function when file transfer progress changes | #### ProgressEvent | Property | Type | Description | API_LEVEL | | --------- | ------------------------------ | --------------------------------------------------- | --------- | | type | `'progress'` | Event type, value is `progress` string | 3.0 | | date | `ProgressEventData` | Event data object, see `ProgressEventData` for type | 3.0 | | timestamp | `number` | UTC timestamp at the time of the event | 3.0 | #### ProgressEventData | Property | Type | Description | API_LEVEL | | ---------- | ------------------- | ----------------------------------------- | --------- | | fileSize | `number` | File size in bytes | 3.0 | | loadedSize | `number` | The size of the transferred file in bytes | 3.0 | ### getOutbox Get the sending file object ```ts getOutbox(): Outbox ``` #### Outbox | Property | Type | Description | API_LEVEL | | ----------- | --------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | | enqueueFile | `(fileName: string, params?: object) => getInbox.FileObject` | Returns `FileObject`, `fileName` is the path to the file, and `params` is a customized file transfer object, retrieved from `FileObject` on the receiving end. The `getInbox.FileObject` type is referenced above | 3.0 | ## Example ```js // Receiving File const transferFile = new TransferFile() const inbox = transferFile.getInbox() Page({ onInit() { inbox.on('NEWFILE', function() { const fileObject = inbox.getNextFile() fileObject.on('progress', (event) => { console.log("progress total size", event.data.fileSize) console.log("progress total size", event.data.loadedSize) }) fileObject.on('change', (event) => { if (event.data.readyState === 'transferred') { console.log('transfered file success') } else (event.data.readyState === 'error') { console.log('error') } }) }) } }) // Send File const transferFile = new TransferFile() const outbox = transferFile.getOutbox() Page({ onInit() { const fileObject = outbox.enqueueFile("assets://logo.png", { test: 1}) fileObject.on('progress', (event) => { console.log("progress total size", event.data.fileSize) console.log("progress total size", event.data.loadedSize) }) file.on('change', (event) => { if (event.data.readyState === 'transferred') { console.log('transfered file success') } else (event.data.readyState === 'error') { console.log('error') } }) } }) ``` --- --- # @zos/ui-animations Widget animation APIs. ## Widget Animation ### Import ```js import { createWidget, widget, align, text_style, prop, anim_status } from '@zos/ui' ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). [Image: widget_anim] Widget animation can add animation effects to some of the widget's property changes. The above image shows the TEXT widget's `x` and `y` properties changing at the same time, creating a moving animation effect. ## Properties that support animations The properties that support setting animations are | anim_prop | | ---------- | | prop.X | | prop.Y | | prop.W | | prop.H | | prop.ALPHA | ## Individual property animation configuration | Property | Type | Description | | ------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------- | | anim_prop | `number` | To add the properties of the animation, refer to [anim_prop](#properties-that-support-animations) | | anim_from | `number` | The value of the property at the start of the animation | | anim_to | `number` | The value of the property at the end of the animation | | anim_rate | `string` | Animation curve, optional values `linear`, `easein`, `easeout`, `easeinout`, `bounce`, refer to [https://easings.net/](https://easings.net/) | | anim_duration | `number` | Animation duration, in milliseconds | | anim_offset | `number` | The delay before the animation starts, in milliseconds | ## Animation Configuration | Property | Type | Description | API_LEVEL | | ------------------ | -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------- | | anim_steps | `Array` | Attribute animation configuration array, refer to [anim_config](#individual-property-animation-configuration), multiple sets of animations can be performed simultaneously | 2.0 | | anim_fps | `number` | Animation frame rate, default `25` | 2.0 | | anim_auto_start | `number` | If or not the animation plays automatically, default `1`, `0`: don't play automatically; `1`: play automatically | 2.0 | | anim_auto_destroy | `number` | If or not the animation is automatically destroyed, default `1`, `0`: not automatically destroyed; `1`: automatically destroyed | 2.0 | | anim_repeat | `number` | Animation loop, default `0`, `-1`: infinite loop; `0`: play once; or specify the number of times to play directly | 2.0 | | anim_frame_func | `() => void` | Callback function for each frame of animation playback | 2.0 | | anim_complete_func | `() => void` | End of animation callback function | 2.0 | | anim_repeat_func | `() => void` | The animation plays the callback function of each loop, which takes effect when `anim_repeat` is greater than '0' | 3.6 | ## Animation Status anim_status - Use `widget.setProperty` to set the animation play state - Use `widget.getProperty` to get the animation play state | anim_status | Description | | ------------------ | ----------- | | anim_status.START | start | | anim_status.STOP | stop | | anim_status.PAUSE | pause | | anim_status.RESUME | resume | | anim_status.UNKNOW | unknown | ## Code example ```js Page({ build() { const textWidget = createWidget(widget.TEXT, { x: px(96), y: px(120), w: px(288), h: px(46), color: 0xffffff, text_size: px(36), align_h: align.CENTER_H, align_v: align.CENTER_V, text_style: text_style.NONE, text: 'HELLO ZEPPOS' }) const anim_step1 = { anim_rate: 'linear', anim_duration: 2000, anim_from: px(10), anim_to: px(110), anim_prop: prop.X } const anim_step2 = { anim_rate: 'linear', anim_duration: 2000, anim_from: px(120), anim_to: px(300), anim_prop: prop.Y } const animId = textWidget.setProperty(prop.ANIM, { anim_steps: [anim_step1, anim_step2], anim_fps: 25 }) textWidget.setProperty(prop.ANIM_STATUS, { anim_id: animId, anim_status: anim_status.PAUSE }) textWidget.setProperty(prop.ANIM_STATUS, { anim_id: animId, anim_status: anim_status.RESUME }) const currentStatus = textWidget.getProperty(prop.ANIM_STATUS, animId) } }) ``` --- --- # @zos/ui-methods General UI methods, page-level helpers, layout helpers, dialogs, toast, keyboard, and widget lifecycle APIs. ## addEventListener ### Import ```js import { createWidget, widget, event } from '@zos/ui' ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Register a listener to the UI widget and the given callback function will be executed when the specified event is triggered. ## Type ```ts (eventId: EventId, callback: (event: Event) => void) => void ``` ## Parameters | Parameter | Description | Type | | --------- | --------------------------------------------------- | --------- | | eventId | Event type. (e.g., `event.MOVE`, `event.CLICK_DOWN`, etc.) | `EventId` | | event | Event details, refer to different events. | `object` | ### EventId | Value | Description | | ----------------------- | ----------- | | `event.MOVE` | Slide | | `event.CLICK_DOWN` | Press | | `event.CLICK_UP` | Lift up | | `event.MOVE_IN` | Move in | | `event.MOVE_OUT` | Move out | ## Code example ```js const img_bkg = createWidget(widget.IMG) img_bkg.addEventListener(event.CLICK_DOWN, function (info) { //Registering event listeners. console.log(info.x) }) ``` --- ## removeEventListener ### Import ```js import { createWidget, widget, event } from '@zos/ui' ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Remove event listeners registered by the UI widget using the `widget.addEventListener` method. ## Type ```ts (eventId: EventId, callback) => void ``` ## Parameters | Parameter | Description | Type | | --------- | ------------------------------------------ | ---------- | | eventId | Event type (e.g., swipe, press, lift, etc.)| `number` | | callback | The callback function to register. | `function` | ### EventId Refer to the `EventId` of `addEventListener`. ## Code example ```js const img_bkg = createWidget(widget.IMG) const listenerFunc = (info) => { console.log(info.x) } img_bkg.addEventListener(event.CLICK_DOWN, listenerFunc) img_bkg.removeEventListener(event.CLICK_DOWN, listenerFunc) ``` --- ## setProperty ### Import ```js import { createWidget, widget, prop, align } from '@zos/ui' ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Set the properties of the UI widget. ## Type ```ts (propertyId: string, val: any) => void ``` ## Parameters | Parameter | Description | Type | | ---------- | --------------------------------------------------------------------------------------------------------------------------------------- | ------------ | | propertyId | The property of ID. | `PropertyId` | | val | Set the value. (when property is `prop.MORE`, val is used in the same way as createWidget's option, which can set multiple parameters.) | `any` | ### PropertyId List the properties commonly supported by the widgets. | Properties | Description | Type | | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------- | | x | The x-axis coordinate of the widget. | `number` | | y | The y-axis coordinate of the widget. | `number` | | w | The width of the widget. | `number` | | h | The height of the widget. | `number` | | VISIBLE | Whether the widget is visible or not, `true` is visible, `false` is not, this property does not support `setProperty(prop.MORE, {})`, only `setProperty` sets the `VISIBLE` property alone | `boolean` | | DATASET | Developer-defined properties of the widget, obtained via `widget.getProperty(prop.DATASET)` | `any` | ## Code example ```js const button = createWidget(widget.BUTTON, Param) button.setProperty(prop.VISIBLE, false) const text = createWidget(widget.TEXT, Param) text.setProperty(prop.MORE, { x: 0, y: 0, w: 200, h: 200, text: 'hello', color: 0x34e073, align_h: align.LEFT }) text.setProperty(prop.DATASET, { name: 'text1' }) const dataset = text.getProperty(prop.DATASET) ``` --- ## getProperty ### Import ```js import { createWidget, widget, prop } from '@zos/ui' ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Get the UI widget properties, use `widget.getProperty(prop.MORE, {})` to get all the properties of the widget. ## Type ```ts (key: any) => result ``` ## Parameters | Parameter | Description | Type | | --------- | ---------------------- | ----- | | key | The value of property. | `any` | ## Code example ```js const img_bkg = createWidget(widget.IMG) const img_prop = img_bkg.getProperty(prop.MORE, {}) const { angle, w, h } = img_prop const imgHeight = img_bkg.getProperty(prop.H) ``` > **⚠️ Caution** > > At this stage, some widgets do not support property acquisition, it is recommended to try to get first, if you can not get the value, you can refer to the following code snippet, manually maintain a variable in the current page to record the corresponding property changes ```js Page({ state: { buttonY: 0 }, build() { this.state.buttonY = 300 createWidget(widget.BUTTON, { y: this.state.buttonY, // ... }) showToast({ text: this.state.buttonY }) } }) ``` --- ## getType > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Get the UI widget type. ## Type ```ts () => result ``` ## Parameters ### result | Description | Type | | ---------------------- | -------- | | The type of UI widget. Refer to `WIDGET_ID` in `createWidget`. | `number` | --- ## getId > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Get the unique ID of the widget. ## Type ```ts () => result ``` ## Parameters ### result | Description | Type | | ----------- | -------- | | unique ID | `number` | --- ## setAlpha ### Import ```js import { createWidget, widget, text_style, align } from '@zos/ui' ``` > Start from API_LEVEL `2.1` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Set the opacity of the widget. > **ℹ️ Info** > > For widgets that do not support the `alpha` property, use `widget.setAlpha` to set opacity. ## Type ```ts (val: any) => void ``` ### val | Description | Type | | --------------------------------------------- | -------- | | Transparency, 0 - 255, default value is 255 for opaque, 0 for full | `number` | ## Code example ```js const text = createWidget(widget.TEXT, { x: 96, y: 120, w: 288, h: 46, color: 0xffffff, text_size: 36, align_h: align.CENTER_H, align_v: align.CENTER_V, text_style: text_style.NONE, text: 'HELLO ZEPPOS' }) text.setAlpha(80) ``` --- ## gettersetter ### Import ```js import { createWidget, widget, prop } from '@zos/ui' ``` > Supported since API_LEVEL `4.0`. For API compatibility, please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Starting from API_LEVEL 4.0, Zepp OS supports direct access and modification of widget properties through getter/setter features, making property read/write operations more concise and intuitive. ## Overview Before API_LEVEL 4.0, we needed to use `getProperty` and `setProperty` methods to read and set widget properties. Now, we can directly use the `.` operator to access or set these properties, just like accessing regular JavaScript object properties. ## Usage ### Reading Properties (getter) ```js // Old way const textWidth = textWidget.getProperty(prop.W) // New way (API_LEVEL 4.0+) const textWidth = textWidget.w ``` ### Setting Properties (setter) ```js // Old way textWidget.setProperty(prop.TEXT, 'Hello Zepp OS') // New way (API_LEVEL 4.0+) textWidget.text = 'Hello Zepp OS' ``` ## Code Example Here's a complete example demonstrating the getter/setter features using a TEXT widget: ```js Page({ build() { // Create TEXT widget const textWidget = createWidget(widget.TEXT, { x: 96, y: 120, w: 288, h: 46, color: 0xffffff, text: 'Hello Zepp OS', text_size: 36 }) // Using getter to read properties console.log('Text content:', textWidget.text) console.log('Text color:', textWidget.color) console.log('Text position:', textWidget.x, textWidget.y) // Using setter to set properties textWidget.text = 'Updated Text' textWidget.color = 0xff0000 textWidget.x = 120 } }) ``` Comparison with `getProperty` and `setProperty` methods ```js // Reading properties const oldText = textWidget.getProperty(prop.TEXT) console.log('Old way - Text content:', oldText) // Setting properties textWidget.setProperty(prop.TEXT, 'Set by old method') textWidget.setProperty(prop.MORE, { color: 0x00ff00, x: 150 }) ``` ## Property Access Support List Different widgets may support different properties through getter/setter access. Please refer to the property support table in each widget's documentation. Here's an example of the property list supported by the `TEXT` widget: | Property Name | setProperty | setProperty | setter | getter | | ----------- | ----------- | ----------- | ------ | ------ | | x | Y | Y | Y | Y | | y | Y | Y | Y | Y | | w | Y | Y | Y | Y | | h | Y | Y | Y | Y | | color | Y | Y | Y | Y | | align_h | Y | Y | Y | Y | | align_v | Y | Y | Y | Y | | text | Y | Y | Y | Y | | text_size | Y | Y | Y | Y | | font | Y | Y | Y | Y | | text_style | Y | Y | Y | Y | | line_space | Y | Y | Y | Y | | char_space | Y | Y | Y | Y | | text_i18n | N | N | Y | Y | | start_angle | N | N | N | N | | end_angle | N | N | N | N | | mode | N | N | N | N | | radius | N | N | N | N | - Y: Indicates the property access method is supported - N: Indicates the property access method is not supported ## Related References - [createWidget](https://docs.zepp.com/docs/reference/device-app-api/newAPI/ui/createWidget) - [setProperty](https://docs.zepp.com/docs/reference/device-app-api/newAPI/ui/setProperty) - [getProperty](https://docs.zepp.com/docs/reference/device-app-api/newAPI/ui/getProperty) --- ## createWidget ### Import ```js import { createWidget, widget, align, text_style } from '@zos/ui' ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Create UI widgets. ## Type ```ts (widgetId: WIDGET_ID, option?: Option) => widget: WIDGET ``` ## Parameters | Parameter | Description | Required | Type | | --------- | --------------------------------------------------------- | -------- | ---- | | widgetId | The ID of the widget to be created. (Reference WIDGET_ID) | YES | - | | option | Parameters. | NO | - | | widget | The instance of widget. | - | - | ### WIDGET_ID | Value | Description | | --------------- | ----------------------------------------------------------------------- | | `widget.BUTTON` | Button widget ID. | | IMG` | Image widget ID. | | ... | The rest of the values are not listed, refer to the `widget` directory. | ### WIDGET | Description | Type | | ------------- | -------- | | Widget object | `object` | ## Code examples > Reference to a widget example. ```js Page({ build() { const textWidget = createWidget(widget.TEXT, { x: 96, y: 120, w: 288, h: 46, color: 0xffffff, text_size: 36, align_h: align.CENTER_H, align_v: align.CENTER_V, text_style: text_style.NONE, text: 'HELLO ZEPPOS' }) } }) ``` --- ## deleteWidget ### Import ```js import { createWidget, widget, align, text_style, deleteWidget } from '@zos/ui' ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Delete the UI widget. ## Type ```ts (widget: WIDGET) => void ``` ## Parameters ### WIDGET | Description | Type | | -------------------------------------- | -------- | | widget object, returned by `createWidget` | `number` | ## Code Example ```js Page({ build() { const textWidget = createWidget(widget.TEXT, { x: 96, y: 120, w: 288, h: 46, color: 0xffffff, text_size: 36, align_h: align.CENTER_H, align_v: align.CENTER_V, text_style: text_style.NONE, text: 'HELLO ZEPPOS' }) deleteWidget(textWidget) } }) ``` --- ## createDialog ### Import ```js import { createDialog } from '@zos/ui' ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). [Image: create_dialog] Create a Dialog. ## Type ```ts (option: Option) => result ``` ## Parameters ### Option: object | Properties | Description | Required | Type | | ------------- | ---------------------------------------------------------------------------------------------- | -------- | -------------------------- | | title | The title of the widget. | YES | `string` | | show | Whether to display Dialog immediately after the creation is completed, default `false`. | NO | `boolean` | | click_listener | Callback function, type: 0 click to cancel, type: 1 click to confirm. | YES | `({type: number}) => void` | | auto_hide | Whether the dialog disappears after clicking the "Confirm" or "Cancel" button, default `true`. | NO | `boolean` | > **⚠️ Caution** > > Setting `auto_hide` to `false` allows the Dialog to be shown and hidden manually through the `show` API via the Dialog instance method. > > If you need to call routing-related APIs like `back` in the popup callback function, it is recommended to set `auto_hide` to `false` to make the page jump smoother. Otherwise, when the page is switched, the Dialog popup will be destroyed first, and then the page will be jumped, which will make the page feel switched once more. ### dialog instance #### dialog.show() ```ts (isShow: boolean) => void ``` | `isShow` | Description | | -------- | ----------- | | `true` | show | | `false` | hide | ## Code examples ```js Page({ build() { const dialog = createDialog({ title: 'HELLO ZEPP OS', auto_hide: false, click_listener: ({ type }) => { dialog.show(false) console.log('type', type) console.log('click dialog') } }) dialog.show(true) } }) ``` --- ## setStatusBarVisible ### Import ```js import { setStatusBarVisible } from '@zos/ui' ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). This interface is only available on square screen devices, set the status bar visible or not. For square screen title bar, refer to [Screen Adaptation](https://docs.zepp.com/docs/guides/best-practice/multi-screen-adaption). ## Type ```ts (visible: boolean) => void ``` ## Parameters | parameter | description | type | | ------- | --------------------------------------- | --------- | | visible | `true`: show the status bar; `false`: hide the status bar | `boolean` | ## Code examples ```js setStatusBarVisible(false) ``` --- ## updateStatusBarTitle ### Import ```js import { updateStatusBarTitle } from '@zos/ui' ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). This interface is only available on square screen devices, set the status bar to display text content. For square screen title bar, refer to [Screen Adaptation](https://docs.zepp.com/docs/guides/best-practice/multi-screen-adaption). ## Type ```ts (title: string) => void ``` ## Parameters | parameter | description | type | | ----- | -------------- | -------- | | title | Status bar display text | `string` | ## Code example ```js const title = 'Mini Program Title' updateStatusBarTitle(title) ``` --- ## getTextLayout ### Import ```js import { getTextLayout } from '@zos/ui' ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Calculate the height and width of the target text after the layout is completed, and does not actually render it, only performs the layout calculation. Can be used to calculate the height of a multi-line text layout with a fixed width, or the width of a single-line text layout. ## Type ```ts (text: string, options: object) => result ``` ## Parameters | Parameter | Description | Required | Type | | --------- | ------------------------------------------- | -------- | --------- | | text | Text content of the layout to be calculated | YES | `string` | | options | Options | YES | `Options` | ### Options | Properties | Description | Required | Type | API_LEVEL | | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------- | -------- | --------- | | text_size | Text size | YES | `number` | 2.0 | | text_width | Width of a single line of text | YES | `number` | 2.0 | | wrapped | whether the text is line feed, `0`: no line feed; `1`: line feed | NO | `number` | 2.0 | | rows_max | Limit the maximum number of lines (when the given text exceeds the maximum number of lines, it will be truncated and followed by an ellipsis). The default value is `0`, which means there is no limit | NO | `number` | 3.0 | ### result: object | Properties | Description | Type | API_LEVEL | | ---------- | ---------------------------------------------------------------------- | -------- | --------- | | width | Width pixel value | `number` | 2.0 | | height | Height pixel value | `number` | 2.0 | | rows | The text displays the number of lines. When the `wrapped` field is `false`, the value of `rows` is `1`. | `number` | 2.0 | | result | Calculation result, `-1` - error, `0` - success, `1` - success, characters truncated and ellipses added | `number` | 2.0 | | text | When the calculation is successful, the truncated and ellipsed text content is returned, which can be used for the display of actual UI widgets | `string` | 2.0 | ## Code example ```js const { width, height } = getTextLayout('turn right and go alone the road', { text_size: 30, text_width: 200 }) console.log('width', width) console.log('height', height) ``` ```js const { width, height } = getTextLayout('turn right and go alone the road', { text_size: 30, text_width: 0, wrapped: 0 }) console.log('width', width) console.log('height', height) ``` --- ## getImageInfo ### Import ```js import { getImageInfo } from '@zos/ui' ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Get information about the image resources in the `/assets` resource directory. ## Type ```ts (img_path: string) => result ``` ## Parameters | Parameter | Description | Required | Type | | --------- | ------------------------------------------------------------------------ | -------- | -------- | | img_path | The path to the image file, relative to the `/assets` resource directory | YES | `string` | ### result: object | Parameter | Description | Type | | --------- | ------------------ | -------- | | width | Image width value | `number` | | height | Image height value | `number` | ## Code example ```js getImageInfo('test.png') ``` --- ## redraw ### Import ```js import { redraw } from '@zos/ui' ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). In some boundary cases, after `deleteWidget`, the view may not be updated in time, need to call `redraw()` manually to update the view ## Type ```ts () => undefined ``` ## Code example ```js redraw() ``` --- ## setEnable > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Set whether the widget responds to screen gesture interaction events, the default is to respond. If the widgets are stacked in the Z-axis direction, the widgets above the stack will block events and the widgets below will not receive events such as `CLICK_DOWN` and `CLICK_UP`. If you want the widgets below to receive gesture events, set `widget.setEnable(false)` for the widgets stacked above. ## Type ```ts (response: boolean) => void ``` ## Parameters ### response | Description | Type | | ---------------------------------------------------------------------------------------------------- | --------- | | Whether the widget responds to gesture interaction events, `true` responds, `false` does not respond | `boolean` | --- ## setAppWidgetSize ### Import ```js import { setAppWidgetSize } from '@zos/ui' ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Set the size of the Shortcut cards, currently only height adjustment is supported. ## Type ```ts (option: Option) => undefined ``` ## Parameters ### Option: object | Properties | Description | Required | Type | | ---------- | -------------------- | -------- | -------- | | h | Shortcut card height | `YES` | `number` | ## Code example ```js setAppWidgetSize({ h: 100 }) ``` --- ## getAppWidgetSize ### Import ```js import { getAppWidgetSize } from '@zos/ui' ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Get the system default shortcut card size for developers to layout the widget. ## Type ```ts () => result ``` ### result: object | Parameter | Description | Type | | --------- | ------------------------------------------------------- | -------- | | w | Shortcut card width | `number` | | h | shortcut card height | `number` | | margin | Margin of the shortcut card from the edge of the screen | `number` | | radius | Quick Card Rounded Corners | `number` | ## Code example ```js const { w } = getAppWidgetSize() ``` --- ## getRtlLayout ### Import ```js import { getRtlLayout } from '@zos/ui' ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Query whether the current system language setting is RTL language. Setting the language to Hebrew and Arabic will return `true`. ## Type ```ts () => result ``` ### result: boolean | Description | Type | | -------------------------------------------------------------------------------- | --------- | | Query results, `true` indicates RTL language, `false` indicates non-RTL language | `boolean` | ## Code example ```js const result = getRtlLayout() console.log(result) ``` --- ## relayoutRtl ### Import ```js import { relayoutRtl } from '@zos/ui' ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Apply RTL layout to the widget based on the current system language. > **📝 Note** > > After calling this method, the current system language will be queried. If it is an RTL language, RTL layout adjustments will be made to all widgets on the current calling page. If there are widgets on the current page that do not need to be flipped, you need to organize the calling timing of `relayoutRtl()` and widget creation > Design specification reference [Design Specifications - Internationalization - Interface layouts](https://docs.zepp.com/docs/designs/internationalization/interface-layouts) ## Type ```ts () => result ``` ### result: boolean | Description | Type | | ------------------------------- | --------- | | Call result, `true` succeeds, `false` fails | `boolean` | ## 代码示例 ```js const result = relayoutRtl() console.log(result) ``` --- ## setLayoutParent > Supported from API_LEVEL `4.0`. For API compatibility, please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Sets the parent node of the current node. ## Type ```ts (parent: UIWidget) => void ``` ## Parameters | Parameter | Type | Description | | --------- | --------- | ----------------------------- | | parent | `UIWidget` | Widget instance object participating in layout | ## Example ```js const container = hmUI.createWidget(hmUI.widget.VIRTUAL_CONTAINER, { x: 0, y: 0, w: 480, h: 480 }) const text = hmUI.createWidget(hmUI.widget.TEXT, { text: 'Hello Zepp OS' }) // Set text widget as child node of container text.setLayoutParent(container) ``` ## Related References - [Flex Layout Guide](https://docs.zepp.com/docs/guides/framework/device/layout) --- ## addLayoutChild ### Import ```js import { createWidget, widget } from '@zos/ui' ``` > Supported from API_LEVEL `4.0`. For API compatibility, please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Adds a child node to the current widget. ## Type ```ts (child: UIWidget, index?: number) => void ``` ## Parameters | Parameter | Type | Required | Description | | --------- | ---------- | -------- | --------------------------- | | child | `UIWidget` | Yes | Child widget instance to add | | index | `number` | No | Insertion position index | ## Example ```js const container = createWidget(widget.VIRTUAL_CONTAINER) const button = createWidget(widget.BUTTON) // Add child node to the end of container container.addLayoutChild(button) // Add child node at specified position container.addLayoutChild(button, 0) ``` ## Related References - [Widget layout property implements Flex layout](https://docs.zepp.com/docs/guides/framework/device/layout) --- ## removeLayoutChild > Supported from API_LEVEL `4.0`. For API compatibility, please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Removes the specified child node from the current node. ## Type ```ts (child: UIWidget) => void ``` ## Parameters | Parameter | Type | Description | | --------- | --------- | --------------------------- | | child | `UIWidget` | Child widget instance to remove | ## Example ```js // Remove child widget from parent container container.removeLayoutChild(button) ``` ## Related References - [Flex Layout Guide](https://docs.zepp.com/docs/guides/framework/device/layout) --- ## updateLayoutStyle ### Import ```js import { createWidget, widget } from '@zos/ui' ``` > Supported from API_LEVEL `4.0`. For API compatibility, please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Updates the layout style of a widget node. For detailed `layout` object properties, please refer to [layout property configuration](https://docs.zepp.com/docs/guides/framework/device/layout.md#layout-properties). ## Type ```ts (style: LayoutStyle) => void ``` ## Parameters | Parameter | Type | Description | | --------- | ------------- | ------------------------- | | style | `LayoutStyle` | Object containing layout properties, the `layout` object | ## Example ```js const container = createWidget(widget.VIRTUAL_CONTAINER) // Update container layout style container.updateLayoutStyle({ display: 'flex', 'flex-direction': 'row', 'justify-content': 'space-between', 'align-items': 'center', width: '100%', height: '200px' }) ``` ## Related References - [Widget layout properties for Flex layout](https://docs.zepp.com/docs/guides/framework/device/layout) --- ## updateLayout ### Import ```js import { createWidget, widget, updateLayout } from '@zos/ui' ``` > Supported from API_LEVEL `4.0`. For API compatibility, please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Used to re-render the view after modifying the widget tree. ## Type ```ts () => void ``` ## Example ```js const container = createWidget(widget.VIRTUAL_CONTAINER) const button = createWidget(widget.BUTTON) // Add child node container.addLayoutChild(button) // Update layout and re-render the view updateLayout() ``` ## Related References - [Widget layout properties for Flex layout](https://docs.zepp.com/docs/guides/framework/device/layout) --- ## openInspector ### Import ```js import { openInspector } from '@zos/ui' ``` > Supported since API_LEVEL `4.0`. For API compatibility, please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). During development, especially when using Flex layout, you may need to check the actual layout position and size of each widget. Using `openInspector()` can visually display the boundaries of all widgets participating in layout in the simulator, helping developers debug layout issues. Used in the simulator to draw boundary rectangles for all widgets participating in layout, helping developers debug layout issues. This method should be called after the `build()` lifecycle. ## Type ```ts function openInspector(): Inspector ``` ## Parameters None ## Return Value | Type | Description | | ----------- | ------------------------- | | `Inspector` | Inspector object instance | ## Inspector Object Methods ### draw(options) Draws boundary rectangles for all widgets participating in layout. #### Parameters | Parameter | Type | Required | Default | Description | | --------- | ------------------- | -------- | ------- | ------------ | | options | `object` | No | - | Draw options | #### options Object Properties | Property | Type | Required | Default | Description | | ----------- | ------------------- | -------- | ------- | ----------------------------------------------------------------- | | line_color | `number` | No | - | Border line color, hexadecimal value, e.g., `0xff0000` for red | | line_width | `number` | No | - | Border line width | | border_mode | `number` | No | `0` | Border draw mode, `0` for outward drawing, `1` for inward drawing | ### clear() Clears all drawn boundary rectangles. ## Code Example ```js Page({ build() { // Create layout... // Draw boundary rectangles for all widgets participating in layout setTimeout(() => { openInspector().draw({ line_color: 0xff0000, // Red line_width: 1, // Line width of 1 border_mode: 1 // Draw border inward }) }, 100) } }) ``` --- ## keyboard API ### Import ```js import { keyboard } from '@zos/ui' ``` > Start from API_LEVEL `4.2`. Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). The keyboard API provides rich input interface capabilities, greatly simplifying the development complexity of custom keyboards. ## Overview The Keyboard API includes the following main functional modules: - Input: input field management, cursor and text operations - Keyboard switching - Input buffer management - System integration ## Import ```js ``` ## API List ### 1. Input Field Area #### setContentRect(rect) Set the size and position of the input field. ##### Type ```ts (rect: object) => void ``` ##### Parameters | Parameter | Description | Required | Type | | --------- | ---------------------------------- | -------- | -------- | | rect | Object containing x, y, w, h properties | YES | `object` | ##### Code Example ```js keyboard.setContentRect({ x: 10, y: 20, w: 300, h: 310 }) ``` #### getContentRect() Get the size and position of the input area. ##### Type ```ts () => {x: number, y: number, w: number, h: number} ``` ##### Code Example ```js let rect = keyboard.getContentRect() console.log(rect.x, rect.y, rect.w, rect.h) ``` ### 2. Input Field Text Operations #### getTextContext() Get the text content of the current input field. ##### Type ```ts () => string ``` ##### Code Example ```js const text = keyboard.getTextContext() ``` #### inputText(text) Insert text at the current cursor position. ##### Type ```ts (text: string) => void ``` ##### Parameters | Parameter | Description | Required | Type | | --------- | ---------------- | -------- | -------- | | text | Text to be inserted | YES | `string` | ##### Code Example ```js keyboard.inputText('yesterday') ``` #### backspace(count) Delete a specified number of characters. ##### Type ```ts (count?: number) => void ``` ##### Parameters | Parameter | Description | Required | Type | Default | | --------- | -------------------------- | -------- | -------- | ------- | | count | Number of characters to delete | NO | `number` | 1 | ##### Code Example ```js keyboard.backspace() // Delete 1 character keyboard.backspace(4) // Delete 4 characters ``` #### clearInput() Clear the input field content. ##### Type ```ts () => void ``` ##### Code Example ```js keyboard.clearInput() ``` ### 3. Special Key Operations #### sendFnKey(keyType) Send special function key events. ##### Type ```ts (keyType: number) => void ``` ##### Parameters | Parameter | Description | Required | Type | | --------- | ---------------- | -------- | -------- | | keyType | Key type constant | YES | `number` | ##### Key Type Constants | Constant | Description | | -------------------- | --------------------- | | `keyboard.BACKSPACE` | Backspace delete | | `keyboard.ENTER` | Confirm/submit input | | `keyboard.SWITCH` | Switch keyboard input method | | `keyboard.SELECT` | Enter keyboard selection | ##### Code Example ```js keyboard.sendFnKey(keyboard.BACKSPACE) keyboard.sendFnKey(keyboard.ENTER) ``` ### 4. Cache Management #### inputBuffer(text, color, underlineColor) Set input buffer content. ##### Type ```ts (text: string, color?: number, underlineColor?: number) => void ``` ##### Parameters | Parameter | Description | Required | Type | Default | | -------------- | ---------------- | -------- | -------- | ---------- | | text | Buffer text | YES | `string` | - | | color | Text color | NO | `number` | `0xffffff` | | underlineColor | Underline color | NO | `number` | `0xffffff` | ##### Code Example ```js keyboard.inputBuffer('国') keyboard.inputBuffer('me', 0xff00ff, 0x00ff00) ``` #### getBuffer() Read buffer text. ##### Type ```ts () => string ``` ##### Code Example ```js let text = keyboard.getBuffer() ``` #### clearBuffer() Clear buffer text. ##### Type ```ts () => void ``` ##### Code Example ```js keyboard.clearBuffer() ``` ### 5. Keyboard Switching #### switchInputType(inputType) Switch to a specified type of keyboard. ##### Type ```ts (inputType: number) => void ``` ##### Parameters | Parameter | Description | Required | Type | | --------- | ------------------ | -------- | -------- | | inputType | Input type constant | YES | `number` | ##### Input Type Constants | Constant | Description | | ----------------- | ---------------- | | `inputType.EMOJI` | Emoji keyboard | | `inputType.NUM` | Number keyboard | | `inputType.CHAR` | Character keyboard | | `inputType.VOICE` | Voice input | | `inputType.JSKB` | Custom keyboard | ##### Code Example ```js keyboard.switchInputType(inputType.NUM) ``` ### 6. System Integration #### checkVoiceInputAvailable() Check if voice input is supported. ##### Type ```ts () => boolean ``` ##### Code Example ```js let voiceSupport = keyboard.checkVoiceInputAvailable() ``` #### isEnabled() Check if the current keyboard is enabled in settings. ##### Type ```ts () => boolean ``` ##### Code Example ```js let enable = keyboard.isEnabled() ``` #### isSelected() Check if the current keyboard is selected for use. ##### Type ```ts () => boolean ``` ##### Code Example ```js let select = keyboard.isSelected() ``` #### gotoSettings() Navigate to the keyboard settings page in system settings: System Settings -> Preferences -> Keyboard. ##### Type ```ts () => void ``` ##### Code Example ```js keyboard.gotoSettings() ``` ## Code Example ```js // Keyboard Widget usage example DataWidget({ build() { // Set input area keyboard.setContentRect({ x: 10, y: 20, w: 300, h: 310 }) // Check keyboard status if (keyboard.isEnabled()) { console.log('Keyboard is enabled') } // Handle text input keyboard.inputText('Hello') // Switch to number keyboard keyboard.switchInputType(inputType.NUM) } }) ``` ## Related References - [Custom Keyboard](https://docs.zepp.com/docs/guides/keyboard/intro) - [SYSTEM_KEYBOARD](https://docs.zepp.com/docs/reference/device-app-api/newAPI/ui/widget/SYSTEM_KEYBOARD) --- --- # @zos/ui-widget-basic Basic widget APIs. ## TEXT ### Import ```js import { createWidget, widget } from '@zos/ui' ``` > Start from API_LEVEL `2.0`. Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). [Image: text_sample] Text widget for displaying text. Support setting text size, color, alignment, font. ## Create UI widget ```js const text = createWidget(widget.TEXT, Param) ``` ## Type ## Param: object | Properties | Description | Required | Type | | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ------------ | | x | The x-axis coordinate of the widget | YES | `number` | | y | The y-axis coordinate of the widget | YES | `number` | | w | The width of the widget | YES | `number` | | h | The height of the widget | YES | `number` | | color | The color of the text | NO | `number` | | align_h | The alignment of the horizontal axis (see ALIGN for values) | NO | `ALIGN` | | align_v | Alignment of the vertical axis (see ALIGN for values) | NO | `ALIGN` | | text | Text | NO | `string` | | text_size | The size of the font | NO | `number` | | text_style | Text overlength handling, default is scrolling text (see TEXT_STYLE for values) | NO | `TEXT_STYLE` | | line_space | Row spacing | NO | `number` | | char_space | Character spacing | NO | `number` | | font | Font path, resource storage path reference [Folder Structure](https://docs.zepp.com/docs/guides/architecture/folder-structure) | NO | `string` | | text_i18n | Multi-language text support, refer to the code example, where the 'en-US' field is required. When the current country language is not configured, the value of 'en-US' will be used. When passed in this way, the `text` attribute is disabled | NO | `object` | | start_angle | Arc layout starting angle | NO | `number` | | end_angle | Arc layout ending angle (start_angle < end_angle) | NO | `number` | | mode | Arc layout mode, default 0
0: inner
1: outer | NO | `number` | | radius | Controls the arc layout radius, defaults to half of the widget's width and height | NO | `number` | ### ALIGN alignment | Value | Description | | -------------- | ----------------------------- | | align.LEFT | Horizontal axis-left aligned | | align.RIGHT | Horizontal axis-right aligned | | align.CENTER_H | Horizontal axis-centered | | align.TOP | Vertical axis-top | | align.BOTTOM | Vertical axis-bottom | | align.CENTER_V | Vertical axis-centered | ### TEXT_STYLE Text layout | Value | Description | | ------------------- | ----------------------------------------- | | text_style.ELLIPSIS | Single line overflow character display... | | text_style.NONE | Scrolling text | | text_style.WRAP | Line wrap | ## Property Access Support List | Property | setProperty | getProperty | [setter](https://docs.zepp.com/docs/reference/device-app-api/newAPI/ui/gettersetter) | [getter](https://docs.zepp.com/docs/reference/device-app-api/newAPI/ui/gettersetter) | | ----------- | ----------- | ----------- | ----------------------------- | ----------------------------- | | x | Y | Y | Y | Y | | y | Y | Y | Y | Y | | w | Y | Y | Y | Y | | h | Y | Y | Y | Y | | color | Y | Y | Y | Y | | align_h | Y | Y | Y | Y | | align_v | Y | Y | Y | Y | | text | Y | Y | Y | Y | | text_size | Y | Y | Y | Y | | font | Y | Y | Y | Y | | text_style | Y | Y | Y | Y | | line_space | Y | Y | Y | Y | | char_space | Y | Y | Y | Y | | text_i18n | N | N | Y | Y | | start_angle | N | N | N | N | | end_angle | N | N | N | N | | mode | N | N | N | N | | radius | N | N | N | N | ## Code example ```js Page({ build() { const text = createWidget(widget.TEXT, { x: 96, y: 120, w: 288, h: 46, color: 0xffffff, text_size: 36, align_h: align.CENTER_H, align_v: align.CENTER_V, text_style: text_style.NONE, text: 'HELLO, Zepp OS' }) text.addEventListener(event.CLICK_DOWN, (info) => { text.setProperty(prop.MORE, { y: 200 }) }) const textWithFont = createWidget(widget.TEXT, { x: 96, y: 300, w: 288, h: 46, color: 0xffffff, text_size: 36, align_h: align.CENTER_H, align_v: align.CENTER_V, text_style: text_style.NONE, font: 'fonts/custom.ttf', text_i18n: { 'en-US': 'Hello Zepp OS', 'zh-CN': '你好 Zepp OS' } }) } }) ``` ## Additional Examples ### Example 1 ```js createWidget(widget.TEXT, { x: 0, y: 0, w: 200, h: 200, text: 'hello', color: 0x34e073, align_h: align.LEFT, font: 'fonts/Pacifico-Regular.ttf', }) ``` ### Example 2 ```js const rootContainer = createWidget(widget.VIRTUAL_CONTAINER, { layout: { x: '10vw', y: '10vh', width: '80vw', height: '50vh' }, }) const groupRoot = createWidget(widget.GROUP, { parent: rootContainer, layout: { display: 'flex', 'flex-flow': 'row wrap', 'column-gap': '20', 'row-gap': '10', 'justify-content': 'space-evenly', 'align-items': 'center', width: '100%', height: '100%', }, }) for (let i = 0; i < 3; i += 1) { groupRoot.createWidget(widget.TEXT, { text: 'hello zepp os', color: 0x34e073, align_v: align.CENTER_V, layout: { width: '30%', height: '25%', 'font-size': '16', }, }) } ``` --- ## IMG ### Import ```js import { createWidget, widget } from '@zos/ui' ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). [Image: img_sample] The image widget is used to display images and supports image rotation. > **💡 Tip** > > 1. Recommend using 24-bit or 32-bit png format images with RGB or RGBA color scheme. > ## Create UI widget ```js const img = createWidget(widget.IMG, Param) ``` ## Type ### Param: object | Properties | Description | Required | Type | | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | --------- | | src | The path of the image. Reference [folder-structure structure](https://docs.zepp.com/docs/guides/architecture/folder-structure) | YES | `string` | | w | The width of the widget.If not passed then set the width of the image itself | NO | `number` | | h | The height of the widget.If not passed then set the height of the image itself | NO | `number` | | x | The x-axis coordinate of the widget. | YES | `number` | | y | The y-axis coordinate of the widget. | YES | `number` | | pos_x | Relative coordinates.Horizontal offset of the image relative to the widget coordinates. | NO | `number` | | pos_y | Relative coordinates.Vertical offset of the image relative to the widget coordinates. | NO | `number` | | angle | The rotation angle of the picture (the 12-point direction is 0 degrees). | NO | `number` | | center_x | The rotation center of the picture. | NO | `number` | | center_y | The rotation center of the picture. | NO | `number` | | alpha | Transparency, 0 - 255, default value is 255 for opaque, 0 for full transparency | NO | `number` | | auto_scale | Whether the image scales with the widget width and height, the default image area size is the size of the resource file itself | NO | `boolean` | | auto_scale_obj_fit | This field takes effect only when `auto_scale` is `true`, indicating whether the image fills the entire widget area (without maintaining the image aspect ratio) | NO | `boolean` | ## Image example > **⚠️ Caution** > > `w` and `h` are the width and height of the image widget, and the IMG area is the display boundary of the image resource [Image: axis] [Image: rotate] ## Code example ```js Page({ build() { const img = createWidget(widget.IMG, { x: 125, y: 125, src: 'zeppos.png' }) img.addEventListener(event.CLICK_DOWN, (info) => { img.setProperty(prop.MORE, { y: 200 }) }) } }) ``` ```js Page({ build() { const img_hour = createWidget(widget.IMG) img_hour.setProperty(prop.MORE, { x: 0, y: 0, w: 454, h: 454, pos_x: 454 / 2 - 27, pos_y: 50 + 50, center_x: 454 / 2, center_y: 454 / 2, src: 'hour.png', angle: 30 }) } }) ``` ## Additional Examples ### Example 1 ```js const rootContainer = createWidget(widget.VIRTUAL_CONTAINER, { layout: { x: '10vw', y: '10vh', width: '80vw', height: '50vh' }, }) const groupRoot = createWidget(widget.GROUP, { parent: rootContainer, layout: { display: 'flex', 'flex-flow': 'row wrap', 'column-gap': '20', 'row-gap': '10', 'justify-content': 'space-evenly', 'align-items': 'center', width: '100%', height: '100%', }, }) for (let i = 0; i < 5; i += 1) { const imgWidget = groupRoot.createWidget(widget.IMG, { src: 'images/icons/ic_moon.png', layout: { width: '15%', height: '25%', pos_x: '20', radius: '5.25vw', }, }) fill_rect_list.push(imgWidget) } ``` --- ## BUTTON ### Import ```js import { createWidget, widget } from '@zos/ui' ``` > Supported from API_LEVEL `2.0`. For API compatibility, please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). [Image: button_sample] The button widget supports setting images and colors for normal and pressed states. ## Create UI Widget ```js const button = createWidget(widget.BUTTON, Param) ``` ## Types ### Param: object | Properties | Description | Required | Type | API_LEVEL | | -------------- | -------------------------------------------------------------------------------------------------------- | -------- | ----------- | --------- | | x | The x-coordinate of the widget | YES | `number` | 2.0 | | y | The y-coordinate of the widget | YES | `number` | 2.0 | | w | The width of the widget. Note: If set to -1, it will prioritize adapting to normal_src size, default is 100 | YES | `number` | 2.0 | | h | The height of the widget. Note: If set to -1, it will prioritize adapting to normal_src size, default is 40 | YES | `number` | 2.0 | | text | Text displayed on the button | NO | `string` | 2.0 | | color | Text color | NO | `number` | 2.0 | | text_size | Text font size | NO | `number` | 2.0 | | normal_color | Background color in normal state, must be set together with `press_color` to take effect | NO | `number` | 2.0 | | press_color | Background color when pressed, must be set together with `normal_color` to take effect | NO | `number` | 2.0 | | radius | Corner radius when using color as button background | NO | `number` | 2.0 | | normal_src | Background image in normal state, must be set together with `press_src` to take effect | NO | `string` | 2.0 | | press_src | Background image when pressed, must be set together with `normal_src` to take effect | NO | `string` | 2.0 | | click_func | Button click callback | NO | `ClickFunc` | 2.0 | | longpress_func | Long press (700ms) button callback | NO | `ClickFunc` | 2.0 | | font | Font path, refer to [Directory Structure](https://docs.zepp.com/docs/guides/architecture/folder-structure) | NO | `string` | 3.6 | | text_w | Button text width | NO | `number` | 3.6 | > **⚠️ Caution** > > - When neither background nor color is set for the button, it will use the default click state background color (normal black, clicked gray) > - When both background and color are set for the button, background color takes precedence over background image > - The radius field only works after setting the background color > - Background color `normal_color` and pressed color `press_color` must be set together to take effect > - Background image `normal_src` and pressed image `press_src` must be set together to take effect > - When using [`widget.setProperty`](https://docs.zepp.com/docs/reference/device-app-api/newAPI/ui/setProperty) API to modify BUTTON widget properties, you must pass in the required fields `x`, `y`, `w`, `h` (refer to code example) ### ClickFunc ```js (button: Button) => void ``` The `button` instance created by the `createWidget` method ## Property Access Support List | Property Name | setProperty | getProperty | [setter](https://docs.zepp.com/docs/reference/device-app-api/newAPI/ui/gettersetter) | [getter](https://docs.zepp.com/docs/reference/device-app-api/newAPI/ui/gettersetter) | | -------------- | ----------- | ----------- | ----------------------------- | ----------------------------- | | x | Y | Y | Y | Y | | y | Y | Y | Y | Y | | w | Y | Y | Y | Y | | h | Y | Y | Y | Y | | text | Y | Y | Y | Y | | color | Y | Y | Y | Y | | text_size | Y | Y | Y | Y | | font | Y | Y | Y | Y | | press_src | N | N | Y | Y | | normal_src | N | N | Y | Y | | press_color | N | N | Y | Y | | normal_color | N | N | Y | Y | | radius | Y | Y | Y | Y | | click_func | N | N | Y | Y | | longpress_func | N | N | Y | Y | | text_w | N | N | Y | Y | ## Code Example > **💡 Tip** > > Please refer to [Design Resources](https://docs.zepp.com/docs/reference/related-resources/design-resources) for the image resources in the code example ```js Page({ build() { const img_button = createWidget(widget.BUTTON, { x: (480 - 96) / 2, y: 120, text: 'Hello', w: -1, h: -1, normal_src: 'button_normal.png', press_src: 'button_press.png', click_func: () => { console.log('button click') } }) createWidget(widget.BUTTON, { x: (480 - 400) / 2, y: 240, w: 400, h: 100, radius: 12, normal_color: 0xfc6950, press_color: 0xfeb4a8, text: 'Hello', click_func: (button_widget) => { button_widget.setProperty(prop.MORE, { x: (480 - 400) / 2, y: 300, w: 400, h: 100 }) } }) } }) ``` ## Additional Examples ### Example 1 ```js const button = createWidget(widget.BUTTON, { x: 0, y: 100, w: 218, h: 74, press_color: 0x1976d2, normal_color: 0xef5350, text: 'button', click_func: () => { console.log('button clicked') }, longpress_func: () => { console.log('button long pressed') }, }) ``` ### Example 2 > Supported from API_LEVEL `4.0`. ```js const buttonContainer = createWidget(widget.VIRTUAL_CONTAINER, { layout: { x: '0', y: '60vh', width: '100vw', height: '40vh' }, }) const buttonSubContainer = createWidget(widget.VIRTUAL_CONTAINER, { parent: buttonContainer, layout: { display: 'flex', 'flex-flow': 'row wrap', 'column-gap': '20', 'row-gap': '10', 'justify-content': 'space-evenly', 'align-items': 'center', width: '100%', height: '100%', }, }) const addButton = createWidget(widget.BUTTON, { parent: buttonSubContainer, layout: { width: '25%', height: '20%', radius: '3vw' }, press_src: 'images/test/normalbtn_h.png', normal_src: 'images/test/normalbtn_n.png', text: 'add widget', click_func: () => {}, }) ``` --- ## FILL_RECT ### Import ```js import { createWidget, widget } from '@zos/ui' ``` > Supported from API_LEVEL `2.0`. For API compatibility, please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). [Image: fill_rect_sample] The Fill Rectangle widget is used to draw a solid color rectangular area. ## Create UI Widget ```js const fillRect = createWidget(widget.FILL_RECT, Param) ``` ## Types ### Param: object | Property | Description | Required | Type | API_LEVEL | | ----------- | ------------------------------------------------------------------- | -------- | -------- | --------- | | x | The x-coordinate of the widget | YES | `number` | 2.0 | | y | The y-coordinate of the widget | YES | `number` | 2.0 | | w | The width of the widget | YES | `number` | 2.0 | | h | The height of the widget | YES | `number` | 2.0 | | color | The color of the widget | YES | `number` | 2.0 | | radius | The corner radius of the rectangle | NO | `number` | 2.0 | | angle | The rotation angle | NO | `number` | 2.0 | | alpha | Opacity, value range 0-255, default 255 (opaque), 0 (transparent) | NO | `number` | 3.0 | | pos_x | Drawing area x offset (only works when angle%360!=0) | NO | `number` | 4.0 | | pos_y | Drawing area y offset (only works when angle%360!=0) | NO | `number` | 4.0 | | rect_width | Width of the drawing area (only works when angle%360!=0) | NO | `number` | 4.0 | | rect_height | Height of the drawing area (only works when angle%360!=0) | NO | `number` | 4.0 | ## Property Access Support List | Property | setProperty | getProperty | [setter](https://docs.zepp.com/docs/reference/device-app-api/newAPI/ui/gettersetter) | [getter](https://docs.zepp.com/docs/reference/device-app-api/newAPI/ui/gettersetter) | | ----------- | ----------- | ----------- | ----------------------------- | ----------------------------- | | x | Y | Y | Y | Y | | y | Y | Y | Y | Y | | w | Y | Y | Y | Y | | h | Y | Y | Y | Y | | color | Y | Y | Y | Y | | radius | Y | Y | Y | Y | | angle | Y | Y | Y | Y | | pos_x | N | Y | N | Y | | pos_y | N | Y | N | Y | | rect_width | N | N | N | Y | | rect_height | N | N | N | Y | | center_x | Y | Y | Y | Y | | center_y | Y | Y | Y | Y | | alpha | Y | Y | Y | Y | ## Code Example ```js Page({ build() { const fill_rect = createWidget(widget.FILL_RECT, { x: 125, y: 125, w: 230, h: 150, radius: 20, color: 0xfc6950 }) fill_rect.addEventListener(event.CLICK_DOWN, (info) => { fill_rect.setProperty(prop.MORE, { x: 125, y: 200, w: 230, h: 150 }) }) } }) ``` --- ## STROKE_RECT ### Import ```js import { createWidget, widget } from '@zos/ui' ``` > Supported from API_LEVEL `2.0`. For API compatibility, please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). [Image: stroke_rect_sample] The stroked rectangle widget adds a stroke on the basis of the filled rectangle widget. ## Create UI Widget ```js const strokeRect = createWidget(widget.STROKE_RECT, Param) ``` ## Type ### Param: object | Property | Description | Required | Type | API_LEVEL | | ------------ | ------------------------------------------------------------ | -------- | -------- | --------- | | x | The x-axis coordinate of the widget | YES | `number` | 2.0 | | y | The y-axis coordinate of the widget | YES | `number` | 2.0 | | w | The width of the widget | YES | `number` | 2.0 | | h | The height of the widget | YES | `number` | 2.0 | | color | The widget's color | YES | `number` | 2.0 | | radius | The rectangle's rounded corners | NO | `number` | 2.0 | | line_width | The width of stroke | NO | `number` | 2.0 | | angle | Rotation angle | NO | `number` | 2.0 | | pos_x | Drawing area x offset (only effective when angle%360!=0) | NO | `number` | 4.0 | | pos_y | Drawing area y offset (only effective when angle%360!=0) | NO | `number` | 4.0 | | rect_width | Width of the drawing area (only effective when angle%360!=0) | NO | `number` | 4.0 | | rect_height | Height of the drawing area (only effective when angle%360!=0) | NO | `number` | 4.0 | ## Property Access Support List | Property Name | setProperty | getProperty | [setter](https://docs.zepp.com/docs/reference/device-app-api/newAPI/ui/gettersetter) | [getter](https://docs.zepp.com/docs/reference/device-app-api/newAPI/ui/gettersetter) | | ------------- | ----------- | ----------- | ---------------------------- | ---------------------------- | | x | Y | Y | Y | Y | | y | Y | Y | Y | Y | | w | Y | Y | Y | Y | | h | Y | Y | Y | Y | | color | Y | Y | Y | Y | | radius | Y | Y | Y | Y | | line_width | Y | Y | Y | Y | | angle | Y | Y | Y | Y | | pos_x | N | Y | N | Y | | pos_y | N | Y | N | Y | | rect_width | N | N | N | Y | | rect_height | N | N | N | Y | ## Code Example ```js Page({ build() { const strokeRect = createWidget(widget.STROKE_RECT, { x: 125, y: 125, w: 230, h: 150, radius: 20, line_width: 4, color: 0xfc6950 }) strokeRect.addEventListener(event.CLICK_DOWN, (info) => { strokeRect.setProperty(prop.MORE, { y: 200 }) }) } }) ``` --- ## CIRCLE ### Import ```js import { createWidget, widget } from '@zos/ui' ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). [Image: circle_sample] Draws a circle with support for color, transparency, and other properties. ## Creating UI widgets ```js const circle = createWidget(widget.CIRCLE, Param) ``` ## Type ### Param: object | Properties | Description | Required | Type | | ---------- | -------------------------------------------- | -------- | -------- | | center_x | Center of circle x. | YES | `number` | | center_y | Center of circle y. | YES | `number` | | radius | Radius. | YES | `number` | | color | Color 16-increment value. | YES | `number` | | alpha | Transparency.[0-255] 0 for full transparency | NO | `number` | ## Supported Property Access List | Property | setProperty | getProperty | [setter](https://docs.zepp.com/docs/reference/device-app-api/newAPI/ui/gettersetter) | [getter](https://docs.zepp.com/docs/reference/device-app-api/newAPI/ui/gettersetter) | |------------|-------------|-------------|-------------------------------|-------------------------------| | center_x | Y | Y | Y | Y | | center_y | Y | Y | Y | Y | | radius | Y | Y | Y | Y | | color | Y | Y | Y | Y | | alpha | Y | Y | Y | Y | ## Code example ```js Page({ build() { const circle = createWidget(widget.CIRCLE, { center_x: 240, center_y: 240, radius: 120, color: 0xfc6950, alpha: 200 }) } }) ``` --- ## ARC ### Import ```js import { createWidget, widget } from '@zos/ui' ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). [Image: arc_sample] Arc widget to display arc progress. Support setting line width, color, start and end angle. ## Create UI widget ```js const arc = createWidget(widget.ARC, Param) ``` ## Type ### Param: object | Properties | Description | Required | Type | | ----------------- | ------------------------------------------------------------------------------------------ | --------- | -------- | | x | The x-coordinate of widgets | YES | `number` | | y | The y-coordinate of widgets | YES | `number` | | w | The width of widgets | YES | `number` | | h | The height of widgets | YES | `number` | | radius | Radius | YES | `number` | | start_angle | The angle at the beginning of the arc. (0 degrees is the positive three o'clock direction) | YES | `number` | | end_angle | The angle at the end of the arc. (0 degrees is the positive three o'clock direction) | YES | `number` | | line_width | Width of circular arc. | YES | `number` | | color | Color of circular arc. | YES | `number` | > **ℹ️ Info** > > The `ARC` widget draws an ellipse within the boundaries of a rectangle of width `w` and height `h` with the (`x`,`y`) coordinates as the upper left corner, and then cuts it into an arc at a given angle ## Supported Property Access List | Property | setProperty | getProperty | [setter](https://docs.zepp.com/docs/reference/device-app-api/newAPI/ui/gettersetter) | [getter](https://docs.zepp.com/docs/reference/device-app-api/newAPI/ui/gettersetter) | |--------------|-------------|-------------|-------------------------------|-------------------------------| | x | Y | Y | Y | Y | | y | Y | Y | Y | Y | | w | Y | Y | Y | Y | | h | Y | Y | Y | Y | | start_angle | Y | Y | Y | Y | | end_angle | Y | Y | Y | Y | | line_width | Y | Y | Y | Y | | color | Y | Y | Y | Y ## Code example ```js Page({ build() { const arc = createWidget(widget.ARC, { x: 100, y: 100, w: 250, h: 250, start_angle: -90, end_angle: 90, color: 0xfc6950, line_width: 20 }) arc.addEventListener(event.CLICK_DOWN, (info) => { arc.setProperty(prop.MORE, { y: 150 }) }) } }) ``` --- ## IMG_ANIM ### Import ```js import { createWidget, widget } from '@zos/ui' ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). [Image: img_anim_sample] Play the pre-given image at the set frame rate to create an animation effect. ## Create UI widget ```js const imgAnim = createWidget(widget.IMG_ANIM, Param) ``` ## Type ### Param: object | Properties | Description | Required | Type | | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------- | ---------- | | x | The x-coordinate of animation. | YES | `number` | | y | The y-coordinate of animation. | YES | `number` | | anim_path | The path to the image for animation. | YES | `string` | | anim_prefix | The name to the image for animation. | YES | `string` | | anim_ext | Image extensions. | YES | `string` | | anim_fps | Number of frames of animation. | YES | `number` | | repeat_count | Number of animation repetitions, can be set `0`: infinite repetition, `1`: single repetition. | YES | `number` | | anim_repeat | Whether to repeat the playback; this value is true if repeat_count is 0. | No | `boolean` | | anim_size | The number of images. | YES | `number` | | anim_status | The status of animation; Reference `anim_status` | YES | `number` | | anim_complete_call | This function is callback when the animation is executed successfully. `repeat_count` is invalid if `0`. Parameters `anim` is an instance to create the animation. | NO | `function` | | step | Frame animation step size, more than '1' will jump frame | NO | `number` | ### Supported properties `anim_status` Please pay attention to the animation order of the current settings when setting animation properties, the widget has been protected internally. | Value | Description | | ------------------ | -------------------------------------------------------------------------------------- | | anim_status.START | Start animation; only pause stop is allowed to be called after starting the animation. | | anim_status.PAUSE | Pause animation; can only be called after starting the animation and resuming it. | | anim_status.RESUME | Resume animation; can only be called after pausing the animation. | | anim_status.STOP | Stop animation; can only be called after starting the animation and resuming it. | ### Get animation status Return type boolean | Value | Description | | -------------------- | --------------------------------- | | prop.ANIM_IS_RUNINNG | Is the animation running. | | prop.ANIM_IS_PAUSE | Whether the animation is paused. | | prop.ANIM_IS_STOP | Whether the animation is stopped. | ## Supported Property Access List | Property | setProperty | getProperty | [setter](https://docs.zepp.com/docs/reference/device-app-api/newAPI/ui/gettersetter) | [getter](https://docs.zepp.com/docs/reference/device-app-api/newAPI/ui/gettersetter) | |-----------------------|-------------|-------------|-------------------------------|-------------------------------| | x | Y | Y | Y | Y | | y | Y | Y | Y | Y | | w | Y | Y | Y | Y | | h | Y | Y | Y | Y | | anim_path | N | N | N | Y | | anim_prefix | N | N | N | Y | | anim_ext | N | N | N | Y | | anim_fps | N | N | N | Y | | repeat_count | N | N | N | Y | | anim_repeat | N | N | N | N | | anim_size | N | N | N | N | | anim_status | N | N | N | N | | anim_complete_call | N | N | N | N | | display_on_restart | N | N | N | N | | anim_auto_resume_call | N | N | N | N | | step | Y | Y | Y | Y | | default_frame_index | N | N | N | N | ## Code example > **💡 Tip** > > Please refer to [Design Resources](https://docs.zepp.com/docs/reference/related-resources/design-resources) for the image resources in the code example ```tree // Resource Storage Directory . └── assets └── gtr-3 └── anim // anim_path ├── animation_0.png ├── animation_1.png ├── animation_2.png ├── animation_3.png ├── animation_4.png └── animation_5.png ``` ```js Page({ build() { const imgAnimation = createWidget(widget.IMG_ANIM, { anim_path: 'anim', anim_prefix: 'animation', anim_ext: 'png', anim_fps: 60, anim_size: 36, repeat_count: 1, anim_status: 3, x: 208, y: 230, anim_complete_call: () => { console.log('animation complete') } }) imgAnimation.setProperty(prop.ANIM_STATUS, anim_status.START) imgAnimation.addEventListener(event.CLICK_DOWN, () => { const isRunning = imgAnimation.getProperty(prop.ANIM_IS_RUNINNG) if (!isRunning) { imgAnimation.setProperty(prop.ANIM_STATUS, anim_status.START) } }) } }) ``` --- ## QRCODE ### Import ```js import { createWidget, widget } from '@zos/ui' ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). The QRCODE widget consists of a QR code and a background (white). [Image: qrcode_sample] ## Create UI widget ```js const qrcode = createWidget(widget.QRCODE, Param) ``` ## Type ### Param: object | Properties | Description | Required | Required | Version | | ---------- | ------------------------------- | -------- | -------- | ------- | | content | QR code content | YES | `string` | - | | x | QR Code x Coordinate | YES | `number` | - | | y | QR Code y Coordinate | YES | `number` | - | | w | QR code width | YES | `number` | - | | h | QR code height | YES | `number` | - | | bg_x | Background x coordinates | NO | `number` | - | | bg_y | Background y coordinates | NO | `number` | - | | bg_w | Background width | NO | `number` | - | | bg_h | Background height | NO | `number` | - | | bg_radius | Background area rounding radius | NO | `number` | 2.1 | ## Supported Property Access List | Property | setProperty | getProperty | [setter](https://docs.zepp.com/docs/reference/device-app-api/newAPI/ui/gettersetter) | [getter](https://docs.zepp.com/docs/reference/device-app-api/newAPI/ui/gettersetter) | | --------- | ----------- | ----------- | ----------------------------- | ----------------------------- | | x | Y | Y | Y | Y | | y | Y | Y | Y | Y | | w | N | N | N | N | | h | N | N | N | N | | bg_x | N | N | N | N | | bg_y | N | N | N | N | | bg_w | N | N | N | N | | bg_h | N | N | N | N | | bg_radius | N | N | N | N | | content | N | N | N | N | ## Code example ```js Page({ build() { const qrcode = createWidget(widget.QRCODE, { content: 'Hello Zepp OS', x: 140, y: 140, w: 200, h: 200, bg_x: 120, bg_y: 120, bg_w: 240, bg_h: 240 }) } }) ``` ## Additional Examples ### Example 1 ```js createWidget(widget.QRCODE, { x: 96, y: 120, w: 288, h: 288, bg_x: 80, bg_y: 104, bg_w: 320, bg_h: 320, content: 'zepp/url/@my:long page2', }) ``` --- ## DIALOG ### Import ```js import { createWidget, widget } from '@zos/ui' ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). > **⚠️ Caution** > > This widget has been discontinued. It is recommended to replace it with the more powerful [@zos/interaction createModal API](https://docs.zepp.com/docs/reference/device-app-api/newAPI/interaction/createModal) [Image: dialog_sample.jpg] Dialog popup consists of a piece of text and two buttons. The popup box disappears when the buttons are clicked. ## Create UI widget ```js const dialog = createWidget(widget.DIALOG, Param) ``` ## Type ### Param: object | Properties | Description | Required | Type | | -------------------- | ------------------------------------------------------ | -------- | -------------------------- | | text | Contents of dialog. | YES | `string` | | content_text_size | The text size of the dialog content. | NO | `number` | | content_text_color | The text color of the dialog content. | NO | `number` | | content_bg_color | The background color of the dialog content. | NO | `number` | | content_text_align_h | Alignment of dialog content text.(horizontal axis) | NO | `string` | | content_text_align_v | Alignment of dialog content text.(vertical axis) | NO | `string` | | ok_text | Text on the confirmed button. | NO | `string` | | ok_text_color | The color of the text on the confirmed button. | NO | `number` | | ok_press_color | The color when the confirmed button is pressed. | NO | `number` | | ok_nomal_color | The color when the confirmed button is normal. | NO | `number` | | ok_press_src | Background image when the confirmed button is pressed. | NO | `string` | | ok_nomal_src | Background image when the confirmed button is normal. | NO | `string` | | cancel_text | Text on the canceled button. | NO | `string` | | cancel_text_color | The color of the text on the canceled button. | NO | `number` | | cancel_press_color | The color when the canceled button is pressed. | NO | `number` | | cancel_nomal_color | The color when the canceled button is normal. | NO | `number` | | cancel_press_src | Background image when the canceled button is pressed. | NO | `string` | | cancel_nomal_src | Background image when the canceled button is normal. | NO | `string` | | dialog_align_h | The horizontal axis of the dialog. | NO | `number` | | dialog_align_v | The vertical axis of the dialog. | NO | `number` | | ok_func | Click the callback of the confirmed button. | NO | `(dialog: Dialog) => void` | | cancel_func | Click the callback of the canceled button. | NO | `(dialog: Dialog) => void` | ### Dialog: object | Property | Description | Type | | ----------- | ------------------------------------------------------- | -------- | | text | The content of dialog. | `string` | | ... omitted | Refer to dialog related properties in the setting field | ### prop Properties | Properties | Support get/set | Type | Notes | | -------------- | --------------- | --------- | -------------------------- | | prop.SHOW | set | `boolean` | dialog whether to display. | ## Code example ```js Page({ build() { const dialog = createWidget(widget.DIALOG, { ok_text: 'OK', cancel_text: 'CANCEL' }) dialog.setProperty(prop.MORE, { text: 'DIALOG', content_text_size: 40, content_bg_color: 0x000000, content_text_color: 0xffffff, dialog_align_h: align.CENTER_H, content_text_align_h: align.CENTER_H, content_text_align_v: align.CENTER_V, ok_func: () => { console.log('OK') }, cancel_func: () => { console.log('CANCEL') } }) dialog.setProperty(prop.SHOW, true) } }) ``` --- ## HISTOGRAM ### Import ```js import { createWidget, widget } from '@zos/ui' ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). [Image: histogram] Draws a histogram. ## Create UI widget ```js const histoGram = createWidget(widget.HISTOGRAM, Param) ``` ## Type ### Param: object | Properties | Description | Required | Type | | --------------- | --------------------------------------------------------------------------------- | -------- | --------------- | | x | The x-coordinate of widget. | YES | `number` | | y | The y-coordinate of widget. | YES | `number` | | w | The width of widget. | YES | `number` | | h | The height of the widget. | YES | `number` | | item_width | Width of column. | YES | `number` | | item_space | Space of column. | YES | `number` | | item_radius | Radius of column. | YES | `number` | | item_start_y | The starting Y point of the column, relative coordinate, default is 0 if not filled. | NO | `number` | | item_max_height | Maximum height of column.If unfilled,default is widget height. | NO | `number` | | item_color | Column color. In API_LEVEL 3.5, supports passing an array `Array` to specify the color of each column | YES | `number` | | item_alpha | Column color transparency. In API_LEVEL 3.5, supports passing an array `Array` to specify the transparency of each column | NO | `number` | | data_min_value | Minimum value of the column.Used to calculate the actual height of the column. | YES | `number` | | data_max_value | Maximum value of the column.Used to calculate the actual height of the column. | YES | `number` | | data_array | Data array of columns. | YES | `Array` | | data_count | Length of data. | YES | `number` | | xline | Configuration objects for the x-axis. | YES | `XLine` | | xText | Configuration object for x-axis text. | YES | `XText` | | yline | Configuration objects for the y-axis. | YES | `YLine` | | yText | Configuration object for y-axis text. | YES | `YText` | ### XLine: object | Properties | Description | Required | Type | | ------------ | ------------------------------------------------------------------------------------- | -------- | -------- | | pading | Margin of dividing line based on x-axis. | YES | `number` | | space | The interval of the dividing line. | YES | `number` | | start | The y-axis coordinates of the start of the divider. | YES | `number` | | end | The y-axis coordinate of the end of the divider end-start is the width of the divider. | YES | `number` | | width | The width of the line. | YES | `number` | | count | The number of dividers. | YES | `number` | | color | The color of the dividing line. | YES | `number` | ### YLine: object | Properties | Description | Required | Type | | ------------ | ------------------------------------------------------------------------------------- | -------- | -------- | | pading | Margin of dividing line based on y-axis. | YES | `number` | | space | The interval of the dividing line. | YES | `number` | | start | The x-axis coordinates of the start of the divider. | YES | `number` | | end | The x-axis coordinate of the end of the divider end-start is the width of the divider. | YES | `number` | | width | The width of the line. | YES | `number` | | count | The number of dividers. | YES | `number` | | color | The color of the dividing line. | YES | `number` | ### XText: object | Properties | Description | Required | Type | | ---------- | ------------------------------------------------------------------------------ | -------- | --------------- | | x | The initial x-coordinate of the text. | YES | `number` | | y | The initial y-coordinate of the text. | YES | `number` | | w | The width of the text. | YES | `number` | | h | The height of the text. | YES | `number` | | space | The spacing of the text.The x-coordinate of the nth text = x + (w + space)\*(n - 1). | YES | `number` | | color | The color of the text | YES | `number` | | data_array | The array of text. | YES | `Array` | | count | The length of the array. | YES | `number` | ### yText: object | Properties | Description | Required | Type | | ---------- | ------------------------------------------------------------------------------ | -------- | --------------- | | x | The initial x-coordinate of the text. | YES | `number` | | y | The initial y-coordinate of the text. | YES | `number` | | w | The width of the text. | YES | `number` | | h | The height of the text. | YES | `number` | | space | The spacing of the text.The x-coordinate of the nth text = y + (h + space)\*(n - 1). | YES | `number` | | color | The color of the text | YES | `number` | | data_array | The array of text. | YES | `Array` | | count | The length of the array. | YES | `number` | ## Update item data ```js const view = ......; view.setProperty(prop.UPDATE_DATA, { data_array: [100, 100, 0, 0, 0, 100], data_count: 6 }) ``` ## Code example ```js Page({ build() { const fillRect = createWidget(widget.FILL_RECT, { x: 100, y: 120, w: 300, h: 300, color: 0xffffff }) const view = createWidget(widget.HISTOGRAM, { x: 100, y: 120, h: 300, w: 300, item_width: 20, item_space: 10, item_radius: 10, item_start_y: 50, item_max_height: 230, item_color: 0x304ffe, data_array: [20, 30, 40, 50, 60, 100, 80, 90, 20, 30], data_count: 10, data_min_value: 10, data_max_value: 100, xline: { pading: 20, space: 20, start: 0, end: 300, color: 0x00c853, width: 1, count: 15 }, yline: { pading: 10, space: 10, start: 0, end: 300, color: 0xff6d00, width: 1, count: 30 }, xText: { x: 12, y: 270, w: 20, h: 50, space: 10, align: align.LEFT, color: 0x000000, count: 10, data_array: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'] }, yText: { x: 0, y: 20, w: 50, h: 50, space: 10, align: align.LEFT, color: 0x000000, count: 6, data_array: ['a', 'b', 'c', 'd', 'e', 'f'] } }) } }) ``` --- ## POLYLINE ### Import ```js import { createWidget, widget } from '@zos/ui' ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). [Image: polyline] Draws polylines that can be done on a line graph with multiple segments. ## Create UI widget ```js const polyline = createWidget(widget.GRADKIENT_POLYLINE, Param) ``` ## Type ### Param: object | Properties | Description | Required | Type | | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------- | -------- | | x | The x-coordinate of widget. | YES | `number` | | y | The y-coordinate of widget. | YES | `number` | | w | The width of widget. | YES | `number` | | h | Widget height, the maximum height on a circular screen with a screen height of `480` and a square device with a screen height of `390` is `150`, and the maximum height of other models is scaled proportionally according to the screen height. | YES | `number` | | line_color | Line color, default `0xe60039` | NO | `number` | | line_width | Line width, default `2` px | NO | `number` | ### polyline instance #### polyline.clear() ```ts () => void ``` Clear drawn lines #### polyline.addLine() ```ts (option: Option) => void ``` ##### Option: object | Properties | Description | Type | Version | | ----------- | ---------------------------------------------------- | ----------------- | ------- | | data | Coordinate arrays | `Array` | - | | count | Coordinate array length | `number` | - | | color_from | Initial fill gradient color | `number` | 2.1 | | color_to | End fill gradient color | `number` | 2.1 | | curve_style | Whether to use interpolation, smoothing curve effect | `boolean` | 2.1 | ##### AxisItem: object | Properties | Description | Type | | ---------- | --------------------------------------------------------------------------------------- | -------- | | x | Horizontal coordinates, relative coordinates, distance from the left side of the widget | `number` | | y | Vertical coordinates, relative coordinates, distance from the bottom of the widget | `number` | ## Supported Property Access List | Property | setProperty | getProperty | [setter](https://docs.zepp.com/docs/reference/device-app-api/newAPI/ui/gettersetter) | [getter](https://docs.zepp.com/docs/reference/device-app-api/newAPI/ui/gettersetter) | |-------------|-------------|-------------|-------------------------------|-------------------------------| | x | N | Y | N | Y | | y | N | Y | N | Y | | w | N | Y | N | Y | | h | N | Y | N | Y | | line_color | N | N | N | N | | line_width | N | N | N | N | | bg_color | N | N | N | N | ## Code example ```js Page({ build() { const lineDataList = [ { x: 0, y: px(120) }, { x: px(100), y: px(10) }, { x: px(200), y: px(50) }, { x: px(300), y: px(50) }, { x: px(400), y: px(150) } ] const polyline = createWidget(widget.GRADKIENT_POLYLINE, { x: 0, y: px(200), w: px(480), h: px(150), line_color: 0x00ffff, line_width: 4 }) polyline.clear() polyline.addLine({ data: lineDataList, count: lineDataList.length }) } }) ``` --- ## CANVAS ### Import ```js import { createWidget, widget } from '@zos/ui' ``` > Start from API_LEVEL `3.0`. Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility)。 [Image: canvas_demo.jpg] Canvas Current Canvas capabilities include 1. Basic drawing, line, point, rectangle, rectangle fill, ellipse, sector, polygon 1. Image drawing 1. Text drawing 1. Paint 1. The canvas is stacked vertically, up to three layers can be stacked 1. Clean up the canvas 1. Support `addEventListener` method to listen for user interaction events ## Create UI widget ```js const canvas = createWidget(widget.CANVAS, Param) ``` ### Param: object | Properties | Description | Required | Type | | ---------- | -------------------- | -------- | -------- | | x | Canvas x coordinates | YES | `number` | | y | Canvas y coordinates | YES | `number` | | w | Canvas canvas width | YES | `number` | | h | Canvas canvas height | YES | `number` | ```js const canvas = createWidget(widget.CANVAS, { x: 0, y: 0, w: 100, h: 100 }) ``` ## canvas.setPaint Set Paint ```js setPaint(Param: object): void ``` #### Param: object | Properties | Description | Required | Type | | ---------- | ----------- | -------- | -------- | | color | Color | YES | `number` | | line_width | Line Width | YES | `number` | ```js canvas.setPaint({ color: 0xff0000, line_width: 10 }) ``` ## canvas.drawPixel Drawing individual pixel point ```js drawPixel(Param: object): void ``` #### Param: object | Properties | Description | Required | Type | | ---------- | ------------- | -------- | -------- | | x | x coordinates | YES | `number` | | y | y coordinates | YES | `number` | | color | Color | NO | `number` | ```js canvas.drawPixel({ x: 0, y: 0, color: 0xffffff }) ``` ## canvas.drawLine Draws a line segment, with the line width and color set by `setPaint` paint ```js drawLine(Param: object): void ``` #### Param: object | Properties | Description | Required | Type | | ---------- | ------------------------- | -------- | -------- | | x1 | Start point x coordinates | YES | `number` | | y1 | Start point y coordinates | YES | `number` | | x2 | End point x coordinates | YES | `number` | | y2 | End point y coordinates | YES | `number` | | color | Color | NO | `number` | ```js canvas.drawLine({ x1: 100, y1: 100, x2: 200, y2: 100, color: 0xffffff }) ``` ## Rectangle 1. Draw a rectangle path with line width and color set using the `setPaint` brush ```js strokeRect(Param: object): void ``` 2. Draw rectangle fill ```js drawRect(Param: object): void ``` #### Param: object | Properties | Description | Required | Type | | ---------- | ------------------------- | -------- | -------- | | x1 | Start point x coordinates | YES | `number` | | y1 | Start point y coordinates | YES | `number` | | x2 | End point x coordinates | YES | `number` | | y2 | End point y coordinates | YES | `number` | | color | Color | NO | `number` | ```js canvas.drawRect({ x1: 60, y1: 20, x2: 120, y2: 60, color: 0xff00ff }) ``` ## Circle 1. Draw a circle path with line width and color set using the `setPaint` brush ```js strokeCircle(Param: object): void ``` 2. Draw circle fill ```js drawCircle(Param: object): void ``` #### Param: object | Properties | Description | Required | Type | | ---------- | -------------------- | -------- | -------- | | center_x | Center x coordinates | YES | `number` | | center_y | Center y coordinates | YES | `number` | | radius | Radius | YES | `number` | | color | Color | NO | `number` | ```js canvas.drawCircle({ center_x: 80, center_y: 140, radius: 40, color: 0xfff400 }) ``` ## Ellipse 1. Draw a ellipse path with line width and color set using the `setPaint` brush ```js strokeEllipse(Param: object): void ``` 2. Draw ellipse fill ```js drawEllipse(Param: object): void ``` #### Param: object | Properties | Description | Required | Type | | ---------- | ---------------------------- | -------- | -------- | | center_x | Ellipse center x coordinates | YES | `number` | | center_y | Ellipse center y-coordinate | YES | `number` | | radius_x | x-directional axis radius | YES | `number` | | radius_y | y-directional axis radius | YES | `number` | | color | Color | NO | `number` | ```js canvas.drawEllipse({ center_x: 80, center_y: 300, radius_x: 60, radius_y: 80, color: 0xff0000 }) ``` ## Arc Compared to `drawEllipse`, `start_angle` and `end_angle` are added to intercept a part of the ellipse from the center of the ellipse as a sector. 1. Draw path ```js strokeArc(Param: object): void ``` 2. Draw fill ```js drawArc(Param: object): void ``` #### Param: object | Properties | Description | Required | Type | | ----------- | -------------------------------------------------- | -------- | -------- | | center_x | Ellipse center x coordinates | YES | `number` | | center_y | Ellipse center y-coordinate | YES | `number` | | radius_x | x-directional axis radius | YES | `number` | | radius_y | y-directional axis radius | YES | `number` | | start_angle | Start angle (0 degrees in the 3 o'clock direction) | YES | `number` | | end_angle | Start angle (0 degrees in the 3 o'clock direction) | YES | `number` | | color | Color | NO | `number` | ```js canvas.drawArc({ center_x: 280, center_y: 200, radius_x: 60, radius_y: 80, start_angle: -150, end_angle: -30, color: 0xfff400 }) ``` ## Polygon 1. Draw a polygon path with line width and color set using the `setPaint` brush ```js strokePoly(Param: object): void ``` 2. Draw polygon fill ```js drawPoly(Param: object): void ``` #### Param: object | Properties | Description | Required | Type | | ---------- | ---------------------------------------------- | -------- | ------------ | | data_array | An array of coordinates of at least '3' length | YES | `Coordinate` | | color | Color | NO | `number` | #### Coordinate | Properties | Description | Type | | ---------- | ------------ | -------- | | x | x coordinates | `number` | | y | y coordinates | `number` | ```js const coordinateArray = [ { x: 233, y: 30 }, { x: 130, y: 230 }, { x: 400, y: 200 }, { x: 233, y: 30 } ] canvas.strokePoly({ data_array: coordinateArray color: 0x00ffff, }) ``` ## canvas.drawText Drawing text ```js drawText(Param: object): void ``` #### Param: object | Properties | Description | Required | Type | | ---------- | ------------------ | -------- | -------- | | x | Text x Coordinates | YES | `number` | | y | Text y Coordinates | YES | `number` | | text | Text Content | YES | `string` | | text_size | Text Size | YES | `number` | | color | Color | NO | `number` | ```js canvas.drawText({ x: 200, y: 260, text_size: 30, text: 'Hello Zepp OS' }) ``` ## canvas.drawImage Drawing Image ```js drawImage(Param: object): void ``` #### Param: object | Properties | Description | Required | Type | | ---------- | --------------------------------------------- | -------- | -------- | | x | Image x Coordinates | YES | `number` | | y | Image y Coordinates | YES | `number` | | w | Image width | YES | `number` | | h | Image height | YES | `number` | | image | Image path | YES | `string` | | alpha | Transparency [0-255], 0 for full transparency | NO | `number` | ```js canvas.drawImage({ x: 0, y: 0, w: 466, h: 466, alpha: 255, image: 'images/canvas/background.png' }) ``` ## canvas.clear Clean up the canvas by rectangular area ```js clear(Param: object): void ``` #### Param: object | Properties | Description | Required | Type | | ---------- | ----------------------- | -------- | -------- | | x | Rectangle x Coordinates | YES | `number` | | y | Rectangle y Coordinates | YES | `number` | | w | Rectangle area width | YES | `number` | | h | Rectangle area height | YES | `number` | ```js canvas.clear({ x: 400, y: 0, w: 64, h: 64 }) ``` ## Interaction events Canvas supports `widget.addEventListener` to listen for interaction events, see [widget.addEventListener(eventId, callback)](https://docs.zepp.com/docs/reference/device-app-api/newAPI/ui/addEventListener) ```js canvas.addEventListener(event.CLICK_UP, function cb(info) { console.log(info.x) console.log(info.y) }) ``` --- ## PAGE_INDICATOR ### Import ```js import { createWidget, widget } from '@zos/ui' ``` > Start from API_LEVEL `2.1` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). When a page is set to Swiper scroll mode using the `@zos/page setScrollMode` method, an indicator control is created on the page to indicate the total number of pages and to indicate which page is currently stopped. ## Create UI widget ```js const pageIndicator = createWidget(widget.PAGE_INDICATOR, Param) ``` ## Type ### Param: object | Properties | Description | Required | Type | API_LEVEL | | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------- | --------- | --------- | | x | The x-axis coordinate of the widget. | YES | `number` | 2.1 | | y | The y-axis coordinate of the widget. | YES | `number` | 2.1 | | w | The width of the widget. | YES | `number` | 2.1 | | h | The height of the widget. | YES | `number` | 2.1 | | align_h | The alignment of the horizontal axis (see ALIGN for values). | NO | `ALIGN` | 2.1 | | h_space | Horizontal spacing | NO | `number` | 2.1 | | v_space | Vertical spacing | NO | `number` | 3.0 | | select_src | Indicator current page highlight image path, resource storage path reference [Folder Structure](https://docs.zepp.com/docs/guides/architecture/folder-structure) | YES | `string` | 2.1 | | unselect_src | Indicator non-current page highlight image path, resource storage path reference [Folder Structure](https://docs.zepp.com/docs/guides/architecture/folder-structure) | YES | `string` | 2.1 | | horizontal | Horizontal or not, default is `true`, set `false` for vertical layout | NO | `boolean` | 3.0 | | use_color | Whether to use colors to configure indicator dots | NO | `boolean` | 4.0 | | select_color | Selected color configuration | NO | `number` | 4.0 | | unselect_color | Unselected color configuration | NO | `number` | 4.0 | | element_height | Width of the page indicator element | NO | `number` | 4.0 | | element_radius | Height of the page indicator element | NO | `number` | 4.0 | ### ALIGN alignment | Value | Description | | -------------- | ----------------------------- | | align.LEFT | Horizontal axis-left aligned. | | align.RIGHT | Horizontal axis-align right. | | align.CENTER_H | Horizontal axis-centered. | ## Code Example ```js Page({ build() { const itemCount = 10 const pageSize = px(480) setScrollMode({ mode: SCROLL_MODE_SWIPER_HORIZONTAL, options: { height: pageSize, count: itemCount } }) const pageIndicator = createWidget(widget.PAGE_INDICATOR, { x: 0, y: px(470), w: px(480), h: px(10), align_h: align.CENTER_H, h_space: 8, select_src: 'images/test/select/select.png', unselect_src: 'images/test/select/unselect.png' }) for (let i = 0; i < itemCount; i++) { let xPos = 0 let yPos = px(400) + pageSize * i createWidget(widget.TEXT, { x: xPos, y: yPos, w: px(480), h: px(120), text_size: 35, color: 0xffffff, align_h: align.CENTER_H, text: `PAGE ${i}` }) } } }) ``` ## Additional Examples ### Example 1 ```js const pageCount = 10 const vertical = false const pageSize = 480 setScrollMode({ mode: vertical ? SCROLL_MODE_SWIPER : SCROLL_MODE_SWIPER_HORIZONTAL, options: { count: pageCount, height: vertical ? pageSize : undefined, width: vertical ? undefined : pageSize, }, }) createWidget(widget.PAGE_INDICATOR, { x: 0, y: 470, w: 480, h: 100, align_h: align.CENTER_H, h_space: 8, select_src: 'images/test/select/select.png', unselect_src: 'images/test/select/unselect.png', }) for (let i = 0; i < pageCount; i += 1) { const xPos = vertical ? 0 : pageSize * i const yPos = vertical ? 400 + pageSize * i : 400 createWidget(widget.TEXT, { x: xPos, y: yPos, w: 480, h: 120, text_size: 35, color: 0xffffff, align_h: align.CENTER_H, text: `PAGE ${i}`, }) } ``` --- ## PAGE_SCROLLBAR ### Import ```js import { createWidget, widget } from '@zos/ui' ``` > Start from API_LEVEL `3.0`. Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility)。 Page Scrollbar. ## Create UI widget ```js const scrollBar = createWidget(widget.PAGE_SCROLLBAR, Param) ``` ### Param: object | Properties | Description | Required | Type | | ------ | ---------------------------------------------------- | -------- | -------- | | target | The `VIEW_CONTAINER` widget that needs to be bound is the whole page scroll bar by default, and the `VIEW_CONTAINER` scroll bar is passed in | NO | `object` | ## Code example ```js const scrollBar = createWidget(widget.PAGE_SCROLLBAR) ``` ## Additional Examples ### Example 1 ```js const vc0 = createWidget(widget.VIEW_CONTAINER, { x: 0, y: 0, w: 466, h: 466, }) const scrollVer = createWidget(widget.PAGE_SCROLLBAR, {}) scrollVer.setProperty(prop.TARGET, vc0) ``` --- ## SPORT_DATA ### Import ```js import { createWidget, widget } from '@zos/ui' ``` > Start from API_LEVEL `3.6` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Displaying workout data in the workout extension can display a rich variety of workouts data types. ## Create UI widget ```js const sportData = createWidget(widget.SPORT_DATA, Param) ``` ### Param: object | Properties | Description | Required | Type | | ---------------- | ----------------------------------------------------------------------------------------------------------------------- | -------- | --------- | | x | Widget x coordinate | YES | `number` | | y | Widget y coordinate | YES | `number` | | w | Widget display width | YES | `number` | | h | Widget display height | YES | `number` | | edit_id | Widget ID, ensuring uniqueness of each instance | YES | `number` | | category | Data type, currently only supports `edit_widget_group_type.SPORTS` | YES | `number` | | default_type | Displayed data items, see supported data items below | YES | `number` | | text_size | Text font size, default `36` px | NO | `number` | | text_color | Text color, default `0x0000FF` | NO | `number` | | sub_text_visible | Whether to display subtext, default is `false` | NO | `boolean` | | sub_text_size | Subtext font size, default `36` px | NO | `number` | | sub_text_color | Subtext color, default `0x0000FF` | NO | `number` | | rect_visible | Whether to display the text box, default is `false` | NO | `boolean` | | line_color | Text box color, default `0x0000FF` | NO | `number` | | text_x | Relative coordinates.Text box displays location x coordinates | NO | `number` | | text_y | Relative coordinates.Text box displays position y coordinates | NO | `number` | | text_w | Text box width | NO | `number` | | text_h | Text box height | NO | `number` | | sub_text_x | Relative coordinates.Subtext box displays position x coordinates | NO | `number` | | sub_text_y | Relative coordinates.Subtext box displays position y coordinates | NO | `number` | | sub_text_w | Secondary text box width | NO | `number` | | sub_text_h | Secondary text box height | NO | `number` | | mock_data | The simulated data only takes effect in the emulator, and the data items of the widget will display the incoming string | NO | `string` | ### Data item type Data item types are accessed through the `sport_data` object of the `@zos/ui` module | Data item Key | Description | | ----------------------------- | ---------------------------------------------- | | DURATION_NET | Exercise time | | DURATION_CUR_SECTION | This segment time | | DURATION_PREV_SECTION | Previous segment time | | DURATION_AVG_SECTION | Average segment time | | DURATION_CUR_GROUP | This set time | | DISTANCE_TOTAL | Distance | | DISTANCE_CUR_SECTION | This segment distance | | DISTANCE_PREV_SECTION | Previous segment distance | | COUNT_TOTAL | Total count | | COUNT_CUR_ROPE | This set count | | COUNT_BROKEN_ROPE | Number of broken ropes | | COUNT_TOTAL_BOAT | Total strokes | | COUNT_CUR_BOAT | This set strokes | | COUNT_CUR_FITNESS | This set count | | GLIDE_COUNT | Number of descents | | GLIDE_TOTAL_DISTANCE | Cumulative descent distance | | GLIDE_CUR_DISTANCE | This descent distance | | GLIDE_TOTAL_ALTITUDE | Cumulative descent drop | | GLIDE_CUR_ALTITUDE | This descent drop | | CLIMB_UP_FLOORS | Floors ascended | | CLIMB_UP_CUR_FLOORS | This segment floors ascended | | CLIMB_UP_PREV_FLOORS | Previous segment floors ascended | | CLIMB_DOWN_FLOORS | Floors descended | | CLIMB_DOWN_CUR_FLOORS | This segment floors descended | | CLIMB_DOWN_PREV_FLOORS | Previous segment floors descended | | CLIMB_UP_FLOORS_IN_MIN | Floors ascended per minute | | CLIMB_UP_TOTAL_ALTITUDE | Ascent height | | CLIMB_UP_CUR_ALTITUDE | This segment ascent height | | CLIMB_UP_PREV_ALTITUDE | Previous segment ascent height | | CLIMB_DOWN_ALTITUDE_TOTAL | Descent height | | CLIMB_DOWN_CUR_ALTITUDE | This segment descent height | | CLIMB_DOWN_PREV_ALTITUDE | Previous segment descent height | | SWIM_TOTAL_LAPS | Number of trips | | SWIM_CUR_LAPS | This segment trips | | SWIM_PREV_LAPS | Previous segment trips | | SWIM_TOTAL_STROKE_count | Total paddle strokes | | SWIM_CUR_STROKE_count | This segment paddle strokes | | SWIM_PREV_STROKE_count | Previous segment paddle strokes | | SWIM_AVG_STROKE_DISTANCE | Average paddle distance | | SWIM_AVG_SECTION_STROKE_count | Average paddle strokes per segment | | SWIM_STROKE_SPEED | Paddle stroke rate | | SWIM_CUR_STROKE_SPEED | This segment paddle stroke rate | | SWIM_PREV_STROKE_SPEED | Previous segment paddle stroke rate | | SWIM_AVG_STROKE_SPEED | Average paddle stroke rate | | SWIM_AVG_SWOLF | Average Swolf | | SWIM_CUR_SWOLF | This segment Swolf | | SWIM_PREV_SWOLF | Previous segment Swolf | | PACE | Pace | | PACE_AVG | Average pace | | PACE_CUR_AVG | This segment pace | | PACE_PREV_AVG | Previous segment pace | | STRIDE_FREQ | Cadence | | STRIDE_AVG_FREQ | Average cadence | | STRIDE_CUR_FREQ | This segment cadence | | STRIDE_PREV_FREQ | Previous segment cadence | | STRIDE | Stride length | | STRIDE_AVG | Average stride length | | STRIDE_CUR | This segment stride length | | STRIDE_PREV | Previous segment stride length | | STRIDE_COUNT | Steps | | SPEED | Speed | | SPEED_AVG | Average speed | | SPEED_AVG_GLIDE | Average descent speed | | SPEED_PREV_GLIDE | Previous descent speed | | SPEED_CUR_SECTION | This segment speed | | SPEED_PREV_SECTION | Previous segment speed | | SPEED_MAX | Maximum speed | | SPEED_VERTICAL | Vertical speed | | ALTITUDE | Altitude | | ALTITUDE_MAX | Maximum altitude | | ALTITUDE_MIN | Minimum altitude | | ALTITUDE_AVG | Average altitude | | SLOPE_TOTAL_RISING_DISTANCE | Cumulative ascent | | SLOPE_CUR_RISING_DISTANCE | This segment ascent | | SLOPE_PREV_RISING_DISTANCE | Previous segment ascent | | ALTITUDE_TOTAL_UP | Cumulative ascent | | ALTITUDE_CUR_UP | This segment ascent | | ALTITUDE_PREV_UP | Previous segment ascent | | ALTITUDE_TOTAL_DOWN | Cumulative descent | | ALTITUDE_CUR_DOWN | This segment descent | | ALTITUDE_PREV_DOWN | Previous segment descent | | SLOPE | Gradient | | SLOPE_AVG | Average gradient | | SLOPE_CUR | This segment gradient | | SLOPE_PREV | Previous segment gradient | | SLOPE_GLIDE | Glide ratio | | SLOPE_AVG_GLIDE | Average glide ratio | | SLOPE_CUR_GLIDE | This segment glide ratio | | SLOPE_PREV_GLIDE | Previous segment glide ratio | | BRANDISH_TOTAL_count | Total shots | | BRANDISH_POSITIVE_count | Forehand shots | | BRANDISH_NEGATIVE_count | Backhand shots | | BRANDISH_SERVE_count | Serves | | CONSUME | Consumption | | CONSUME_CUR | This set consumption | | BOATING_FREQ | Stroke rate | | BOATING_AVG_FREQ | Average stroke rate | | BOATING_CUR_FREQ | This set average stroke rate | | BOATING_PULL | Pull time | | BOATING_PUSH | Recovery time | | FREQ | Frequency | | FREQ_AVG | Average frequency | | FREQ_CUR | This set average frequency | | GOLF_SPEED | Hand speed | | GOLF_ANGLE | Plane | | GOLF_UP_TIME | Upstroke time | | GOLF_DOWN_TIME | Downstroke time | | GOLF_BEAT | Rhythm | | GOLF_SWING_COUNTER_GROUP | This set strokes | | GOLF_SWING_COUNTER | Total strokes | | GOLF_AVG_SCORE | Average score | | GOLF_SCORE | Score | | HR | Heart rate | | HR_AVG | Average heart rate | | HR_CUR_AVG | This set average heart rate | | HR_INTERVAL | Heart rate zone | | HR_MAX_PERCENT | Maximum heart rate percentage | | HR_RESERVED_PERCENT | Reserve heart rate percentage | | HR_AVG_MAX_PERCENT | Average maximum heart rate percentage | | HR_AVG_RESERVED_PERCENT | Average reserve heart rate percentage | | HR_CUR_SECTION | This segment heart rate | | HR_CUR_MAX_PERCENT | This segment maximum heart rate percentage | | HR_CUR_RESERVED_PERCENT | This segment reserve heart rate percentage | | HR_PREV_SECTION | Previous segment heart rate | | HR_PREV_MAX_PERCENT | Previous segment maximum heart rate percentage | | HR_PREV_RESERED_PERCENT | Previous segment reserve heart rate percentage | | PRESSURE | Pressure | | PRESSURE_AVG | Average pressure | | PRESSURE_CUR | This segment pressure | | PRESSURE_PREV | Previous segment pressure | | TEMP | Temperature | | TEMP_MAX | Maximum temperature | | TEMP_MIN | Minimum temperature | | OTHER_SECTION_ORDER | Current set | | OTHER_AEROBIC_TE | Aerobic TE | | OTHER_ANAEROBIC_TE | Anaerobic TE | | OTHER_TRAIN_LOAD | Training load | | OTHER_CUR_TIME | Current time | | OTHER_SUNRISE_TIME | Sunrise time | | OTHER_SUNSET_TIME | Sunset time | | OTHER_BORAMETER | Barometric pressure | | OTHER_ACTIONNAME | Movement name | | CHART_HR | Heart rate graph | | CHART_SPEED | Speed graph | | CHART_STROKE_FREP | Stroke rate graph | | CHART_TE | Training effect graph | | CHART_STROKE_SPEED | Paddle stroke rate graph | | CHART_PACE | Pace graph | | CHART_ALTITUDE | Altitude graph | | CHART_FREQ | Frequency graph | | DEVICE_POWER | Power | | DEVICE_POWER_WEIGHT | Power-to-weight ratio | | DEVICE_WORK | Work | | DEVICE_AVG_POWER | Average power | | DEVICE_MAX_POWER | Maximum power | | DEVICE_3S_AVG_POWER | 3s average power | | DEVICE_10S_AVG_POWER | 10s average power | | DEVICE_30S_AVG_POWER | 30s average power | | DEVICE_LAP_AVG_POWER | This segment power | | DEVICE_PREV_AVG_POWER | Previous segment power | | DEVICE_CADENCE | Cadence | | DEVICE_FAST_CADENCE | Maximum cadence | | DEVICE_AVG_CADENCE | Average cadence | | DEVICE_LAP_AVG_CADENCE | This segment cadence | | DEVICE_PREV_AVG_CADENCE | Previous segment cadence | | DURATION_GLIDE | Descent time | | DURATION_TOTAL_CLIMB | Ascent time | | GLIDE_PREV_DISTANCE | Previous descent distance | | GLIDE_PREV_ALTITUDE | Previous descent drop | | SPEED_MAX_GLIDE | Maximum descent speed | | SLOPE_GLIDE_MAX | Maximum descent gradient | | SLOPE_GLIDE_AVG | Average descent gradient | | GLIDE_ANGLE_MAX | Maximum descent angle | | GLIDE_ANGLE_AVG | Average descent angle | | DURATION_SURFACE | Time on water | | DURATION_CUR_DIVING | This dive time | | DURATION_PREV_DIVING | Previous dive time | | COUNT_DIVING | Number of dives | | COUNT_CAUGHT | Catch count | | SPEED_DIVING | Dive speed | | DEPTH | Depth | | DEPTH_AVG | Average depth | | DEPTH_MAX | Maximum depth | | DEPTH_MAX_PREV | Previous dive depth | | HEIGHT | Elevation | | DESENT_SPEED | Descent rate | | DESENT_SPEED_MAX | Maximum descent rate | | DESENT_SPEED_AVG | Average descent rate | | SKYDIVING_HEIGHT | Parachute jump height | | COUNT_CONTINUOUS_ROPE | Maximum consecutive jumps | ## Code example ```js createWidget(widget.SPORT_DATA, { edit_id: 1, category: edit_widget_group_type.SPORTS, default_type: sport_data.CONSUME, x: 50, y: 200, w: 380, h: 80 }) ``` ## Additional Examples ### Example 1 ```js createWidget(widget.SPORT_DATA, { x: 60, y: 120, w: 360, h: 120, edit_id: 1, category: edit_widget_group_type.SPORTS, default_type: sport_data.DURATION_NET, line_color: 0x0000ff, text_size: 36, text_color: 0xffffff, text_x: 24, text_y: 16, text_w: 312, text_h: 40, }) ``` --- --- # @zos/ui-widget-form Form widget APIs. ## RADIO_GROUP ### Import ```js import { createWidget, widget } from '@zos/ui' ``` > Start from API_LEVEL `2.0`. Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). [Image: radio_group_sample] Used to select a single option among multiple options. Each individual option is a `STATE_BUTTON` widget that needs to be created separately. ## Create UI Widget ```js const radioGroup = createWidget(widget.RADIO_GROUP, radioGroupParam) const stateButton = createWidget(widget.STATE_BUTTON, stateButtonParam) ``` ## Types ### radioGroupParam: object | Properties | Description | Required | Type | API_LEVEL | | ------------ | ----------------------------------------- | -------- | ----------- | --------- | | x | The x-coordinate of the widget | YES | `number` | 2.0 | | y | The y-coordinate of the widget | YES | `number` | 2.0 | | w | Width of the widget | YES | `number` | 2.0 | | h | Height of the widget | YES | `number` | 2.0 | | select_src | Image displayed when widget is selected | YES | `string` | 2.0 | | unselect_src | Image displayed when widget is unselected | YES | `string` | 2.0 | | check_func | Callback when button state changes | NO | `CheckFunc` | 2.0 | | use_color | Whether to display widget using colors | NO | `boolean` | 4.0 | ### CheckFunc: function ```js (radioGroup: RadioGroup, index: number, checked: boolean) => void ``` | Parameters | Description | Type | | ---------- | --------------------------- | ------------ | | radioGroup | The radioGroup instance | `RadioGroup` | | index | Index of the option | `number` | | checked | Whether selected | `boolean` | ### StateButton: object | Properties | Description | Required | Type | API_LEVEL | | -------------- | ------------------------------------------------------------ | -------- | -------- | --------- | | x | The x-coordinate relative to radioGroup | YES | `number` | 2.0 | | y | The y-coordinate relative to radioGroup | YES | `number` | 2.0 | | w | Width of the widget | YES | `number` | 2.0 | | h | Height of the widget | YES | `number` | 2.0 | | select_color | Color when selected | NO | `number` | 4.0 | | unselect_color | Color when unselected | NO | `number` | 4.0 | | fill_width | Button color display area width | NO | `number` | 4.0 | | fill_height | Button color display area height | NO | `number` | 4.0 | > **⚠️ Caution** > > The widget must be initialized once with `prop.INIT` to render the view ### Prop Properties | Properties | Support get/set | Type | Notes | | ---------------- | -------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------- | | `prop.INIT` | set | `object` | Initialize the component and set the default selected item | | `prop.CHECKED` | set/get | `object` | Set the selected child widget to selected state, or get the selected state of the child widget, the value type is `boolean` | | `prop.UNCHECKED` | get | `object` | Set the selected child widget to unselected state, or get the selected state of the child widget, the value type is `boolean` | ## Property Access Support List ### RADIO_GROUP | Property Name | setProperty | getProperty | [setter](https://docs.zepp.com/docs/reference/device-app-api/newAPI/ui/gettersetter) | [getter](https://docs.zepp.com/docs/reference/device-app-api/newAPI/ui/gettersetter) | | ------------ | ----------- | ----------- | ----------------------------- | ----------------------------- | | x | Y | Y | Y | Y | | y | Y | Y | Y | Y | | w | Y | Y | Y | Y | | h | Y | Y | Y | Y | | select_src | N | N | N | N | | unselect_src | N | N | N | N | | check_func | N | N | N | N | | use_color | N | N | N | N | ### STATE_BUTTON | Property Name | setProperty | getProperty | [setter](https://docs.zepp.com/docs/reference/device-app-api/newAPI/ui/gettersetter) | [getter](https://docs.zepp.com/docs/reference/device-app-api/newAPI/ui/gettersetter) | | -------------- | ----------- | ----------- | ----------------------------- | ----------------------------- | | x | Y | Y | Y | Y | | y | Y | Y | Y | Y | | w | Y | Y | Y | Y | | h | Y | Y | Y | Y | | select_color | N | N | N | N | | unselect_color | N | N | N | N | | fill_width | N | N | N | N | | fill_height | N | N | N | N | ## Code Example > **💡 Tip** > > Please refer to [Design Resources](https://docs.zepp.com/docs/reference/related-resources/design-resources) for the image resources in the code example ```js Page({ build() { const radioGroup = createWidget(widget.RADIO_GROUP, { x: 0, y: 0, w: 480, h: 64, select_src: 'selected.png', unselect_src: 'unselected.png', check_func: (group, index, checked) => { console.log('index', index) console.log('checked', checked) } }) const button1 = radioGroup.createWidget(widget.STATE_BUTTON, { x: 40, y: 200, w: 64, h: 64 }) const button2 = radioGroup.createWidget(widget.STATE_BUTTON, { x: 190, y: 200, w: 64, h: 64 }) const button3 = radioGroup.createWidget(widget.STATE_BUTTON, { x: 340, y: 200, w: 64, h: 64 }) radioGroup.setProperty(prop.INIT, button3) } }) ``` --- ## CHECKBOX_GROUP ### Import ```js import { createWidget, widget } from '@zos/ui' ``` > Supported from API_LEVEL `2.0`. Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility) for API compatibility. [Image: check_group_sample] Used to select multiple options from a set of choices. Each option needs to be created using `STATE_BUTTON`. ## Create UI Widget ```js const checkGroup = createWidget(widget.CHECKBOX_GROUP, checkboxGroupParam) const stateButton = createWidget(widget.STATE_BUTTON, stateButtonParam) ``` ## Types ### checkboxGroupParam: object | Properties | Description | Required | Type | API_LEVEL | | ------------ | --------------------------------------- | -------- | ----------- | --------- | | x | The x-coordinate of the widget | YES | `number` | 2.0 | | y | The y-coordinate of the widget | YES | `number` | 2.0 | | w | The width of the widget | YES | `number` | 2.0 | | h | The height of the widget | YES | `number` | 2.0 | | select_src | Image displayed when selected | YES | `string` | 2.0 | | unselect_src | Image displayed when unselected | YES | `string` | 2.0 | | check_func | Callback when button state changes | NO | `CheckFunc` | 2.0 | | use_color | Whether to display widget using colors | NO | `boolean` | 4.0 | ### CheckFunc: function ```js (checkboxGroup: CheckboxGroup, index: number, checked: boolean) => void ``` | Parameters | Description | Type | | ------------- | ------------------------------- | --------------- | | checkboxGroup | The `checkboxGroup` instance | `CheckboxGroup` | | index | Index of the option | `number` | | checked | Whether selected | `boolean` | ### StateButton: object | Properties | Description | Required | Type | API_LEVEL | | -------------- | ---------------------------------------------------- | -------- | -------- | --------- | | x | The x-coordinate relative to `radioGroup` | YES | `number` | 2.0 | | y | The y-coordinate relative to `radioGroup` | YES | `number` | 2.0 | | w | The width of the widget | YES | `number` | 2.0 | | h | The height of the widget | YES | `number` | 2.0 | | select_color | Color when selected | NO | `number` | 4.0 | | unselect_color | Color when unselected | NO | `number` | 4.0 | | fill_width | Button color display area width | NO | `number` | 4.0 | | fill_height | Button color display area height | NO | `number` | 4.0 | ### Prop Properties | Properties | Supports get/set | Type | Notes | | ------------------ | --------------- | -------- | ----------------------------------------------------------------------- | | `prop.INIT` | set | `object` | Initialize the widget and set default selected item | | `prop.CHECKED` | set/get | `object` | Set/get selected sub-widget state, returns boolean type when getting | | `prop.UNCHECKED` | set | `object` | Set sub-widget to unselected state | > **⚠️ Caution** > > The widget must be initialized once with `prop.INIT` to render the view. Currently, initialization only supports single option parameter passing. To initialize multiple options, use `prop.CHECKED` to set them. ## Property Access Support List ### CHECKBOX_GROUP | Property | setProperty | getProperty | [setter](https://docs.zepp.com/docs/reference/device-app-api/newAPI/ui/gettersetter) | [getter](https://docs.zepp.com/docs/reference/device-app-api/newAPI/ui/gettersetter) | | ------------ | ----------- | ----------- | ----------------------------- | ----------------------------- | | x | Y | Y | Y | Y | | y | Y | Y | Y | Y | | w | Y | Y | Y | Y | | h | Y | Y | Y | Y | | select_src | N | N | N | N | | unselect_src | N | N | N | N | | check_func | N | N | N | N | | use_color | N | N | N | N | ### STATE_BUTTON | Property | setProperty | getProperty | [setter](https://docs.zepp.com/docs/reference/device-app-api/newAPI/ui/gettersetter) | [getter](https://docs.zepp.com/docs/reference/device-app-api/newAPI/ui/gettersetter) | | -------------- | ----------- | ----------- | ----------------------------- | ----------------------------- | | x | Y | Y | Y | Y | | y | Y | Y | Y | Y | | w | Y | Y | Y | Y | | h | Y | Y | Y | Y | | select_color | N | N | N | N | | unselect_color | N | N | N | N | | fill_width | N | N | N | N | | fill_height | N | N | N | N | ## Code Example > **💡 Tip** > > Please refer to [Design Resources](https://docs.zepp.com/docs/reference/related-resources/design-resources) for the image resources in the code example ```js Page({ build() { const checkbox_group = createWidget(widget.CHECKBOX_GROUP, { x: 0, y: 0, w: 480, h: 64, select_src: 'selected.png', unselect_src: 'unselected.png', check_func: (group, index, checked) => { console.log('index', index) console.log('checked', checked) } }) const button1 = checkbox_group.createWidget(widget.STATE_BUTTON, { x: 40, y: 200, w: 64, h: 64 }) const button2 = checkbox_group.createWidget(widget.STATE_BUTTON, { x: 190, y: 200, w: 64, h: 64 }) const button3 = checkbox_group.createWidget(widget.STATE_BUTTON, { x: 340, y: 200, w: 64, h: 64 }) checkbox_group.setProperty(prop.INIT, button2) checkbox_group.setProperty(prop.CHECKED, button3) } }) ``` --- ## SLIDE_SWITCH ### Import ```js import { createWidget, widget } from '@zos/ui' ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). [Image: slide_switch_sample] Used to switch between open and closed states. ## Create UI widget ```js const slideSwitch = createWidget(widget.SLIDE_SWITCH, Param) ``` ## Type ### Param: object | Properties | Description | Required | Type | | ------------------- | -------------------------------------------------------------------- | -------- | ------------------- | | x | The x-axis coordinate of the widget. | YES | `number` | | y | The y-axis coordinate of the widget. | YES | `number` | | w | The width of the widget. | YES | `number` | | h | The height of the widget. | YES | `number` | | select_bg | The selected background. | YES | `string` | | un_select_bg | Unselected background. | YES | `string` | | slide_src | Switch button. | YES | `string` | | slide_select_x | Relative coordinates.The selected state of the switch button. | YES | `number` | | slide_un_select_x | Relative coordinates.The unselected state of the switch button. | YES | `number` | | slide_y | Relative coordinates.The y-axis offset of the switch button. | NO | `number` | | checked_change_func | Callback on state change. | NO | `CheckedChangeFunc` | | checked | Default switch state. | NO | `boolean` | ### CheckedChangeFunc: function ```js (slideSwitch: SlideSwitch, checked: boolean) => void ``` | Parameters | Description | Type | | ----------- | --------------------------- | ------------- | | slideSwitch | The instance of slideSwitch | `SlideSwitch` | | checked | checked or unchecked | `boolean` | ### Prop Properties | properties | description | support get/set | types | | ------------------- | --------------------------------- | --------------- | ---------------------------------------- | | `prop.CHECKED` | Set switch state.Get switch state | set/get | `boolean` returns bool type when you get | ## Code example > **💡 Tip** > > Please refer to [Design Resources](https://docs.zepp.com/docs/reference/related-resources/design-resources) for the image resources in the code example ```js Page({ build() { const slide_switch = createWidget(widget.SLIDE_SWITCH, { x: 200, y: 200, w: 96, h: 64, select_bg: 'switch_on.png', un_select_bg: 'switch_off.png', slide_src: 'radio_select.png', slide_select_x: 40, slide_un_select_x: 8, checked: true, checked_change_func: (slideSwitch, checked) => { console.log('checked', checked) } }) console.log('slide checked', slide_switch.getProperty(prop.CHECKED)) } }) ``` --- ## PICK_DATE ### Import ```js import { createWidget, widget } from '@zos/ui' ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). > **⚠️ Warning** > > After API_LEVEL 3.6, please use the [`TIME_PICKER`](https://docs.zepp.com/docs/reference/device-app-api/newAPI/ui/widget/TIME_PICKER) widget. [Image: pick_date] Time picker widget, providing user choice ## Create UI widget ```js const pickDate = createWidget(widget.PICK_DATE, Param) ``` ## Type ### Param: object | Properties | Description | Required | Type | | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------ | -------- | -------- | | x | x-coordinate (x \<= 0 will be centered by default) | YES | `number` | | y | y-coordinate | YES | `number` | | w | Width of the entire widget (width less than 1/2 of the device width will be determined as an exception, set to the default value of 300px) | NO | `number` | | padding_1 | padding between the first and second columns | NO | `number` | | padding_2 | padding between two and three columns | NO | `number` | | font_size | The size of the text on the widget, default 36 | NO | `number` | | startYear | Start year | NO | `number` | | endYear | End year | NO | `number` | | initYear | Initial year | NO | `number` | | initMonth | Initial month | NO | `number` | | initDay | Initial day | NO | `number` | | initHour | Initial hour | NO | `number` | | initMin | Initial minute | NO | `number` | ### `getProperty` supported Fields | Properties | Description | Type | | ---------- | ----------- | -------- | | year | Year | `number` | | month | Month | `number` | | day | Day | `number` | | hour | Hour | `number` | | minute | Minute | `number` | ## Code example ```js Page({ build() { const pick_date_date = createWidget(widget.PICK_DATE) pick_date_date.setProperty(prop.MORE, { w: 480, x: 20, y: 120, startYear: 2000, endYear: 2030, initYear: 2021, initMonth: 2, initDay: 3 }) const confirm = createWidget(widget.TEXT, { x: 0, y: 400, w: 480, h: 80, text_size: 42, color: 0xffffff, text: 'confirm' }) confirm.addEventListener(event.CLICK_UP, (info) => { const dateObj = pick_date_date.getProperty(prop.MORE, {}) const { year, month, day } = dateObj console.log('year', year) console.log('month', month) console.log('day', day) }) } }) ``` --- ## KEYBOARD ### Import ```js import { createWidget, widget, prop } from '@zos/ui' ``` > Start from API_LEVEL `3.0`. Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility)。 ## Create UI widget ```js const keyboard = createWidget(widget.KEYBOARD, Param) ``` ### Param: object | Properties | Description | Required | Type | | ---------- | ------------------------------------------------------------------------------------------------------- | -------- | ---------------- | | x | X position, default value is `0` | NO | `number` | | y | Y position, default value is `0` | NO | `number` | | click_func | Callback function when Key clicked | YES | `ClickFunc` | | key_attr | Key attributes, if no key attribute is passed in, the default configuration of numeric keyboard is used | NO | `Array` | #### ClickFunc: function ```ts click_func(keyboard: WIDGET, id: number, value: number): void ``` | Param | Description | | -------- | --------------------- | | keyboard | The keyboard instance | | id | Key id | | value | Key value | #### KeyAttr: object | Properties | Description | Required | Type | | ---------- | ---------------------------------------------------- | -------- | -------- | | id | Key id | NO | `number` | | x | X position of key | YES | `number` | | y | Y position of key | YES | `number` | | text | Key text, Only single ASCII characters are supported | NO | `string` | | image | Key image path, recommended image size is 64 x 64 px | NO | `string` | | value | Key value | NO | `number` | ## Property Operations Property operations are set via `widget.setProperty` ```js keyboard.setProperty(prop, Param) ``` ### `prop.ADD_KEY` Add a new key, Params refer to `KeyAttr` ```js keyboard.setProperty(prop.ADD_KEY, { id: 100, x: 280, y: 350, text: '!' }) ``` ### `prop.DEL_KEY` Delete a key #### Param: object | Properties | Description | Required | Type | | ---------- | ----------- | -------- | -------- | | id | Key id | NO | `number` | ```js keyboard.setProperty(prop.DEL_KEY, { id: 20 }) ``` ### `prop.KEY_PARA` Modify a key properties, Params refer to `KeyAttr` ```js keyboard.setProperty(prop.KEY_PARA, { id: 1, x: 50, y: 30, image: 'images/common/widgetsbc/phoneCall/phone call_ic_answer_64px.png', text: 'c', value: 98 }) ``` ### `prop.TEXT_STYLE` Text styles #### Param: object | Properties | Description | Required | Type | | ---------- | --------------------------------------------------------------- | -------- | --------- | | x | X position of text | YES | `number` | | w | Text width | YES | `number` | | align_h | The alignment of the horizontal axis, alignment refer to `TEXT` | NO | `number` | | alpha | Text alpha value [0-255], 0 for full transparency | NO | `number` | | color | Text color | NO | `number` | | show | Text showon | NO | `boolean` | ```js keyboard.setProperty(prop.TEXT_STYLE, { x: 0, w: 480, align_h: align.CENTER, alpha: 255, color: 0xff0000, show: 1 }) ``` ### `prop.TEXT` Update text, `Param` is `string` ```js keyboard.setProperty(prop.TEXT, 'hello rose !') ``` ### `prop.X` and `prop.Y` Adjust the overall position of the keyboard, `Param` is `number` ```js keyboard.setProperty(prop.X, 0) keyboard.setProperty(prop.Y, 10) ``` ## Code example ```js function callback(keyboard, id, value) { console.log(`id:${id} char:${value}`) keyboard.setProperty(prop.TEXT, `id:${id} char:${value}`) ret = keyboard.getProperty(prop.KEY_PARA, id) if (ret !== undefined) { console.log(id) console.log(ret.value) console.log(ret.x) console.log(ret.y) } } const keyboard = createWidget(widget.KEYBOARD, { click_func: callback, key_attr: [ { id: 0, x: 0, y: 150, text: 'H', value: 1 }, { id: 1, x: 90, y: 150, text: 'E', value: 2 }, { id: 20, x: 180, y: 150, text: 'L', value: 3 }, { id: 3, x: 270, y: 150, text: 'L', value: 4 }, { id: 4, x: 360, y: 150, text: 'O', value: 5 }, { id: 6, x: 45, y: 250, text: 'R', value: 6 }, { id: 7, x: 135, y: 250, text: 'O', value: 7 }, { id: 8, x: 225, y: 250, text: 'S', value: 8 }, { id: 9, x: 315, y: 250, text: 'E', value: 9 }, { id: 10, x: 180, y: 350, image: 'images/common/widgetsbc/phoneCall/phone call_ic_answer_64px.png', text: ' ', value: 10 } ] }) keyboard.setProperty(prop.TEXT_STYLE, { x: 0, w: 480, align_h: align.CENTER, alpha: 255, color: 0xff0000, show: 1 }) keyboard.setProperty(prop.TEXT, 'hello rose !') keyboard.setProperty(prop.X, 0) keyboard.setProperty(prop.Y, 10) keyboard.setProperty(prop.KEY_PARA, { id: 1, text: 'c', value: 98 }) keyboard.setProperty(prop.DEL_KEY, { id: 20 }) keyboard.setProperty(prop.ADD_KEY, { id: 100, x: 280, y: 350, text: '!', value: 11 }) keyboard.setProperty(prop.ADD_KEY, { id: 99, x: 80, y: 350, text: '!', value: 11 }) ``` ## Additional Examples ### Example 1 ```js let keyboardLock = createWidget(widget.KEYBOARD, { click_func: presscb, key_attr: [ { cntr_coord_style: true, id: 0, x: 8, y: '35vh', text: 'H', value: 1 }, { id: 1, x: 90, y: 150, text: 'E', value: 2 }, { id: 20, x: 180, y: 150, text: 'L', value: 3 }, { id: 3, x: 270, y: 150, text: 'L', value: 4 }, ], }) keyboardLock.setProperty(prop.TEXT, 'hello rose !') ``` --- ## PICKER ### Import ```js import { createWidget, widget, prop } from '@zos/ui' ``` > Start from API_LEVEL `3.0`. Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility)。 An universal selector, use to text and number list selection ## Create UI widget ```js const picker_widget = createWidget(widget.WIDGET_PICKER, Param) ``` ### Param: object | Properties | Description | Required | Type | | -------------- | ---------------------------------------------------- | -------- | ------------------- | | nb_of_columns | Maximum Picker columns (Maximum number is 5) | YES | `number` | | data_config | Array of column configuration, refer to `DataConfig` | YES | `Array` | | title | Title of Picker | NO | `string` | | subtitle | Subtitle of Picker | NO | `string` | | done_icon | Resource path of icon about done status | NO | `string` | | picker_cb | Callback function of Picker | NO | `CallBack` | | init_col_index | Initialize the index of the focused column | NO | `number` | | normal_color | Color value of unselected item | NO | `number` | | select_color | Color value of selected item | NO | `number` | #### DataConfig: object | Properties | Description | Required | Type | | ------------------- | ----------------------------------------------- | -------- | -------------------------------------- | | data_array | Data array of column | YES | `Array\` | | support_loop | support circular drag and drop | YES | `boolean` | | unit | Unit | NO | `string` | | connector | Data separator | NO | `string` | | font_name | Path of font file, refer to `TEXT` | NO | `string` | | font_size | Font size | NO | `number` | | select_font_size | Font size of selected item | NO | `number` | | connector_font_size | Font size of separator | NO | `number` | | unit_font_size | Font size of unit | NO | `number` | | init_val_index | Default selected index | NO | `number` | | col_width | Column width, all columns need to be configured | NO | `number` | #### CallBack: function Callback function of Picker ```ts picker_cb(picker: WIDGET, event_type: number, column_index: number, select_index: index): void ``` | Properties | Description | | ------------ | ----------------------------------------- | | picker | The Picker instance | | event_type | Event type of Picker, see `EVENT_TYPE` | | column_index | Column index for triggering Picker events | | select_index | The index of selected item | | EVENT_TYPE value | Description | | ---------------- | ------------------------- | | `0` | Lose focus | | `1` | Get focus | | `2` | Selected item has a value | ```js function picker_cb(picker, event_type, column_index, select_index) { if (event_type == 2) { picker.setProperty(prop.TITLE, 'End Date') picker.setProperty(prop.SUBTITLE, '3 days in totals') picker.setProperty(prop.UPDATE_DATA, { col_index: 0, val_index: 5, data_array: new Array(10).fill(0).map((d, index) => index + 1) }) picker.setProperty(prop.CUR_COLUMN, 1) } } ``` ## Property Operations The `SET` and `GET` means `widget.setProperty` and `widget.getProperty` | Property Name | SET/GET | Description | | ------------------ | --------- | ------------------------- | | `prop.TITLE` | `SET` | Update `title` | | `prop.SUBTITLE` | `SET` | Update `subtitle` | | `prop.UPDATE_DATA` | `SET` | Update data of a column | | `prop.CUR_COLUMN` | `SET/GET` | Update the current column | ## Code example ```js const time = new Time() const picker_widget = createWidget(widget.WIDGET_PICKER, { title: 'Start Date', subtitle: '', nb_of_columns: 3, single_wide: true, init_col_index: 1, data_config: [ { data_array: new Array(12).fill(0).map((d, index) => index + 1), init_val_index: time.getMonth() - 1, unit: 'Month', support_loop: true, font_name: 'fonts/x.ttf', font_size: 24, select_font_size: 48, connector_font_size: 18, unit_font_size: 18, col_width: 80 }, { data_array: new Array(31).fill(0).map((d, index) => index + 1), init_val_index: time.getDate() - 1, unit: 'Day', support_loop: true, font_name: 'fonts/x.ttf', font_size: 24, select_font_size: 48, connector_font_size: 36, unit_font_size: 36, col_width: 80 }, { data_array: new Array(100).fill(0).map((d, index) => index + 1970), init_val_index: time.getFullYear() - 1970, unit: 'Year', support_loop: true, font_name: 'fonts/x.ttf', font_size: 24, select_font_size: 48, connector_font_size: 36, unit_font_size: 36, col_width: 80 } ], picker_cb }) function picker_cb(picker, event_type, column_index, select_index) { console.log( 'timePickerCb: ' + event_type, 'column_index: ' + column_index, 'select_index: ' + select_index ) } ``` ## Additional Examples ### Example 1 ```js createWidget(widget.WIDGET_PICKER, { title: 'Start Date', subtitle: '', nb_of_columns: 3, init_col_index: 1, data_config: [ { data_array: new Array(12).fill(0).map((_, index) => index + 1), init_val_index: 5, unit: 'Month', support_loop: true, font_name: 'fonts/x.ttf', font_size: 24, select_font_size: 48, connector_font_size: 18, unit_font_size: 18, col_width: 80, }, { data_array: new Array(31).fill(0).map((_, index) => index + 1), init_val_index: 10, unit: 'Day', support_loop: true, font_name: 'fonts/x.ttf', font_size: 24, select_font_size: 48, connector_font_size: 36, unit_font_size: 36, col_width: 80, }, { data_array: new Array(30).fill(0).map((_, index) => index + 2020), init_val_index: 4, unit: 'Year', support_loop: true, font_name: 'fonts/x.ttf', font_size: 24, select_font_size: 48, connector_font_size: 36, unit_font_size: 36, col_width: 80, }, ], picker_cb: (picker, eventType, column, valueIndex) => { console.log('picker event', eventType, column, valueIndex) }, }) ``` --- ## TIME_PICKER ### Import ```js import { createWidget, widget, prop } from '@zos/ui' ``` > Start from API_LEVEL `3.6`. Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility)。 [Image: time_picker] A full-screen widget that supports time and date selection. ## Create UI widget ```js const time_picker = createWidget(widget.WIDGET_TIME_PICKER, Param) ``` ### Param: object | Properties | Description | Required | Type | | ------------------ | ----------------------------------- | -------- | ---------- | | `type` | Selector type, `0` time, `1` date | YES | `number` | | `style` | Value must be `1` | YES | `number` | | `title` | Title of selector | NO | `string` | | `done_icon` | Image path of done icon | NO | `string` | | `font_size` | Font size setting | YES | `number` | | `select_font_size` | Font size setting for selected item | YES | `number` | | `initHour` | Initial hour, default is 12 | NO | `number` | | `initMin` | Initial minute, default is 0 | NO | `number` | | `startYear` | Start year, default is 1970 | NO | `number` | | `endYear` | End year, default is 2100 | NO | `number` | | `initYear` | Initial year, default is 2020 | NO | `number` | | `initMonth` | Initial month, default is 1 | NO | `number` | | `initDay` | Initial day, default is 1 | NO | `number` | | `picker_cb` | Callback function of picker | NO | `CallBack` | #### CallBack: function Time/Date picker callback function ```ts picker_cb(picker: WIDGET, event_type: number, column: number, value_index: number): void ``` | Properties | Description | | ------------- | ------------------------------------------------------------------ | | `picker` | The time/date picker widget instance | | `event_type` | Event type of picker, see `EVENT_TYPE` | | `column` | Index of current focus column (only valid under UPDATE event type) | | `value_index` | Current value of the column (only valid under UPDATE event type) | | EVENT_TYPE Value | Description | | ---------------- | ------------------ | | `0` | Cancel selection | | `1` | Update selection | | `2` | Complete selection | ## Property Operations The `SET` and `GET` means `widget.setProperty` and `widget.getProperty` | Property Name | SET/GET | Description | | ----------------------- | ------- | ----------- | | `prop.type` | - | - | | `prop.style` | - | - | | `prop.title` | - | - | | `prop.done_icon` | - | - | | `prop.font_size` | - | - | | `prop.select_font_size` | - | - | | `prop.initHour` | - | - | | `prop.initMin` | - | - | | `prop.startYear` | - | - | | `prop.endYear` | - | - | | `prop.initYear` | - | - | | `prop.initMonth` | - | - | | `prop.initDay` | - | - | | `prop.picker_cb` | - | - | | `prop.YEAR` | `GET` | Get year | | `prop.MONTH` | `GET` | Get month | | `prop.DAY` | `GET` | Get day | | `prop.HOUR` | `GET` | Get hour | | `prop.MINUTE` | `GET` | Get minute | ## Code example ```js const time_picker = createWidget(widget.WIDGET_TIME_PICKER, { type: 0, // 0: select time 1: select date style: 1, title: 'Time Picker', initHour: 16, initMin: 55, font_size: 45, select_font_size: 48, picker_cb: callbackFunc }) function callbackFunc(picker, event_type, column, value_index) { console.log('timePickerCb: ' + event_type, 'column: ' + column, 'value_index: ' + value_index) } ``` --- ## SYSTEM_KEYBOARD ### Import ```js import { createKeyboard, inputType } from '@zos/ui' ``` > Start from API_LEVEL `4.0`. Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Create a system-level input keyboard that supports multiple input modes. ## Create Keyboard Widget ```js const keyboard = createKeyboard({ // Required parameters inputType: inputType.NUM, onComplete: (keyboardWidget, result) => { /* Handle input completion */ }, onCancel: (keyboardWidget, result) => { /* Handle input cancellation */ }, // Optional parameters text: 'Initial text' }) ``` ## Type Definitions ### Param: object | Property | Description | Required | Type | Version | | ---------- | ------------------------------------------------------ | -------- | ---------- | ------- | | inputType | Input type, refer to `inputType` enum | YES | `number` | 4.0 | | onComplete | Callback when user confirms input | YES | `function` | 4.0 | | onCancel | Callback when user swipes right or presses back button | YES | `function` | 4.0 | | text | Initial text for editing | NO | `string` | 4.0 | | onClick | Click event callback (Not available yet) | NO | `function` | 4.0 | | selection | Quick reply options (Not available yet) | NO | `array` | 4.0 | ### `inputType` Enum | Value | Description | API_LEVEL | | --------------- | ------------------ | --------- | | inputType.EMOJI | Emoji keyboard | 4.0 | | inputType.NUM | Number keyboard | 4.0 | | inputType.CHAR | Character keyboard | 4.0 | | inputType.VOICE | Voice input | 4.0 | | inputType.JSKB | Custom Keyboard Widget | 4.2 | ## Methods ### deleteKeyboard() Exit and destroy the current keyboard input interface ```js deleteKeyboard() ``` ## Code Example ```js Page({ onInit() { this.createKeyboard() }, createKeyboard() { createKeyboard({ inputType: inputType.NUM, onComplete: (_, result) => { console.log('Input content:', result.data) this.destroyKeyboard() }, onCancel: (_, result) => { console.log('Input cancelled') this.destroyKeyboard() }, text: '100' // Initial text }) }, destroyKeyboard() { deleteKeyboard() // Execute subsequent operations like page navigation... } }) ``` --- --- # @zos/ui-widget-layout Layout widget APIs. ## GROUP ### Import ```js import { createWidget, widget } from '@zos/ui' ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). GROUP group widget is used to group a series of widgets together for unified widget of show/hide, registering events, etc. The returned `group` instance has the method `createWidget`, which is used to Create UI widget belonging to the `group` group, and the sub-widgets need to use relative positions for layout. > **⚠️ Caution** > > 1. The `group` instance of `createWidget` cannot create child `GROUP` components, i.e. `GROUP` components cannot be nested. > 2. GROUP cannot be used in [SecondaryWidget](https://docs.zepp.com/docs/reference/device-app-api/newAPI/global/SecondaryWidget) and [Shorcut cards](https://docs.zepp.com/docs/reference/device-app-api/newAPI/global/AppWidget) ## Create UI widget ```js const group = createWidget(widget.GROUP, Param) // Creating UI sub-widgets group.createWidget(xxx, xxx) ``` ## Type ### Param: object | Properties | Description | Required | Type | | --------- | --------------------------------- | -------- | -------- | | x | The x-coordinate of widget. | YES | `number` | | y | The y-coordinate of widget. | YES | `number` | | w | The width of widget. | YES | `number` | | h | The height of the widget. | YES | `number` | --- ## SCROLL_LIST ### Import ```js import { createWidget, widget } from '@zos/ui' ``` > Start from API_LEVEL `2.0`. Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). [Image: scroll_list_sample] Create a list area with sliding support, where each list item can contain images and text, and supports horizontal sliding. ## Create UI widget ```js const scrollList = createWidget(widget.SCROLL_LIST, Param) ``` ## Type ### Param: object | Properties | Description | Required | Type | API_LEVEL | | ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ----------------------- | --------- | | x | The x-coordinate of the widget | YES | `number` | 2.0 | | y | The y-coordinate of the widget | YES | `number` | 2.0 | | w | Width of the widget | YES | `number` | 2.0 | | h | Height of the widget | YES | `number` | 2.0 | | item_space | Space between items | NO | `number` | 2.0 | | item_config | Item type configuration, see [`ItemConfig`](#itemconfig-object) | YES | `Array` | 2.0 | | item_config_count | Length of the item_config array | YES | `number` | 2.0 | | data_array | Data array | YES | `DataArray` | 2.0 | | data_count | Length of the data array | YES | `number` | 2.0 | | item_click_func | Item click callback function, where the item index corresponds to the data_array, see [`ItemClickFunc`](#itemclickfunc) | NO | `ItemClickFunc` | 2.0 | | data_type_config | Item index type configuration array, see [DataTypeConfig](#datatypeconfig-object) | NO | `Array` | 2.0 | | data_type_config_count | Length of the item index type configuration array | NO | `number` | 2.0 | | on_page | Used when updating data, set to `1` to keep the list at current position after update, otherwise returns to list top | NO | `number` | 2.0 | | snap_to_center | Whether the list should snap to the center height of SCROLL_LIST | NO | `boolean` | 2.0 | | item_focus_change_func | List sliding focus change callback function, see [ItemFocusChangeFunc](#itemfocuschangefunc) | NO | `ItemFocusChangeFunc` | 2.0 | | item_enable_horizon_drag | Whether items can be dragged horizontally | NO | `boolean` | 2.0 | | item_drag_max_distance | Maximum horizontal drag distance, positive values for left drag, negative for right drag | NO | `number` | 2.0 | | snap_type | Set snap mode (see snap_type snap mode) | NO | `number` | 4.0 | | item_common_focus | Whether to show common focus (effective in key mode) | NO | `boolean` | 4.0 | | item_key_focus_change_func | Key event listener callback in key mode | NO | `function` | 4.0 | | enable_scroll_bar | Create page indicator (arcScrollBar) | NO | `boolean` | 4.0 | | view_index | Set list item to visible area (Note: Round screen: center screen, Square screen: top of screen) | NO | `number` | 4.0 | ### ItemConfig: object | Properties | Description | Required | Type | | ---------------- | -------------------------------------------------------------------------------------------------------- | -------- | ------------------ | | type_id | Current item type ID, optional when item_config_count is `0`, required otherwise | NO | `number` | | item_height | Item height | YES | `number` | | item_bg_color | Item background color | YES | `number` | | item_bg_radius | Item background corner radius | YES | `number` | | text_view | Array of textView structures, each item is a `textView`, see explanation below | NO | `Array` | | text_view_count | Length of text_view array | NO | `number` | | image_view | Array of imageView, each item is an `imageView`, see explanation below | NO | `Array` | | image_view_count | Length of image_view array | NO | `number` | ### TextView: object | Properties | Description | Required | Type | | ---------- | -------------------------------------------------------------------------------------------------------------------------- | -------- | --------- | | x | The x-coordinate, relative coordinate | YES | `number` | | y | The y-coordinate, relative coordinate | YES | `number` | | w | Widget width | YES | `number` | | h | Widget height | YES | `number` | | color | Text color | NO | `number` | | text_size | Font size | NO | `number` | | key | Data binding key, see examples and data_array description for details | YES | `string` | | action | Whether to respond to click events, after response, the corresponding data `key` can be captured in `item_click_func`, default `false` | NO | `boolean` | ```js const text_view = [ { x: 100, y: 0, w: 100, h: 20, key: 'name', color: 0xffffff, action: true }, { x: 0, y: 30, w: 100, h: 100, key: 'age', color: 0xffffff, text_size: 20 } ] ``` ### ImageView: object | Properties | Description | Required | Type | | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------ | -------- | --------- | | x | The x-coordinate, relative coordinate | YES | `number` | | y | The y-coordinate, relative coordinate | YES | `number` | | w | Widget width | YES | `number` | | h | Widget height | YES | `number` | | key | Data binding key, see examples and data_array description for details | YES | `string` | | action | Whether to respond to click events, after response, the corresponding data `key` can be captured in `item_click_func`, default `false` | NO | `boolean` | ```js // Each structure in the array is an imageView const image_view = [{ x: 0, y: 0, w: 20, h: 20, key: 'img_src', action: true }] ### data_array Data arrays, TextView and ImageView take values from each data_array object based on property names (configured via `key`) and render them to the view based on the corresponding configuration. ```js const dataList = [ { img_src: rootPath + 'step/step_num_1.png', name: 'name1', age: '12' }, { img_src: rootPath + 'step/step_num_1.png', name: 'name1', age: '13' }, { img_src: rootPath + 'step/step_num_1.png', name: 'name1', age: '13' } ] ``` ### DataTypeConfig: object Set the type of list index item. Each index item uses the configuration of `item_config[0]` by default. | Properties | Description | Required | Type | | ------- | -------------------------------------- | -------- | -------- | | start | Starting index | YES | `number` | | end | Ending index | YES | `number` | | type_id | The `type_id` corresponding to the type configuration in item_config | YES | `number` | `start` and `end` form a closed interval `[start, end]` ```js { data_type_config:[ // Represents that data entries from index 0 to 2 use the style configuration with type_id 2 { start: 0, end: 2, type_id: 2, }, { start: 3, end: 10, type_id: 1, }, ], data_type_config_count:2 } ``` ### ItemClickFunc ```ts (list: ScrollList, index: number, data_key: string) => void ``` | Parameters | Description | Type | | -------- | ---------------------------------------------------- | -------- | | list | SCROLL_LIST widget | `any` | | index | Clicked item index | `number` | | data_key | Clicked data `key` name, can locate the clicked area through `key` | `string` | ### ItemFocusChangeFunc ```ts (list: ScrollList, index: number, focus: boolean) => void ``` | Parameters | Description | Type | | ----- | ----------------- | --------- | | list | SCROLL_LIST widget | `any` | | index | Item index | `number` | | focus | Whether the item is in focus state | `boolean` | ### snap_type Snap Mode | Snap Mode Enum Value | Description | | --- | --- | | SCROLL_LIST.snap_type.SNAPCENTER_ALL | Center snap | | SCROLL_LIST.snap_type.SNAPCENTER_EXCEPTTITLE | Center snap except for title | | SCROLL_LIST.snap_type.SNAP_TOP | Top snap | | SCROLL_LIST.snap_type.SNAP_BOTTOM | Bottom snap | ```js console.log(SCROLL_LIST.snap_type.SNAPCENTER_ALL) ``` ## Refresh Data ```js const scrollList = createWidget(widget.SCROLL_LIST, Param) scrollList.setProperty(prop.UPDATE_DATA, { // Reset configuration information data_type_config: [ { start: 0, end: 2, type_id: 2 } ], // Configuration information length data_type_config_count: 1, // New data data_array: [ { img_src: rootPath + 'test/normalbtn_h.png', name: 'Name', age: '12', like: 'type2' }, { img_src: rootPath + 'test/normalbtn_h.png', name: 'namex1', age: '13', like: 'type2' }, { img_src: rootPath + 'test/normalbtn_h.png', name: 'namex2', age: '13', like: 'type2' }, { img_src: rootPath + 'test/normalbtn_h.png', name: 'namex3', age: '12', like: 'type2' }, { img_src: rootPath + 'test/normalbtn_h.png', name: 'name666', age: '13', like: 'type2' } ], // Data length data_count: 5, // Stay on current page after data refresh, if not set or set to 0, it will return to the top of the list on_page: 1 }) ``` ## Update/Delete Single Item ```js // Update a specific data scrollList.setProperty(prop.UPDATE_ITEM, { index: gScrollListSelectIndex, item_data: dataList2[gScrollListSelectIndex] }) // Delete a specific data list.setProperty(prop.DELETE_ITEM, { index: delete_index }) ``` ## Control Horizontal Sliding Parameters of Single Item ```js scrollList.setProperty(prop.MOVE_ITEM, { start: 0, // Start row end: 0, // End row item_enable_horizon_drag: false, // Whether horizontal sliding is enabled item_drag_max_distance: -200 // Horizontal sliding distance, only takes effect when enabled }) ``` ## Property Access Support List | 属性名 | setProperty | getProperty | [setter](https://docs.zepp.com/docs/reference/device-app-api/newAPI/ui/gettersetter) | [getter](https://docs.zepp.com/docs/reference/device-app-api/newAPI/ui/gettersetter) | | -------------------------- | ----------- | ----------- | ----------------------------- | ----------------------------- | | x | N | Y | N | Y | | y | N | Y | N | Y | | w | N | Y | N | Y | | h | N | Y | N | Y | | item_space | N | N | N | N | | item_config | N | N | N | N | | item_config_count | N | N | N | N | | data_array | N | N | N | N | | data_count | N | N | N | N | | item_click_func | N | N | N | N | | data_type_config | N | N | N | N | | data_type_config_count | N | N | N | N | | on_page | N | N | N | N | | snap_to_center | N | N | N | N | | item_focus_change_func | N | N | N | N | | item_enable_horizon_drag | N | N | N | N | | item_drag_max_distance | N | N | N | N | | snap_type | N | N | N | N | | item_common_focus | N | N | N | N | | item_key_focus_change_func | N | N | N | N | | enable_scroll_bar | N | N | N | N | | view_index | N | N | N | N | ## 代码示例 ```js Page({ build() { const dataList = [ { name: 'Amazfit T-Rex 2', size: 454, del_img: 'btn/delete.png' }, { name: 'Amazfit GTR 3 Pro', size: 480, del_img: 'btn/delete.png' }, { name: 'Amazfit GTR 3', size: 454, del_img: 'btn/delete.png' } ] const scrollList = createWidget(widget.SCROLL_LIST, { x: 0, y: 120, h: 300, w: 480, item_space: 20, snap_to_center: true, item_enable_horizon_drag: true, item_drag_max_distance: -120, item_config: [ { type_id: 1, item_bg_color: 0xef5350, item_bg_radius: 10, text_view: [ { x: 0, y: 0, w: 480, h: 80, key: 'name', color: 0xffffff, text_size: 20 }, { x: 0, y: 80, w: 480, h: 40, key: 'size', color: 0xffffff } ], text_view_count: 2, image_view: [{ x: 492, y: 28, w: 64, h: 64, key: 'del_img', action: true }], image_view_count: 1, item_height: 120 }, { type_id: 2, item_bg_color: 0xef5350, item_bg_radius: 10, text_view: [ { x: 0, y: 0, w: 480, h: 80, key: 'name', color: 0x000000, text_size: 20 }, { x: 0, y: 80, w: 480, h: 40, key: 'size', color: 0x000000 } ], text_view_count: 2, image_view: [{ x: 492, y: 28, w: 64, h: 64, key: 'del_img', action: true }], image_view_count: 1, item_height: 120 } ], item_config_count: 2, data_array: dataList, data_count: dataList.length, item_focus_change_func: (list, index, focus) => { console.log('scrollListFocusChange index=' + index) console.log('scrollListFocusChange focus=' + focus) }, item_click_func: (item, index, data_key) => { console.log(`scrollListItemClick index=${index}`) if (data_key === 'del_img') { scrollList.setProperty(prop.DELETE_ITEM, { index }) dataList.splice(index, 1) } else { updateConfig() } }, data_type_config: [ { start: 0, end: 1, type_id: 1 }, { start: 1, end: 2, type_id: 2 } ], data_type_config_count: 2, snap_to_center: true, item_enable_horizon_drag: true, item_drag_max_distance: -112 }) function updateConfig() { scrollList.setProperty(prop.UPDATE_DATA, { data_type_config: [ { start: 0, end: dataList.length - 1, type_id: 1 } ], data_type_config_count: 1, data_array: dataList, data_count: dataList.length, on_page: 1 }) } } }) ``` ## Additional Examples > Supported from API_LEVEL `4.0`. ```js const rootPath = 'images/' const dataList = [ { icon_image: rootPath + 'icons/ic_aqi.png', icon_name: 'Air Quality' }, { icon_image: rootPath + 'icons/ic_stand.png', icon_name: 'Standing Time' }, { icon_image: rootPath + 'icons/ic_hr.png', icon_name: 'Heart Rate' }, ] createWidget(widget.SCROLL_LIST, { item_space: 10, snap_to_center: true, item_enable_horizon_drag: true, item_drag_max_distance: -150, item_config: [ { type_id: 1, item_bg_color: 0x333333, item_bg_radius: 36, item_height: 128, layout: { height: '26vh', display: 'flex', 'flex-flow': 'row wrap', 'column-gap': '20', 'row-gap': '10', 'justify-content': 'space-evenly', 'align-items': 'center', }, text_view: [ { key: 'icon_name', color: 0xffffff, bg_color: 0x0000ff, bg_alpha: 30, layout: { width: '25%', height: '66%', 'font-size': '16', }, }, ], text_view_count: 1, image_view: [ { key: 'icon_image', action: true, layout: { width: '25%', height: '66%', }, }, ], image_view_count: 1, }, ], item_config_count: 1, data_array: dataList, data_count: dataList.length, data_type_config: [ { start: 0, end: dataList.length - 1, type_id: 1, }, ], data_type_config_count: 1, layout: { x: '1vw', y: '1vh', width: '50vw', height: '100vh', }, }) ``` --- ## VIEW_CONTAINER ### Import ```js import { createWidget, widget } from '@zos/ui' ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility).
The `VIEW_CONTAINER` widget container is a very powerful layout widget with the following features. - It is a rectangular layout container that can create child widgets by its instance method - The `z_index` property controls the cascading order of the widget container, allowing for vertical cascading of widgets. And you can create multiple VIEW_CONTAINER widgets in the same page. In Zepp OS v3, you can create up to 7 - The VIEW_CONTAINER widget container itself supports scrolling and can be used as a scrolling container - Used with [`setScrollMode`](https://docs.zepp.com/docs/reference/device-app-api/newAPI/page/setScrollMode) Swiper mode to achieve the complex layout in the second GIF (full-screen scrolling, where each screen can also be viewed as a scrollable independent container) ## Create UI widget ```js const viewContainer = createWidget(widget.VIEW_CONTAINER, Param) // Creating UI sub-widgets viewContainer.createWidget(xxx, xxx) ``` ## Type ## Param: object | Properties | Description | Required | Type | API_LEVEL | | --- | --- | --- | --- | --- | | x | Widget x-coordinate, default `0` | NO | `number` | 2.0 | | y | Widget y-coordinate, default `0` | NO | `number` | 2.0 | | w | Widget width, default screen width | NO | `number` | 2.0 | | h | Widget height, default screen height | NO | `number` | 2.0 | | scroll_enable | When the layout of widgets in VIEW_CONTAINER exceeds the width/height, it is considered a long page. `0`: disable scrolling, you can set container scroll position offset by `pos_x` or `pos_y`; `1`: allow scrolling (default) | NO | `number` | 2.0 | | pos_x | When VIEW_CONTAINER is a long horizontal page layout, you can read/set the horizontal offset | NO | `number` | 2.0 | | pos_y | When VIEW_CONTAINER is a long vertical page layout, you can read/set the vertical offset | NO | `number` | 2.0 | | z_index | When using multiple VIEW_CONTAINER widgets, the cascading relationship can be controlled by this field, with `0` at the bottom by default | NO | `number` | 2.0 | | modal | Modal layer switch. `0`: disable; `1`: enable (default). When enabled, it can be used to create a modal overlay/dialog inside a `VIEW_CONTAINER` and block the base layer from scrolling. | NO | `number` | 2.0 | | bounce | Rebound effect, `0`: disabled, `1`: enabled (default) | NO | `number` | 3.0 | | page | Used with [`setScrollMode`](https://docs.zepp.com/docs/reference/device-app-api/newAPI/page/setScrollMode) Swiper mode. The entire screen uses Swiper mode, and each independent page is implemented using `VIEW_CONTAINER`. Marks the page index to coordinate with Swiper mode | NO | `number` | 3.0 | ### FrameParams: object | Properties | Description | Type | API_LEVEL | | ---------- | ------------------------------------------------------------------------------------------------------------------------ | -------- | --------- | | type | `0`: the user is still touching the screen and dragging, `1`: the user has let go and is in an inertial scrolling effect | `number` | 2.0 | | yoffset | y-axis offset pixels | `number` | 3.0 | ## Supported Property Access List | Properties | setProperty | getProperty | [setter](https://docs.zepp.com/docs/reference/device-app-api/newAPI/ui/gettersetter) | [getter](https://docs.zepp.com/docs/reference/device-app-api/newAPI/ui/gettersetter) | | -------------------- | ----------- | ----------- | ----------------------------- | ----------------------------- | | x | Y | Y | Y | Y | | y | Y | Y | Y | Y | | w | Y | Y | Y | Y | | h | Y | Y | Y | Y | | pos_x | Y | Y | Y | Y | | pos_y | Y | Y | Y | Y | | page | N | N | N | Y | | modal | N | N | N | Y | | z_index | N | N | N | Y | | bounce | N | N | N | Y | | scroll_enable | N | Y | N | Y | | scroll_frame_func | N | N | N | N | | scroll_complete_func | N | N | N | N | ## Code example The code runs as shown in the image at the top of the document, creating two VIEW_CONTAINER widgets ```js const getRandomColor = () => { const randomArr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'] function getRandomFromSection(low, high) { const RANDOM = Math.random() const RANGE = high - low + 1 return Math.floor(RANDOM * RANGE) + low } const colorStr = Array.from({ length: 6 }).reduce((prev, curr) => { const random = getRandomFromSection(0, 15) return prev + randomArr[random] }, '0x') return Number(colorStr) } Page({ build() { createWidget(widget.TEXT, { x: px(96), y: px(40), w: px(288), h: px(46), color: 0xffffff, text_size: px(36), align_h: align.CENTER_H, align_v: align.CENTER_V, text_style: text_style.NONE, text: 'VIEW_CONTAINER' }) const viewContainer = createWidget(widget.VIEW_CONTAINER, { x: px(0), y: px(86), w: px(480), h: px(400) }) Array.from({ length: 5 }).forEach((_, index) => { viewContainer.createWidget(widget.FILL_RECT, { x: 0, y: px(index * 400), w: px(480), h: px(400), color: getRandomColor() }) viewContainer.createWidget(widget.TEXT, { x: px(96), y: px(170) + px(index * 400), w: px(288), h: px(46), text_size: px(36), color: 0xffffff, align_h: align.CENTER_H, align_v: align.CENTER_V, text: `INDEX: ${index}` }) }) const viewContainerButton = createWidget(widget.VIEW_CONTAINER, { x: px(0), y: px(86), w: px(480), h: px(400), z_index: 1, scroll_enable: false }) viewContainerButton.createWidget(widget.BUTTON, { x: 0, y: px(50), w: px(200), h: px(100), text: 'Click', radius: px(12), normal_color: DEFAULT_COLOR, press_color: DEFAULT_COLOR_TRANSPARENT, click_func: () => { console.log('click button') } }) } }) ``` Used in conjunction with SetScrollMode Swiper mode, the effect is shown in the second GIF at the top. ```js const PAGE_WIDTH = 480; const PAGE_HEIGHT = 480; Page({ build() { setScrollMode({ mode: SCROLL_MODE_SWIPER_HORIZONTAL, options: { width: px(PAGE_WIDTH), count: 2, }, }); const viewContainer1 = createWidget(widget.VIEW_CONTAINER, { x: px(0), y: px(0), w: px(PAGE_WIDTH), h: px(PAGE_HEIGHT), scroll_enable: 1, page: 0, }); viewContainer1.createWidget(widget.TEXT, { x: 0, y: 0, w: px(PAGE_WIDTH), h: px(40), text: "ViewContainer1", text_size: px(26), color: 0xffffff, align_h: align.CENTER_H, align_v: align.CENTER_V, }); viewContainer1.createWidget(widget.FILL_RECT, { x: 0, y: px(40), w: px(PAGE_WIDTH), h: px(440), color: 0xF84E3F, }); viewContainer1.createWidget(widget.FILL_RECT, { x: 0, y: px(480), w: px(PAGE_WIDTH), h: px(480), color: 0x42A5F5, }); const viewContainer2 = createWidget(widget.VIEW_CONTAINER, { x: px(0), y: px(0), w: px(PAGE_WIDTH), h: px(PAGE_HEIGHT), scroll_enable: 1, page: 1, }); viewContainer2.createWidget(widget.TEXT, { x: 0, y: 0, w: px(PAGE_WIDTH), h: px(40), text: "ViewContainer2", text_size: px(26), color: 0xffffff, align_h: align.CENTER_H, align_v: align.CENTER_V, }); viewContainer2.createWidget(widget.FILL_RECT, { x: 0, y: px(40), w: px(PAGE_WIDTH), h: px(PAGE_HEIGHT) / 2, color: 0xFFA726, }); viewContainer2.createWidget(widget.FILL_RECT, { x: 0, y: px(280), w: px(PAGE_WIDTH), h: px(PAGE_HEIGHT) / 2, color: 0xFFD54F, }); viewContainer2.createWidget(widget.FILL_RECT, { x: 0, y: px(40) + px(PAGE_HEIGHT), w: px(PAGE_WIDTH), h: px(PAGE_HEIGHT) / 2, color: 0x66BB6A, }); }, }); ``` ## Additional Examples ### Example 1 ```js const vc = createWidget(widget.VIEW_CONTAINER, { x: 0, y: 0, w: 416, h: 416, page: 1, scroll_enable: 1, scroll_frame_func: (info) => { console.log('scrolling', info) }, scroll_complete_func: (info) => { console.log('scrolled', info) }, }) vc.createWidget(widget.TEXT, { x: 150, y: 416, w: 200, h: 50, color: 0xffffff, text_size: 30, text: 'hello1', }) ``` --- ## CYCLE_LIST ### Import ```js import { createWidget, widget } from '@zos/ui' ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). [Image: cycle_list_sample] Create a list that scrolls in a loop, which can be populated with images. ## Create UI widget ```js const cycleList = createWidget(widget.CYCLE_LIST, Param) ``` ## Type ### Param: object | Properties | Description | Required | Type | | ----------------- | --------------------------------------------------| --------- | --------------- | | item_bg_color | Background color. | YES | `number` | | item_height | The height of item. | YES | `number` | | x | The x-coordinate of widgets. | YES | `number` | | y | The y-coordinate of widgets. | YES | `number` | | w | The width of widgets. | YES | `number` | | h | The height of widgets. | YES | `number` | | data_array | Data arrays. | YES | `Array` | | data_size | The length of the array. | YES | `number` | | item_click_func | Callback for item click. | NO | `ItemClickFunc` | | item_focus_change_func | Item focus state callback. | NO | `ItemFocusChangeFunc` | ### ItemClickFunc: function ```ts (cycleList: CycleList, index: number) => void ``` | Properties | Type | Notes | | ---------- | -------- | -------------------------- | | cycleList | `object` | The instance of cycleList. | | index | `number` | Clicked item index.Starting from 0. | ### ItemFocusChangeFunc: function ```ts (cycleList: CycleList, index: number, isFocus: boolean) => void ``` | 参数 | 说明 | 类型 | | --------- | -------------------------- | -------- | | cycleList | The instance of cycleList. | `object` | | index | Losing/getting the index of the focus item. | `number` | | isFocus | Whether to get the focus. | `boolean` | ## Code example > **💡 Tip** > > Please refer to [Design Resources](https://docs.zepp.com/docs/reference/related-resources/design-resources) for the image resources in the code example ```js Page({ state: { pageName: 'CYCLE_LIST' }, build() { const imgArray = ['number-img/0.png', 'number-img/1.png', 'number-img/2.png', 'number-img/3.png', 'number-img/4.png'] const cycleList = createWidget(widget.CYCLE_LIST, { x: 230, y: 120, h: 300, w: 30, data_array: imgArray, data_size: 5, item_height: 100, item_click_func: (list, index) => { console.log(index) }, item_bg_color: 0xffffff }) } }) ``` ## Additional Examples ### Example 1 ```js const imgListStyleObj = { data_array: imgArray, data_size: 11, item_bg_color: 0x0007f, layout: { width: '20vw', height: '65vh', item_height: '13vh', }, } const rootContainer = createWidget(widget.VIRTUAL_CONTAINER, { layout: { x: '0vw', y: '0vh', width: '100vw', height: '70vh' }, }) const groupRoot = createWidget(widget.GROUP, { parent: rootContainer, layout: { display: 'flex', 'flex-flow': 'row wrap', 'column-gap': '20', 'row-gap': '10', 'justify-content': 'space-evenly', 'align-items': 'center', width: '100%', height: '100%', }, }) for (let i = 0; i < 3; i += 1) { groupRoot.createWidget(widget.CYCLE_LIST, imgListStyleObj) } ``` --- ## CYCLE_IMAGE_TEXT_LIST ### Import ```js import { createWidget, widget } from '@zos/ui' ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). [Image: cycle_image_text_list_sample] Create a list that can be scrolled in a loop, and each list item can be placed with an image and text. ## Create UI widget ```js const cycleImageTextList = createWidget(widget.CYCLE_IMAGE_TEXT_LIST, Param) ``` ## Type ### Param: object | Properties | Description | Required | Type | | ----------------- | ----------------------------------------------------- | --------- | --------------- | | x | The x-coordinate of widgets. | YES | `number` | | y | The y-coordinate of widgets. | YES | `number` | | w | The width of widgets. | YES | `number` | | h | The height of widgets. | YES | `number` | | item_image_x | The x-coordinate of Image.(Relative coordinate) | YES | `number` | | item_image_y | The y-coordinate of Image.(Relative coordinate) | YES | `number` | | item_text_x | The x-coordinate of text.(Relative coordinate) | YES | `number` | | item_text_y | The y-coordinate of text.(Relative coordinate) | YES | `number` | | item_text_size | Font Size. | YES | `number` | | item_text_color | Font color. | YES | `number` | | item_bg_color | Background color. | YES | `number` | | item_height | The height of item. | YES | `number` | | data_array | Data arrays. | YES | `Array` | | data_size | The length of the array. | YES | `number` | | item_text_align_h | Text horizontal orientation.Unfilled default horizontal centering. | NO | `number` | | item_text_align_v | Vertical orientation of text.Unfilled defaults to vertical centering. | NO | `number` | | item_text_height | Actual display area of text.Default to item_height if not filled. | NO | `number` | | item_text_width | The actual text display area.Default to the widget display width if not filled. | NO | `number` | | item_image_x | item Image x-coordinate, relative coordinates | NO | `number` | | item_image_y | item Image y-coordinate, relative coordinates | NO | `number` | | item_click_func | Callback for item click. | NO | `ItemClickFunc` | | item_focus_change_func | Item focus state callback. | NO | `ItemFocusChangeFunc` | ### Data: object | Properties | Description | Required | Type | | --------- | -------------------- | -------- | -------- | | src | The path of image. | NO | `string` | | text | The content of text. | YES | `string` | ### ItemClickFunc: function ```ts (cycleList: CycleList, index: number) => void ``` | Properties | Type | Notes | | ---------- | -------- | -------------------------- | | cycleList | `object` | The instance of cycleList. | | index | `number` | Clicked item index.Starting from 0. | ### ItemFocusChangeFunc: function ```ts (cycleList: CycleList, index: number, isFocus: boolean) => void ``` | 参数 | 说明 | 类型 | | --------- | -------------------------- | -------- | | cycleList | The instance of cycleList. | `object` | | index | Losing/getting the index of the focus item. | `number` | | isFocus | Whether to get the focus. | `boolean` | ## Set the properties of a single item text > **⚠️ Caution** > > Setting the properties of a single `item` text is not stored by the widget and the changed values are not available via `getProperty`. | Properties | Description | Required | Type | | --------------- | ---------------------------------- | -------- | -------- | | index | The index of item.Starting from 0. | YES | `number` | | item_text_color | The color of the text. | NO | `number` | | item_text_size | The size of the text. | NO | `number` | ```js const widget = ... widget.setProperty(prop.ITEM_MORE,{ index:0, item_text_color:0x2f4988, item_text_size:50 }) ``` ## Refresh ITEM - This is set for the property `ITEM_MORE`. After setting the property with `ITEM_MORE`, you can refresh `ITEM` if you want to revert to its original state. ```js widget.setProperty(prop.ITEM_REFRESH, 0) // 0 is the index of item , starting from 0. ``` ## Set the top item index of the list - Set the index value of the top `item` of the `list` with the `LIST_TOP` property to display the `list` at the specified position of the `item`. | Name | Description | Required | Type | | ------ | ---------------------------------- | --------- | -------- | | index | The index of item.Starting from 0. | YES | `number` | ## Code example ```js const data_array = [ { src: rootPath + 'step/step_num_0.png', text: '1' }, { src: rootPath + 'step/step_num_1.png', text: '2' }, { src: rootPath + 'step/step_num_2.png', text: '3' } ] cycleList = createWidget(widget.CYCLE_IMAGE_TEXT_LIST, { x: 0, y: 0, w: 200, h: 400, data_array: data_array, data_size: 3, item_height: 100, item_bg_color: 0xffffff, item_text_color: 0x000000, item_text_x: 10, item_text_y: 10, item_text_size: 18 }) //Get the index value of the first row. ret = cycleList.getProperty(prop.MORE, {}) console.log(ret.index) ``` ## Additional Examples ### Example 1 ```js function _itemClick(list, index) {} const dataArray = [ { src: rootPath + 'step/step_num_0.png', text: '1' }, { src: rootPath + 'step/step_num_1.png', text: '2' }, { src: rootPath + 'step/step_num_2.png', text: '3' }, ] createWidget(widget.CYCLE_IMAGE_TEXT_LIST, { x: 0, y: 0, w: 200, h: 400, data_array: dataArray, data_size: 3, item_height: 100, item_bg_color: 0xffffff, item_text_color: 0x000000, item_text_x: 10, item_text_y: 10, item_text_size: 18, item_click_func: _itemClick, }) ``` ### Example 2 ```js function _itemClick(list, index) {} function _scrollListFocusChange(list, index, bfocus) {} const dataArray = [ { src: rootPath + 'step/step_num_0.png', text: '1' }, { src: rootPath + 'step/step_num_1.png', text: '2' }, { src: rootPath + 'step/step_num_2.png', text: '3' }, ] createWidget(widget.CYCLE_IMAGE_TEXT_LIST, { x: 0, y: 0, w: 200, h: 400, data_array: dataArray, data_size: 3, item_height: 100, item_bg_color: 0xffffff, item_text_color: 0x000000, item_text_x: 10, item_text_y: 10, item_text_size: 18, item_click_func: _itemClick, item_focus_change_func: _scrollListFocusChange, }) ``` --- ## VIRTUAL_CONTAINER ### Import ```js import { createWidget, widget } from '@zos/ui' ``` > Supported from API_LEVEL `4.0`. Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility) for compatibility. VIRTUAL_CONTAINER is a special container widget used to implement Flex layout. It serves as the root node of a Flex layout container, and the widgets inside the container will be arranged and rendered according to the rules of Flex layout. ## Creating UI Widget ```js const container = createWidget(widget.VIRTUAL_CONTAINER, Param) ``` ## Types ### Param: object | Property | Description | Required | Type | API_LEVEL | | -------- | ----------------------------------------------- | -------- | -------- | --------- | | layout | Layout properties for Flex layout configuration | YES | `object` | 4.0 | ## Layout Properties VIRTUAL_CONTAINER widget supports Flex layout through the `layout` property. For detailed layout property configuration, please refer to [Widget Layout Properties for Flex Layout](https://docs.zepp.com/docs/guides/framework/device/layout). ## Instance Methods ### setLayoutParent(parent) Sets the parent node of the current node. **Parameters** - `parent`: Widget instance participating in the layout **Return Value** None ### addLayoutChild(child, index) Adds a child node to the current node. **Parameters** - `child`: Child widget instance to be added - `index`: Optional, specifies the insertion position index, defaults to adding at the end **Return Value** None ### removeLayoutChild(child) Removes the specified child node from the current node. **Parameters** - `child`: Child widget instance to be removed **Return Value** None ### updateLayoutStyle(style) Updates the layout style of the node. **Parameters** - `style`: Object containing layout properties **Return Value** None ## Code Example The following example shows how to use VIRTUAL_CONTAINER to create a simple Flex layout: ```js // Create root container const root = createWidget(widget.VIRTUAL_CONTAINER, { layout: { x: '0', y: '0', width: '100%', height: '100%', display: 'flex', 'flex-flow': 'column', 'justify-content': 'center', 'align-items': 'center' } }) // Create child element const text = createWidget(widget.TEXT, { text: 'Hello Zepp OS', align_h: align.CENTER_H, layout: { width: '100%', height: 'auto', 'font-size': '36' } }) // Set text widget as a child node of root text.setLayoutParent(root) // Create button const button = createWidget(widget.BUTTON, { text: 'Click Me', layout: { width: '80%', height: '60px', 'margin-top': '20px' } }) // Add button as a child node of root root.addLayoutChild(button) // Update layout style button.updateLayoutStyle({ 'background-color': '#ff0000' }) ``` ## Notes 1. VIRTUAL_CONTAINER widget is mainly used to implement Flex layout and needs to be used with the `layout` property and widget node operation APIs. 2. When using Flex layout, it is recommended to use relative units (such as %, vw, vh, etc.) to implement responsive layouts. 3. After updating the layout style, you may need to call `updateLayout()` to refresh the layout. --- --- # @zos/ui UI documentation is split into smaller files that follow the sidebar structure. ## Submodules - [@zos/ui-methods](/llms/@zos-ui-methods.md) — General methods, dialogs, keyboard, toast, layout helpers, and page-level UI APIs - [@zos/ui-animations](/llms/@zos-ui-animations.md) — Widget animation APIs - [@zos/ui-widget-basic](/llms/@zos-ui-widget-basic.md) — Basic widgets - [@zos/ui-widget-form](/llms/@zos-ui-widget-form.md) — Form widgets - [@zos/ui-widget-layout](/llms/@zos-ui-widget-layout.md) — Layout widgets --- # @zos/user ## Constants | Constant | Description | API_LEVEL | |----------|-------------|-----------| | `GENDER_MALE` | Male | — | | `GENDER_FEMALE` | Female | — | | `GENDER_UNSPECIFIED` | User not specified | — | ## addHealthData ### Import ```js import { addHealthData } from '@zos/user' ``` ### Typings - Description: Set user health data information - API_LEVEL: 3.0 - Permission: `data:user.health` - Example: ```js import { addHealthData } from '@zos/user' addHealthData({ weight: 65, bmi: 1900 }) ``` > Start from API_LEVEL `3.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Set user health data information. > **ℹ️ Info** > > permission code: `data:user.health` ## Type ```ts function addHealthData(option: Option): Result ``` ## Parameters ### Option | Property | Type | Required | DefaultValue | Description | API_LEVEL | | -------- | ------------------- | -------- | ------------ | -------------------------- | --------- | | weight | `number` | Y | - | Weight, in g | 3.0 | | bmi | `number` | Y | - | 100 times the value of BMI | 3.0 | ### Result | Type | Description | | -------------------- | ----------- | | `boolean` | undefined | ## Example ```js addHealthData({ weight: 65, bmi: 1900, }) ``` --- ## getProfile ### Import ```js import { getProfile, GENDER_MALE } from '@zos/user' ``` ### Typings - Description: Get user information - Permission: `data:user.info` - Constants: `gender` - Example: ```js import { getProfile, GENDER_MALE } from '@zos/user' const { age, gender } = getProfile() console.log(age) if (gender === GENDER_MALE) { console.log('male') } ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Get user information. > **ℹ️ Info** > > permission code: `data:user.info` ## Type ```ts function getProfile(): Result ``` ## Parameters ### Result | Property | Type | Description | API_LEVEL | | -------- | ------------------- | ---------------------------------------------------------------------- | --------- | | age | `number` | User age, `0` if no data | 2.0 | | height | `number` | User height, `0` if no data | 2.0 | | weight | `number` | User weight, `0` if no data | 2.0 | | gender | `number` | User gender, value refer to user gender constants | 2.0 | | nickName | `string` | User's nickname | 2.0 | | region | `string` | ISO code of the country or region where the user account is registered | 2.0 | ## Constants ### User gender constants | Constant | Description | API_LEVEL | | -------------------- | ------------------ | --------- | | `GENDER_MALE` | Male | 2.0 | | `GENDER_FEMALE` | Female | 2.0 | | `GENDER_UNSPECIFIED` | User not specified | 2.0 | ## Example ```js const { age, gender } = getProfile() console.log(age) if (gender === GENDER_MALE) { console.log('male') } ``` --- --- # @zos/utils ## EventBus ### Import ```js import { EventBus } from '@zos/utils' ``` ### Typings - Description: EventBus is a utility class that provides event publishing/subscribing, an implementation of the publish-subscribe pattern - Example: ```js import { EventBus } from '@zos/utils' const eventBus = new EventBus() eventBus.on('data', (data) => { console.log(data) }) eventBus.emit('data', 'Hello Zepp OS!') ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). EventBus is a utility class that provides event publishing/subscribing, an implementation of the publish-subscribe pattern. ## Methods ### on Adds the listener function to the end of the listeners array for the event named eventName ```ts on(eventName: string, listener: (...args: any[]) => void): void ``` ### off Removes the specified listener from the listener array for the event named eventName ```ts off(eventName: string, listener: (...args: any[]) => void): void ``` ### emit Triggers the listener functions for the event named eventName ```ts emit(eventName: string, ...args: any[]): void ``` ### once Adds a one-time listener function for the event named eventName ```ts once(eventName: string, listener: (...args: any[]) => void): void ``` ### clear Removes all listeners, or those of the specified eventName ```ts clear(): void ``` ### count Gets the number of registered event listeners corresponding to `eventName`. If `eventName` is not passed, get the number of registered `eventName` types ```ts count(eventName?: string): number ``` ## Example ```js const eventBus = new EventBus() eventBus.on('data', (data) => { console.log(data) }) eventBus.emit('data', 'Hello Zepp OS!') ``` --- ## assets ### Import ```js import { assets } from '@zos/utils' ``` ### Typings - Description: Used to handle resource file paths, splice `basePath`. and can pass in parameters for rtl path conversion of images, for RTL adaptation of Mini Program - Example: ```js import { assets } from '@zos/utils' const imagePath = 'zeppos-logo.png' const assetsPathFunc = assets('img') console.log(assetsPathFunc(imagePath)) // img/zeppos-logo.png console.log(assetsPathFunc(imagePath, true)) // img/zeppos-logo@rtl.png ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Used to handle resource file paths, splice `basePath`. and can pass in parameters for rtl path conversion of images, for RTL adaptation of Mini Program. ## Type ```ts function assets(basePath: BasePath): AssetsPathFunc ``` ## Parameters ### BasePath | Type | Description | | ------------------- | ------------------------------------------------------------------ | | `string` | The base path, which will be spliced before the resource file path | ### AssetsPathFunc | Type | Description | | ---------------------------------------------------------- | ------------------------------ | | `(path: Path, isRtl?: IsRtl) => ResultPath` | Resource file path constructor | ### Path | Type | Description | | ------------------- | ------------------ | | `string` | Resource file path | ### IsRtl | Type | Description | | -------------------- | ------------------------------ | | `boolean` | Whether to splice the rtl path | ### ResultPath | Type | Description | | ------------------- | --------------- | | `string` | Final file path | ## Example ```js const imagePath = 'zeppos-logo.png' const assetsPathFunc = assets('img') console.log(assetsPathFunc(imagePath)) // img/zeppos-logo.png console.log(assetsPathFunc(imagePath, true)) // img/zeppos-logo@rtl.png ``` --- ## bufferToString ### Import ```js import { bufferToString } from '@zos/utils' ``` ### Typings - Description: Convert `ArrayBuffer` type to string type - API_LEVEL: 4.0 - Example: ```js import { bufferToString } from '@zos/utils' const str = bufferToString(buffer) ``` > Start from API_LEVEL `4.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Convert `ArrayBuffer` type to string type. ## Type ```ts function bufferToString(buffer: InputBuffer): Result ``` ## Parameters ### InputBuffer | Type | Description | | ------------------------ | --------------------------------- | | `ArrayBuffer` | The `ArrayBuffer` to be converted | ### Result | Type | Description | | ------------------- | -------------------- | | `string` | The converted string | ## Example ```js const str = bufferToString(buffer) ``` --- ## log ### Import ```js import { log } from '@zos/utils' ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). The `log` instance is used for log printing and has multiple levels of logging methods for easy filtering in the console. ## Methods ### getLogger Returns a new `log` instance with the `name` tag, which is added when the print log method is executed to make it easier to distinguish ```ts getLogger(name: string): log ``` ### log Print log level logs ```ts log(...args: string[]): void ``` ### warn Print warn level logs ```ts warn(...args: string[]): void ``` ### debug Print debug level logs ```ts debug(...args: string[]): void ``` ### error Print error level logs ```ts error(...args: string[]): void ``` ### info Print info level logs ```ts info(...args: string[]): void ``` ## Example ```js const pageLogger = log.getLogger('page') pageLogger.log('page created') pageLogger.error('page error') ``` --- ## px ### Import ```js import { px } from '@zos/utils' ``` ### Typings - Description: Pixel scaling calculation. The `designWidth` of each model in the `targets` object in the `app.json` is used as the base. - Example: ```js import { px } from '@zos/utils' px(480) ``` > Start from API_LEVEL `2.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Pixel scaling calculation. The `designWidth` of each model in the `targets` object in the `app.json` is used as the base.. ## Type ```ts function px(value: PxValue): Result ``` ## Parameters ### PxValue | Type | Description | | ------------------- | ----------------------------------- | | `number` | Pixel values based on `designWidth` | ### Result | Type | Description | | ------------------- | -------------------------------------- | | `number` | Pixel values after scaling calculation | ## Example ```js px(480) ``` --- ## stringToBuffer ### Import ```js import { stringToBuffer } from '@zos/utils' ``` ### Typings - Description: Convert string type to `ArrayBuffer` type - API_LEVEL: 4.0 - Example: ```js import { stringToBuffer } from '@zos/utils' const buffer = stringToBuffer('Hello Zepp OS') ``` > Start from API_LEVEL `4.0` . Please refer to [API_LEVEL](https://docs.zepp.com/docs/guides/framework/device/compatibility). Convert string type to `ArrayBuffer` type. ## Type ```ts function stringToBuffer(str: InputString): Result ``` ## Parameters ### InputString | Type | Description | | ------------------- | -------------------------- | | `string` | The string to be converted | ### Result | Type | Description | | ------------------------ | --------------------------- | | `ArrayBuffer` | The converted `ArrayBuffer` | ## Example ```js const buffer = stringToBuffer('Hello Zepp OS') ``` ---