Web Bluetooth characteristic.writeValue break the connection automatically - android

I follows Google/chrome samples for Web Bluetooth. I have two writeValue operations. One is within the requestDevice promise and it works perfectly. Second one, I save the characteristic reference and writeValue when the action trigger. The message is sent but connection broke automatically. I am using Mac OSX 10.13.3 and chrome64 and modify Android BLE Peripheral Simulator (From google github)
The code segment ---
var bluetoothDevice;
var myCharacteristic;
navigator.bluetooth.requestDevice({
...
})
.then(device => {
bluetoothDevice = device;
....
})
....
.then(characteristic =>{
myCharacteristic = characteristic;
let encoder = new TextEncoder('utf-8');
let sendMsg = encoder.encode("hello");
/*
It works...
*/
myCharacteristic.writeValue(sendMsg);
})
....
function onSendMessage() {
if (!bluetoothDevice.gatt.connected) {
log("device is disconnected")
return
}
if (!myCharacteristic){
log("no characteristic defined")
return
}
let encoder = new TextEncoder('utf-8');
let sendMsg = encoder.encode("hello");
/*
message sent but auto disconnect the peripheral
*/
myCharacteristic.writeValue(sendMsg);
}
Does anyone has same experience and any suggestion for keep connection persistence for writeValue?

Your code looks good to me. A similar code can be found as well at https://googlechrome.github.io/samples/web-bluetooth/link-loss.html
However I wonder which characteristic you're trying to write to. If that is not supported, the Android device might simply disconnect.
Check out https://www.chromium.org/developers/how-tos/file-web-bluetooth-bugs#TOC-Android and grab Android adb logs if that helps.

Related

How to change bluetooth device name in Flutter?

How can I set my device name for bluetooth in Flutter?
In Java, there is one plugin BluetoothAdapter which could be used to set the bluetootg device name, but in Flutter, I did not find a way to do this.
thanks
Try FlutterBlue which is a bluetooth plugin for Flutter. You should able to do that via that plugin. Here is an example of reading/writing a characteristic from that page just in case if link goes poof:
// Reads all characteristics
var characteristics = service.characteristics;
for(BluetoothCharacteristic c in characteristics) {
List<int> value = await c.read();
print(value);
}
// Writes to a characteristic
await c.write([0x12, 0x34])

How do I send/receive data using bluetooth in flutter?

I'm trying to receive and send data from and to an arduino uno. I've tried looking into flutter blue plugin and flutter bluetooth serial plugin ,flutter serial plugin
seems to be incomplete and flutter blue lacks examples or documentation, and the official github example is way too complicated and is irrelevant to what i want to do. I want a very simple method of sending or retrieving data from an arduino using a HC-05 module.
If you are working with a HC-05 module (No Low Energy Bluetooth). Use ´flutter_bluetooth_serial´ package. It is not a great package, but it should work.
This example may not work.
Scan for devices:
//Here the scan results will be saved
List<BluetoothDiscoveryResult> results = List<BluetoothDiscoveryResult>();
void startDiscovery() {
streamSubscription = FlutterBluetoothSerial.instance.startDiscovery().listen((r) {
results.add(r);
});
streamSubscription.onDone(() {
//Do something when the discovery process ends
});
}
Connect to device:
Use this function when you select a device from the result list.
BluetoothConnection connection;
connect(String address) async {
try {
connection = await BluetoothConnection.toAddress(address);
print('Connected to the device');
connection.input.listen((Uint8List data) {
//Data entry point
print(ascii.decode(data));
})
} catch (exception) {
print('Cannot connect, exception occured');
}
}
Send data:
Future send(Uint8List data) async {
connection.output.add(data);
await _connection.output.allSent;
}
Try the example app from the ´flutter_bluetooth_serial´-package now. They even included reading data from an HC-05-module! If you want something simpler, try extracting the essential code from the example and copycoding it into another app.

Not able to send data to BLE Peripheral (ZL-RC04A) device

I am trying to write data using code snippet.
- (void)peripheral:(CBPeripheral *)peripheral1 didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
// Again, we loop through the array, just in case.
for (CBCharacteristic *characteristic in service.characteristics) {
// And check if it's the right one
if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:TRANSFER_CHARACTERISTIC_UUID]]) {
NSString *payloadMessage = #"3N";
NSData *payload = [payloadMessage dataUsingEncoding:NSUTF8StringEncoding];
[_discoveredPeripheral discoverDescriptorsForCharacteristic:characteristic];
[_discoveredPeripheral writeValue:payload forCharacteristic:characteristic
type:CBCharacteristicWriteWithResponse];
[_discoveredPeripheral setNotifyValue:YES forCharacteristic:characteristic];
}
}
}
But getting error in
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(nullable NSError *)error
{
}
As:
Error Domain=CBATTErrorDomain Code=3 "Writing is not permitted." UserInfo={NSLocalizedDescription=Writing is not permitted.}
Although same is working android.
You get that error if you use the wrong write type for the characteristic (given the characteristic is writable after all). There are two types of writing data to a characteristic:
CBCharacteristicWriteWithResponse: In this case you will get an acknowledge packet by the peripheral. You can think of this as a TCP packet.
CBCharacteristicWriteWithoutResponse: This is a "fire and forget" kind of write. You can think of this as a UDP packet.
Therefore, try to use CBCharacteristicWriteWithoutResponse instead of CBCharacteristicWriteWithResponse. If that does not work as well you might have to check if your characteristic is writable after all.

WebSocket not closed on reload app(React Native)

I'm using WebSocket with React Native and have some issues on it. When I refresh the app, I found that previous WebSocket connection(used before refresh) was still alive, and not closed properly. Every time I was reloaded the App, it makes new connection. Then I shutdown the app, it releases all connections together.
When I'm testing almost same code with browser, when I refresh the page, socket is closed automatically and create new Websocket on page loads.
If this problem is still existing on production environment, it could be very critical.
This is server side code(I used express-ws):
const sockets = {};
app.ws('/', (socket, req) => {
// Generate unique id to socket and save to socket list
const uid = uuid.v4();
socket.uid = uid;
console.log(`Socket ${uid} connected.`);
sockets[uid] = socket;
socket.on('message', (data) => {
broadcast(data);
});
socket.on('close', () => {
console.log(`Socket ${uid} disconnected.`);
delete sockets[uid];
broadcast({
type: 'plain',
message: `User ${socket.username} leaved the channel.`
});
socket = null; // make sure to remove socket
});
});
Server just saves received WebSocket on connected, and remove it when closed. You can see that I logged Socket id that I made when got connection for identify each websocket handy, it looks like this(used node-uuid):
Socket d0b62d3a-2ed9-4258-9d2d-e83a3eb99e6c disconnected.
Ok, when I tested this server with Web browsers, it worked well. Every refresh successfully were closed socket and created new one.
But with React Native, socket never closed on refresh the app. After several refreshes, and finally exit the app, suddenly these messages were appear on the console at once:
Socket d0b62d3a-2ed9-4258-9d2d-e83a3eb99e6c disconnected.
Socket 2e1a2bba-ac64-4368-aeca-a02721f28ce5 disconnected.
Socket 6673c9a3-9667-425a-8923-efbc40196226 disconnected.
Socket 08fee145-e9bf-4af0-a245-dda2fe6a8e56 disconnected.
Socket 55ce1926-d7fa-488b-92d9-ff3dea874496 disconnected.
Socket 9c4c166d-d6d6-4a11-b400-a3eac51ab91f disconnected.
Socket 9f6db512-649c-440e-8b88-9a77d20e1943 disconnected.
Socket a9e6c0bd-419c-40af-865a-2573eca26a0f disconnected.
Socket 70835c7a-3230-4e20-b133-b6c2942dff22 disconnected.
Socket 5c83d81c-c0f1-4b9a-b5fb-7f09430a2f09 disconnected.
Socket 4f11aea4-d0ad-4e2b-9613-9e994657ecaf disconnected.
Below code is WebSocket handling part of my React Native app.
import store from './store';
import * as ChatActions from './actions/Chat';
import * as NetworkActions from './actions/Network';
const socket = null;
export function init() {
socket = new WebSocket('ws://mywebsite.com:3300');
socket.onopen = () => {
store.dispatch({
type: NetworkActions.NETWORK_SOCK_CONNECTED,
data: {}
});
};
socket.onmessage = (e) => {
var data = e.data;
try {
data = JSON.parse(e.data);
}
catch(err) {}
store.dispatch({
type: ChatActions.CHAT_RECV,
data: data.message
});
};
socket.onclose = (e) => {
store.dispatch({
type: NetworkActions.NETWORK_SOCK_CLOSED,
data: {}
});
};
}
export function send(data) {
data = typeof data === 'object' ? JSON.stringify(data) : data;
socket.send(data);
}
If I should close socket before app ends manually, and anyone know about this, please gimme some advice. I'm not much know about React Native, and not found related posts on google, so it will be very appreciate it gimme some advice. Thanks!
P.S. Oh, and I used Android for testing.
Your code looks good. By refresh do you mean refreshing the javascript while running in debug mode? That should never happen in production, the javascript is stored on the device.
If you need to explicitly close the connection when the app is in the background, check out:
http://facebook.github.io/react-native/docs/appstate.html
Then you can call ws.close() when the app is in the background :)

WebRTC flow of function calls for making calls [Android]

I am referring and also going through source code of AppRTCDemo which is a demo application for WebRTC.
What i am trying is:
Build my own WebRTC application which will do AV calls on a Android Device.
Replace existing https://apprtc.appspot.com/ server and related functionality.
For archiving above points, I want to understand basic flow of WebRTC function calls and steps to make/receive calls (functions that i need to calls and there flow).
I have gone through the source code and understood few things,
but as code is pretty complicated to understand, and without any documentation.
It will be great help if some one provides any examples or documents explaining the steps for making/receiving AV calls (how we get/set SDP, how to render local/remote video etc.).
I have seen these posts and are very helpful:
WebRTC java server trouble
https://www.webrtc-experiment.com/docs/WebRTC-PeerConnection.html
I am able to build and run AppRTCDemo App.
Any help on this will be great help!
There is no timeline, it's asynchronous but i will try to explain but there is two main flow, the flow of offer and answer with SDP and the flow of icecandidate.
Flow 1 : SDP
Step 1 - Offer peer :
On the offer side, create a RTCPeerconnection (with stun, trun servers as parameters).
var STUN = {
url:'stun:stun.l.google.com:19302'
};
var TURN = {
url: 'turn:homeo#turn.bistri.com:80',
credential: 'homeo'
};
var iceServers = {
iceServers: [STUN, TURN]
};
var peer = new RTCPeerConnection(iceServers);
Step 2 - Offer peer :
Call getUserMedia with your constraints. In the success callback, add the stream to the RTCPeerconnection using the addStream method. Then you can create the offer with calling createOffer on the Peerconnection Object.
navigator.webkitGetUserMedia(
{
audio: false,
video: {
mandatory: {
maxWidth: screen.width,
maxHeight: screen.height,
minFrameRate: 1,
maxFrameRate: 25
}
}
},
gotStream, function(e){console.log("getUserMedia error: ", e);});
function gotStream(stream){
//If you want too see your own camera
vid.src = webkitURL.createObjectURL(stream);
peer.addStream(stream);
peer.createOffer(onSdpSuccess, onSdpError);
}
Step 3 - Offer peer :
In the callback method of the createOffer, set the parameter (the sdp offer) as the localDescription of the RTCPeerConnection (who will start gathering the ICE candidate). Then send the offer to the other peer using the signaling server. (I will not describe signaling server, it's just passing data to one from another).
function onSdpSuccess(sdp) {
console.log(sdp);
peer.setLocalDescription(sdp);
//I use socket.io for my signaling server
socket.emit('offer',sdp);
}
Step 5 - Answer peer :
The answer peer, each time it receives an offer, create a RTCPeerconnection with TURN, STUN server, then getUserMedia, then in the callback, add the stream to the RTCPeerConnection. With the SDP offer use setRemoteDescription with the sdpOffer. Then Trigger the createAnswer.
In the success callback of the createAnswer, use setLocalDescription with the parameter and then send the answer sdp to the offer peer using signaling server.
//Receive by a socket.io socket
//The callbacks are useless unless for tracking
socket.on('offer', function (sdp) {
peer.setRemoteDescription(new RTCSessionDescription(sdp), onSdpSuccess, onSdpError);
peer.createAnswer(function (sdp) {
peer.setLocalDescription(sdp);
socket.emit('answer',sdp);
}, onSdpError);
});
Step 7 : Offer peer
Receive the sdp answer, setRemoteDescription on the RTCPeerConnection.
socket.on('answer', function (sdp) {
peer.setRemoteDescription(new RTCSessionDescription(sdp), function(){console.log("Remote Description Success")}, function(){console.log("Remote Description Error")});
});
Flow 2 : ICECandidate
Both side :
Each time the RTCPeerConnection fire onicecandidate, send the candidate to the other peer through signalingserver.
When a icecandidate is received, coming from signaling server, just add it to the RTCPeerConnection using the addIceCandidate(New RTCIceCandidate(obj))
peer.onicecandidate = function (event) {
console.log("New Candidate");
console.log(event.candidate);
socket.emit('candidate',event.candidate);
};
socket.on('candidate', function (candidate) {
console.log("New Remote Candidate");
console.log(candidate);
peer.addIceCandidate(new RTCIceCandidate({
sdpMLineIndex: candidate.sdpMLineIndex,
candidate: candidate.candidate
}));
});
Finally :
If two flow above works well use the onaddstream event on each RTCPeerConnection. When ICE Candidates will pair each other and find the best way for peer-to-peer, they will add the stream negociated with the SDP and that is going through the peer to peer connection. So in this event, you juste need to add your stream then to a video tag for example and it's good.
peer.onaddstream = function (event) {
vid.src = webkitURL.createObjectURL(event.stream);
console.log("New Stream");
console.log(event.stream);
};
I will edit tommorow with some code i think to help understand what i'm saying. If have question go for it.
Here is my signaling server :
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(3000);
app.get('/', function (req, res) {
res.send('The cake is a lie');
});
io.on('connection', function (socket) {
console.log('NEW CONNECTION');
socket.on('offer', function (data) {
console.log(data);
socket.broadcast.emit("offer",data);
});
socket.on('answer', function (data) {
console.log(data);
socket.broadcast.emit("answer",data);
});
socket.on('candidate', function (data) {
console.log(data);
socket.broadcast.emit("candidate",data);
});
});

Categories

Resources