Trying to identify and range (with BLE) an iPhone transmitting as a peripheral *in the background8. - bluetooth-lowenergy

When an app running on iOS8 is backgrounded, all uniquely identifiable information appears to be scrubbed from the Bluetooth advertising package. peripheral.name, peripheral.identifier, etc. It all goes away as soon as the app is backgrounded.
The only workaround I have discovered - to identify and range multiple bluetooth-emitting apps - is to scan and connect with a set of known devices (iPhones).
My app transmits as a peripheral, with a service that has a characteristic whose value is a unique identifier. This works.
Where I fall down is once I have read the characteristic (and identified the device) I need to range it. In the delegate call for did get RSSI, I get a peripheral object, but due to the asynchronous nature of the delegate pattern I don't know which of the discovered peripherals I am getting the RSSI signal for. Peripheral appears to remain anonymous, even after connected!
-(void) peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
if (error == nil) {
NSString *valueString=[[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding];
NSLog(#"The new value=%#",valueString);
peripheral.delegate = self;
[peripheral readRSSI];
}
}
-(void) peripheral:(CBPeripheral *)peripheral didReadRSSI:(NSNumber *)RSSI error:(NSError *)error {
NSLog(#"Got RSSI update in didReadRSSI : %4.1f", [RSSI doubleValue]);
// but which peripheral (and associated id) did we get back??
}
This is either a limitation of Apple's spec, or something wrong with my expectations. One central to many peripherals, unlike the original Bluetooth architecture of one-to-one.
Any ideas how I can identify and range an app broadcasting as a peripheral while backgrounded? Huge thanks if so!

The CBPeripheral object itself should be unique. You can keep a dictionary of your discovered / connected peripherals along with the custom identifier from your characteristic. When the didReadRSSI delegate is called, you can check against your 'known' collection of devices to identify a specific device.

Related

Axon Partialy replay, how do i get a TrackingToken for the startPosition for the replay?

I want my Axon replay events, not all but partially.
A full replay is up and running but when i want a partially replay i need a TrackingToken startPosition for the method resetTokens(), my problem is how to get this token for the partial replay?
I tried with GapAwareTracingToken but this does not work.
public void resetTokensWithRestartIndexFor(String trackingEventProcessorName, Long restartIndex) {
eventProcessingConfiguration
.eventProcessorByProcessingGroup(trackingEventProcessorName, TrackingEventProcessor.class)
.filter(trackingEventProcessor -> !trackingEventProcessor.isReplaying())
.ifPresent(trackingEventProcessor -> {
// shutdown this streaming processor
trackingEventProcessor.shutDown();
// reset the tokens to prepare the processor with start index for replay
trackingEventProcessor.resetTokens(GapAwareTrackingToken.newInstance(restartIndex - 1, Collections.emptySortedSet()));
// start the processor to initiate the replay
trackingEventProcessor.start();
});
}
When i use the GapAwareTrackingToken then i get the exception:
[] - Resolved [java.lang.IllegalArgumentException: Incompatible token type provided.]
I see that there is also a GlobalSequenceTrackingToken i can use, but i don't see any documentatieon about when these can/should be used.
The main "challenge" when doing a partial reset, is that you need to be able to tell where to reset to. In Axon, the position in a stream is defined with a TrackingToken.
The source that you read from will provide you with such a token with each event that it provides. However, when you're doing a reset, you probably didn't store the relevant token while you were consuming those events.
You can also create tokens using any StreamableMessageSource. Generally, this is your Event Store, but if you read from other sources, it could be something else, too.
The StreamableMessageSource provides 4 methods to create a token:
createHeadToken - the position at the most recent edge of the stream, where only new events will be read
createTailToken - the position at the very beginning of the stream, allowing you to replay all events.
createTokenAt(Instant) - the most recent position in the stream that will return all events created on or after the given Instant. Note that some events may still have a timestamp earlier than this timestamp, as event creation and event storage isn't guaranteed to be the same.
createTokenSince(Duration) - similar to createTokenAt, but accepting an amount of time to go back.
So in your case, createTokenAt should do the trick.

BLE UART - Sending data from the peripheral to the central?

I am trying to implement a BLE UART service where the central can send down a request, the peripheral takes that request and forwards it to a peripheral application to do processing, and then returns a response back to the central. The design is similar to Figure 2 found in https://punchthrough.com/serial-over-ble/
I am having trouble with the last part to return data back to the central.
Below are the tx/rx characteristics I came across to implement the UART
class TxCharacteristic(Characteristic):
def __init__(self, bus, index, service):
Characteristic.__init__(self, bus, index, UART_TX_CHARACTERISTIC_UUID,
['notify'], service)
self.notifying = False
GLib.io_add_watch(sys.stdin, GLib.IO_IN, self.on_console_input)
def on_console_input(self, fd, condition):
s = fd.readline()
if s.isspace():
pass
else:
self.send_tx(s)
return True
def send_tx(self, s):
if not self.notifying:
return
value = []
for c in s:
value.append(dbus.Byte(c.encode()))
self.PropertiesChanged(GATT_CHRC_IFACE, {'Value': value}, [])
def StartNotify(self):
if self.notifying:
return
self.notifying = True
def StopNotify(self):
if not self.notifying:
return
self.notifying = False
class RxCharacteristic(Characteristic):
def __init__(self, bus, index, service):
Characteristic.__init__(self, bus, index, UART_RX_CHARACTERISTIC_UUID,
['write'], service)
def WriteValue(self, value, options):
data = bytearray(value).decode('utf-8')
print(f'Incoming UART data: {data}')
handle_request(data)
With a BLE scanner phone app, I can write data to the RxCharacteristic OK and when RxCharacteristic receives it, I call handle_request(data) for processing.
This is where I'm stuck. How do I get a handle or reference the TxCharacteristic so that I can call send_tx()? Is the 'notify' characteristic flag what I want or do I want a 'write' flag?
Typically with UART over BLE people use the Notify flag. The central device (phone app) will need to enable notifications so that it gets notified when values change.
Using the Nordic UART Service (NUS) is normally a good example to follow. If you do implement NUS then there are several apps that work with it.
Looking at your code, it looks like the plumbing is there to connect your console to the send_tx method. I suspect that your app isn't doing a StartNotify
It is the icon I've circled in Lime Green in the image below. This is from nRF Connect which is a generic Bluetooth Low Energy scanning and exploration tool.
Apps like Serial Bluetooth Terminal will do StartNotify automatically for NUS

Does C++ Actor Framework guarantee message order?

Can C++ Actor Framework be used in such a way that it guarantees message ordering between two actors? I couldn't find anything about this in the manual.
If you have only two actors communicating directly, CAF guarantees that messages arrive in the order they have been sent. Only multi-hop scenarios can cause non-determinism and message reordering.
auto a = spawn(A);
self->send(a, "foo");
self->send(a, 42); // arrives always after "foo"
At the receiving end, it is possible to change the message processing order by changing the actor behavior with become:
[=](int) {
self->become(
keep_behavior,
[=](const std::string&) {
self->unbecome();
}
);
}
In the above example, this will process the int before the string message, even though they have arrived in opposite order at the actor's mailbox.

Any way to implement BLE notifications in Android-L preview

This question is not about Android notificatinos, but BLE notifications (as the title may hint)
I have got basic BLE peripheral mode working on Android-L
Is there any way to implement BLE notifications in Android-L preview. I could do some thing like the following to make a charecteritic be able to notify, but trying to listen for
BluetoothGattCharacteristic firstServiceChar = new BluetoothGattCharacteristic(
UUID.fromString(serviceOneCharUuid),
BluetoothGattCharacteristic.PROPERTY_NOTIFY, BluetoothGattCharacteristic.PERMISSION_READ );
But in LightBlue app on iOS I cannot subscribe to this characteristic. Apprently there is no API that could be use to respond to the calls when a char is subscribed (like there are in iOS)
Kindly share your code if you have successfully enabled BLE notifications on Android-L
On top of what OP has done:
BluetoothGattCharacteristic firstServiceChar = new BluetoothGattCharacteristic(UUID.fromString(serviceOneCharUuid), BluetoothGattCharacteristic.PROPERTY_NOTIFY, BluetoothGattCharacteristic.PERMISSION_READ )
The next thing is to add a Client Characteristic Configuration descriptor (UUID is the 128 bit version of the 16 bit 0x2902 using the Bluetooth base UUID), so that the connected device can tell yours that it wants notifications (or indications), and then add that descriptor to your characteristic:
BluetoothGattDescriptor gD = new BluetoothGattDescriptor(UUID.fromString("00002902-0000-1000-8000-00805F9B34FB"), BluetoothGattDescriptor.PERMISSION_WRITE | BluetoothGattDescriptor.PERMISSION_READ);
firstServiceChar.addDescriptor(gD);
That UUID is from the Bluetooth spec. Apparently a device subscribes to notifications by updating this descriptor, so you've got to handle this in your BluetoothGattServerCallback by overriding onDescriptorWriteRequest:
#Override
public void onDescriptorWriteRequest (BluetoothDevice device, int requestId, BluetoothGattDescriptor descriptor, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value) {
btClient = device; // perhaps add to some kind of collection of devices to update?
// now tell the connected device that this was all successfull
btGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, value);
}
Now update your value and notify the connectee:
firstServiceChar.setValue("HI");
btGattServer.notifyCharacteristicChanged(btClient, firstServiceChar, false);
Hopefully this quick and dirty code will help, because it was OP's code that I used in the first place to even get basic peripheral mode working :)

Broadcast TCP-Server with libevent

I am looking for some sample code of a dead simple libevent-based TCP-Server which broadcasts incoming Messages to all connected clients. On the Web I only found TCP-Servers which echoes back messages.
One echo example if found is on the bottom of this page http://www.wangafu.net/~nickm/libevent-book/Ref8_listener.html
I am sure that its not so difficult to change the code provided on this Site, so that messages are brodcast to all connected clients, but I don't know how.
Could someone advise me?
EDIT: Yes, some kind of a chat server. It seams i need to do sth like this:
void server_read_cb(struct bufferevent *bev, void *data)
{
struct evbuffer *input = bufferevent_get_input(bev);
struct evbuffer *output = bufferevent_get_output(bev);
char *mem = malloc(len); /* XXX: check for malloc failure */
evbuffer_remove(input, mem, len);
"for every connection conn" {
/* XXX you'll need to implement a real connection list;
the above isn't real C. */
evbuffer_add(bufferevent_get_output(conn), mem, len);
}
free(mem);
}
But i can't put this to work.
Seems you want something similar to a chat server. One example is here. Basically, when you receive data from one connection, you just go through the list of connections and send that same data to each one (including/excluding the original).

Resources