Skip to content

Commit

Permalink
lots of linting
Browse files Browse the repository at this point in the history
  • Loading branch information
Codel1417 committed Jun 12, 2024
1 parent 30b743a commit 789e43f
Show file tree
Hide file tree
Showing 59 changed files with 1,432 additions and 1,251 deletions.
4 changes: 2 additions & 2 deletions .github/actions/build_android/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ runs:
ANDROID_KEY_JKS: ${{ inputs.android-key-jks }}
- name: Build APK
shell: bash
run: flutter build apk --split-debug-info=./symbols --build-number="$BUILD_NUMBER" --build-name="$VERSION" --dart-define=cronetHttpNoPlay=true --dart-define=SENTRY_DSN=$SENTRY_DSN
run: flutter build apk --split-debug-info=./symbols --build-number="$BUILD_NUMBER" --build-name="$VERSION" --dart-define=cronetHttpNoPlay=true --dart-define=SENTRY_DSN="$SENTRY_DSN"
env:
VERSION: ${{ inputs.version }}
BUILD_NUMBER: ${{ inputs.build-number }}
Expand All @@ -56,7 +56,7 @@ runs:
#SENTRY_URL: ${{ inputs.sentry-url }}
- name: Build AppBundle
shell: bash
run: flutter build appbundle --split-debug-info=./symbols --build-number="$BUILD_NUMBER" --build-name="$VERSION" --dart-define=SENTRY_DSN=$SENTRY_DSN
run: flutter build appbundle --split-debug-info=./symbols --build-number="$BUILD_NUMBER" --build-name="$VERSION" --dart-define=SENTRY_DSN="$SENTRY_DSN"
env:
VERSION: ${{ inputs.version }}
BUILD_NUMBER: ${{ inputs.build-number }}
Expand Down
52 changes: 48 additions & 4 deletions analysis_options.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,57 @@ linter:
# `// 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
# avoid_print: false # Uncomment to disable the `avoid_print` rule
# prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule
- cancel_subscriptions
- close_sinks
- discarded_futures
- no_adjacent_strings_in_list
- no_self_assignments
- unnecessary_statements
- always_declare_return_types
- always_put_required_named_parameters_first
- always_put_control_body_on_new_line
- avoid_multiple_declarations_per_line
- avoid_positional_boolean_parameters
- avoid_returning_this
- avoid_unused_constructor_parameters
- avoid_void_async
- cascade_invocations
- cast_nullable_to_non_nullable
- join_return_with_assignment
- missing_whitespace_between_adjacent_strings
- one_member_abstracts
- prefer_constructors_over_static_methods
- require_trailing_commas
- unnecessary_await_in_return
- unnecessary_breaks
- unnecessary_lambdas
- unnecessary_raw_strings
- use_enums
- use_if_null_to_convert_nulls_to_bools
- avoid_slow_async_io
- avoid_type_to_string
- literal_only_boolean_expressions
- prefer_void_to_null
- prefer_relative_imports
- test_types_in_equals

# Additional information about this file can be found at
# https://dart.dev/guides/language/analysis-options
analyzer:
exclude: [ build/**, pub_cache/** ]
exclude:
- build/**
- pub_cache/**
- lib/**.g.dart
- lib/l10n/**

language:
#strict-casts: true
strict-raw-types: true
strict-raw-types: true
plugins:
- custom_lint
custom_lint:
rules:
# Explicitly disable one lint rule
- missing_provider_scope: false
5 changes: 2 additions & 3 deletions lib/Backend/Bluetooth/bluetooth_manager.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ import 'dart:async';

import 'package:logging/logging.dart' as log;
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:tail_app/Backend/logging_wrappers.dart';

import '../../constants.dart';
import '../Definitions/Device/device_definition.dart';
import '../device_registry.dart';
import '../logging_wrappers.dart';

part 'bluetooth_manager.g.dart';

Expand Down Expand Up @@ -44,8 +44,7 @@ class KnownDevices extends _$KnownDevices {
}

Future<void> remove(String id) async {
Map<String, BaseStatefulDevice> state2 = Map.from(state);
state2.remove(id);
Map<String, BaseStatefulDevice> state2 = Map.from(state)..remove(id);
state = state2;
await store();
}
Expand Down
48 changes: 25 additions & 23 deletions lib/Backend/Bluetooth/bluetooth_manager_plus.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,17 @@ import 'package:flutter_foreground_task/flutter_foreground_task.dart';
import 'package:logging/logging.dart' as log;
import 'package:permission_handler/permission_handler.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:tail_app/Backend/Bluetooth/bluetooth_utils.dart';
import 'package:tail_app/Backend/Definitions/Device/device_definition.dart';
import 'package:tail_app/Backend/device_registry.dart';
import 'package:wakelock_plus/wakelock_plus.dart';

import '../../Frontend/utils.dart';
import '../../constants.dart';
import '../Definitions/Device/device_definition.dart';
import '../device_registry.dart';
import '../logging_wrappers.dart';
import '../sensors.dart';
import 'bluetooth_manager.dart';
import 'bluetooth_message.dart';
import 'bluetooth_utils.dart';

part 'bluetooth_manager_plus.g.dart';

Expand Down Expand Up @@ -86,8 +86,7 @@ Future<void> initFlutterBluePlus(InitFlutterBluePlusRef ref) async {
baseStoredDevice = statefulDevice.baseStoredDevice;
//transaction.setTag('Known Device', 'Yes');
} else {
baseStoredDevice = BaseStoredDevice(deviceDefinition.uuid, deviceID, deviceDefinition.deviceType.color(ref: ref).value);
baseStoredDevice.name = getNameFromBTName(deviceDefinition.btName);
baseStoredDevice = BaseStoredDevice(deviceDefinition.uuid, deviceID, deviceDefinition.deviceType.color(ref: ref).value)..name = getNameFromBTName(deviceDefinition.btName);
statefulDevice = BaseStatefulDevice(deviceDefinition, baseStoredDevice);
//transaction.setTag('Known Device', 'No');
Future(() => ref.read(knownDevicesProvider.notifier).add(statefulDevice));
Expand All @@ -109,8 +108,9 @@ Future<void> initFlutterBluePlus(InitFlutterBluePlusRef ref) async {
}
if (Platform.isAndroid) {
//start foreground service on device connected. Library handles duplicate start calls
_bluetoothPlusLogger.fine('Requesting notification permission');
_bluetoothPlusLogger.finer('Requesting notification permission result${await Permission.notification.request()}'); // Used only for Foreground service
_bluetoothPlusLogger
..fine('Requesting notification permission')
..finer('Requesting notification permission result${await Permission.notification.request()}'); // Used only for Foreground service
FlutterForegroundTask.init(
androidNotificationOptions: AndroidNotificationOptions(
channelId: 'foreground_service',
Expand Down Expand Up @@ -275,23 +275,26 @@ Future<void> initFlutterBluePlus(InitFlutterBluePlusRef ref) async {
}
}
},
onError: (e) => _bluetoothPlusLogger.severe(e),
onError: (e, s) => _bluetoothPlusLogger.severe("", e, s),
);

_keepAliveStreamSubscription = Stream.periodic(const Duration(seconds: 15)).listen((event) async {
Map<String, BaseStatefulDevice> knownDevices = ref.read(knownDevicesProvider);
for (var element in flutterBluePlus.connectedDevices) {
BaseStatefulDevice? device = knownDevices[element.remoteId.str];
if (device != null) {
device.commandQueue.addCommand(BluetoothMessage(message: "PING", device: device, priority: Priority.low, type: CommandType.system));
device.commandQueue.addCommand(BluetoothMessage(message: "BATT", device: device, priority: Priority.low, type: CommandType.system));
element.readRssi();
if (device.baseDeviceDefinition.deviceType != DeviceType.ears && device.hasGlowtip.value == GlowtipStatus.unknown) {
device.commandQueue.addCommand(BluetoothMessage(message: "VER", device: device, priority: Priority.low, type: CommandType.system));
_keepAliveStreamSubscription = Stream.periodic(const Duration(seconds: 15)).listen(
(event) async {
Map<String, BaseStatefulDevice> knownDevices = ref.read(knownDevicesProvider);
for (var element in flutterBluePlus.connectedDevices) {
BaseStatefulDevice? device = knownDevices[element.remoteId.str];
if (device != null) {
device.commandQueue.addCommand(BluetoothMessage(message: "PING", device: device, priority: Priority.low, type: CommandType.system));
device.commandQueue.addCommand(BluetoothMessage(message: "BATT", device: device, priority: Priority.low, type: CommandType.system));
element.readRssi();
if (device.baseDeviceDefinition.deviceType != DeviceType.ears && device.hasGlowtip.value == GlowtipStatus.unknown) {
device.commandQueue.addCommand(BluetoothMessage(message: "VER", device: device, priority: Priority.low, type: CommandType.system));
}
}
}
}
}, cancelOnError: true);
},
cancelOnError: true,
);

// Shut down bluetooth related things
ref.onDispose(() async {
Expand Down Expand Up @@ -354,7 +357,7 @@ Future<void> connect(String id) async {
Future<void> beginScan({Duration? timeout}) async {
if (_didInitFlutterBluePlus && !flutterBluePlus.isScanningNow) {
_bluetoothPlusLogger.info("Starting scan");
await flutterBluePlus.startScan(withServices: DeviceRegistry.getAllIds().map((e) => Guid(e)).toList(), continuousUpdates: timeout == null, androidScanMode: AndroidScanMode.lowPower, timeout: timeout);
await flutterBluePlus.startScan(withServices: DeviceRegistry.getAllIds().map(Guid.new).toList(), continuousUpdates: timeout == null, androidScanMode: AndroidScanMode.lowPower, timeout: timeout);
}
}

Expand Down Expand Up @@ -392,8 +395,7 @@ Future<void> sendMessage(BaseStatefulDevice device, List<int> message, {bool wit
return;
}

Future<void> future = bluetoothCharacteristic.write(message, withoutResponse: withoutResponse && bluetoothCharacteristic.properties.writeWithoutResponse);
future.catchError((e) {
Future<void> future = bluetoothCharacteristic.write(message, withoutResponse: withoutResponse && bluetoothCharacteristic.properties.writeWithoutResponse).catchError((e) {
_bluetoothPlusLogger.severe("Unable to send message to ${device.baseDeviceDefinition.btName} $e", e);
});
await future;
Expand Down
2 changes: 1 addition & 1 deletion lib/Backend/Bluetooth/bluetooth_message.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import 'dart:core';

import 'package:tail_app/Backend/Definitions/Device/device_definition.dart';
import '../Definitions/Device/device_definition.dart';

enum Priority { low, normal, high }

Expand Down
2 changes: 1 addition & 1 deletion lib/Backend/Bluetooth/bluetooth_utils.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import 'package:flutter_blue_plus/flutter_blue_plus.dart';
/// Wrapper for FlutterBluePlus in order to easily mock it
/// Wraps all static calls for testing purposes
class FlutterBluePlusMockable {
get onScanResults => FlutterBluePlus.onScanResults;
Stream<List<ScanResult>> get onScanResults => FlutterBluePlus.onScanResults;

Future<void> startScan({
List<Guid> withServices = const [],
Expand Down
6 changes: 3 additions & 3 deletions lib/Backend/Definitions/Action/base_action.dart
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import 'package:hive/hive.dart';
import 'package:tail_app/Frontend/translation_string_definitions.dart';
import 'package:uuid/uuid.dart';

import '../../../Frontend/translation_string_definitions.dart';
import '../Device/device_definition.dart';

part 'base_action.g.dart';
Expand Down Expand Up @@ -92,7 +92,7 @@ class CommandAction extends BaseAction {
final String command;
final String? response;

CommandAction({required this.command, this.response, required super.name, required super.deviceCategory, required super.actionCategory, required super.uuid, super.nameAlias});
CommandAction({required this.command, required super.name, required super.deviceCategory, required super.actionCategory, required super.uuid, this.response, super.nameAlias});

factory CommandAction.hiddenEars(String command, String response) {
return CommandAction(command: command, response: response, deviceCategory: [DeviceType.ears], actionCategory: ActionCategory.hidden, uuid: const Uuid().v4(), name: command);
Expand All @@ -104,5 +104,5 @@ class AudioAction extends BaseAction {
@HiveField(5)
String file;

AudioAction({required super.name, super.deviceCategory = DeviceType.values, super.actionCategory = ActionCategory.audio, required super.uuid, required this.file});
AudioAction({required super.name, required super.uuid, required this.file, super.deviceCategory = DeviceType.values, super.actionCategory = ActionCategory.audio});
}
34 changes: 19 additions & 15 deletions lib/Backend/Definitions/Device/device_definition.dart
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:hive/hive.dart';
import 'package:pub_semver/pub_semver.dart';
import 'package:sentry_flutter/sentry_flutter.dart';
import 'package:tail_app/Backend/Bluetooth/bluetooth_manager.dart';
import 'package:tail_app/Backend/Bluetooth/bluetooth_manager_plus.dart';
import 'package:tail_app/Backend/firmware_update.dart';

import '../../../Frontend/translation_string_definitions.dart';
import '../../../Frontend/utils.dart';
import '../../Bluetooth/bluetooth_manager.dart';
import '../../Bluetooth/bluetooth_manager_plus.dart';
import '../../Bluetooth/bluetooth_message.dart';
import '../../firmware_update.dart';

part 'device_definition.g.dart';

Expand Down Expand Up @@ -149,8 +149,9 @@ class BaseStatefulDevice extends ChangeNotifier {
} else if (deviceConnectionState.value == ConnectivityState.connected) {
// Add initial commands to the queue
Future.delayed(const Duration(seconds: 2), () {
commandQueue.addCommand(BluetoothMessage(message: "VER", device: this, priority: Priority.low, type: CommandType.system));
commandQueue.addCommand(BluetoothMessage(message: "HWVER", device: this, priority: Priority.low, type: CommandType.system));
commandQueue
..addCommand(BluetoothMessage(message: "VER", device: this, priority: Priority.low, type: CommandType.system))
..addCommand(BluetoothMessage(message: "HWVER", device: this, priority: Priority.low, type: CommandType.system));
});
}
});
Expand Down Expand Up @@ -182,11 +183,11 @@ class BaseStatefulDevice extends ChangeNotifier {
Future<void> getFirmwareInfo() async {
// Try to get firmware update information from Tail Company site
if (baseDeviceDefinition.fwURL != "" && fwInfo.value == null) {
Future<Response<String>> valueFuture = (await initDio()).get(baseDeviceDefinition.fwURL, options: Options(responseType: ResponseType.json));
valueFuture.onError((error, stackTrace) {
bluetoothLog.warning("Unable to get Firmware info for ${baseDeviceDefinition.fwURL} :$error", error, stackTrace);
return Response(requestOptions: RequestOptions(), statusCode: 500);
});
Future<Response<String>> valueFuture = (await initDio()).get(baseDeviceDefinition.fwURL, options: Options(responseType: ResponseType.json))
..onError((error, stackTrace) {
bluetoothLog.warning("Unable to get Firmware info for ${baseDeviceDefinition.fwURL} :$error", error, stackTrace);
return Response(requestOptions: RequestOptions(), statusCode: 500);
});
Response<String> value = await valueFuture;
if (value.statusCode == 200) {
fwInfo.value = FWInfo.fromJson(const JsonDecoder().convert(value.data.toString()));
Expand Down Expand Up @@ -308,16 +309,19 @@ class CommandQueue {
// We use a timeout as sometimes a response isn't sent by the gear
timer = Timer(timeoutDuration, () {});
response = device.rxCharacteristicStream
.timeout(timeoutDuration, onTimeout: (sink) {
sink.addError("");
})
.timeout(
timeoutDuration,
onTimeout: (sink) {
sink.addError("");
},
)
.where((event) {
bluetoothLog.info('Response:$event');
return event.contains(message.responseMSG!);
})
.handleError((string) => "")
.first;
response.catchError((string) => "");
.first
..catchError((string) => "");
}
await sendMessage(device, const Utf8Encoder().convert(message.message));
device.messageHistory.add(MessageHistoryEntry(type: MessageHistoryType.send, message: message.message));
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:plausible_analytics/plausible_analytics.dart';

Expand All @@ -13,7 +15,7 @@ class CustomNavObserver extends NavigatorObserver {
String? name = route.settings.name;
String refferalName = previousRoute?.settings.name ?? "";
if (name != null) {
plausible.event(page: route.settings.name.toString(), referrer: refferalName);
unawaited(plausible.event(page: route.settings.name.toString(), referrer: refferalName));
}
}
}
15 changes: 7 additions & 8 deletions lib/Backend/action_registry.dart
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import 'package:flutter/material.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:tail_app/Backend/audio.dart';
import 'package:tail_app/Backend/move_lists.dart';

import 'Bluetooth/bluetooth_manager.dart';
import 'Bluetooth/bluetooth_manager_plus.dart';
import 'Definitions/Action/base_action.dart';
import 'Definitions/Device/device_definition.dart';
import 'audio.dart';
import 'move_lists.dart';

part 'action_registry.g.dart';

Expand Down Expand Up @@ -276,7 +276,8 @@ Map<ActionCategory, Set<BaseAction>> getAvailableActions(GetAvailableActionsRef
Map<String, BaseStatefulDevice> knownDevices = ref.watch(knownDevicesProvider);
Map<ActionCategory, Set<BaseAction>> sortedActions = {};
for (BaseAction baseAction in List.from(ActionRegistry.allCommands)
..addAll(ref.read(moveListsProvider))..addAll(ref.read(userAudioActionsProvider))) {
..addAll(ref.read(moveListsProvider))
..addAll(ref.read(userAudioActionsProvider))) {
Set<BaseAction>? baseActions = {};
for (BaseStatefulDevice baseStatefulDevice in knownDevices.values.where((element) => element.deviceConnectionState.value == ConnectivityState.connected)) {
// check if command matches device type
Expand All @@ -301,13 +302,11 @@ Map<ActionCategory, Set<BaseAction>> getAvailableActions(GetAvailableActionsRef
Map<ActionCategory, Set<BaseAction>> getAllActions(GetAllActionsRef ref, Set<DeviceType> deviceType) {
Map<ActionCategory, Set<BaseAction>> sortedActions = {};
for (BaseAction baseAction in List.from(ActionRegistry.allCommands)
..addAll(ref.read(moveListsProvider))..addAll(ref.read(userAudioActionsProvider))) {
..addAll(ref.read(moveListsProvider))
..addAll(ref.read(userAudioActionsProvider))) {
Set<BaseAction>? baseActions = {};
// check if command matches device type
if (baseAction.deviceCategory
.toSet()
.intersection(deviceType)
.isNotEmpty) {
if (baseAction.deviceCategory.toSet().intersection(deviceType).isNotEmpty) {
// get category if it exists
if (sortedActions.containsKey(baseAction.actionCategory)) {
baseActions = sortedActions[baseAction.actionCategory];
Expand Down
Loading

0 comments on commit 789e43f

Please sign in to comment.