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"/>
Related
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.
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
I have used the Tizen sample Heart Rate Monitor code for Samsung Gear S3 from https://developer.tizen.org/ko/community/tip-tech/accessing-heart-rate-monitor-hrm-sensor-data-native-applications?langredirect=1
I want to develop Android or Tizen for Retrieving Data from the Heart Rate Monitor which is in S3 Gear. I found the sample code from https://developer.tizen.org/ko/development/guides/web-application/sensors/human-activity-monitor?langredirect=1#retrieve
How can I integrate this. Pls share your ideas. Thanks a lot.
With Samsung Accessory SDK, you can develop an app in Android which can communicate with Tizen app(Gear).
Here is a working example
How to integrate Samsung Gear Steps in android Application?
Edit:
Here i am giving the code to measure Heart Rate and return back to Android phone when a request is sent from Android . I have just modified code from previously mentioned post and sharing here.
Here i am giving only contents from dataOnReceive function
if (!SAAgent.channelIds[0]) {
createHTML("Something goes wrong...NO CHANNEL ID!");
return;
}
function sendHrData(heartRate){
// return Data to Android
SASocket.sendData(SAAgent.channelIds[0], 'HR: '+heartRate);
createHTML("Send massage:<br />" +
newData);
tizen.humanactivitymonitor.stop('HRM');
}
var heartRateData=0;
function onsuccessCB(hrmInfo) {
console.log('Heart rate: ' + hrmInfo.heartRate);
heartRateData = hrmInfo.heartRate;
// holding 15 seconds as HRM sensor needs some time
setTimeout(function(){
sendHrData(heartRateData);
}, 15000);
}
function onerrorCB(error) {
tizen.humanactivitymonitor.stop('HRM');
console.log('Error occurred: ' + error.message);
}
function onchangedCB(hrmInfo) {
//alert("onChanged...");
tizen.humanactivitymonitor.getHumanActivityData('HRM', onsuccessCB, onerrorCB);
}
tizen.humanactivitymonitor.start('HRM', onchangedCB);
And this code continuously returning Heart Rate. Please modified according to your requirements, i am just sharing the idea to communicate between Android phone and Samsung Gear.
Send Data to Server:
You can use Ajax or XmlHttpRequest to send data to server
Ajax:
function sendDataToServer() {
'use strict';
console.log( "ready!" );
$.ajax({
type: "Post",
url: "http://YOUR_URL",
success: function (data) {
console.log(JSON.stringify(data));
}
});
}
XmlHttpRequest:
function postDataToServer() {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
alert("data posted successfully..");
} else {
alert("failed to send data..");
}
}
}
xmlHttp.open("POST", "YOUR_URL");
xmlHttp.send("_TEST_STRING_DATA");
Auto generated code from REST viewer not working in Tizen IDE(Wearable) web app
XmlHttpRequest on Tizen TV exits application
RESTful service on emulator
Note: You need to install Samsung Gear application in your Android phone.
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 am writing an open source framework to use BLE Mini module with Android and iOS mobile devices using Unity engine.
This framework should allow to establish a connection between the mobile device and the BLE Mini module, and to send/receive data using it. The framework can be theoretically adapted to work with any BLE module.
The idea is to make the existing BLE Mini frameworks (available for iOS and Android) work in Unity engine, hence I am writing native plugins for iOS and Android that will allow Unity apps use the native frameworks.
The iOS plugin is working as expected, while I am having problems writing the Android plugin.
Everything works as expected except the fact that I cannot send data to my characteristic. If I send the data the BLE Mini module does not receive it.
The code controlling the BLE Mini data reception is correct because it works when iOS sends the data. So I am pretty sure the problem is in the Android plugin.
The Android plugin is composed by Android native code that can be found here:
https://github.com/giomurru/ble-framework/tree/master/AndroidPlugin/src/com/gmurru/bleframework
and by Unity c# code that can call the public java methods: https://github.com/giomurru/ble-framework/blob/master/Unity/Assets/BLE/BLEController.cs
The code contained in RBLGattAttributes.java and RBLService.java is correct because it is the framework provided by RedBearLab and I tested it and it works correctly with native Android apps.
The code in which I need help and that probably contains the bug is the one in BleFramework.java
The BleFramework class contains a series of functions that can be called by the Unity engine. The functions are called following this order:
Call the get static method BleFramework.getInstance() to get a singleton instance of the class BleFramework. This method returns one and only one instance of the BleFramework class.
After I have the instance of the class I can call the BleFramework methods using this instance (which is always the same instance).
The methods are called following this order:
1) Call the function _InitBLEFramework from Unity. The function should initialize the BLE framework. When the initialization is finished the Android plugin answer to Unity with a OnBleDidInitialize "Success" message.
2) If Unity receives the OnBleDidInitialize "Success" message, I can call the function _ScanForPeripherals from Unity. The function scans for available BLE modules peripherals. When the available peripherals are found the plugin answer to Unity with a OnBleDidCompletePeripheralScan "Success" message.
3) If Unity receives the OnBleDidCompletePeripheralScan "Success" message, I can call the function _GetListOfDevices to get the list of found devices.
4) Once I have the list of BLE module devices I found, I can try to connect to one of them using the function _ConnectPeripheralAtIndex(int peripheralIndex). When the _mGattUpdateReceiver receives RBLService.ACTION_GATT_SERVICES_DISCOVERED I can say the connection is established and I can let Unity know I am ready to send/receive data by sending a OnBleDidConnect "Success" message.
Up to here the plugin works as expected, and the connection is established.
The problem is when I try to send data in step 5.
5) When Unity receives the OnBleDidConnect "Success" message it is ready to send data through the established connection. Hence I try to send the data by using _SendData function in the plugin. Unfortunately it does not work.
This is the code:
public void _SendData(byte[] data)
{
Log.d(TAG,"_SendData: ");
BluetoothGattCharacteristic characteristic = _map.get(RBLService.UUID_BLE_SHIELD_TX);
Log.d(TAG, "Set data in the _characteristicTx");
byte[] tx = hexStringToByteArray("fefefe");
characteristic.setValue(tx);
Log.d(TAG, "Write _characteristicTx in the _mBluetoothLeService: " + tx[0] + " " + tx[1] + " " + tx[2]);
if (_mBluetoothLeService==null)
{
Log.d(TAG, "_mBluetoothLeService is null");
}
_mBluetoothLeService.writeCharacteristic(characteristic);
}
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i+1), 16));
}
return data;
}
Just for the purpose of testing I ignored byte[] data parameter and I try to send byte[] tx data that I create inside the _SendData function using hexStringToByteArray function (that I found in this StackOverflow post: Convert a string representation of a hex dump to a byte array using Java?)
I also tried to create the tx data as:
byte tx[] = new byte[] { (byte) 0xfe, (byte) 0xfe, (byte) 0xfe };
or to send the data directly like this:
public void _SendData(byte[] data)
{
Log.d(TAG,"_SendData: ");
BluetoothGattCharacteristic characteristic = _map.get(RBLService.UUID_BLE_SHIELD_TX);
Log.d(TAG, "Set data in the _characteristicTx");
characteristic.setValue(data);
Log.d(TAG, "Write _characteristicTx in the _mBluetoothLeService: " + data[0] + " " + data[1] + " " + data[2]);
if (_mBluetoothLeService==null)
{
Log.d(TAG, "_mBluetoothLeService is null");
}
_mBluetoothLeService.writeCharacteristic(characteristic);
}
In all the cases I failed to send the data.
I really can't understand why this is happening. The code I am using to search ble devices, establish connection, send receive data is very similar to the Android native samples available in ReadBearLab github page: https://github.com/RedBearLab/Android/tree/master/Examples
The only difference is that I am not extending Activity.
I tried to make BleFramework class an extension of Activity but it didn't work. The problem I had was that while BleFramework activity was running I was not able to send messages back to Unity using the UnityPlayer.UnitySendMessage function.
I answer my own question just for reference if anybody is interested in the solution I found.
I fixed the bug by updating the code to the latest Android APIs. Please check out the commits from June 15th 2019 to June 22nd 2019 in the repository if you are interested in the modifications. In particular the commit named "Android tx/rx works"
https://github.com/giomurru/ble-framework