I want to connect 2 Arduino to the same mobile app using BLE I have the code for one Arduino connection how to manage it so I can have two Arduino connected
is it possible to connect two Arduinos with BLE to the same app?
Or should I find another alternative
void _connectBLE() {
setState(() {
temperatureStr = 'Loading';
});
_disconnect();
_subscription = _ble.scanForDevices(
withServices: [],
scanMode: ScanMode.lowLatency,
requireLocationServicesEnabled: true).listen((device) {
if (device.name == 'Arduino3') {
print('NiclaSenseME found!');
_connection = _ble
.connectToDevice(
id: device.id,
)
.listen((connectionState) async {
// Handle connection state updates
print('connection state:');
print(connectionState.connectionState);
if (connectionState.connectionState ==
DeviceConnectionState.connected) {
Timer.periodic(Duration(milliseconds: 5), (timer) async{
final characteristic = QualifiedCharacteristic(
serviceId: Uuid.parse("181A"),
characteristicId: Uuid.parse("2A6E"),
deviceId: device.id);
final response = await _ble.readCharacteristic(characteristic);
print(response);
setState(() {
temperature = fromBytesToInt32(response[0],response[1],response[2],response[3]);
print(temperature);
temperatureStr = temperature.toString();
});
});
_disconnect();
print('disconnected');
}
}, onError: (dynamic error) {
// Handle a possible error
print(error.toString());
});
}
}, onError: (error) {
print('error!');
print(error.toString());
});
}
Related
I use socket_io_client to connect to a server socket. it works fine but after getting the first response it dissconnects and I should connect it again and again. It doesnt listen to the sever infinintly. here is my code
initSocket(String msg,String userStr) async {
if(socket!=null){
await loginToServer('$userName\n');
}else{
socket = await Socket.connect(socketIpAddress, 1500);
print('Connected to: ${socket!.remoteAddress.address}:${socket!.remotePort}');
await loginToServer('$userName\n');
// listen for responses from the server
socket?.listen(
// handle data from the server
(Uint8List data) {
final serverResponse = String.fromCharCodes(data);
print('Server: $serverResponse');
if(serverResponse.contains('hello')){
sendMessage(msg, userStr);
}else{
ParserSocket().getMessage(serverResponse.substring(9), serverResponse.substring(3,9), SentType.Internet, false, ctx);
}
},
// handle errors
onError: (error) {
print(error);
socket?.destroy();
},
// handle server ending connection
onDone: () {
print('Server left.');
socket!.destroy();
},
cancelOnError: false
);
}
}
Future<void> sendMessage(String message,String userName) async {
print('Client: $msg');
socket?.write(msg);
}
I checked onDone() method but no result
I am developing an app that works with various health measuring bluetooth devices.
I am using with React-native and react-native-ble-plx.
I don't know much about Bluetooth, so I'm searching each device and developing it.
Some sphygmomanometers and scales have completed, but the blood glucose meter, which requires input of a serial number, cannot be linked.
The connection Bluetooth that has been developed so far is as follows.
Scan -> Found device -> Stop scan -> Connect -> discover all services&characteristics -> Find service list -> filter measurement service -> find characteristics list from filtered service -> monitor those
The device I am having a hard time developing right now is the “Accu-check Guide Me” blood glucose device.
Other devices are receiving the measured values well.
But after this device is connected, if the test strip is inserted into the machine, the Bluetooth connection is cut off.
Connect -> Popup to insert serial number -> insert serial number -> connected success -> insert test strip into Accu-check -> disconnected
Perhaps unlike other devices, this device seems to have to do something more in between the normal flow, but it is difficult to find out from my knowledge even if I search hard.
I'd appreciate it if you could tell me what more to do in the code below.
const scanAndConnectAcucheckGlucoseMeter = () => {
return new Promise((resolve, reject) => {
let result = 0;
console.log('scanStart');
manager.startDeviceScan(null, null, (error, device) => {
if (error) {
console.log('error : ' + error);
return;
}
const deviceName = device.name;
if (deviceName != null) {
if (deviceName.includes('meter+')) {
console.log('detected!!');
manager.stopDeviceScan();
resolve(device);
}
}
});
});
};
const MonitoringForAcucheckGuideMe = device => {
return new Promise((resolve, reject) => {
device
.connect()
.then(device => {
const result = device.discoverAllServicesAndCharacteristics();
return result;
})
.then(device => {
return device.services();
})
.then(services => {
// 180A : device information
// 1800 : generic access
// 1808 : glucose
// 00000000-0000-1000-1000-00000000000 : custom service
const result = services.filter(id => id.uuid.indexOf('1808') != -1); // Glucose Service
return result[0].characteristics();
})
.then(characters => {
// Glucose Measurement :00002A18 / Descriptors 2902
// Glucose Feature : 2A51
// Record Access Control Point 2A52 / Descriptors 2902
// DateTime 2A08
const glucoseMeasurement = characters.filter(
data => data.uuid.indexOf('2a18') != -1, // 2a35 is for blood sugar measurement
);
// popup to insert pin number on mobile when monitor()
glucoseMeasurement[0].monitor((error, characteristic) => {
if (error) {
console.log('error:::::', error);
reject(error);
}
const Valuebytes = Buffer.from(characteristic.value, 'base64');
console.log(Valuebytes);
const result = "Not yet"
resolve(result)
});
})
.catch(error => console.log(error));
});
};
I'm working in an Ionic App with angular and socket IO (also I'm using ngrx), but I have a problem that the socket stops when the screen is inactive.
The fail process is this:
First you enter the app, so the socket connects. The socket connects only if my redux state has a token, in other case, the socket will not has to connect
Then, imagine that you left the app executing and your phone automatically locks the screen, so the app changes to an "pause" state
After 10 minutes on the pause state, you unlock your phone which causes that the app enter in a resume state and then is when the socket makes crash the whole app an it simply closes
The socket works correctly
I know is the socket becouse I tried removing just some lines of my socket service and the app are not closing. If I just wait 7 or 8 or 5 minutes or less to unlock the phone, the app won't crash. The crash only happens after 10 minutes with the screen locked
This is my ngx-socket-io configuration
const config: SocketIoConfig = { url: 'http://localhost:5000', options: { transports: ["websocket", "xhr-polling", "jsonp-polling"], autoConnect: false } };
#NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [
BrowserModule,
HttpClientModule,
IonicModule.forRoot(),
AppRoutingModule,
StoreModule.forRoot(appReducers),
StoreDevtoolsModule.instrument({ maxAge: 25, logOnly: environment.production}),
EffectsModule.forRoot(effectsArray),
SocketIoModule.forRoot(config),
],
providers: [{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy } ],
bootstrap: [AppComponent],
})
export class AppModule {}
And this is my app.component.ts
constructor(public store: Store<AppState>, public websocketService: WebsocketService, public appStatusService: AppStatusService, public platform: Platform) { }
ngOnInit() {
this.store.select('session').pipe(filter(session => session !== null)).subscribe(session => {
// IF I REMOVE THIS CONDITION, THE APP WON'T CRASH
if (session.currentSession.token === null) {
// DISCONNECT IF WAS CONNECTED
this.websocketService.disconnectSocket();
} else {
// CONNECT
this.websocketService.connectSocket();
}
});
this.initializeApp();
}
initializeApp() {
this.platform.ready().then(() => {
this.platform.pause.subscribe(e => { this.appStatusService.setStatus(false); });
this.platform.resume.subscribe(e => { this.appStatusService.setStatus(true); });
});
}
This is my webSocket Service
export class WebsocketService {
socketConnected = false;
socketStatus:boolean;
constructor(private socket: Socket, public http: HttpClient, public apiConfigService: ApiConfigService, public authService: AuthService, public platform: Platform) {
this.checkStatus();
}
async connectSocket() {
const data = await this.socketCredentials();
if (data !== null && data !== undefined) {
this.socket.ioSocket.io.opts.query = { sessionUUID: data.sessionUUID, channelUUID: data.channelUUID } ;
this.socketConnected = true;
this.socket.connect();
this.socket.emit( 'JOIN_ROOM', {channelID: data.channelUUID } );
}
}
disconnectSocket() {
if (this.socketConnected === true) { this.socket.disconnect(); this.socketConnected = false; }
}
checkStatus() {
this.socket.on('connect', () => { console.log('SOCKET CONNECTED'); });
this.socket.on('disconnect', () => { console.log('SOCKET DISCONNECTED'); });
}
socketCredentials(): Promise<any> {
// I need to get some credentials to connect the socket. Only can connect to my server if I have this credentials
return new Promise(resolve => {
this.http.get('http://localhost:3000/socket/auth').toPromise().then(response => { resolve(response); });
});
}
}
I've been using flutter Blue for some now and I'm stuck on the following:
I'm using the example App I downloaded on https://github.com/pauldemarco/flutter_blue, through here the basic idea is that as soon as I connect to my bluetooth device it starts checking if the service "FFE0" exists and then the characteristic "FFE1".
This Characteristic spits out random strings I need for my project.
Image of screen with characteristic open
Through the screen I can see the above is true I just need to somehow automatically set notifications for the characteristic as soon as it connects to the bluetooth device.
This is some current code i'm testing out in the _Connect Function.
_connect(BluetoothDevice d) async {
device = d;
// Connect to device
deviceConnection = _flutterBlue
.connect(device, timeout: const Duration(seconds: 4))
.listen(
null,
onDone: _disconnect,
);
// Update the connection state immediately
device.state.then((s) {
setState(() {
deviceState = s;
});
});
// Subscribe to connection changes
deviceStateSubscription = device.onStateChanged().listen((s) {
setState(() {
deviceState = s;
});
if (s == BluetoothDeviceState.connected) {
device.discoverServices().then((service) {
service.forEach((_service){
var characteristics = _service.characteristics;
_service.characteristics.map((c) {
print(c);
});
for(BluetoothCharacteristic _characteristic in characteristics) {
device.readCharacteristic(_characteristic).then((_value){
print(_value);
if (_value.contains("FFE0")) {
print("Found!!");
// do something
}
});
}
});
setState(() {
services = service;
});
_getServices();
});
}
});
}
I maybe someone has a suggestion on how to approach my problem.
Robin
I found https://github.com/Sensirion/smart-gadget-flutter/tree/master/lib and I was able to fix my problem using the following code:
for(BluetoothService service in services) {
for(BluetoothCharacteristic c in service.characteristics) {
if(c.uuid == new Guid("0000ffe1-0000-1000-8000-00805f9b34fb")) {
_setNotification(c);
} else {
print("Nope");
}
}
}
This was added in the _connect function.
_connect(BluetoothDevice d) async {
device = d;
// Connect to device
deviceConnection = _flutterBlue
.connect(device, timeout: const Duration(seconds: 4))
.listen(
null,
onDone: _disconnect,
);
// Update the connection state immediately
device.state.then((s) {
setState(() {
deviceState = s;
});
});
// Subscribe to connection changes
deviceStateSubscription = device.onStateChanged().listen((s) {
setState(() {
deviceState = s;
});
if (s == BluetoothDeviceState.connected) {
device.discoverServices().then((s) {
services = s;
for(BluetoothService service in services) {
for(BluetoothCharacteristic c in service.characteristics) {
if(c.uuid == new Guid("0000ffe1-0000-1000-8000-00805f9b34fb")) {
_setNotification(c);
} else {
print("Nope");
}
}
}
setState(() {
services = s;
});
_getServices();
});
}
});
}
here is code
beacon-provider.ts >>
initialise(): any {
let promise = new Promise((resolve, reject) => {
if (this.platform.is('cordova')) {
IBeacon.enableBluetooth();
this.delegate = IBeacon.Delegate();
this.delegate.didRangeBeaconsInRegion()
.subscribe(
data => {
this.events.publish('didRangeBeaconsInRegion', data);
},
error => console.error()
);
this.region = IBeacon.BeaconRegion('deskBeacon', '24DDF411-8CF1-440C-87CD-E368DAF9C93E');
IBeacon.startRangingBeaconsInRegion(this.region)
.then(
() => {
resolve(true);
},
error => {
console.error('Failed to begin monitoring: ', error);
resolve(false);
}
);
} else {
console.error("This application needs to be running on a device");
resolve(false);
}
});
return promise;
}
}
home.ts >>
export class HomePage {
beacons: BeaconModel[] = [];
zone: any;
constructor(public navCtrl: NavController, public platform: Platform, public beaconProvider: BeaconProvider, public events: Events) {
this.zone = new NgZone({ enableLongStackTrace: false });
}
ionViewDidLoad() {
this.platform.ready().then(() => {
this.beaconProvider.initialise().then((isInitialised) => {
if (isInitialised) {
this.listenToBeaconEvents();
}
});
});
}
listenToBeaconEvents() {
this.events.subscribe('didRangeBeaconsInRegion', (data) => {
this.zone.run(() => {
this.beacons = [];
let beaconList = data.beacons;
beaconList.forEach((beacon) => {
let beaconObject = new BeaconModel(beacon);
this.beacons.push(beaconObject);
});
});
});
}
}
In this code, the result of alert(JSON.stringify(data)) is:
{"eventType":"didRangeBeaconslnRegion","region":{"identifier":"desk beacon","uuid":"24DDF411-8CF1-440C-87CD-E368DAF9C93E","typeName":"BeaconRegion"}, "beacons":[]}
The field data.beacons is empty.
What is the problem?
one more question i try BLE-central plugin first but,
when i was using BLE-central plugin i get signal but it was not given to me major , minor value if i get this value from advertising ?
There are lots of things that might cause this behavior:
Verify that Bluetooth is on
Verify that your app has been granted runtime location permissions needed to detect Bluetooth devices. Go to Settings -> Apps -> [Your app name] -> Permissions, and make sure you see a Location entry with the switch turned on.
Verify using an off-the-shelf detector app that your beacon actually is transmitting the identifier you expect. Try my Locate app here: https://play.google.com/store/apps/details?id=com.radiusnetworks.locate&hl=en