flutter_smartconfig/lib/flutter_smartconfig.dart

94 lines
2.9 KiB
Dart

import 'dart:async';
import 'package:flutter/services.dart';
import 'dart:convert';
import 'dart:io' show Platform;
// Note support only Android
// for iOS https://github.com/lou-lan/SmartConfig
class FlutterSmartconfig {
static const platform =
const MethodChannel("plugins.flutter.io/flutter_smartconfig");
static Future<void> stopConfigure() async {
if (Platform.isAndroid) {
try {
await platform.invokeMethod('stopSmartConfig');
} on PlatformException catch (e) {
return Future<Map<String, String>>(() {
throw new PlatformException(
code: "Failed to get connected WiFi name: '${e.message}'.");
});
}
} else {
return Future<Map<String, String>>(() {
throw new PlatformException(code: "only Android is supported");
});
}
}
static Future<dynamic> configureEsp(
{String ssid, String bssid, String password, bool multicast, Duration timeout}) async {
if (Platform.isAndroid) {
try {
// Change if required.
const String deviceCount = "1"; // the expect result count
String broadcast = (multicast != null && multicast) ? "0" : "1"; // broadcast (1) or multicast (0)
Duration _kLongTimeout = timeout ?? const Duration(seconds: 20);
final String result =
await platform.invokeMethod('startSmartConfig', <String, dynamic>{
'ssid': ssid,
'bssid': bssid,
'pass': password,
'deviceCount': deviceCount,
'broadcast': broadcast,
}).timeout(_kLongTimeout);
final parsed = json.decode(result);
final devices = parsed["devices"];
return Future<dynamic>(() {
return devices;
});
} on PlatformException catch (e) {
return Future<Map<String, String>>(() {
throw new PlatformException(
code: "Failed to configure: '${e.message}'.");
});
}
} else {
return Future<Map<String, String>>(() {
throw new PlatformException(code: "only Android is supported");
});
}
}
// Build.VERSION.SDK_INT >= 28 needs Manifest.permission.ACCESS_COARSE_LOCATION
static Future<Map<String, String>> getConnectedWiFiInfo() async {
if (Platform.isAndroid) {
try {
String wiFiInfo = await platform.invokeMethod('getConnectedWiFiInfo');
final parsed = json.decode(wiFiInfo);
return Future<Map<String, String>>(() {
return {
"ssid": parsed["ssid"],
"bssid": parsed["bssid"],
"is5G": parsed["is5G"]
};
});
} on PlatformException catch (e) {
return Future<Map<String, String>>(() {
throw new PlatformException(
code: "Failed to get connected WiFi name: '${e.message}'.");
});
}
} else {
return Future<Map<String, String>>(() {
throw new PlatformException(code: "only Android is supported");
});
}
}
}