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

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.

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])

Twilio voice call answering and talking

I have implemented android twilio call with this tutorial,
https://github.com/twilio/voice-quickstart-android
Everything works perfectly as they have mentioned. The call rings I can attend the call and listen to the VoiceResponse message I saved in server. My requirement is I need to talk to the one android twilio application to other android with same twilio application instead of receiving VoiceResponse message. If I make phone calls to actual phone numbers then I can talk and listen without any problem, but from application to application speaking does not work.
I am using node js as server code, the first calling person code is given below.
client.api.calls.create({
url: url,
to: phoneNumber,
from: callerId,
}, function(err, call) {
if (err) { console.error('There was a problem starting the call: ', err); }
console.log('Call with sid: ${call.sid} was started');
});
xml response for url is
router.post('/callSecond', function(request, response) {
const voiceResponse = new VoiceResponse();
const dial = voiceResponse.dial({ callerId: 'client:al' });
voiceResponse.say("Congratulations! You have received your first inbound call! Good bye. Welcome to Twilio! Welcome to Twilio!!!! Welcome to Twilio");
dial.client("leo");
console.log('Response :' + voiceResponse.toString());
response.send(voiceResponse.toString());
});
Can anyone please help me to find a solution for this, speaking to each other using twilio mobile application.
Thank you in advance

Web Bluetooth characteristic.writeValue break the connection automatically

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.

i want to create android app to control arduino car with bluetooth

my project has 2 steps:
Establish a connection between my phone and the arduino board
Use accelerometer sensor to move the car
The motion part i can handle it, but i can't find a way to use bluetooth. I just can't figure how to work with this Api.
What should i do to connect to the arduino and start sending signals to it?
Check this link out, its a Guide on Connecting Android Device with Arduino and Bluetooth
I'll just paste the Steps here, in case the link expires someday.
At the top of your source code, include these libs.
#include "SoftwareSerial.h"
#include "Bluetooth.h"
To start using it, at the top of your source declare a public variable to access it:
Bluetooth *blue = new Bluetooth(2, 3);
With Bluetooth(RX_Pin, TX_Pin)
The default pin is 1234, name is “PNGFramework” and baudrate is 9600
Now, on your Setup(), add the follow line:
void setup(){
Serial.begin(9600);
blue->setupBluetooth();
}
Send a message when we receive some data from Serial.
void loop(){
String msg = blue->Read();
if(msg.length() > 1){
Serial.print("Received: ");
Serial.println(msg);
}
if(Serial.available()){
blue->Send("Example message#");
}
}
In Android
First, create a bluetooth object, use the following code, make sure to use the same RobotName that you used in the Arduino project. (default is “PNGFramework”).
BluetoothArduino mBlue = BluetoothArduino.getInstance("PNGFramework");
To connect with the Arduino, add the command bellow:
mBlue.Connect();
Now, to read a message, run the command:
String msg = mBlue.getLastMessage();

Accessory SAP communication Tizen and Android PeerAgent_No_Response

Currently i am creating a safety application for the samsung smartwatch. I want users to be able to register on their smartphone and send these data to the smartwatch app. I followed the samsung tutorial for Accessory SAP communication. Everything works till i get the PEERAGENT_NO_RESPONSE error, the first parts work fine, it tries to connect without any problems.
The method i call on tizen is this:
SAAgent.setServiceConnectionListener(agentCallback);
var agentCallback = {
onconnect: function(socket){
alert("agentCallback connect" + socket);
SASocket = socket;
alert("connected");
SASocket.setSocketStatusListener(function(reason){
console.log("Service Connection lost, Reason: ["+ reason+"]");
disconnect();
})
},
onerror: function(error){
alert("agentCallBack"+error);
}
};
When i call SAAgent.setServiceConnectionListener(agentCallback), the android code below here is triggered. But this always returns PEERAGENT_NO_RESPONSE error.
#Override
protected void onServiceConnectionRequested(SAPeerAgent peerAgent){
//Toast.makeText(getBaseContext(), "TESTG", Toast.LENGTH_SHORT).show();
super.acceptServiceConnectionRequest(peerAgent)
}
I was wondering what i am doing wrong.
After debugging and some help i finally fixed the problem:
This had to be Public instead of protected on android side. Which caused the runtime to crash and not send any data to the tizen wearable.
public SAPServiceProviderConnection() {
super(SAPServiceProviderConnection.class.getName());
}
I also changed supportedTransports on both android and tizen side to: (i had BT on android side and WIFI/BT on tizin side.)
<transport type="TRANSPORT_BT"/>
<transport type="TRANSPORT_WIFI"/>
Servicechannel, data to high:
<serviceChannel
id="104"
dataRate="high"
priority="low"
reliability="enable"/>

Categories

Resources