diff --git a/OAT.xml b/OAT.xml index 921de7086caf44239a6f03c7c981eb9b37468f88..a3f824e949f32179b77535877df18c7ffc9b5495 100644 --- a/OAT.xml +++ b/OAT.xml @@ -142,8 +142,10 @@ + + diff --git a/packages/sensors_plus/sensors_plus/ohos/.gitignore b/packages/sensors_plus/sensors_plus/ohos/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..96486fd9302436d1f5334df3e5240c1ea252e7e9 --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/.gitignore @@ -0,0 +1,30 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock. +/pubspec.lock +**/doc/api/ +.dart_tool/ +.packages +build/ diff --git a/packages/sensors_plus/sensors_plus/ohos/CHANGELOG.md b/packages/sensors_plus/sensors_plus/ohos/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..fd91ecfdf17a21968366cf4c79a85b56b010e121 --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/CHANGELOG.md @@ -0,0 +1,3 @@ +## 1.0.0 + +* Support OpenHarmony diff --git a/packages/sensors_plus/sensors_plus/ohos/LICENSE b/packages/sensors_plus/sensors_plus/ohos/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..7b995420294b5e05e7244e5979f0493a1a74d2fb --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/LICENSE @@ -0,0 +1,27 @@ +Copyright 2017 The Chromium Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/packages/sensors_plus/sensors_plus/ohos/README.md b/packages/sensors_plus/sensors_plus/ohos/README.md new file mode 100644 index 0000000000000000000000000000000000000000..dc40d6e4706c634b5a083cd81f03ca3f4cd31196 --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/README.md @@ -0,0 +1,110 @@ +# sensors_plus_ohos + +Flutter插件,用于访问加速计、陀螺仪和磁力计传感器 + +## Usage +```yaml +dependencies: + sensors_plus: 3.0.0 + sensors_plus_ohos: 1.0.0 +``` + +### Example + +```pod +import 'package:sensors_plus_ohos/sensors_plus_ohos.dart'; + + @override + void initState() { + super.initState(); + _streamSubscriptions.add( + userAccelerometerEvents.listen( + (UserAccelerometerEvent event) { + setState(() { + _userAccelerometerValues = [event.x, event.y, event.z]; + }); + }, + onError: (e) { + showDialog( + context: context, + builder: (context) { + return const AlertDialog( + title: Text("Sensor Not Found"), + content: Text( + "It seems that your device doesn't support Accelerometer Sensor"), + ); + }); + }, + cancelOnError: true, + ), + ); + _streamSubscriptions.add( + accelerometerEvents.listen( + (AccelerometerEvent event) { + setState(() { + _accelerometerValues = [event.x, event.y, event.z]; + }); + }, + onError: (e) { + showDialog( + context: context, + builder: (context) { + return const AlertDialog( + title: Text("Sensor Not Found"), + content: Text( + "It seems that your device doesn't support Gyroscope Sensor"), + ); + }); + }, + cancelOnError: true, + ), + ); + _streamSubscriptions.add( + gyroscopeEvents.listen( + (GyroscopeEvent event) { + setState(() { + _gyroscopeValues = [event.x, event.y, event.z]; + }); + }, + onError: (e) { + showDialog( + context: context, + builder: (context) { + return const AlertDialog( + title: Text("Sensor Not Found"), + content: Text( + "It seems that your device doesn't support User Accelerometer Sensor"), + ); + }); + }, + cancelOnError: true, + ), + ); + _streamSubscriptions.add( + magnetometerEvents.listen( + (MagnetometerEvent event) { + setState(() { + _magnetometerValues = [event.x, event.y, event.z]; + }); + }, + onError: (e) { + showDialog( + context: context, + builder: (context) { + return const AlertDialog( + title: Text("Sensor Not Found"), + content: Text( + "It seems that your device doesn't support Magnetometer Sensor"), + ); + }); + }, + cancelOnError: true, + ), + ); + } +``` + +### Document +```pod +Android :https://github.com/fluttercommunity/plus_plugins/tree/main/packages/sensors_plus/sensors_plus +``` diff --git a/packages/sensors_plus/sensors_plus/ohos/analysis_options.yaml b/packages/sensors_plus/sensors_plus/ohos/analysis_options.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a5744c1cfbe77ae2daba29c74156c617b5f09b77 --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/analysis_options.yaml @@ -0,0 +1,4 @@ +include: package:flutter_lints/flutter.yaml + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/packages/sensors_plus/sensors_plus/ohos/example/.gitignore b/packages/sensors_plus/sensors_plus/ohos/example/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..24476c5d1eb55824c76d8b01a3965f94abad1ef8 --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/example/.gitignore @@ -0,0 +1,44 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.packages +.pub-cache/ +.pub/ +/build/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/packages/sensors_plus/sensors_plus/ohos/example/README.md b/packages/sensors_plus/sensors_plus/ohos/example/README.md new file mode 100644 index 0000000000000000000000000000000000000000..82c5c2bd9b364116b934ba5ee8be895477a55f26 --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/example/README.md @@ -0,0 +1,16 @@ +# sensors_plus_ohos_example + +Demonstrates how to use the sensors_plus_ohos plugin. + +## Getting Started + +This project is a starting point for a Flutter application. + +A few resources to get you started if this is your first Flutter project: + +- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) +- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook) + +For help getting started with Flutter development, view the +[online documentation](https://docs.flutter.dev/), which offers tutorials, +samples, guidance on mobile development, and a full API reference. diff --git a/packages/sensors_plus/sensors_plus/ohos/example/analysis_options.yaml b/packages/sensors_plus/sensors_plus/ohos/example/analysis_options.yaml new file mode 100644 index 0000000000000000000000000000000000000000..61b6c4de17c96863d24279f06b85e01b6ebbdb34 --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/example/analysis_options.yaml @@ -0,0 +1,29 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at + # https://dart-lang.github.io/linter/lints/index.html. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/packages/sensors_plus/sensors_plus/ohos/example/lib/main.dart b/packages/sensors_plus/sensors_plus/ohos/example/lib/main.dart new file mode 100644 index 0000000000000000000000000000000000000000..272468a0bde6be0e2e83b53d705734c7477dde52 --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/example/lib/main.dart @@ -0,0 +1,237 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// ignore_for_file: public_member_api_docs + +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:sensors_plus_ohos/sensors_plus_ohos.dart'; + +import 'snake.dart'; + +void main() { + WidgetsFlutterBinding.ensureInitialized(); + SystemChrome.setPreferredOrientations( + [ + DeviceOrientation.portraitUp, + DeviceOrientation.portraitDown, + ], + ); + + runApp(const MyApp()); +} + +class MyApp extends StatelessWidget { + const MyApp({Key? key}) : super(key: key); + + @override + Widget build(BuildContext context) { + return MaterialApp( + title: 'Sensors Demo', + theme: ThemeData( + useMaterial3: true, + colorSchemeSeed: const Color(0x9f4376f8), + ), + home: const MyHomePage(title: 'Flutter Demo Home Page'), + ); + } +} + +class MyHomePage extends StatefulWidget { + const MyHomePage({Key? key, this.title}) : super(key: key); + + final String? title; + + @override + State createState() => _MyHomePageState(); +} + +class _MyHomePageState extends State { + static const int _snakeRows = 20; + static const int _snakeColumns = 20; + static const double _snakeCellSize = 10.0; + + List? _userAccelerometerValues; + List? _accelerometerValues; + List? _gyroscopeValues; + List? _magnetometerValues; + final _streamSubscriptions = >[]; + + @override + Widget build(BuildContext context) { + final userAccelerometer = _userAccelerometerValues + ?.map((double v) => v.toStringAsFixed(1)) + .toList(); + final accelerometer = + _accelerometerValues?.map((double v) => v.toStringAsFixed(1)).toList(); + final gyroscope = + _gyroscopeValues?.map((double v) => v.toStringAsFixed(1)).toList(); + final magnetometer = + _magnetometerValues?.map((double v) => v.toStringAsFixed(1)).toList(); + + return Scaffold( + appBar: AppBar( + title: const Text('Sensors Plus Example'), + elevation: 4, + ), + body: Column( + mainAxisAlignment: MainAxisAlignment.spaceEvenly, + children: [ + Center( + child: DecoratedBox( + decoration: BoxDecoration( + border: Border.all(width: 1.0, color: Colors.black38), + ), + child: SizedBox( + height: _snakeRows * _snakeCellSize, + width: _snakeColumns * _snakeCellSize, + child: Snake( + rows: _snakeRows, + columns: _snakeColumns, + cellSize: _snakeCellSize, + ), + ), + ), + ), + Padding( + padding: const EdgeInsets.all(16.0), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text('UserAccelerometer: $userAccelerometer'), + ], + ), + ), + Padding( + padding: const EdgeInsets.all(16.0), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text('Accelerometer: $accelerometer'), + ], + ), + ), + Padding( + padding: const EdgeInsets.all(16.0), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text('Gyroscope: $gyroscope'), + ], + ), + ), + Padding( + padding: const EdgeInsets.all(16.0), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text('Magnetometer: $magnetometer'), + ], + ), + ), + ], + ), + ); + } + + @override + void dispose() { + super.dispose(); + for (final subscription in _streamSubscriptions) { + subscription.cancel(); + } + } + + @override + void initState() { + super.initState(); + _streamSubscriptions.add( + userAccelerometerEvents.listen( + (UserAccelerometerEvent event) { + setState(() { + _userAccelerometerValues = [event.x, event.y, event.z]; + }); + }, + onError: (e) { + showDialog( + context: context, + builder: (context) { + return const AlertDialog( + title: Text("Sensor Not Found"), + content: Text( + "It seems that your device doesn't support Accelerometer Sensor"), + ); + }); + }, + cancelOnError: true, + ), + ); + _streamSubscriptions.add( + accelerometerEvents.listen( + (AccelerometerEvent event) { + setState(() { + _accelerometerValues = [event.x, event.y, event.z]; + }); + }, + onError: (e) { + showDialog( + context: context, + builder: (context) { + return const AlertDialog( + title: Text("Sensor Not Found"), + content: Text( + "It seems that your device doesn't support Gyroscope Sensor"), + ); + }); + }, + cancelOnError: true, + ), + ); + _streamSubscriptions.add( + gyroscopeEvents.listen( + (GyroscopeEvent event) { + setState(() { + print('zhangLei-_gyroscopeValues-x: ${event.x.toString()}-y: ${event.y.toString()}-z: ${event.z.toString()}'); + _gyroscopeValues = [event.x, event.y, event.z]; + }); + }, + onError: (e) { + showDialog( + context: context, + builder: (context) { + return const AlertDialog( + title: Text("Sensor Not Found"), + content: Text( + "It seems that your device doesn't support User Accelerometer Sensor"), + ); + }); + }, + cancelOnError: true, + ), + ); + _streamSubscriptions.add( + magnetometerEvents.listen( + (MagnetometerEvent event) { + setState(() { + _magnetometerValues = [event.x, event.y, event.z]; + }); + }, + onError: (e) { + showDialog( + context: context, + builder: (context) { + return const AlertDialog( + title: Text("Sensor Not Found"), + content: Text( + "It seems that your device doesn't support Magnetometer Sensor"), + ); + }); + }, + cancelOnError: true, + ), + ); + } +} diff --git a/packages/sensors_plus/sensors_plus/ohos/example/lib/snake.dart b/packages/sensors_plus/sensors_plus/ohos/example/lib/snake.dart new file mode 100644 index 0000000000000000000000000000000000000000..5f1219e14df92d157987254b2d497a60616feb67 --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/example/lib/snake.dart @@ -0,0 +1,132 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// ignore_for_file: public_member_api_docs + +import 'dart:async'; +import 'dart:math' as math; + +import 'package:flutter/material.dart'; +import 'package:sensors_plus_ohos/sensors_plus_ohos.dart'; + +class Snake extends StatefulWidget { + Snake({Key? key, this.rows = 20, this.columns = 20, this.cellSize = 10.0}) + : super(key: key) { + assert(10 <= rows); + assert(10 <= columns); + assert(5.0 <= cellSize); + } + + final int rows; + final int columns; + final double cellSize; + + @override + // ignore: no_logic_in_create_state + State createState() => SnakeState(rows, columns, cellSize); +} + +class SnakeBoardPainter extends CustomPainter { + SnakeBoardPainter(this.state, this.cellSize); + + GameState? state; + double cellSize; + + @override + void paint(Canvas canvas, Size size) { + final blackLine = Paint()..color = Colors.black; + final blackFilled = Paint() + ..color = Colors.black + ..style = PaintingStyle.fill; + canvas.drawRect( + Rect.fromPoints(Offset.zero, size.bottomLeft(Offset.zero)), + blackLine, + ); + for (final p in state!.body) { + final a = Offset(cellSize * p.x, cellSize * p.y); + final b = Offset(cellSize * (p.x + 1), cellSize * (p.y + 1)); + + canvas.drawRect(Rect.fromPoints(a, b), blackFilled); + } + } + + @override + bool shouldRepaint(CustomPainter oldDelegate) { + return true; + } +} + +class SnakeState extends State { + SnakeState(int rows, int columns, this.cellSize) { + state = GameState(rows, columns); + } + + double cellSize; + GameState? state; + AccelerometerEvent? acceleration; + late StreamSubscription _streamSubscription; + late Timer _timer; + + @override + Widget build(BuildContext context) { + return CustomPaint(painter: SnakeBoardPainter(state, cellSize)); + } + + @override + void dispose() { + super.dispose(); + _streamSubscription.cancel(); + _timer.cancel(); + } + + @override + void initState() { + super.initState(); + _streamSubscription = + accelerometerEvents.listen((AccelerometerEvent event) { + setState(() { + acceleration = event; + }); + }); + + _timer = Timer.periodic(const Duration(milliseconds: 200), (_) { + setState(() { + _step(); + }); + }); + } + + void _step() { + final newDirection = acceleration == null + ? null + : acceleration!.x.abs() < 1.0 && acceleration!.y.abs() < 1.0 + ? null + : (acceleration!.x.abs() < acceleration!.y.abs()) + ? math.Point(0, acceleration!.y.sign.toInt()) + : math.Point(-acceleration!.x.sign.toInt(), 0); + state!.step(newDirection); + } +} + +class GameState { + GameState(this.rows, this.columns) { + snakeLength = math.min(rows, columns) - 5; + } + + int rows; + int columns; + late int snakeLength; + + List> body = >[const math.Point(0, 0)]; + math.Point direction = const math.Point(1, 0); + + void step(math.Point? newDirection) { + var next = body.last + direction; + next = math.Point(next.x % columns, next.y % rows); + + body.add(next); + if (body.length > snakeLength) body.removeAt(0); + direction = newDirection ?? direction; + } +} diff --git a/packages/sensors_plus/sensors_plus/ohos/example/ohos/.gitignore b/packages/sensors_plus/sensors_plus/ohos/example/ohos/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..6ca13b3170eec5dd5ac5ad7f1c4dd0118845f473 --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/example/ohos/.gitignore @@ -0,0 +1,19 @@ +/node_modules +/oh_modules +/local.properties +/.idea +**/build +/.hvigor +.cxx +/.clangd +/.clang-format +/.clang-tidy +**/.test +*.har +**/BuildProfile.ets +**/oh-package-lock.json5 + +**/src/main/resources/rawfile/flutter_assets/ +**/libs/arm64-v8a/libapp.so +**/libs/arm64-v8a/libflutter.so +**/libs/arm64-v8a/libvmservice_snapshot.so diff --git a/packages/sensors_plus/sensors_plus/ohos/example/ohos/AppScope/app.json5 b/packages/sensors_plus/sensors_plus/ohos/example/ohos/AppScope/app.json5 new file mode 100644 index 0000000000000000000000000000000000000000..5a788d32801a24755b6d21eadba01992bac94535 --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/example/ohos/AppScope/app.json5 @@ -0,0 +1,10 @@ +{ + "app": { + "bundleName": "com.example.sensors_plus_ohos_example", + "vendor": "example", + "versionCode": 1000000, + "versionName": "1.0.0", + "icon": "$media:app_icon", + "label": "$string:app_name" + } +} \ No newline at end of file diff --git a/packages/sensors_plus/sensors_plus/ohos/example/ohos/AppScope/resources/base/element/string.json b/packages/sensors_plus/sensors_plus/ohos/example/ohos/AppScope/resources/base/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..3717fad8df8bd3f8bf77245617a6309c201db973 --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/example/ohos/AppScope/resources/base/element/string.json @@ -0,0 +1,8 @@ +{ + "string": [ + { + "name": "app_name", + "value": "sensors_plus_ohos_example" + } + ] +} diff --git a/packages/sensors_plus/sensors_plus/ohos/example/ohos/AppScope/resources/base/media/app_icon.png b/packages/sensors_plus/sensors_plus/ohos/example/ohos/AppScope/resources/base/media/app_icon.png new file mode 100644 index 0000000000000000000000000000000000000000..ce307a8827bd75456441ceb57d530e4c8d45d36c Binary files /dev/null and b/packages/sensors_plus/sensors_plus/ohos/example/ohos/AppScope/resources/base/media/app_icon.png differ diff --git a/packages/sensors_plus/sensors_plus/ohos/example/ohos/build-profile.json5 b/packages/sensors_plus/sensors_plus/ohos/example/ohos/build-profile.json5 new file mode 100644 index 0000000000000000000000000000000000000000..1d12140d202702d7c73d64f1b291fe5c45a660ce --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/example/ohos/build-profile.json5 @@ -0,0 +1,27 @@ +{ + "app": { + "signingConfigs": [], + "products": [ + { + "name": "default", + "signingConfig": "default", + "compatibleSdkVersion": "5.0.0(12)", + "runtimeOS": "HarmonyOS" + } + ] + }, + "modules": [ + { + "name": "entry", + "srcPath": "./entry", + "targets": [ + { + "name": "default", + "applyToProducts": [ + "default" + ] + } + ] + } + ] +} \ No newline at end of file diff --git a/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/.gitignore b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..2795a1c5b1fe53659dd1b71d90ba0592eaf7e043 --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/.gitignore @@ -0,0 +1,7 @@ + +/node_modules +/oh_modules +/.preview +/build +/.cxx +/.test \ No newline at end of file diff --git a/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/build-profile.json5 b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/build-profile.json5 new file mode 100644 index 0000000000000000000000000000000000000000..633d360fbc91a3186a23b66ab71b27e5618944cb --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/build-profile.json5 @@ -0,0 +1,29 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +{ + "apiType": 'stageMode', + "buildOption": { + }, + "targets": [ + { + "name": "default", + "runtimeOS": "HarmonyOS" + }, + { + "name": "ohosTest", + } + ] +} \ No newline at end of file diff --git a/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/hvigorfile.ts b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/hvigorfile.ts new file mode 100644 index 0000000000000000000000000000000000000000..894fc15c6b793f085e6c8506e43d719af658e8ff --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/hvigorfile.ts @@ -0,0 +1,17 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// Script for compiling build behavior. It is built in the build plug-in and cannot be modified currently. +export { hapTasks } from '@ohos/hvigor-ohos-plugin'; diff --git a/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/oh-package.json5 b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/oh-package.json5 new file mode 100644 index 0000000000000000000000000000000000000000..307db85eb6e206b1bea5afc1c6d5fedd646c064e --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/oh-package.json5 @@ -0,0 +1,11 @@ +{ + "name": "entry", + "version": "1.0.0", + "description": "Please describe the basic information.", + "main": "", + "author": "", + "license": "", + "dependencies": { + "sensors_plus_ohos": "file:../har/sensors_plus_ohos.har" + } +} \ No newline at end of file diff --git a/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/main/ets/entryability/EntryAbility.ets b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/main/ets/entryability/EntryAbility.ets new file mode 100644 index 0000000000000000000000000000000000000000..8bc48be8773196f34cccb15cf517f87f5c6b94d2 --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/main/ets/entryability/EntryAbility.ets @@ -0,0 +1,24 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import { FlutterAbility, FlutterEngine } from '@ohos/flutter_ohos'; +import { GeneratedPluginRegistrant } from '../plugins/GeneratedPluginRegistrant'; + +export default class EntryAbility extends FlutterAbility { + configureFlutterEngine(flutterEngine: FlutterEngine) { + super.configureFlutterEngine(flutterEngine) + GeneratedPluginRegistrant.registerWith(flutterEngine) + } +} diff --git a/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/main/ets/pages/Index.ets b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/main/ets/pages/Index.ets new file mode 100644 index 0000000000000000000000000000000000000000..1125f9fdd95f4310a182c1c9e3680f37f73686c9 --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/main/ets/pages/Index.ets @@ -0,0 +1,38 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import common from '@ohos.app.ability.common'; +import { FlutterPage } from '@ohos/flutter_ohos' + +let storage = LocalStorage.getShared() +const EVENT_BACK_PRESS = 'EVENT_BACK_PRESS' + +@Entry(storage) +@Component +struct Index { + private context = getContext(this) as common.UIAbilityContext + @LocalStorageLink('viewId') viewId: string = ""; + + build() { + Column() { + FlutterPage({ viewId: this.viewId }) + } + } + + onBackPress(): boolean { + this.context.eventHub.emit(EVENT_BACK_PRESS) + return true + } +} \ No newline at end of file diff --git a/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/main/ets/plugins/GeneratedPluginRegistrant.ets b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/main/ets/plugins/GeneratedPluginRegistrant.ets new file mode 100644 index 0000000000000000000000000000000000000000..d212a6d274b8910e95aabb29911756a88467aa8a --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/main/ets/plugins/GeneratedPluginRegistrant.ets @@ -0,0 +1,41 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { FlutterEngine, Log } from '@ohos/flutter_ohos'; +import SensorsPlusOhosPlugin from 'sensors_plus_ohos'; + +/** + * Generated file. Do not edit. + * This file is generated by the Flutter tool based on the + * plugins that support the Ohos platform. + */ + +const TAG = "GeneratedPluginRegistrant"; + +export class GeneratedPluginRegistrant { + + static registerWith(flutterEngine: FlutterEngine) { + try { + flutterEngine.getPlugins()?.add(new SensorsPlusOhosPlugin()); + } catch (e) { + Log.e( + TAG, + "Tried to register plugins with FlutterEngine (" + + flutterEngine + + ") failed."); + Log.e(TAG, "Received exception while registering", e); + } + } +} diff --git a/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/main/module.json5 b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/main/module.json5 new file mode 100644 index 0000000000000000000000000000000000000000..a479c149d002d4d3635c332bf08c7e0b8fa319ac --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/main/module.json5 @@ -0,0 +1,55 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +{ + "module": { + "name": "entry", + "type": "entry", + "description": "$string:module_desc", + "mainElement": "EntryAbility", + "deviceTypes": [ + "phone" + ], + "deliveryWithInstall": true, + "installationFree": false, + "pages": "$profile:main_pages", + "abilities": [ + { + "name": "EntryAbility", + "srcEntry": "./ets/entryability/EntryAbility.ets", + "description": "$string:EntryAbility_desc", + "icon": "$media:icon", + "label": "$string:EntryAbility_label", + "startWindowIcon": "$media:icon", + "startWindowBackground": "$color:start_window_background", + "exported": true, + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ] + } + ], + "requestPermissions": [ + {"name" : "ohos.permission.INTERNET"}, + {"name" : "ohos.permission.GYROSCOPE"}, + {"name" : "ohos.permission.ACCELEROMETER"}, + ] + } +} \ No newline at end of file diff --git a/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/main/resources/base/element/color.json b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/main/resources/base/element/color.json new file mode 100644 index 0000000000000000000000000000000000000000..3c712962da3c2751c2b9ddb53559afcbd2b54a02 --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/main/resources/base/element/color.json @@ -0,0 +1,8 @@ +{ + "color": [ + { + "name": "start_window_background", + "value": "#FFFFFF" + } + ] +} \ No newline at end of file diff --git a/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/main/resources/base/element/string.json b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/main/resources/base/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..cfc0c13b4083eda3710f3817e2135051e2175286 --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/main/resources/base/element/string.json @@ -0,0 +1,16 @@ +{ + "string": [ + { + "name": "module_desc", + "value": "module description" + }, + { + "name": "EntryAbility_desc", + "value": "description" + }, + { + "name": "EntryAbility_label", + "value": "sensors_plus_ohos_example" + } + ] +} \ No newline at end of file diff --git a/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/main/resources/base/media/icon.png b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/main/resources/base/media/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..ce307a8827bd75456441ceb57d530e4c8d45d36c Binary files /dev/null and b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/main/resources/base/media/icon.png differ diff --git a/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/main/resources/base/profile/main_pages.json b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/main/resources/base/profile/main_pages.json new file mode 100644 index 0000000000000000000000000000000000000000..1898d94f58d6128ab712be2c68acc7c98e9ab9ce --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/main/resources/base/profile/main_pages.json @@ -0,0 +1,5 @@ +{ + "src": [ + "pages/Index" + ] +} diff --git a/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/main/resources/en_US/element/string.json b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/main/resources/en_US/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..cfc0c13b4083eda3710f3817e2135051e2175286 --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/main/resources/en_US/element/string.json @@ -0,0 +1,16 @@ +{ + "string": [ + { + "name": "module_desc", + "value": "module description" + }, + { + "name": "EntryAbility_desc", + "value": "description" + }, + { + "name": "EntryAbility_label", + "value": "sensors_plus_ohos_example" + } + ] +} \ No newline at end of file diff --git a/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/main/resources/zh_CN/element/string.json b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/main/resources/zh_CN/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..3b48c4baec8d4275d15e1f5ad1f2f8455fb19e60 --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/main/resources/zh_CN/element/string.json @@ -0,0 +1,16 @@ +{ + "string": [ + { + "name": "module_desc", + "value": "模块描述" + }, + { + "name": "EntryAbility_desc", + "value": "description" + }, + { + "name": "EntryAbility_label", + "value": "sensors_plus_ohos_example" + } + ] +} \ No newline at end of file diff --git a/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/ohosTest/ets/test/Ability.test.ets b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/ohosTest/ets/test/Ability.test.ets new file mode 100644 index 0000000000000000000000000000000000000000..25d4c71ff3cd584f5d64f6f8c0ac864928c234c4 --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/ohosTest/ets/test/Ability.test.ets @@ -0,0 +1,50 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import hilog from '@ohos.hilog'; +import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium' + +export default function abilityTest() { + describe('ActsAbilityTest', function () { + // Defines a test suite. Two parameters are supported: test suite name and test suite function. + beforeAll(function () { + // Presets an action, which is performed only once before all test cases of the test suite start. + // This API supports only one parameter: preset action function. + }) + beforeEach(function () { + // Presets an action, which is performed before each unit test case starts. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: preset action function. + }) + afterEach(function () { + // Presets a clear action, which is performed after each unit test case ends. + // The number of execution times is the same as the number of test cases defined by **it**. + // This API supports only one parameter: clear action function. + }) + afterAll(function () { + // Presets a clear action, which is performed after all test cases of the test suite end. + // This API supports only one parameter: clear action function. + }) + it('assertContain',0, function () { + // Defines a test case. This API supports three parameters: test case name, filter parameter, and test case function. + hilog.info(0x0000, 'testTag', '%{public}s', 'it begin'); + let a = 'abc' + let b = 'b' + // Defines a variety of assertion methods, which are used to declare expected boolean conditions. + expect(a).assertContain(b) + expect(a).assertEqual(a) + }) + }) +} \ No newline at end of file diff --git a/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/ohosTest/ets/test/List.test.ets b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/ohosTest/ets/test/List.test.ets new file mode 100644 index 0000000000000000000000000000000000000000..f4140030e65d20df6af30a6bf51e464dea8f8aa6 --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/ohosTest/ets/test/List.test.ets @@ -0,0 +1,20 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import abilityTest from './Ability.test' + +export default function testsuite() { + abilityTest() +} \ No newline at end of file diff --git a/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/ohosTest/ets/testability/TestAbility.ets b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/ohosTest/ets/testability/TestAbility.ets new file mode 100644 index 0000000000000000000000000000000000000000..4ca645e6013cfce8e7dbb728313cb8840c4da660 --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/ohosTest/ets/testability/TestAbility.ets @@ -0,0 +1,63 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import UIAbility from '@ohos.app.ability.UIAbility'; +import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; +import hilog from '@ohos.hilog'; +import { Hypium } from '@ohos/hypium'; +import testsuite from '../test/List.test'; +import window from '@ohos.window'; + +export default class TestAbility extends UIAbility { + onCreate(want, launchParam) { + hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility onCreate'); + hilog.info(0x0000, 'testTag', '%{public}s', 'want param:' + JSON.stringify(want) ?? ''); + hilog.info(0x0000, 'testTag', '%{public}s', 'launchParam:'+ JSON.stringify(launchParam) ?? ''); + var abilityDelegator: any + abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator() + var abilityDelegatorArguments: any + abilityDelegatorArguments = AbilityDelegatorRegistry.getArguments() + hilog.info(0x0000, 'testTag', '%{public}s', 'start run testcase!!!'); + Hypium.hypiumTest(abilityDelegator, abilityDelegatorArguments, testsuite) + } + + onDestroy() { + hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility onDestroy'); + } + + onWindowStageCreate(windowStage: window.WindowStage) { + hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility onWindowStageCreate'); + windowStage.loadContent('testability/pages/Index', (err, data) => { + if (err.code) { + hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); + return; + } + hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', + JSON.stringify(data) ?? ''); + }); + } + + onWindowStageDestroy() { + hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility onWindowStageDestroy'); + } + + onForeground() { + hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility onForeground'); + } + + onBackground() { + hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility onBackground'); + } +} \ No newline at end of file diff --git a/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/ohosTest/ets/testability/pages/Index.ets b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/ohosTest/ets/testability/pages/Index.ets new file mode 100644 index 0000000000000000000000000000000000000000..cef0447cd2f137ef82d223ead2e156808878ab90 --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/ohosTest/ets/testability/pages/Index.ets @@ -0,0 +1,49 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import hilog from '@ohos.hilog'; + +@Entry +@Component +struct Index { + aboutToAppear() { + hilog.info(0x0000, 'testTag', '%{public}s', 'TestAbility index aboutToAppear'); + } + @State message: string = 'Hello World' + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + Button() { + Text('next page') + .fontSize(20) + .fontWeight(FontWeight.Bold) + }.type(ButtonType.Capsule) + .margin({ + top: 20 + }) + .backgroundColor('#0D9FFB') + .width('35%') + .height('5%') + .onClick(()=>{ + }) + } + .width('100%') + } + .height('100%') + } + } \ No newline at end of file diff --git a/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/ohosTest/ets/testrunner/OpenHarmonyTestRunner.ts b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/ohosTest/ets/testrunner/OpenHarmonyTestRunner.ts new file mode 100644 index 0000000000000000000000000000000000000000..1def08f2e9dcbfa3454a07b7a3b82b173bb90d02 --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/ohosTest/ets/testrunner/OpenHarmonyTestRunner.ts @@ -0,0 +1,64 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import hilog from '@ohos.hilog'; +import TestRunner from '@ohos.application.testRunner'; +import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; + +var abilityDelegator = undefined +var abilityDelegatorArguments = undefined + +async function onAbilityCreateCallback() { + hilog.info(0x0000, 'testTag', '%{public}s', 'onAbilityCreateCallback'); +} + +async function addAbilityMonitorCallback(err: any) { + hilog.info(0x0000, 'testTag', 'addAbilityMonitorCallback : %{public}s', JSON.stringify(err) ?? ''); +} + +export default class OpenHarmonyTestRunner implements TestRunner { + constructor() { + } + + onPrepare() { + hilog.info(0x0000, 'testTag', '%{public}s', 'OpenHarmonyTestRunner OnPrepare '); + } + + async onRun() { + hilog.info(0x0000, 'testTag', '%{public}s', 'OpenHarmonyTestRunner onRun run'); + abilityDelegatorArguments = AbilityDelegatorRegistry.getArguments() + abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator() + var testAbilityName = abilityDelegatorArguments.bundleName + '.TestAbility' + let lMonitor = { + abilityName: testAbilityName, + onAbilityCreate: onAbilityCreateCallback, + }; + abilityDelegator.addAbilityMonitor(lMonitor, addAbilityMonitorCallback) + var cmd = 'aa start -d 0 -a TestAbility' + ' -b ' + abilityDelegatorArguments.bundleName + var debug = abilityDelegatorArguments.parameters['-D'] + if (debug == 'true') + { + cmd += ' -D' + } + hilog.info(0x0000, 'testTag', 'cmd : %{public}s', cmd); + abilityDelegator.executeShellCommand(cmd, + (err: any, d: any) => { + hilog.info(0x0000, 'testTag', 'executeShellCommand : err : %{public}s', JSON.stringify(err) ?? ''); + hilog.info(0x0000, 'testTag', 'executeShellCommand : data : %{public}s', d.stdResult ?? ''); + hilog.info(0x0000, 'testTag', 'executeShellCommand : data : %{public}s', d.exitCode ?? ''); + }) + hilog.info(0x0000, 'testTag', '%{public}s', 'OpenHarmonyTestRunner onRun end'); + } +} \ No newline at end of file diff --git a/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/ohosTest/module.json5 b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/ohosTest/module.json5 new file mode 100644 index 0000000000000000000000000000000000000000..fab77ce2e0c61e3ad010bab5b27ccbd15f9a8c96 --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/ohosTest/module.json5 @@ -0,0 +1,51 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +{ + "module": { + "name": "entry_test", + "type": "feature", + "description": "$string:module_test_desc", + "mainElement": "TestAbility", + "deviceTypes": [ + "phone" + ], + "deliveryWithInstall": true, + "installationFree": false, + "pages": "$profile:test_pages", + "abilities": [ + { + "name": "TestAbility", + "srcEntry": "./ets/testability/TestAbility.ets", + "description": "$string:TestAbility_desc", + "icon": "$media:icon", + "label": "$string:TestAbility_label", + "exported": true, + "startWindowIcon": "$media:icon", + "startWindowBackground": "$color:start_window_background", + "skills": [ + { + "actions": [ + "action.system.home" + ], + "entities": [ + "entity.system.home" + ] + } + ] + } + ] + } +} diff --git a/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/ohosTest/resources/base/element/color.json b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/ohosTest/resources/base/element/color.json new file mode 100644 index 0000000000000000000000000000000000000000..3c712962da3c2751c2b9ddb53559afcbd2b54a02 --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/ohosTest/resources/base/element/color.json @@ -0,0 +1,8 @@ +{ + "color": [ + { + "name": "start_window_background", + "value": "#FFFFFF" + } + ] +} \ No newline at end of file diff --git a/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/ohosTest/resources/base/element/string.json b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/ohosTest/resources/base/element/string.json new file mode 100644 index 0000000000000000000000000000000000000000..65d8fa5a7cf54aa3943dcd0214f58d1771bc1f6c --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/ohosTest/resources/base/element/string.json @@ -0,0 +1,16 @@ +{ + "string": [ + { + "name": "module_test_desc", + "value": "test ability description" + }, + { + "name": "TestAbility_desc", + "value": "the test ability" + }, + { + "name": "TestAbility_label", + "value": "test label" + } + ] +} \ No newline at end of file diff --git a/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/ohosTest/resources/base/media/icon.png b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/ohosTest/resources/base/media/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..ce307a8827bd75456441ceb57d530e4c8d45d36c Binary files /dev/null and b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/ohosTest/resources/base/media/icon.png differ diff --git a/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/ohosTest/resources/base/profile/test_pages.json b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/ohosTest/resources/base/profile/test_pages.json new file mode 100644 index 0000000000000000000000000000000000000000..b7e7343cacb32ce982a45e76daad86e435e054fe --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/example/ohos/entry/src/ohosTest/resources/base/profile/test_pages.json @@ -0,0 +1,5 @@ +{ + "src": [ + "testability/pages/Index" + ] +} diff --git a/packages/sensors_plus/sensors_plus/ohos/example/ohos/hvigor/hvigor-config.json5 b/packages/sensors_plus/sensors_plus/ohos/example/ohos/hvigor/hvigor-config.json5 new file mode 100644 index 0000000000000000000000000000000000000000..541ba35711b75986f9295410ee38fdb8f2572878 --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/example/ohos/hvigor/hvigor-config.json5 @@ -0,0 +1,20 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +{ + "modelVersion": "5.0.0", + "dependencies": { + } +} \ No newline at end of file diff --git a/packages/sensors_plus/sensors_plus/ohos/example/ohos/hvigorfile.ts b/packages/sensors_plus/sensors_plus/ohos/example/ohos/hvigorfile.ts new file mode 100644 index 0000000000000000000000000000000000000000..8f2d2aafe6d6a3a71a9944ebd0c91fbc308ac9d1 --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/example/ohos/hvigorfile.ts @@ -0,0 +1,21 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import { appTasks } from '@ohos/hvigor-ohos-plugin'; + +export default { + system: appTasks, /* Built-in plugin of Hvigor. It cannot be modified. */ + plugins:[] /* Custom plugin to extend the functionality of Hvigor. */ +} \ No newline at end of file diff --git a/packages/sensors_plus/sensors_plus/ohos/example/ohos/oh-package.json5 b/packages/sensors_plus/sensors_plus/ohos/example/ohos/oh-package.json5 new file mode 100644 index 0000000000000000000000000000000000000000..6a0918696894e78ad886034142f32f90eaecd039 --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/example/ohos/oh-package.json5 @@ -0,0 +1,20 @@ +{ + "modelVersion": "5.0.0", + "name": "sensors_plus_ohos_example", + "version": "1.0.0", + "description": "Please describe the basic information.", + "main": "", + "author": "", + "license": "", + "dependencies": { + "@ohos/flutter_ohos": "file:./har/flutter.har" + }, + "devDependencies": { + "@ohos/hypium": "1.0.6" + }, + "overrides": { + "@ohos/flutter_ohos": "file:./har/flutter.har", + "sensors_plus_ohos": "file:F:./har/sensors_plus_ohos.har", + "@ohos/flutter_module": "file:./entry" + } +} \ No newline at end of file diff --git a/packages/sensors_plus/sensors_plus/ohos/example/pubspec.yaml b/packages/sensors_plus/sensors_plus/ohos/example/pubspec.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fe4ddf3c86a411130f451a539f937df8b2279188 --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/example/pubspec.yaml @@ -0,0 +1,83 @@ +name: sensors_plus_ohos_example +description: Demonstrates how to use the sensors_plus_ohos plugin. +# The following line prevents the package from being accidentally published to +# pub.dev using `flutter pub publish`. This is preferred for private packages. +publish_to: 'none' # Remove this line if you wish to publish to pub.dev + +environment: + sdk: '>=2.19.6 <3.0.0' + +# Dependencies specify other packages that your package needs in order to work. +# To automatically upgrade your package dependencies to the latest versions +# consider running `flutter pub upgrade --major-versions`. Alternatively, +# dependencies can be manually updated by changing the version numbers below to +# the latest version available on pub.dev. To see which dependencies have newer +# versions available, run `flutter pub outdated`. +dependencies: + flutter: + sdk: flutter + + sensors_plus_ohos: + # When depending on this package from a real application you should use: + # sensors_plus_ohos: ^x.y.z + # See https://dart.dev/tools/pub/dependencies#version-constraints + # The example app is bundled with the plugin so we use a path dependency on + # the parent directory to use the current plugin's version. + path: ../ + + # The following adds the Cupertino Icons font to your application. + # Use with the CupertinoIcons class for iOS style icons. + cupertino_icons: ^1.0.2 + +dev_dependencies: + flutter_test: + sdk: flutter + + # The "flutter_lints" package below contains a set of recommended lints to + # encourage good coding practices. The lint set provided by the package is + # activated in the `analysis_options.yaml` file located at the root of your + # package. See that file for information about deactivating specific lint + # rules and activating additional ones. + flutter_lints: ^2.0.0 + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + +# The following section is specific to Flutter packages. +flutter: + + # The following line ensures that the Material Icons font is + # included with your application, so that you can use the icons in + # the material Icons class. + uses-material-design: true + + # To add assets to your application, add an assets section, like this: + # assets: + # - images/a_dot_burr.jpeg + # - images/a_dot_ham.jpeg + + # An image asset can refer to one or more resolution-specific "variants", see + # https://flutter.dev/assets-and-images/#resolution-aware + + # For details regarding adding assets from package dependencies, see + # https://flutter.dev/assets-and-images/#from-packages + + # To add custom fonts to your application, add a fonts section here, + # in this "flutter" section. Each entry in this list should have a + # "family" key with the font family name, and a "fonts" key with a + # list giving the asset and other descriptors for the font. For + # example: + # fonts: + # - family: Schyler + # fonts: + # - asset: fonts/Schyler-Regular.ttf + # - asset: fonts/Schyler-Italic.ttf + # style: italic + # - family: Trajan Pro + # fonts: + # - asset: fonts/TrajanPro.ttf + # - asset: fonts/TrajanPro_Bold.ttf + # weight: 700 + # + # For details regarding fonts from package dependencies, + # see https://flutter.dev/custom-fonts/#from-packages diff --git a/packages/sensors_plus/sensors_plus/ohos/example/test/widget_test.dart b/packages/sensors_plus/sensors_plus/ohos/example/test/widget_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..ed6be073eadd955dc2c32831294f1f0e445962a6 --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/example/test/widget_test.dart @@ -0,0 +1,27 @@ +// This is a basic Flutter widget test. +// +// To perform an interaction with a widget in your test, use the WidgetTester +// utility in the flutter_test package. For example, you can send tap and scroll +// gestures. You can also use WidgetTester to find child widgets in the widget +// tree, read text, and verify that the values of widget properties are correct. + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:sensors_plus_ohos_example/main.dart'; + +void main() { + testWidgets('Verify Platform version', (WidgetTester tester) async { + // Build our app and trigger a frame. + await tester.pumpWidget(const MyApp()); + + // Verify that platform version is retrieved. + expect( + find.byWidgetPredicate( + (Widget widget) => widget is Text && + widget.data!.startsWith('Running on:'), + ), + findsOneWidget, + ); + }); +} diff --git a/packages/sensors_plus/sensors_plus/ohos/lib/sensors_plus_ohos.dart b/packages/sensors_plus/sensors_plus/ohos/lib/sensors_plus_ohos.dart new file mode 100644 index 0000000000000000000000000000000000000000..bfa305f721882bf188277cbeef8c55bf4ec5aedb --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/lib/sensors_plus_ohos.dart @@ -0,0 +1,29 @@ +import 'package:sensors_plus_platform_interface/sensors_plus_platform_interface.dart'; + +import 'src/sensors_ohos.dart'; + +export 'package:sensors_plus_platform_interface/sensors_plus_platform_interface.dart'; + +export 'src/sensors_ohos.dart' if (dart.library.html) 'src/sensors_plus_web_ohos.dart'; + +final _sensors = Sensors(); + +/// A broadcast stream of events from the device accelerometer. +Stream get accelerometerEvents { + return _sensors.accelerometerEvents; +} + +/// A broadcast stream of events from the device gyroscope. +Stream get gyroscopeEvents { + return _sensors.gyroscopeEvents; +} + +/// Events from the device accelerometer with gravity removed. +Stream get userAccelerometerEvents { + return _sensors.userAccelerometerEvents; +} + +/// A broadcast stream of events from the device magnetometer. +Stream get magnetometerEvents { + return _sensors.magnetometerEvents; +} diff --git a/packages/sensors_plus/sensors_plus/ohos/lib/src/sensors_ohos.dart b/packages/sensors_plus/sensors_plus/ohos/lib/src/sensors_ohos.dart new file mode 100644 index 0000000000000000000000000000000000000000..59ac78cb8fa9dce35bec47c816a3ea632d722272 --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/lib/src/sensors_ohos.dart @@ -0,0 +1,39 @@ +import 'package:sensors_plus_platform_interface/sensors_plus_platform_interface.dart'; + +/// The Sensors implementation. +class Sensors extends SensorsPlatform { + /// Constructs a singleton instance of [Sensors]. + /// + /// [Sensors] is designed to work as a singleton. + factory Sensors() => _singleton ??= Sensors._(); + + Sensors._(); + + static Sensors? _singleton; + + static SensorsPlatform get _platform => SensorsPlatform.instance; + + /// A broadcast stream of events from the device accelerometer. + @override + Stream get accelerometerEvents { + return _platform.accelerometerEvents; + } + + /// A broadcast stream of events from the device gyroscope. + @override + Stream get gyroscopeEvents { + return _platform.gyroscopeEvents; + } + + /// Events from the device accelerometer with gravity removed. + @override + Stream get userAccelerometerEvents { + return _platform.userAccelerometerEvents; + } + + /// A broadcast stream of events from the device magnetometer. + @override + Stream get magnetometerEvents { + return _platform.magnetometerEvents; + } +} diff --git a/packages/sensors_plus/sensors_plus/ohos/lib/src/sensors_plus_web_ohos.dart b/packages/sensors_plus/sensors_plus/ohos/lib/src/sensors_plus_web_ohos.dart new file mode 100644 index 0000000000000000000000000000000000000000..0d762c9e09ed88c2661d3d296426481512369db4 --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/lib/src/sensors_plus_web_ohos.dart @@ -0,0 +1,29 @@ +import 'package:sensors_plus_platform_interface/sensors_plus_platform_interface.dart'; + +import 'web_sensors_ohos.dart'; + +export 'package:sensors_plus_platform_interface/sensors_plus_platform_interface.dart'; + +export 'web_sensors_ohos.dart'; + +final _sensors = WebSensorsPlugin(); + +/// A broadcast stream of events from the device accelerometer. +Stream get accelerometerEvents { + return _sensors.accelerometerEvents; +} + +/// A broadcast stream of events from the device gyroscope. +Stream get gyroscopeEvents { + return _sensors.gyroscopeEvents; +} + +/// Events from the device accelerometer with gravity removed. +Stream get userAccelerometerEvents { + return _sensors.userAccelerometerEvents; +} + +/// A broadcast stream of events from the device magnetometer. +Stream get magnetometerEvents { + return _sensors.magnetometerEvents; +} diff --git a/packages/sensors_plus/sensors_plus/ohos/lib/src/web_sensors_ohos.dart b/packages/sensors_plus/sensors_plus/ohos/lib/src/web_sensors_ohos.dart new file mode 100644 index 0000000000000000000000000000000000000000..2f886b0192cd8bad64c123efe4a7b7996a465247 --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/lib/src/web_sensors_ohos.dart @@ -0,0 +1,252 @@ +import 'dart:async'; +import 'dart:developer' as developer; +import 'dart:html' as html + show LinearAccelerationSensor, Accelerometer, Gyroscope, Magnetometer; +import 'dart:js_util'; + +import 'package:flutter_web_plugins/flutter_web_plugins.dart'; +import 'package:sensors_plus_platform_interface/sensors_plus_platform_interface.dart'; + +/// The sensors plugin. +class WebSensorsPlugin extends SensorsPlatform { + /// Factory method that initializes the Sensors plugin platform with an instance + /// of the plugin for the web. + static void registerWith(Registrar registrar) { + SensorsPlatform.instance = WebSensorsPlugin(); + } + + void _featureDetected( + Function initSensor, { + String? apiName, + String? permissionName, + Function? onError, + }) { + try { + initSensor(); + } catch (error) { + if (onError != null) { + onError(); + } + + /// Handle construction errors. + /// + /// If a feature policy blocks use of a feature it is because your code + /// is inconsistent with the policies set on your server. + /// This is not something that would ever be shown to a user. + /// See Feature-Policy for implementation instructions in the browsers. + if (error.toString().contains('SecurityError')) { + /// See the note above about feature policy. + developer.log('$apiName construction was blocked by a feature policy.', + error: error); + + /// if this feature is not supported or Flag is not enabled yet! + } else if (error.toString().contains('ReferenceError')) { + developer.log('$apiName is not supported by the User Agent.', + error: error); + + /// if this is unknown error, rethrow it + } else { + developer.log('Unknown error happened, rethrowing.'); + rethrow; + } + } + } + + StreamController? _accelerometerStreamController; + late Stream _accelerometerResultStream; + + @override + Stream get accelerometerEvents { + if (_accelerometerStreamController == null) { + _accelerometerStreamController = StreamController(); + _featureDetected( + () { + final accelerometer = html.Accelerometer(); + + setProperty( + accelerometer, + 'onreading', + allowInterop( + (_) { + _accelerometerStreamController!.add( + AccelerometerEvent( + accelerometer.x as double, + accelerometer.y as double, + accelerometer.z as double, + ), + ); + }, + ), + ); + + accelerometer.start(); + + accelerometer.onError.forEach( + (e) => developer.log( + 'The accelerometer API is supported but something is wrong!', + error: e), + ); + }, + apiName: 'Accelerometer()', + permissionName: 'accelerometer', + onError: () { + _accelerometerStreamController!.add(AccelerometerEvent(0, 0, 0)); + }, + ); + _accelerometerResultStream = + _accelerometerStreamController!.stream.asBroadcastStream(); + } + + return _accelerometerResultStream; + } + + StreamController? _gyroscopeEventStreamController; + late Stream _gyroscopeEventResultStream; + + @override + Stream get gyroscopeEvents { + if (_gyroscopeEventStreamController == null) { + _gyroscopeEventStreamController = StreamController(); + _featureDetected( + () { + final gyroscope = html.Gyroscope(); + + setProperty( + gyroscope, + 'onreading', + allowInterop( + (_) { + _gyroscopeEventStreamController!.add( + GyroscopeEvent( + gyroscope.x as double, + gyroscope.y as double, + gyroscope.z as double, + ), + ); + }, + ), + ); + + gyroscope.start(); + + gyroscope.onError.forEach( + (e) => developer.log( + 'The gyroscope API is supported but something is wrong!', + error: e), + ); + }, + apiName: 'Gyroscope()', + permissionName: 'gyroscope', + onError: () { + _gyroscopeEventStreamController!.add(GyroscopeEvent(0, 0, 0)); + }, + ); + _gyroscopeEventResultStream = + _gyroscopeEventStreamController!.stream.asBroadcastStream(); + + _gyroscopeEventStreamController!.onCancel = () { + _gyroscopeEventStreamController!.close(); + }; + } + + return _gyroscopeEventResultStream; + } + + StreamController? _userAccelerometerStreamController; + late Stream _userAccelerometerResultStream; + + @override + Stream get userAccelerometerEvents { + if (_userAccelerometerStreamController == null) { + _userAccelerometerStreamController = + StreamController(); + _featureDetected( + () { + final linearAccelerationSensor = html.LinearAccelerationSensor(); + + setProperty( + linearAccelerationSensor, + 'onreading', + allowInterop( + (_) { + _userAccelerometerStreamController!.add( + UserAccelerometerEvent( + linearAccelerationSensor.x as double, + linearAccelerationSensor.y as double, + linearAccelerationSensor.z as double, + ), + ); + }, + ), + ); + + linearAccelerationSensor.start(); + + linearAccelerationSensor.onError.forEach( + (e) => developer.log( + 'The linear acceleration API is supported but something is wrong!', + error: e), + ); + }, + apiName: 'LinearAccelerationSensor()', + permissionName: 'accelerometer', + onError: () { + _userAccelerometerStreamController! + .add(UserAccelerometerEvent(0, 0, 0)); + }, + ); + _userAccelerometerResultStream = + _userAccelerometerStreamController!.stream.asBroadcastStream(); + } + + return _userAccelerometerResultStream; + } + + StreamController? _magnetometerStreamController; + late Stream _magnetometerResultStream; + + @override + Stream get magnetometerEvents { + if (_magnetometerStreamController == null) { + _magnetometerStreamController = StreamController(); + _featureDetected( + () { + final magnetometerSensor = html.Magnetometer(); + + setProperty( + magnetometerSensor, + 'onreading', + allowInterop( + (_) { + _magnetometerStreamController!.add( + MagnetometerEvent( + magnetometerSensor.x as double, + magnetometerSensor.y as double, + magnetometerSensor.z as double, + ), + ); + }, + ), + ); + + magnetometerSensor.start(); + + magnetometerSensor.onError.forEach( + (e) => developer.log( + 'The magnetometer API is supported but something is wrong!', + error: e), + ); + }, + apiName: 'Magnetometer()', + permissionName: 'magnetometer', + onError: () { + _magnetometerStreamController!.add(MagnetometerEvent(0, 0, 0)); + }, + ); + _magnetometerResultStream = + _magnetometerStreamController!.stream.asBroadcastStream(); + } + + return _magnetometerResultStream; + } +} diff --git a/packages/sensors_plus/sensors_plus/ohos/ohos/.gitignore b/packages/sensors_plus/sensors_plus/ohos/ohos/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..c0f9ca4c47ca2d6aea523c5e0cf3331566bbf88a --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/ohos/.gitignore @@ -0,0 +1,9 @@ +/node_modules +/oh_modules +/.preview +/.idea +/build +/.cxx +/.test +/BuildProfile.ets +/oh-package-lock.json5 diff --git a/packages/sensors_plus/sensors_plus/ohos/ohos/build-profile.json5 b/packages/sensors_plus/sensors_plus/ohos/ohos/build-profile.json5 new file mode 100644 index 0000000000000000000000000000000000000000..79961f96a6fe0507354b7952a378c3be2ae4bfab --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/ohos/build-profile.json5 @@ -0,0 +1,10 @@ +{ + "apiType": "stageMode", + "buildOption": { + }, + "targets": [ + { + "name": "default" + } + ] +} diff --git a/packages/sensors_plus/sensors_plus/ohos/ohos/hvigorfile.ts b/packages/sensors_plus/sensors_plus/ohos/ohos/hvigorfile.ts new file mode 100644 index 0000000000000000000000000000000000000000..47e6e1f81d365872f101585f5dbf816bcad65864 --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/ohos/hvigorfile.ts @@ -0,0 +1,2 @@ +// Script for compiling build behavior. It is built in the build plug-in and cannot be modified currently. +export { harTasks } from '@ohos/hvigor-ohos-plugin'; \ No newline at end of file diff --git a/packages/sensors_plus/sensors_plus/ohos/ohos/index.ets b/packages/sensors_plus/sensors_plus/ohos/ohos/index.ets new file mode 100644 index 0000000000000000000000000000000000000000..067d05042443beeaf44dd5d2380d89c9fdfc8005 --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/ohos/index.ets @@ -0,0 +1,17 @@ +/* +* Copyright (c) 2023 Hunan OpenValley Digital Industry Development Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +import SensorsPlusOhosPlugin from './src/main/ets/components/plugin/SensorsPlusOhosPlugin'; +export default SensorsPlusOhosPlugin; diff --git a/packages/sensors_plus/sensors_plus/ohos/ohos/oh-package.json5 b/packages/sensors_plus/sensors_plus/ohos/ohos/oh-package.json5 new file mode 100644 index 0000000000000000000000000000000000000000..25ed6809aae3e16d07e8c085f9158f57a17edc2b --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/ohos/oh-package.json5 @@ -0,0 +1,11 @@ +{ + "name": "sensors_plus_ohos", + "version": "1.0.0", + "description": "Please describe the basic information.", + "main": "index.ets", + "author": "", + "license": "Apache-2.0", + "dependencies": { + "@ohos/flutter_ohos": "file:./har/flutter.har" + } +} diff --git a/packages/sensors_plus/sensors_plus/ohos/ohos/src/main/ets/components/plugin/SensorsPlusOhosPlugin.ets b/packages/sensors_plus/sensors_plus/ohos/ohos/src/main/ets/components/plugin/SensorsPlusOhosPlugin.ets new file mode 100644 index 0000000000000000000000000000000000000000..feb4ed30831984bfd032d0d73dbd672606b04dc9 --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/ohos/src/main/ets/components/plugin/SensorsPlusOhosPlugin.ets @@ -0,0 +1,229 @@ +/* + * Copyright (C) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + BinaryMessenger, + FlutterPlugin, + FlutterPluginBinding, + MethodCall, + MethodCallHandler, + MethodChannel, + MethodResult, + EventChannel, +} from '@ohos/flutter_ohos'; +import { EventSink, StreamHandler } from '@ohos/flutter_ohos/src/main/ets/plugin/common/EventChannel'; +import { sensor } from '@kit.SensorServiceKit'; +import { BusinessError } from '@kit.BasicServicesKit'; + +// StreamHandlerImpl 实现了 StreamHandler 接口 +class StreamHandlerImpl implements StreamHandler { + private event?: EventSink; + private sensorId?: sensor.SensorId; + + constructor(sensorId: sensor.SensorId) { + this.sensorId = sensorId; + this.initSensorData(); + } + + private initSensorData(): void { + switch (this.sensorId) { + case sensor.SensorId.LINEAR_ACCELEROMETER: + this.listenLinearAccelerometer(); + break; + case sensor.SensorId.GYROSCOPE: + this.listenGyroscope(); + break; + case sensor.SensorId.ACCELEROMETER: + this.listenAccelerometer(); + break; + case sensor.SensorId.MAGNETIC_FIELD: + this.listenMagnetic(); + break; + } + } + + // user加速度计传感器 + private listenLinearAccelerometer(): void { + try { + sensor.on(sensor.SensorId.LINEAR_ACCELEROMETER, (data: sensor.LinearAccelerometerResponse) => { + if (this.event) { + let arr: Array = [3]; + arr[0] = data.x; + arr[1] = data.y; + arr[2] = data.z; + if (Number.isInteger(data.x)) { + arr[0] = data.x + 0.00000000001; + } + if (Number.isInteger(data.y)) { + arr[1] = data.y + 0.00000000001; + } + if (Number.isInteger(data.z)) { + arr[2] = data.z + 0.00000000001; + } + this.event.success(arr); + } + }, { interval: 100000000 }); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke on. Code: ${e.code}, message: ${e.message}`); + } + } + + // 陀螺仪 + private listenGyroscope(): void { + try { + sensor.on(sensor.SensorId.GYROSCOPE, (data: sensor.GyroscopeResponse) => { + if (this.event) { + let arr: Array = [3]; + arr[0] = data.x; + arr[1] = data.y; + arr[2] = data.z; + if (Number.isInteger(data.x)) { + arr[0] = data.x + 0.00000000001; + } + if (Number.isInteger(data.y)) { + arr[1] = data.y + 0.00000000001; + } + if (Number.isInteger(data.z)) { + arr[2] = data.z + 0.00000000001; + } + this.event.success(arr); + } + }, { interval: 100000000 }); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke on. Code: ${e.code}, message: ${e.message}`); + } + } + + // 加速度计 + private listenAccelerometer(): void { + try { + sensor.on(sensor.SensorId.ACCELEROMETER, (data: sensor.AccelerometerResponse) => { + if (this.event) { + let arr: Array = [3]; + arr[0] = data.x; + arr[1] = data.y; + arr[2] = data.z; + if (Number.isInteger(data.x)) { + arr[0] = data.x + 0.00000000001; + } + if (Number.isInteger(data.y)) { + arr[1] = data.y + 0.00000000001; + } + if (Number.isInteger(data.z)) { + arr[2] = data.z + 0.00000000001; + } + this.event.success(arr); + } + }, { interval: 100000000 }); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke on. Code: ${e.code}, message: ${e.message}`); + } + } + + // 磁力计 + private listenMagnetic(): void { + try { + sensor.on(sensor.SensorId.MAGNETIC_FIELD, (data: sensor.MagneticFieldResponse) => { + if (this.event) { + let arr: Array = [3]; + arr[0] = data.x; + arr[1] = data.y; + arr[2] = data.z; + if (Number.isInteger(data.x)) { + arr[0] = data.x + 0.00000000001; + } + if (Number.isInteger(data.y)) { + arr[1] = data.y + 0.00000000001; + } + if (Number.isInteger(data.z)) { + arr[2] = data.z + 0.00000000001; + } + this.event.success(arr); + } + }, { interval: 100000000 }); + } catch (error) { + let e: BusinessError = error as BusinessError; + console.error(`Failed to invoke on. Code: ${e.code}, message: ${e.message}`); + } + } + + onListen(args: ESObject, events: EventSink): void { + this.event = events; + } + + onCancel(args: ESObject): void { + } +} + +/** SensorsPlusOhosPlugin **/ +export default class SensorsPlusOhosPlugin implements FlutterPlugin, MethodCallHandler { + private channel: MethodChannel | null = null; + private ACCELEROMETER_CHANNEL_NAME: string = "dev.fluttercommunity.plus/sensors/accelerometer"; + private GYROSCOPE_CHANNEL_NAME: string = "dev.fluttercommunity.plus/sensors/gyroscope"; + private MAGNETOMETER_CHANNEL_NAME: string = "dev.fluttercommunity.plus/sensors/magnetometer"; + private USER_ACCELEROMETER_CHANNEL_NAME: string = "dev.fluttercommunity.plus/sensors/user_accel"; + + constructor() { + } + + getUniqueClassName(): string { + return "SensorsPlusOhosPlugin"; + } + + onAttachedToEngine(binding: FlutterPluginBinding): void { + this.channel = new MethodChannel(binding.getBinaryMessenger(), "dev.fluttercommunity.plus/sensors/method"); + this.channel.setMethodCallHandler(this); + this.setupEventChannels(binding.getApplicationContext(), binding.getBinaryMessenger()); + } + + onDetachedFromEngine(binding: FlutterPluginBinding): void { + if (this.channel != null) { + this.channel.setMethodCallHandler(null); + } + } + + onMethodCall(call: MethodCall, result: MethodResult): void { + if (call.method == "getPlatformVersion") { + result.success("OpenHarmony ^ ^ ") + } else { + result.notImplemented(); + } + } + + private setupEventChannels(context: Context, messenger: BinaryMessenger) { + // user加速度计 + let userAccelerometerChannel = new EventChannel(messenger, this.USER_ACCELEROMETER_CHANNEL_NAME); + let userAccelerationStreamHandler = new StreamHandlerImpl(sensor.SensorId.LINEAR_ACCELEROMETER); + userAccelerometerChannel.setStreamHandler(userAccelerationStreamHandler); + + // 陀螺仪 + let gyroscopeChannel = new EventChannel(messenger, this.GYROSCOPE_CHANNEL_NAME); + let gyroScopeStreamHandler = new StreamHandlerImpl(sensor.SensorId.GYROSCOPE); + gyroscopeChannel.setStreamHandler(gyroScopeStreamHandler); + + // 加速度计 + let accelerometerChannel = new EventChannel(messenger, this.ACCELEROMETER_CHANNEL_NAME); + let accelerationStreamHandler = new StreamHandlerImpl(sensor.SensorId.ACCELEROMETER); + accelerometerChannel.setStreamHandler(accelerationStreamHandler); + + // 磁力计 + let magnetometerChannel = new EventChannel(messenger, this.MAGNETOMETER_CHANNEL_NAME); + let magnetometerStreamHandler = new StreamHandlerImpl(sensor.SensorId.MAGNETIC_FIELD); + magnetometerChannel.setStreamHandler(magnetometerStreamHandler); + } +} diff --git a/packages/sensors_plus/sensors_plus/ohos/ohos/src/main/module.json5 b/packages/sensors_plus/sensors_plus/ohos/ohos/src/main/module.json5 new file mode 100644 index 0000000000000000000000000000000000000000..41a87d178d2b386a9abd3286aaadcc09c2eeaec8 --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/ohos/src/main/module.json5 @@ -0,0 +1,10 @@ +{ + "module": { + "name": "sensors_plus_ohos", + "type": "har", + "deviceTypes": [ + "default", + "tablet" + ] + } +} diff --git a/packages/sensors_plus/sensors_plus/ohos/pubspec.yaml b/packages/sensors_plus/sensors_plus/ohos/pubspec.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4355ad646367baadca070ae2c569927c9fc66d14 --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/pubspec.yaml @@ -0,0 +1,40 @@ +name: sensors_plus_ohos +description: Flutter plugin for accessing accelerometer, gyroscope, and magnetometer sensors. +version: 1.0.0 +homepage: https://gitee.com/openharmony-sig/flutter_plus_plugins/tree/master/packages/sensors_plus/sensors_plus + +environment: + sdk: '>=2.19.6 <3.0.0' + flutter: ">=2.5.0" + +dependencies: + flutter: + sdk: flutter + plugin_platform_interface: ^2.0.2 + sensors_plus_platform_interface: ^1.1.3 + +dev_dependencies: + flutter_test: + sdk: flutter + flutter_lints: ^2.0.0 + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + +# The following section is specific to Flutter packages. +flutter: + # This section identifies this Flutter project as a plugin project. + # The 'pluginClass' specifies the class (in Java, Kotlin, Swift, Objective-C, etc.) + # which should be registered in the plugin registry. This is required for + # using method channels. + # The Android 'package' specifies package in which the registered class is. + # This is required for using method channels on Android. + # The 'ffiPlugin' specifies that native code should be built and bundled. + # This is required for using `dart:ffi`. + # All these are used by the tooling to maintain consistency when + # adding or updating assets for this project. + plugin: + platforms: + ohos: + package: dev.fluttercommunity.plus.sensors + pluginClass: SensorsPlusOhosPlugin \ No newline at end of file diff --git a/packages/sensors_plus/sensors_plus/ohos/test/sensors_plus_ohos_test.dart b/packages/sensors_plus/sensors_plus/ohos/test/sensors_plus_ohos_test.dart new file mode 100644 index 0000000000000000000000000000000000000000..32f9a26ca2c58c17428a628cb7ac04aa06d0b0a6 --- /dev/null +++ b/packages/sensors_plus/sensors_plus/ohos/test/sensors_plus_ohos_test.dart @@ -0,0 +1,71 @@ +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart' + show TestDefaultBinaryMessengerBinding, TestWidgetsFlutterBinding; +import 'package:sensors_plus_ohos/sensors_plus_ohos.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + final MethodChannel methodChannel = MethodChannel('dev.fluttercommunity.plus/sensors/method'); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + methodChannel, + (message) => null, + ); + + test('$accelerometerEvents are streamed', () async { + const channelName = 'dev.fluttercommunity.plus/sensors/accelerometer'; + const sensorData = [1.0, 2.0, 3.0]; + _initializeFakeSensorChannel(channelName, sensorData); + final event = await accelerometerEvents.first; + expect(event.x, sensorData[0]); + expect(event.y, sensorData[1]); + expect(event.z, sensorData[2]); + }); + + test('$gyroscopeEvents are streamed', () async { + const channelName = 'dev.fluttercommunity.plus/sensors/gyroscope'; + const sensorData = [3.0, 4.0, 5.0]; + _initializeFakeSensorChannel(channelName, sensorData); + final event = await gyroscopeEvents.first; + expect(event.x, sensorData[0]); + expect(event.y, sensorData[1]); + expect(event.z, sensorData[2]); + }); + + test('$magnetometerEvents are streamed', () async { + const channelName = 'dev.fluttercommunity.plus/sensors/magnetometer'; + const sensorData = [8.0, 9.0, 10.0]; + _initializeFakeSensorChannel(channelName, sensorData); + final event = await magnetometerEvents.first; + expect(event.x, sensorData[0]); + expect(event.y, sensorData[1]); + expect(event.z, sensorData[2]); + }); +} + +void _initializeFakeSensorChannel(String channelName, List sensorData) { + const standardMethod = StandardMethodCodec(); + void emitEvent(ByteData? event) { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .handlePlatformMessage( + channelName, + event, + (ByteData? reply) {}, + ); + } + + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMessageHandler(channelName, (ByteData? message) async { + final methodCall = standardMethod.decodeMethodCall(message); + if (methodCall.method == 'listen') { + emitEvent(standardMethod.encodeSuccessEnvelope(sensorData)); + emitEvent(null); + return standardMethod.encodeSuccessEnvelope(null); + } else if (methodCall.method == 'cancel') { + return standardMethod.encodeSuccessEnvelope(null); + } else { + fail('Expected listen or cancel'); + } + }); +} \ No newline at end of file