How do I check if a device is connected to Bluetooth? - java

How do I test if my Bluetooth Headset is connected to my phone? I know that the Bluetooth API supports a BluetoothHeadset profile and that it outputs either 2,1,or 0 but I don't know how to use it. Thanks!
^disregard this
Edit: Can I test if Bluetooth.Headset is two?
Like-
if (Bluetooth.Headset = true){
action
}else (blah blah)
Would that let me know if my phone is connected to a Bluetooth headset?
Edit again: So the three states are connecting, connected, and disconnected. How can I test for connected?

For iOS and, if Google is correct, Android, you can look in Settings> Bluetooth> Devices. You should see your device there if it’s connected.
//to prevent repeated alerts
var h = 1
if (BluetoothHeadset == 2 && h == 1) {
alert("You have been connected to your Bluetooth headset.");
h = 0;
} else if (h == 0) {
alert("You have been disconnected from your Bluetooth headset.");
h = 1
}

Related

Android: Target SIM/Number of incoming call

INB4: How to find target sim for an incoming call in dual sim android phone? <- does not work, sadly :(
So, I have a phone (A) with to SIM cards:
SIM 1 number: 123
SIM 2 number: 456
and I call from different phone (B: number 789) to 123.
On phone A I'm able to detect incoming call and I'm able to get the incoming phone call number (789). What I can't do is detect that the call target was SIM 1 number: 123.
Can someone help me?
Ok, I've finally manage to do this, but not directly.
I'm getting all information I need from call history.
Try this:
public class MyCallReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String mySim = "";
mySim = intent.getExtras().getInt("simId", -1);
if(callingSIM == "0"){
//SIM1
}
else if(callingSIM =="1"){
//SIM2
}
}
}

JSON with multi tasking

I am new to Qt C++ development. I have a processor which will control the Hardware. From server (Java) I will send the instructions to that Hardware. According to that particular instruction, it is going to perform. This is the general idea of my project.
Basic control instructions were written on board. Now What I want and What is the problem I am going to describe that? Sorry for my poor English.
I am going to send the JSON string from the server. For example
working|pq|0|1
From web socket I will receive the string
else if(message.contains("working")) {
emit OnMsgRecievedConnect("connect");
workingpq = message;
qDebug() << workingpq;
}
Now I have received a string from the server. I have taken that string into another thread for giving instruction to Hardware.
workingvaluepq = EchoClient::workingpq ;
qDebug() << "End pq value Received from server :" << workingvaluepq ;
QStringList pq = workingvaluepq.split("|");
int pqSize = pq.size(); // get the pq list size;
qDebug() << "End pq size :" << pqSize;
if(pqSize == 5){
p = pq[3];
q = pq[4];
}
int pInt = p.toInt(&ok);
int qInt = q.toInt(&ok);
if(!ok && pqSize == 5){
pend = pInt;
}
if(!ok && pqSize == 5){
qend = qInt;
}
pend = pInt;
qend = qInt;
if(pqSize == 1 ){
pend = jread->endvaluep;
qend = jread->endvalueq;
}
while(true)
{ (All other stuff here)
if(pqSize == 5){
if (pend == pstart && qend == qstart)
{
Jsonendflag = 1;
}
}
if(pqSize == 1){
if (pend == pstart && qend == qstart)
{
Rightstopflag = 1;
}
}
So when this point (whatever we fixed) reached the particular task, finally it will get stop. Maybe above code have some experienced issue. So a person can help me to improve the code. One more question, This is only one task, I have tried.
Note: pstart, qstart, pend, qend these things defined in the onboard JSON file. Just I will read and execute so reading executing is not a big deal
If I receive the multiple string (task) from server machine have to complete the task one by one. For example, will receive the string like given below
working|xy|2|3*working1|xy|8|7*working3|xy|12|15*working4|xy|17|20
Above string have a four different task, I will receive in same time, now I want to split and complete the task one by one continuously. I hope here so many experienced people can help and solve this issue.
After you split using *, use a loop to process your tasks one by one.
const QStringList taskList = QString("working|xy|2|3*working1|xy|8|7*working3|xy|12|15*working4|xy|17|20").split('*');
for (const QString& task : taskList)
{
auto params = task.split('|');
/* Perform 1 task */
// ...
}
/* Report back to server */
// ...
The code above uses a C++ ranged-for-loop.
You can do the same using an older for-loop:
for (int i = 0; i < taskList.count(); ++i)
{
auto params = taskList[i].split('|');
/* Perform 1 task */
// ...
}

How to enable sidetone/microphone pass-thru programmatically

For my current project I'm implementing a native library in C++ that I'll be accessing via JNA, this project is a low-latency communication simulator. There's a requirement to enable sidetone while transmitting in order to mimic the hardware the simulator is based on.
Of course JAVA sound is proving difficult to achieve near-zero latency (best we can get is ~120ms), in order to remain comprehensible we need the latency on sidetone to be near-zero. Fortunately it seems that in Windows there's a method to listen to the usb headset's microphone which produces perfect sidetone.
Audio Properties -> Playback -> Headset Earphone -> Properties -> Levels
An example of what I mean here
(Note that this is different from the 'listen to this device' feature which produces a pretty bad delay)
I've been working with the MSDN examples for the Core Audio API's and am able to query devices and get their channels, volume levels, mute setting, etc. but the microphone level mute/unmute doesn't seem to be accessible from even the core audio apis.
My question is this: is there a way to programmatically interface with a usb headset's microphone level/mute setting?
Our simulators are standardized so we don't have to worry about supporting a wide range of headsets (2 at the moment).
The key to solving this problem was to walk the device topology tree backwards until I found the part responsible for setting the sidetone mute attribute. So in my CPP project I had several methods working together to determine where I was in the topology tree looking for a SuperMix part.
SuperMix seems to be a common name for sidetone and is at least used by the two headsets we support. The tree is identical for both headsets, your mileage may vary. This is what the output may look like from the aforementioned WalkTreeBackwardsFromPart example (see this answer)
Part Name: SuperMix
Part Name: Volume
Part Name: Mute
Here's my modified version of WalkTreeBackwardsFromPart, which for all intents and purposes simply checks whether or not the part we're currently looking at is the SuperMix and the direct child of this part is a volume node, this is to prevent an incorrect assignment as I found that for our headsets there would often be two nodes called SuperMix and the only difference was that the one we wanted had a volume node child.
HRESULT Sidetone::WalkTreeBackwardsFromPart(IPart *part) {
HRESULT hr;
if (wcscmp(this->getPartName(part), L"SuperMix") == 0 && this->treePeek(part, L"Volume")){
this->superMix = part;
IPart** superMixChildren = this->getChildParts(part);
int nSuperMixChildren = sizeof(superMixChildren) / sizeof(superMixChildren[0]);
if (nSuperMixChildren > 0){
for (int i = 0; i < nSuperMixChildren; i++){
if (wcscmp(this->getPartName(superMixChildren[i]), L"Volume") == 0){
this->volumeNode = this->getIPartAsIAudioVolumeLevel(superMixChildren[i]);
if (this->volumeNode != NULL){
IPart** volumeNodeChildren = this->getChildParts(superMixChildren[i]);
int nVolumeNodeChildren = sizeof(volumeNodeChildren) / sizeof(volumeNodeChildren[0]);
if (nVolumeNodeChildren > 0){
for (int j = 0; j < nVolumeNodeChildren; j++){
if (wcscmp(this->getPartName(volumeNodeChildren[j]), L"Mute") == 0){
this->muteNode = this->getIPartAsIAudioMute(volumeNodeChildren[j]);
break;
}
}
}
}
break;
}
}
}
delete[] superMixChildren;
this->muteNode; // = someotherfunc();
this->superMixFound = true;
return S_OK;
} else if(superMixFound == false){
IPartsList *pIncomingParts = NULL;
hr = part->EnumPartsIncoming(&pIncomingParts);
if (E_NOTFOUND == hr) {
// not an error... we've just reached the end of the path
//printf("%S - No incoming parts at this part: 0x%08x\n", this->MSGIDENTIFIER, hr);
return S_OK;
}
if (FAILED(hr)) {
printf("%S - Couldn't enum incoming parts: hr = 0x%08x\n", this->MSGIDENTIFIER, hr);
return hr;
}
UINT nParts = 0;
hr = pIncomingParts->GetCount(&nParts);
if (FAILED(hr)) {
printf("%S - Couldn't get count of incoming parts: hr = 0x%08x\n", this->MSGIDENTIFIER, hr);
pIncomingParts->Release();
return hr;
}
// walk the tree on each incoming part recursively
for (UINT n = 0; n < nParts; n++) {
IPart *pIncomingPart = NULL;
hr = pIncomingParts->GetPart(n, &pIncomingPart);
if (FAILED(hr)) {
printf("%S - Couldn't get part #%u (0-based) of %u (1-basedSmile hr = 0x%08x\n", this->MSGIDENTIFIER, n, nParts, hr);
pIncomingParts->Release();
return hr;
}
hr = WalkTreeBackwardsFromPart(pIncomingPart);
if (FAILED(hr)) {
printf("%S - Couldn't walk tree on part #%u (0-based) of %u (1-basedSmile hr = 0x%08x\n", this->MSGIDENTIFIER, n, nParts, hr);
pIncomingPart->Release();
pIncomingParts->Release();
return hr;
}
pIncomingPart->Release();
}
pIncomingParts->Release();
}
return S_OK;
}
Sidetone::superMixFound is a boolean member used to quickly break our recursive loop and prevent us from walking the device topology tree any further (wasted time).
Sidetone::getPartName() is a simple reusable method for returning a widestring character array of the part's name.
Sidetone::treePeek() returns true if the children of the specified part contains a part with the name specified as the second parameter.
Sidetone::getChildParts() returns an array of pointers for each child of a given part.
After figuring this out it was just a matter of exposing the setMute method to dllmain.cpp and calling it via JNA whenever we needed to activate/deactivate sidetone, so at the beginning and ending of any transmission.

Android BLE: Message Length issue

I am developing an android application with BLE. The requirement of this application is to update the voltage variation in a specific hardware with various inputs.
So I am writing the characters to the BLE as 8-bit input. Each bit value contains its own representations. Based on each request hardware will respond and provide various output combinations. The output contains 24 bytes of information. Each byte position represents different value. eg: position 1& 2 represent current, 3 & 4 represent voltage etc.
My problem here is, I am getting the output as 4 parts. Each message contains 6 bytes. Is it possible to get the same in a single message?
Implementation
public void writeCharacteristic(BluetoothGattCharacteristic characteristic) {
if (mBluetoothAdapter == null || mBluetoothGatt == null) { //Check that we have access to a Bluetooth radio
Log.w(TAG, "BluetoothAdapter not initialized");
return;
}
int test = characteristic.getProperties(); //Get the properties of the characteristic
if ((test & BluetoothGattCharacteristic.PROPERTY_WRITE) == 0 && (test & BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE) == 0) { //Check that the property is writable
return;
}
DebugLogs.writeToFile("BLE MODULE Before Write " + characteristic);
if (mBluetoothGatt.writeCharacteristic(characteristic)) { //Request the BluetoothGatt to do the Write
Log.v(TAG, "****************WRITE CHARACTERISTIC SUCCESSFULL**" + characteristic); //The request was accepted, this does not mean the write completed
DebugLogs.writeToFile("BLE MODULE AFTER Write SUCCESS " + characteristic);
} else {
Log.d(TAG, "writeCharacteristic failed"); //Write request was not accepted by the BluetoothGatt
DebugLogs.writeToFile("BLE MODULE AFTER Write FAIL " + characteristic);
}
}
And the response is getting in the Gatt callback
#Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
Log.w(TAG, "**ACTION_DATA_AVAILABLE**" + characteristic.getUuid());//Indication or notification was received
broadcastUpdate(BLEConstants.ACTION_DATA_AVAILABLE, characteristic); //Go broadc
ast an intent with the characteristic data
}
Unfortunately not. While you could reduce the number of transmissions IF you are the author of the code in the BLE peripheral, you cannot fit 24 bites into a single characteristic, because BLE limits the width of a characteristic to 20 bytes. If you are the BLE peripheral author, you could perhaps change it to send 2 12 byte packets.
If you aren't, then you are probably trying to collect all the data before sending it. An easy way to do this would be create a byte array of length 24 when onCharacteristicWrite is called. Then, every time onCharacteristicChanged is called, add the data to the array. Once you've added all 24 bytes to the array, broadcast it.
Hope this helps!

Java MIDI Device List Duplicates

I'm listing all MIDI devices in a combobox, but for the loopback drivers I get duplicate entries.
The first entries don't work and contain no description (
getDescription() returns "No details available" )
The others, which are the working ones, return "External MIDI Port"
description.
Now, I would like to know why rtpMidi, LoopBE, LoopMidi and all loopback drivers cause these duplicate entries, so that I can exclude them from the list in a secure way.
I could simply avoid the entries without a valid description, but I don't like acting without knowing the reason why those entries are reported in the first place.
Another thing that puzzles me is that if I try filtering the results via "if(dev instanceof Receiver)" I get a blank list, the same with instanceof Transmitter, Synthesizer and Sequencer. So it seems like none of the midi devices are instance of one of those classes, but only instance of MidiDevice class, which doesn't help me with filtering the list...
Could someone please suggest a different solution?
// Get MIDI device list
info = MidiSystem.getMidiDeviceInfo();
device = new ArrayList<MidiDevice>();
deviceDetails = new ArrayList<String>();
int j=0;
for (int i = 0; i < info.length; i++) {
MidiDevice dev = MidiSystem.getMidiDevice(info[i]);
//if ( dev instanceof Receiver ) { // tried Receiver, Transmitter, Synthesizer and Sequencer
// Detailed List
deviceDetails.add("Device ID: " + j);
deviceDetails.set(j, deviceDetails.get(j) + "\nName: " + info[i].getName());
deviceDetails.set(j, deviceDetails.get(j) + "\nDescription: " + info[i].getDescription());
device.add(dev);
deviceDetails.set(j, deviceDetails.get(j) + "\nDevice: " + device.get(j));
//Combo Box (Dev names only)
MidiOutCombo.add(info[i].getName());
j++;
//}
}
Here's the temporary solution I found, it works but it's string-based and I don't know if it works crossplatform...
if (info[i].getDescription().compareTo("External MIDI Port") == 0 ) {
Loopback drivers typically have two ports, one for receiving, and one for transmitting.
To determine if a MIDIDevice has any receivers or transmitters, you must call its getMaxReceivers/getMaxTransmitters methods.

Categories