flutterBlue.connect(device, timeout: const Duration(seconds: 10),).listen(null); in flutter - flutter

sorry,I am a beginner and my English is very bad
i have a trouble in Flutter.
i reference https://pub.dartlang.org/packages/flutter_blue
I want to use flutter to communicate with the ear thermometer device.
when i reopen bluetooth and it can work,but I reopen app and excute second it show error.
i guess bluetooth gatt cahce is causing a error.
how can i solve it?
my code
deviceConnection = flutterBlue.scan(timeout: const Duration(seconds: 5),).listen((scanResult) async {
device = scanResult.device;
deviceConnection2 = await flutterBlue.connect(device, timeout: const Duration(seconds: 10),).listen(null);//this line error is error 1
deviceStateSubscription = device.onStateChanged().listen((s) async {
await device.discoverServices().then((s) async {//this is error 2
.........
}
}
}
it show these error
error 1
Dart Error: Unhandled exception:
PlatformException(already_connected, connection with device already exists, null)
error 2
Dart Error: Unhandled exception:
PlatformException(get_services_error, no instance of BluetoothGatt, have you connected first?, null)

Error 1
Dart Error: Unhandled exception: PlatformException(already_connected, connection with device already exists, null)
Since the app detected that a bluetooth device is already connected, one workaround is check for any connected device disconnect it. You can create a function that does this like the one in this GitHub thread:
What you can do here is that you check for any connected devices and
then disconnect them. I have written a function that does just that,
here it is:
checkConnectedDevices() async{
connectedDevices = await flutterBlue.connectedDevices.whenComplete((){
print(connectedDevices);
for(int i = 0; i < connectedDevices.length; i++){
connectedDevices[i].disconnect();
}
});
}
Error 2
Dart Error: Unhandled exception: PlatformException(get_services_error, no instance of BluetoothGatt, have you connected first?, null)
Since there is an error connecting to the device, you will not be able to call the discoverServices(). Because you need to be connected to a device before you can call this function. Check the following GitHub discussions related to this error:
connected ' discoverServices ' is't get #426
discoverServices is broken #535

Related

How to deal with HTTP connection timed out crashes in Flutter

So I have a method that uses the Flutter HTTP library and is responsible for calling HTTP requests to the server with code like this:
Future<List<DataModel>> fetchData() async {
try {
var url = Uri.parse('${baseUrlParse}myapipath');
var request = await http.get(url);
var data = jsonDecode(request.body);
return data;
} catch (e) {
print('Catch ${e}');
rethrow;
}
}
This code runs fine and has no issues.
It got to the point where when I have no internet connection or server connection fails, the app freezes, and an error file appears (if you're debugging in VS Code), called http_impl.dart, and the error snippet goes something like this:
onError: (error) {
// When there is a timeout, there is a race in which the connectionTask
// Future won't be completed with an error before the socketFuture here
// is completed with a TimeoutException by the onTimeout callback above.
// In this case, propagate a SocketException as specified by the
// HttpClient.connectionTimeout docs.
if (error is TimeoutException) {
assert(connectionTimeout != null);
_connecting--;
_socketTasks.remove(task);
task.cancel();
throw SocketException(
"HTTP connection timed out after $connectionTimeout, "
"host: $host, port: $port");
}
_socketTasks.remove(task);
_checkPending();
throw error;
});
I have tried to implement from this source and this, but when I make a request but have no connection, this error still occurs.
How to deal with this problem?
What I want is, if there is a problem with HTTP either there is no connection, or it fails to contact the server, then I can make a notification..
Is there something wrong with my code?
Please help, thank you
You re throw the exception in your code,
You need to catch exception where you call to this method like this.
try {
await fetchData();
} catch (e) {
// TODO: handle exception
}
You can stop VS Code catching unhandled exceptions from this way
https://superuser.com/a/1609472

SocketException: Failed host lookup: ‘...com’ (OS Error: nodename nor servname provided, or not known, errno = 8)

We are in a situation where the production app is facing the following socket exception and not able to perform any other network operation after this. 
DioError [DioErrorType.DEFAULT]: SocketException: Failed host lookup: ‘xyz.abc.com’ (OS Error: nodename nor servname provided, or not known, errno = 8)
Note: Encountered repetitively with one user having iPhone X, iOS 14.4
We are using Dio as a network client, with Retrofit, which internally uses the HttpClient from the dart. With Dio the exception is not reproducible with the simulated environment but using HttpClient directly, the same exception can be reproduced with the following code in iOS simulator.
HttpClient userAgent = new HttpClient();
bool run = true;
while (run) {
try {
await userAgent.getUrl(Uri.parse('https://www.google.com'));
print('Number of api executed');
} catch (e) {
print(e);
if (e is SocketException) {
if ((e as SocketException).osError.errorCode == 8)
print('***** Exception Caught *****');
}
}
}
Once the exception was thrown, the HttpClient was not able to recover from that stale state and all other API requests were started failing with the same error.
We were able to recover from that stale state by force closing all the previous connections and opening up a new HttpClient.
HttpClient userAgent = new HttpClient();
bool run = true;
while (run) {
try {
await userAgent.getUrl(Uri.parse('https://www.google.com'));
print('Number of api executed');
} catch (e) {
print(e);
if (e is SocketException) {
if ((e as SocketException).osError.errorCode == 8)
print('***** Exception Caught *****');
}
userAgent.close(force: true);
print('Force closing previous connections');
userAgent = HttpClient();
print('Creating new HttpClient instance');
}
}
One interesting fact is after every 236 requests the exception is raising. It could be because of file descriptors over usage but iOS has a limit of 256. 🙄
With a stable internet connection, this issue reproducible every time in iOS simulator.
Although I am not able to reproduce the issue with Dio client but as in production it is occurring. So I am seeking help to understand the root cause of this issue, also how we can prevent it?
Anyone who has come across this kind of situation and how you have overcome it, please help me.
Thanks in advance.
That's a strange error.
This might not answer your question, but may push us towards figuring out what's going on.
The code snippet (copied from question) will open up a new stream with each .getUrl() call and will not close them. (I'm assuming this is intentional to create the socket exception?)
HttpClient userAgent = new HttpClient();
bool run = true;
while (run) {
try {
await userAgent.getUrl(Uri.parse('https://www.google.com'));
print('Number of api executed');
} catch (e) {
print(e);
if (e is SocketException) {
if ((e as SocketException).osError.errorCode == 8)
print('***** Exception Caught *****');
}
}
}
At some point, a limit (of open streams) is hit. I guess that magic number is 236 in your case.
So at that point, is when you're seeing the nodename or servname provided exception?
(Btw, as an aside, I think that error is coming from the underlying host operating system's DNS service, although I'm not sure if it's due to the request spam, the number of open connections, etc. This may not be relevant info.)
So, if you used the HttpClient in a typical way, making requests & closing those open streams, such as this:
var request = await userAgent.getUrl(Uri.parse('http://example.com/'));
var response = await request.close(); // ← close the stream
var body = await response.transform(utf8.decoder).join();
// ↑ convert results to text
// rinse, repeat...
... Are you still seeing the same nodename or servname provided error pop up?
With this "typical usage" code immediately above, the userAgent can be reused until a userAgent.close() call is made (and the HttpClient is permanently closed.
Trying to use it again would throw a Bad State exception).
I'd be interested to hear if the nodename error still occurs with this modified code.
Re: the second code snippet from the question.
In the catch block, the HttpClient is closed, then a new HttpClient is created. This effectively closes all the open streams that were opened in the try block (and I assume, resetting the limit of open streams.)
If you adjusted the 2nd code example to use:
var req = await userAgent.getUrl(Uri.parse('https://www.google.com'));
userAgent.close(force: true);
userAgent = HttpClient();
print('Number of api executed');
Could you run that indefinitely?
i have same issue resolve with this code:-
Exmaple
//Add This Class
class MyHttpOverrides extends HttpOverrides{
#override
HttpClient createHttpClient(SecurityContext? context){
return super.createHttpClient(context)
..badCertificateCallback = (X509Certificate cert, String host, int port)=> true;
}
}
Future<void> main() async {
HttpOverrides.global = MyHttpOverrides(); //call here
runApp(const MyApp());
}
1:Obtain the current limit of file descriptors
ulimit -n
An example output: “256” or “10032”.
PROTIP: On MacOS, the maximum number that can be specified is 12288.
Obtain the current limit of processes
ulimit -u
An example output: “1418”.
sudo launchctl limit maxfiles 65536 200000
I got exactly the same errors in production, it happens intermittently. Like Baker said, close the connections:
import 'package:http/http.dart' as http;
Future<http.Response> get(String url) async {
var httpClient = http.Client() as http.BaseClient;
Map<String, String> headers = {};
headers['Content-Type'] = 'application/json; charset=UTF-8';
var result = await httpClient
.get(Uri.parse(url), headers: headers)
.timeout(
const Duration(seconds: 60),
onTimeout: () => http.Response('Request Timeout', 408),
);
httpClient.close();
return result;
}
I did 10x Future.Delayeds each doing a loop with 300 get requests at the same time, didn't find any issues.
The future delayeds was done like so:
Future.delayed(const Duration(milliseconds: 10), () async {
for (var i = 0; i < 300; i++) {
var pingResult = await Api.instance.ping();
print('Delayed 1 Result (${i}): ${pingResult.success}');
}
});
Future.delayed(const Duration(milliseconds: 10), () async {
for (var i = 0; i < 300; i++) {
var pingResult = await Api.instance.ping();
print('Delayed 2 Result (${i}): ${pingResult.success}');
}
});
//..

Receive commands from a specific channel

How can I make the bot receive commands from specific channels, and if there is no channel, it is received from all channels and it is connected to mongoDB?
I can do the receiving command from a specific channel using channel ID, but I want via the command:
!setChannel #ID_CHANNEL OR mention
I tried these codes
let channel = message.mentions.channels.first()
if(!args[0]) return message.channel.send('Please Mention Channel');
if(!channel) return message.channel.send('Please Mention Vaild Channel');
/*-----------------------------in mongedb add Guild id + channel id------------------------------
in quick.db it is like this -->
db.set("commands_channel_"+ message.guild.id + channel.id, true)*/
message.channel.send(`Commands Channel: ${channel}`);
let CommandsChannel = db.get("commands_channel_"+ message.guild.id + channel.id)
if(!CommandsChannel) return
//-------------------------------//
if(CommandsChannel = true) {
// else command code //
}
wrong with the code
(node:4456) UnhandledPromiseRejectionWarning: Error: `commands_channel_708596988995829762709436321805893753` is an invalid option.
at Mongoose.set (/rbd/pnpm-volume/34e95e32-ea3c-4e44-8fb4-6f803dcbc088/node_modules/.registry.npmjs.org/mongoose/5.10.15/node_modules/mongoose/lib/index.js:179:48)
at Object.run (/app/commands/admin/setchannel.js:19:10)
at module.exports (/app/events/message.js:152:17)
at processTicksAndRejections (internal/process/task_queues.js:88:5)
(node:4456) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)

SignalR Core - Error: Websocket closed with status code: 1006

I use SignalR in an Angular app. When I destroy component in Angular I also want to stop connection to the hub. I use the command:
this.hubConnection.stop();
But I get an error in Chrome console:
Websocket closed with status code: 1006
In Edge: ERROR Error: Uncaught (in promise): Error: Invocation canceled due to connection being closed. Error: Invocation canceled due to connection being closed.
It actually works and connection has been stopped, but I would like to know why I get the error.
This is how I start the hub:
this.hubConnection = new HubConnectionBuilder()
.withUrl("/matchHub")
.build();
this.hubConnection.on("MatchUpdate", (match: Match) => {
// some magic
})
this.hubConnection
.start()
.then(() => {
this.hubConnection.invoke("SendUpdates");
});
EDIT
I finally find the issue. Its caused by change streams from Mongo. If I remove the code from SendUpdates() method then OnDisconnected is triggered.
public class MatchHub : Hub
{
private readonly IMatchManager matchManager;
public MatchHub(IMatchManager matchManager)
{
this.matchManager = matchManager;
}
public async Task SendUpdates() {
using (var changeStream = matchManager.GetChangeStream()) {
while (changeStream.MoveNext()) {
var changeStreamDocument = changeStream.Current.FullDocument;
if (changeStreamDocument == null) {
changeStreamDocument = BsonSerializer.Deserialize<Match>(changeStream.Current.DocumentKey);
}
await Clients.Caller.SendAsync("MatchUpdate", changeStreamDocument);
}
}
}
public override async Task OnDisconnectedAsync(Exception exception)
{
await base.OnDisconnectedAsync(exception);
}
}
Method GetChangeStream from the manager.
ChangeStreamOptions options = new ChangeStreamOptions() { FullDocument = ChangeStreamFullDocumentOption.UpdateLookup };
var watch = mongoDb.Matches.Watch(options).ToEnumerable().GetEnumerator();
return watch;
But I don't know how to fix it.
This can be for many reasons but i think it is most likely this one:
I think this is because of how the server is handling the connected / disconnected events. I can't say for sure but the connection closing needs to handled correctly on the server also with code. Try overriding the built in On Connected /Disconnected methods on the server and see. My assumption only is that you're closing it but the server isn't closing properly and therefore not relaying the proper closed response.
found as a comment at : getting the reason why websockets closed with close code 1006
Where you don't need to change the connection/disconection because evrything works fine. But as an answer this one is the most likely.
It throws error because the callback doesn't get clear properly.
And it is caused by the return data from websocket.
normally it should return like
However, for some reason it might return something like
the very last response breaking into 2 pieces
And that causes the issue.
I don't think there is a way to bypass this without changing the source code.
I reported this on github repo as well at here
It turns out that I can just utilize invocation response to notify client to stop the hub. So it doesn't trigger racing issue.

UWP app wireless connection crashes app without exception

Im trying to connect to wireless network from my uwp application (windows iot core os)
I can scan and list all wireless networks around me without any problem.
When i try to connect without credential connection fails as expected and program continues.
My problem is when i try to connect to a network with credentials my app closes and i cannot catch it even with using try catch.App goes from screen ( rasberry pi 3 ) and debug session is lost.Instead it should return me connection failed invalid credentials.
I'm also testing Microsoft samples for connecting wireless and i observed this behave happens in Microsoft sample when you try to connect to a network that you already connected it crashes without any exception
https://github.com/ms-iot/samples/tree/develop/WiFiConnector/CS
To Summurize; With following code if call firstAdapter.ConnectAsync() without credentials its normal but if call it with credentials program goes off from screen even without exception.
Note: i call await WiFiAdapter.RequestAccessAsync(); before i start.
my code as following
var adapterResult = await WiFiAdapter.FindAllAdaptersAsync();
if (adapterResult.Count >= 1)
{
WiFiAdapter firstAdapter = adapterResult[0];
await firstAdapter.ScanAsync();
var network = firstAdapter.NetworkReport.AvailableNetworks.FirstOrDefault();
PasswordCredential credential = new PasswordCredential();
credential.Password = "zp1PDQPdYFpCU";
try
{
WiFiConnectionResult result;
if (network.SecuritySettings.NetworkAuthenticationType == Windows.Networking.Connectivity.NetworkAuthenticationType.Open80211 &&
network.SecuritySettings.NetworkEncryptionType == NetworkEncryptionType.None)
{
result = await firstAdapter.ConnectAsync(network, WiFiReconnectionKind.Automatic);
}
else
{
result = await firstAdapter.ConnectAsync(network, WiFiReconnectionKind.Automatic, credential);
}
}
catch (Exception)
{
throw;
}