Bluetooth RSSI/Inquiry scan on Mac - proximity detection to iPhone without connecting? - xcode

I have to dash away from the computer frequently, and I want to trigger some commands to run when my iPhone is close enough/far enough from my iMac (next to it vs. 2-3 metres away/other side of a wall). A couple of minutes latency is fine.
Partial solution: proximity
I've downloaded reduxcomputing-proximity and it works, but this only triggers when the device goes in to/out of range of bluetooth, but my desired range is much smaller.
(Proximity polls [IOBluetoothDevice -remoteNameRequest] to see if the device is in bluetooth range or not.)
Enhancement: rawRSSI
I've used [IOBluetoothDevice -rawRSSI] to get the RSSI when I am connected to the iPhone (when disconnected this just returns +127), but in order to save the battery life of my iPhone I'd rather avoid establishing a full bluetooth connection.
Am I correct in thinking that maintaining a connection will consume more battery life than just polling every couple of minutes?
I've overridden the isInRange method of proximity here to give me a working solution that's probably relatively battery intensive compared to the previous remoteNameRequest: method:
- (BOOL)isInRange {
BluetoothHCIRSSIValue RSSI = 127; /* Valid Range: -127 to +20 */
if (device) {
if (![device isConnected]) {
[device openConnection];
}
if ([device isConnected]) {
RSSI = [device rawRSSI];
[device closeConnection];
}
}
return (RSSI >= -60 && RSSI <= 20);
}
(Proximity uses synchronous calls - if and when I fit it to my needs I will edit it to be asynchronous but for now that's not important.)
Under Linux: l2ping - inquiry scan?
This SO post references getting an RSSI during an 'inquiry scan' which sounds like what I want, but it talks about using the Linux Bluez library, whilst I am on a Mac - I'd rather do it without having to stray too far if possible! (I have considered using a VM with USB pass-thru to hook up a second bluetooth device... But a simpler solution would be preferable!)
I see there is a IOBluetoothDeviceInquiry class, but I am not sure if this is useful to me. I don't intend to learn bluetooth protocol just for this simple problem!
The commands
For interest, and not particularly relevant to the solution, here are the Apple Scripts I currently trigger when
in range:
tell application "Skype"
send command "SET USERSTATUS ONLINE" script name "X"
do shell script "afplay '/System/Library/Sounds/Blow.aiff'"
end tell
out of range:
tell application "Skype"
send command "SET USERSTATUS AWAY" script name "X"
do shell script "afplay '/System/Library/Sounds/Basso.aiff'"
end tell
Though these are likely to get longer!

You are correct that making a connection will cost more energy. However, I'm not aware of APIs on mac OS that will give you access to the RSSI from inquiry scan packets. You could get access to the raw packets from your BT adapter using Mac OS PacketLogger. See this post Bluetooth sniffer - preferably mac osx
You could programmaticly put your device in discovery every couple of minutes, capture the inquiry scan packets with the packetlogger, and parse out the RSSI. You can use WireShark to help you understand how to decode the packets and find RSSI.
Your simplest option is probably to just periodically create a connection, measure RSSI, and then tear down the connection.

In terms of tradeoffs for your use case doing a continuous or periodic inquiry will consume same or even a bit more energy as doing a periodic connect / read RSSI and disconnect. Depending on the use case it sometimes may be more efficient to maintain the connection in a low power mode (sniff with 2.56 sec interval) and remain connected if the device is in range. And use RSSI to monitor proximity (although it is not accurate as interference due to objects change rssi drastically even though the device might be in proximity)

Related

Is it a problem to turn off power to a running QSerialPort?

I'm developing an application with several serial ports. Each of these ports is handled by a different thread and has its own QSerialPort object. From a hardware point of view, they are connected hierarchicaly, meaning that there is one main device connected to the PC with a usb cable (1 COM port), to this main device there are several other devices connected, each of them having its own COM port. The main device can turn on/off the power supply to these child ports.
In the application, the ports are handled asynchronously. Each device object is running in its own loop. If its port is opened, it reads the incoming data. If the port is closed, it tries to open it in every loop until it succeeds. Each QSerialPort object handles errors on the errorOccurred signal. If it receives DeviceNotFoundError, PermissionError, ResourceError error, the port is closed (if it was opened) and the looping continues as described above.
The problem is that this serial communication part of the application is crashing (segmentation fault). I spent days finding the issue but with no results so far. To better understand what is going on, I wanted to ask here. Could it be a problem for QSerialPort if the main device turns off the power supply for the child ports while they're opened and are working? Or if the power supply is turned off while the child ports are being opened/closed or any other operation is being executed on them? (I don't want to include the specific executable code as it's a part of a bigger application and would be hard to make and executable from it. I'd like to discuss just the concepts described above if possible.)
Thanks for any help or ideas!
UPDATE
Creating of QSerialPort and putting it into a different thread:
QThread *t = new QThread(this)
SomeObject *o = new SomeObject(this);
o->moveToThread(t);
t->start();
Later in the SomeObject:
QSerialPort *port = new QSerialPort();
Try to destroy port object before power off, and recreate it after power on
QSerialPort *port = new QSerialPort();
//init and use
//....
delete port;
port = nullptr;
//turn the power off
//turn the power on
port = new QSerialPort();

serial stops between mbed and processing

I want a solution right now...
The LPC1768 which is one of a mbed prototyping boards communicates with processing through Serial whose baud rate is 115200. However, as time passes, the serial communication stops.
As a situation, the LPC1768 sends sensor data with serial.putc() of the default serial library. On the other hand, processing receives the data with serial.read(). The processing code is the following:
if(serial.available()>1) { serial.read(); }
To explore the solution of this problem, I tired these things.
I checked serial.available() is 46 and used serial.clear() in processing, but mbed stopped and didn't send data. Because I thought the cause of this was an overflow of receiving buffer of processing.
I added serial.writable() and check the serial buffers for sending has space. If there are no space, I used the following codes and initialized the serial:
LPC_UART2->FCR |= 0x06;
serial.baud(115200);
, because I thought the cause of this was an overflow of sending buffer of mbed. However, they didn't work.
Please note that these codes work correctly and basically.
However, serial communication stops suddenly. What can I do anything else?
Best regards

HM-10 CC2541 IBeacon - Sleep issue after random time

I use HM-10 board (CC2541 inside) with HM-Soft V540 firmware to make IBeacon devices.
But I have a big problem: I configure the HM10 as a beacon, with auto-sleep etc etc, after reset, the HM-10 is sleeping and advertising (2µA when sleep) but after a random time (a few seconds or a few minutes), the HM10 wake up and consume between 15 and 20mA... all the time !! Until I send "AT+RESET" for re-apply the sleeping. (and again, wake up after some seconds...)
This is the commands that I used to set the HM10:
AT+RENEW
AT+RESET
AT
AT+MARJ0x1234
AT+MINO0xFA01
AT+ADVI9
AT+NAMEFAB1
AT+ADTY3
AT+IBEA1
AT+DELO2
AT+PWRM0
AT+RESET
Do you know where is this issue ??
Thanks a lot for your help.
You should change your PWRM0 to PWRM1 worked for me
Guess the problem might be solved for you but as I just run into the same "issue" with the HM-10 (firmware version v549) I wanted to share my solution/finding:
In my case I have figured out that some logger within my code is sending a string of characters via serial extending 80 char. This is actually also the rule that forces the HM-10 to wake up from sleep. So you might use AT+PWRM0 (which enables autosleep) but also make sure that when sending data over serial the string length might not wake up the HM-10 accidentally. Hope this helps a bit.

How to identify PC (motherboard) in win32 api? [duplicate]

How to uniquely identify computer (mainboard) using C#(.Net/Mono, local application)?
Edition. We can identify mainboard in .Net using something like this (see Get Unique System Identifiers in C#):
using System.Management;
...
ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_MotherboardDevice");
...
But unfortunately Mono does not support System.Management. How to do it under Mono for Linux? - I don't know :(
Write a function that takes a few unique hardware parameters as input and generates a hash out of them.
For example, Windows activation looks at the following hardware characteristics:
Display Adapter
SCSI Adapter
IDE Adapter (effectively the motherboard)
Network Adapter (NIC) and its MAC Address
RAM Amount Range (i.e., 0-64mb, 64-128mb, etc.)
Processor Type
Processor Serial Number
Hard Drive Device
Hard Drive Volume Serial Number (VSN)
CD-ROM / CD-RW / DVD-ROM
You can pick up a few of them to generate your unique computer identifier.
Please see: Get Unique System Identifiers in C#
You realistically have MotherboardID, CPUID, Disk Serial and MAC address, from experience none of them are 100%.
Our stats show
Disk serial Is missing 0.1 %
MAC Is missing 1.3 %
Motherboard ID Is missing 30 %
CPUID Is missing 99 %
0.04% of machines tested yielded no information, we couldn't even read the computer name. It maybe that these were some kind of virtual PC, HyperV or VMWare instance, or maybe just very locked down? In any case your design has to be able to cope with these cases.
Disk serial is the most reliable, but easy to change, mac can be changed and depending on the filtering applied when reading it can change if device drivers are added (hyperv, wireshark etc).
Motherboard and CPUID sometimes return values that are invalid "NONE", "AAAA..", "XXXX..." etc.
You should also note that these functions can be very slow to call (they may take a few seconds even on a fast PC), so it may be worth kicking them off on a background thread as early as possible, you ideally don't want to be blocking on them.
Try this:
http://carso-owen.blogspot.com/2007/02/how-to-get-my-motherboard-serial-number.html
Personally though, I'd go with hard drive serial number. If a mainboard dies and is replaced, that PC isn't valid any more. If the HDD drive is replaced, it doesn't matter too much because the software was on it.
Of course, on the other hand, if the HDD is just moved elsewhere, the information goes with it, so you might want to look at a combination of serial numbers, depending what you want it for.
How about the MAC address of the network card?

Is there any way to detect the monitor state in Windows (on or off)?

Does anyone know if there is an API to get the current monitor state (on or off) in Windows (XP/Vista/2000/2003)?
All of my searches seem to indicate there is no real way of doing this.
This thread tries to use GetDevicePowerState which according to Microsoft's docs does not work for display devices.
In Vista I can listen to GUID_MONITOR_POWER_ON but I do not seem to get events when the monitor is turned off manually.
In XP I can hook into WM_SYSCOMMAND SC_MONITORPOWER, looking for status 2. This only works for situations where the system triggers the power off.
The WMI Win32_DesktopMonitor class does not seem to help out as well.
Edit: Here is a discussion on comp.os.ms-windows.programmer.win32 indicating there is no reliable way of doing this.
Anyone else have any other ideas?
GetDevicePowerState sometimes works for monitors. If it's present, you can open the \\.\LCD device. Close it immediately after you've finished with it.
Essentially, you're out of luck—there is no reliable way to detect the monitor power state, short of writing a device driver and filtering all of the power IRPs up and down the display driver chain. And that's not very reliable either.
You could hook up a webcam, point it at your screen and do some analysis on the images you receive ;)
Before doing anything based on the monitor state, just remember that users can use a machine with remote desktop of other systems that don't require a monitor connected to the machine - so don't turn off any visualization based on the monitor state.
You can't.
Look like all monitor power capabilities connected to the "power safe mode"
After searching i found here code that connecting between SC_MONITORPOWER message and system values (post number 2)
I use the code to testing if the system values is changing when i am manually switch off the monitor.
int main()
{
for(;monitorOff()!=1;)
Sleep(500);
return 0;
}//main
And the code is never stopped, no matter how long i am switch off my monitor.
There the code of monitorOff function:
int monitorOff()
{
const GUID MonitorClassGuid =
{0x4d36e96e, 0xe325, 0x11ce,
{0xbf, 0xc1, 0x08, 0x00, 0x2b, 0xe1, 0x03, 0x18}};
list<DevData> monitors;
ListDeviceClassData(&MonitorClassGuid, monitors);
list<DevData>::iterator it = monitors.begin(),
it_end = monitors.end();
for (; it != it_end; ++it)
{
const char *off_msg = "";
//it->PowerData.PD_PowerStateMapping
if (it->PowerData.PD_MostRecentPowerState != PowerDeviceD0)
{
return 1;
}
}//for
return 0;
}//monitorOff
Conclusion : when you manually switch of the the monitor, you cant catch it by windows (if there is no unusual driver interface for this), because all windows capabilities is connected to "power safe mode".
In Windows XP or later you can use the IMSVidDevice Interface.
See
http://msdn.microsoft.com/en-us/library/dd376775(VS.85).aspx
(not sure if this works in Sever 2003)
With Delphi code, you can detect invalid monitor geomerty while standby in progress:
i := 0
('Monitor'+IntToStr(i)+': '+IntToStr(Screen.Monitors[i].BoundsRect.Left)+', '+
IntToStr(Screen.Monitors[i].BoundsRect.Top)+', '+
IntToStr(Screen.Monitors[i].BoundsRect.Right)+', '+
IntToStr(Screen.Monitors[i].BoundsRect.Bottom))
Results:
Monitor geometry before standby:
Monitor0: 0, 0, 1600, 900
Monitor geometry while standby in Deplhi7:
Monitor0: 1637792, 4210405, 31266576, 1637696
Monitor geometry while standby in DeplhiXE:
Monitor0: 4211194, 40, 1637668, 1637693
This is a really old post but if it can help someone, I have found a solution to detect a screen being available or not : the Connecting and Configuring Displays (CCD) API of Windows.
It's part of User32.ddl and the interesting functions are GetDisplayConfigBufferSizes and QueryDisplayConfig. It give us all informations that can be viewed in the Configuration Panel of windows.
In particular the PathInfo contains a TargetInfo property that have a targetAvailable flag. This flag seems to be correctly updated on all the configurations I have tried so far.
This allow you to know the state of every screens connected to the PC and set their configurations.
Here a CCD wrapper for .Net
If your monitor has some sort of built-in USB hub, you could try and use that to detect if the monitor is off/on.
This will of course only work if the USB hub doesn't stay connected when the monitor is consider "off".

Resources