Flutter插件,用于自动wifi连接,无需用户提示



具体用例是一个可穿戴应用程序(Wear OS),我想自动连接到配置文件中指定的wifi网络,以便轻松跨站点部署,甚至不告诉它正在完成。我已经尝试了wifi_iot和plugin_wifi_connect与一些奇怪的结果。两者似乎都连接到了正确的ssid,但它们给出了一些奇怪的提示,说要连接到设备,似乎之后就把连接弄乱了。

wifi_iot实现:

check for wifi setting
WiFiForIoTPlugin.isEnabled().then((val) {
_isEnabled = val;
});
print('isEnabled: $_isEnabled');
//check if connected to wifi
WiFiForIoTPlugin.isConnected().then((val) {
_isConnected = val;
});
print('isConnected: $_isConnected');
//enable and connect if not
if (!_isEnabled) {
//enable wifi
WiFiForIoTPlugin.setWiFiAPEnabled(true);
WiFiForIoTPlugin.setEnabled(true);
}
if (!_isConnected) {
//connect to wifi
WiFiForIoTPlugin.connect(_ssid,
password: _psk, security: NetworkSecurity.WPA);
}

plugin_wifi_connect实现:

var _connectedTo = await PluginWifiConnect.ssid;
print("Comparing $_connectedTo to $_ssid"); //#_connectedTo returns <unidentified_ssid>#
if (_connectedTo.toString() != _ssid) { //#this always fails 
try {
await PluginWifiConnect.connectToSecureNetwork(_ssid, _psk,
saveNetwork: true);
print("Connected to $_ssid");
} catch (e) {
print("Couldn't connect to $_ssid");
}
} else {
print("Already connected to $_ssid");
}

有人有这方面的经验吗?可能我没有使用正确的权限,或者如果我需要做一些事情,如果这是可能的了。29以上的API似乎有一些变化,改变了它的某些方面。plugin_wifi_connect没有太多的文档,看起来它可能是基于一个旧的包,不是null安全的,不是真正的最新的相同的文档。

使用getX对于断开连接检查的连接和计时器,我使用此代码。

Future connect(WifiNetwork wifi) async {
Get.back();
await disconnect();
isConnected = await PluginWifiConnect.connectToSecureNetwork(
wifi.ssid!,
Costanti.passwordEsp,
saveNetwork: false,
) ??
false;
String? ssid = (await PluginWifiConnect.ssid)?.replaceAll('"', '');
connectedMachine = !isConnected ? null : ssid;
timer ??= Timer.periodic(const Duration(seconds: 1), (timer) async {
ssid = (await PluginWifiConnect.ssid)?.replaceAll('"', '');
if (connectedMachine != null && connectedMachine != ssid) {
Logger.error("Disconnesso $connectedMachine -> $ssid");
this.timer = null;
if (Get.currentRoute == "/${THEROUTENAME}") {
await HelperDialog.showConferma(
showAnnulla: false,
titolo: "GENERALE_disconnected_titolo".tr,
contenuto: "GENERALE_disconnected_contenuto".tr,
confermaText: "GENERALE_disconnected_reconnect".tr,
confermaPressed: () async {
await disconnect();
await connect(wifi);
},
);
} else {
await HelperDialog.showConferma(
showAnnulla: false,
titolo: "GENERALE_disconnected_titolo".tr,
contenuto: "GENERALE_disconnected_contenuto".tr,
confermaText: "HOME",
confermaPressed: () async {
await disconnect();
Get.offAll(() => HomePage());
},
);
}
timer.cancel();
this.timer?.cancel();
}
});