How to get rssi value of a connected Bluetooth device - rssi

I am trying to get the rssi value of a connected bluetooth device in my android program.
Below is the code:
gatt = mDevice.connectGatt(getApplicationContext(), false, new BluetoothGattCallback() {
#Override
public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
super.onReadRemoteRssi(gatt, rssi, status);
Log.d(TAG, "rssi is : " + rssi);
((TextView) findViewById(R.id.rssiValue)).setText(rssi);
}
});
gatt.readRemoteRssi();
But the method onReadRemoteRssi doesnot return any value.
Please help me with the issue.

if(ContextCompat.checkSelfPermission(RSSI.this,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
RSSI.this,
new String[] {
Manifest.permission.BLUETOOTH,
Manifest.permission.BLUETOOTH_ADMIN,
Manifest.permission.ACCESS_FINE_LOCATION
},
1
);
}
Make sure that the mDevice variable retrieved from BlueetoothAdapter is not null
Lastly make sure the permissions are set, the above code will give you required privileges to get Bluetooth bonded device(s).

Related

How to use USB to RS232 communication with Android Things

I am using MAX232 device for UART(Raspberry Pi) to RS232 communication(Other Board).
But I want to use USB to Serial cable for this. I have attached the image of a cable. How can I use this in Android Things?
Can anyone tell this.
You can use libraries like this or that. And in case of FTDI-based USB<->UART converters you can use FTDI's solution for Android like d2xx driver with Java wrapper. And you can find many examples (like this) of it's use:
...
private static D2xxManager ftD2xx = null;
private FT_Device ftDev;
...
try {
ftD2xx = D2xxManager.getInstance(this);
int devCount = 0;
devCount = ftD2xx.createDeviceInfoList(this);
Log.d(TAG, "Device number : "+ Integer.toString(devCount));
D2xxManager.FtDeviceInfoListNode[] deviceList = new D2xxManager.FtDeviceInfoListNode[devCount];
ftD2xx.getDeviceInfoList(devCount, deviceList);
if(devCount <= 0) {
return;
}
if(ftDev == null) {
ftDev = ftD2xx.openByIndex(this, 0);
} else {
synchronized (ftDev) {
ftDev = ftD2xx.openByIndex(this, 0);
}
}
...
} catch (D2xxManager.D2xxException ex) {
Log.e(TAG,ex.toString());
}

How to express chainging BLE rssi in android BLE?

I'm trying to show chainging rssi on the list that shows scanned device.
[enter image description here][1]
I want to express chainging rssi value at rssi : _____ from the picture.
I'm able to get chainging rssi value on log, like the picture.
[enter image description here][2]
Please help me.
You will need a scan intervall, that "refreshes" the RSSI by rescanning for devices. Sth. like this:
public void scanLeDevice(final boolean enable)
{
final static int SCAN_PERIOD = 2000; //2s
final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
final BluetoothAdapter mBluetoothAdapter = bluetoothManager.getAdapter();
//to start or stop scanning (true/false)
if (enable)
{
// Stops scanning after a pre-defined scan period
mHandler.postDelayed(new Runnable()
{
#Override
public void run()
{
mBluetoothAdapter.stopLeScan(mLeScanCallback);
if (mGatt == null)
offScan();
}
}, SCAN_PERIOD);
mBluetoothAdapter.startLeScan(mLeScanCallback);
}
else
{
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
}

I want my multihopOscilloscope to send data through radio and Serial port as well

I am trying to modify the multihop Oscilloscope program so that the sink node is able to send data both to UART and radio medium as well. As far as researched, I found out that the same hardware is used for sending packets via UART and radio too.
In this case, how do I modify my code so that I can send data to UART or radio based on a condition I receive. Here in the sample prorgram, I send data via radio on every 10 packets received.
The receive module for my sink node is:
event message_t* Receive.receive(message_t* msg, void *payload, uint8_t len) {
oscilloscope_t* in = (oscilloscope_t*)payload;
counter++;
am_addr_t rec = call AMPacket.source(msg);
oscilloscope_t* out;
counter++;
call Leds.led0On();
if (uartbusy == FALSE) {
out = (oscilloscope_t*)call SerialSend.getPayload(&uartbuf, sizeof(oscilloscope_t));
if (len != sizeof(oscilloscope_t) || out == NULL) {
return msg;
}
else {
memcpy(out, in, sizeof(oscilloscope_t));
}
uartlen = sizeof(oscilloscope_t);
post uartSendTask();
} else {
message_t *newmsg = call UARTMessagePool.get();
if (newmsg == NULL) {
report_problem();
return msg;
}
//Serial port busy, so enqueue.
out = (oscilloscope_t*)call SerialSend.getPayload(newmsg, sizeof(oscilloscope_t));
if (out == NULL) {
return msg;
}
memcpy(out, in, sizeof(oscilloscope_t));
if (call UARTQueue.enqueue(newmsg) != SUCCESS) {
call UARTMessagePool.put(newmsg);
fatal_problem();
return msg;
}
}
if(counter % 10 == 0){
oscilloscope_t* btrpkt = (oscilloscope_t*)(call Packet.getPayload(&pkt, sizeof(oscilloscope_t)));
call Leds.led1On();
if (call AMSend.send(rec, &pkt, sizeof(oscilloscope_t)) == SUCCESS) {
call Leds.led0On();
sendbusy = TRUE;
}
}
return msg;
}
Once the data sends back to the node from where it received the packet , it is unable to process it through UART again. Could anyone help me how could I solve my problem?
According to the question and comments:
You must instantiate AMSenderC with the same id as for the receiver. In this case, AM_OSCILLOSCOPE if you want a message to be processed by the same code. Or another id plus a new implementation of the Receive interface.
You missed putting payload into btrpkt.
You must check for sendbusy - it is a bug if you try to use the radio stack when it is busy.

Serial Connection (Arduino --> Java)

this will be my first post and I will do my best to be clear and concise. I've checked some of the other posts on this forum but was unable to find a satisfactory answer.
My question pertains to the use of JavaFX and the jSSC(java simple serial connection) library. I've designed a very simple GUI application that will host four different charts. Two of the charts will display readings from temperature and solar sensors for the past hour, while the other two display that data over an extended period -- a 14-hour period. Eventually I would like to make that more flexible and set the application to "sleep" when the readings become roughly zero (night).
How can I stream data to display this data in real time?
After referencing several sources online and from "JavaFX 8 Intro. by Example", I've been able to construct most of the serial connection class. I'm having trouble processing the data readings, so that it can be displayed on the chart.
public class SerialComm implements SerialPortEventListener {
Date time = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("mm");
boolean connected;
StringBuilder sb;
private SerialPort serialPort;
final StringProperty line = new SimpleStringProperty("");
//Not sure this is necessary
private static final String [] PORT_NAMES = {
"/dev/tty.usbmodem1411", // Mac OS X
"COM11", // Windows
};
//Baud rate of communication transfer with serial device
public static final int DATA_RATE = 9600;
//Create a connection with the serial device
public boolean connect() {
String [] ports = SerialPortList.getPortNames();
//First, Find an instance of serial port as set in PORT_NAMES.
for (String port : ports) {
System.out.print("Ports: " + port);
serialPort = new SerialPort(port);
}
if (serialPort == null) {
System.out.println("Could not find device.");
return false;
}
//Operation to perform is port is found
try {
// open serial port
if(serialPort.openPort()) {
System.out.println("Connected");
// set port parameters
serialPort.setParams(DATA_RATE,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
serialPort.setEventsMask(SerialPort.MASK_RXCHAR);
serialPort.addEventListener(event -> {
if(event.isRXCHAR()) {
try {
sb.append(serialPort.readString(event.getEventValue()));
String str = sb.toString();
if(str.endsWith("\r\n")) {
line.set(Long.toString(time.getTime()).concat(":").concat(
str.substring(0, str.indexOf("\r\n"))));
System.out.println("line" + line);
sb = new StringBuilder();
}
} catch (SerialPortException ex) {
Logger.getLogger(SerialComm.class.getName()).log(Level.SEVERE, null, ex); }
}
});
}
} catch (Exception e) {
System.out.println("ErrOr");
e.printStackTrace();
System.err.println(e.toString());
}
return serialPort != null;
}
#Override
public void serialEvent(SerialPortEvent spe) {
throw new UnsupportedOperationException("Not supported yet.");
}
public StringProperty getLine() {
return line;
}
}
Within the try block, I understand the port parameters, but the eventListener is where I am having difficulty. The significance of the stringbuilder is to append data the new data as it is read from the device.
How will I account for the two sensor readings? Would I do that by creating separate data rates to differentiate between the incoming data from each sensor??
I hope that this is clear and that I've provided enough information but not too much. Thank you for any assistance.
-------------------------------UPDATE--------------------------
Since your reply Jose, I've started to make the additions to my code. Adding the listener within the JavaFX class, I'm running into some issues. I keep getting a NullPointerException, which I believe is the String[]data not being initialized by any data from the SerialCommunication class.
serialPort.addEventListener(event -> {
if(event.isRXCHAR()) {
try {
sb.append(serialPort.readString(event.getEventValue()));
String str = sb.toString();
if(str.endsWith("\r\n")) {
line.set(Long.toString(time.getTime()).concat(":").concat(
str.substring(0, str.indexOf("\r\n"))));
System.out.println("line" + line);
sb = new StringBuilder();
}
} catch (SerialPortException ex) {
Logger.getLogger(SerialComm.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
} catch (Exception e) {
System.err.println(e.toString());
}
I'm adding the time to the data being read. As Jose mentioned below, I've added tags to the data variables within the arduino code, I'm using: Serial.print("Solar:"); Serial.println(solarData);
Rough code of the JavaFx listener:
serialPort.getLine().addListener((ov, t, t1) -> {
Platform.runLater(()-> {
String [] data = t1.split(":");
try {
//data[0] is the timestamp
//data[1] will contain the label printed by arduino "Solar: data"
switch (data[1]) {
case "Solar":
data[0].replace("Solar:" , "");
solarSeries.getData().add(new XYChart.Data(data[0], data[1]));
break;
case "Temperature":
temperatureSeries.getData().add(new XYChart.Data(data[0], data[1]));
break;
}
Is the reason this code has NullPointerException a result of the String [] data array being uninitialized?
Exception Error
Ports: /dev/tty.usbmodem1411Connected
Exception in thread "EventThread /dev/tty.usbmodem1411" java.lang.NullPointerException
at SerialComm.lambda$connect$0(SerialComm.java:61)
at SerialComm$$Lambda$1/1661773475.serialEvent(Unknown Source)
at jssc.SerialPort$LinuxEventThread.run(SerialPort.java:1299)
The SerialPortEventListener defined in the jssc library allows listening for serial port events. One of those events is the RXCHAR event, that occurs when the Arduino board is sending some data and some bytes are on the input buffer.
event.getEventValue() returns an int with the byte count, and serialPort.readString(event.getEventValue()) get the String format from those bytes.
Note that this method does not return a full line, so you need to listen to carriage return and line feed characters. Once you find "\r\n", you can get the line, and reset the StringBuilder for the next one:
sb.append(serialPort.readString(event.getEventValue()));
String str=sb.toString();
if(str.endsWith("\r\n")){
line.set(str.substring(0,str.indexOf("\r\n")));
sb=new StringBuilder();
}
where line is an observable String:
final StringProperty line=new SimpleStringProperty("");
On the Arduino side, if you want to send values from different sensors at different rates, I suggest you define on the Arduino sketch some identification string for each sensor, and you print for each value the id of its sensor.
For instance, these will be the readings you will get with the serial event listener:
ID1,val1
ID1,val2
ID2,val3
ID1,val4
ID3,val5
...
Finally, on the JavaFX thread, define a listener to changes in line and process the String to get the sensor and the value. Something like this:
serial.getLine().addListener(
(ObservableValue<? extends String> observable, String oldValue, String newValue) -> {
Platform.runLater(()->{
String[] data=newValue.split("\\,");
if(data[0].equals("ID1"){
// add to chart from sensor 1, value data[1];
} else if(data[0].equals("ID2"){
// add to chart from sensor 2, value data[1];
} else if(data[0].equals("ID3"){
// add to chart from sensor 3, value data[1];
}
});
});
Note you need to add Platform.runLater(), since the thread that gets the data from serial port and updates line is not on the JavaFX thread.
From my experience, on the Arduino side, add a comma or something to separate the different values when you print and when you receive that string in Java simply split that string by commas.
String[] stringSeparate = str.split(",");

Setting default TWAIN data source without using API UI menu

Using the twaindotnet library in C#, I'm wondering if there's a way to set the default datasource using the library.
As a feeble attempt, I've tried adding a SetDefault method to the DataSource class of twaindonet, like this
public static void SetDefault(Identity applicationId, IWindowsMessageHook messageHook, DataSource newDataSource)
{
var defaultSourceId = newDataSource.SourceId;
// Attempt to get information about the system default source
var result = Twain32Native.DsmIdentity(
applicationId,
IntPtr.Zero,
DataGroup.Control,
DataArgumentType.Identity,
Message.Set,
defaultSourceId);
if (result != TwainResult.Success)
{
var status = DataSourceManager.GetConditionCode(applicationId, null);
throw new TwainException("Error getting information about the default source: " + result, result, status);
}
}
which is called from the DataSourceManage class like this
public void SelectSource(DataSource dataSource)
{
DataSource.Dispose();
DataSource.SetDefault(ApplicationId, _messageHook, dataSource);
}
But when I try to use SetDefault, Twain32Native.DsmIdentity always results in Failure being returned.
I basically copied from SetDefault the setDefaultDataSource method from TWAIN sample Data Source and Application
pTW_IDENTITY TwainApp::setDefaultDataSource(unsigned int _index)
{
if(m_DSMState < 3)
{
cout << "You need to open the DSM first." << endl;
return NULL;
}
else if(m_DSMState > 3)
{
PrintCMDMessage("A source has already been opened, please close it first\n");
return NULL;
}
if(_index >= 0 && _index < m_DataSources.size())
{
m_pDataSource = &(m_DataSources[_index]);
// set the specific data source
TW_UINT16 twrc;
twrc = _DSM_Entry(
&m_MyInfo,
0,
DG_CONTROL,
DAT_IDENTITY,
MSG_SET,
(TW_MEMREF) m_pDataSource);
switch (twrc)
{
case TWRC_SUCCESS:
break;
case TWRC_FAILURE:
printError(0, "Failed to get the data source info!");
break;
}
}
else
{
return NULL;
}
return m_pDataSource;
}
Any help would be greatly appreciated.
The possible cause is that the version of your TWAIN DSM is too low. Only DSM 2.0 or above supports setting default TWAIN data source.

Resources