Per-connection notifications using BlueZ peripheral - bluez

I want to use BlueZ as a peripheral / GATT server, and have multiple central devices connect and subscribe to a particular characteristic. Then, I want to send a notification to only 1 of the connected centrals via a Python application. The subscription behavior is in a piece of code I can't control, so having only 1 central be subscribed is not an option. I also need the connection to stay active, so disconnecting from the other devices is also not an option.
I have the GATT server working, notifying all connected centrals via the PropertiesChanged DBus method, by following the example-gatt-server method. The DBus API does not provide a way to deliver a notification to a particular connection handle or connected device, so instead I think my application needs to interact with a BlueZ file descriptor directly. I found that adding the NotifyAcquired property could trigger a call to an implementation of AcquireNotify:
class Characteristic(dbus.service.Object):
"""
org.bluez.GattCharacteristic1 interface implementation
"""
def __init__(self, bus, index, uuid, flags, service):
self.path = service.path + '/char' + str(index)
self.bus = bus
self.uuid = uuid
self.service = service
self.flags = flags
self.descriptors = []
dbus.service.Object.__init__(self, bus, self.path)
def get_properties(self):
return {
GATT_CHRC_IFACE: {
'Service': self.service.get_path(),
'UUID': self.uuid,
'Flags': self.flags,
'Descriptors': dbus.Array(
self.get_descriptor_paths(),
signature='o'),
'NotifyAcquired': False
}
}
...
#dbus.service.method(GATT_CHRC_IFACE, in_signature='a{sv}', out_signature='hq')
def AcquireNotify(self, options):
print('Default AcquireNotify called, returning error')
raise NotSupportedException()
This leaves me with two questions:
How do I generate the fd object that AcquireNotify is expected to return?
How can I use the fd object to deliver a notification to a particular connected device?

Related

PubSub vertx redis with event bus consumer after 3.7.0

We are migrating our Vertx code base from 3.6.3 to 3.8.1.
And I am not sure if the redis pub/sub and the event bus consumers still work together. I couldn't find any documentation in the new version either.
from the 3.5.1 documentation:
vertx.eventBus().<JsonObject>consumer("io.vertx.redis.channel1", received -> {
// do whatever you need to do with your message
JsonObject value = received.body().getJsonObject("value");
// the value is a JSON doc with the following properties
// channel - The channel to which this message was sent
// pattern - Pattern is present if you use psubscribe command and is the pattern that matched this message channel
// message - The message payload
});
RedisClient redis = RedisClient.create(vertx, new RedisOptions());
redis.subscribe("channel1", res -> {
if (res.succeeded()) {
// so something...
}
});
How does this work now with the new Redis client / RedisAPI?
The documentation is not very descriptive. (There s not a subscribe command.. nor a trace of channel1)
You should be able to register a handler for subscriptions io.vertx.redis.client.Redis#handler. Which will be called with an io.vertx.redis.client.Response reference (with corresponding information) for published messages.

Paho Rabitmqq connection getting failed

Here is my paho client code
// Create a client instance
client = new Paho.MQTT.Client('127.0.0.1', 1883, "clientId");
// set callback handlers
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
// connect the client
client.connect({onSuccess:onConnect});
// called when the client connects
function onConnect() {
// Once a connection has been made, make a subscription and send a message.
console.log("onConnect");
client.subscribe("/World");
message = new Paho.MQTT.Message("Hello");
message.destinationName = "/World";
client.send(message);
}
// called when the client loses its connection
function onConnectionLost(responseObject) {
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost:"+responseObject.errorMessage);
}
}
// called when a message arrives
function onMessageArrived(message) {
console.log("onMessageArrived:"+message.payloadString);
}
On Rabbitmq server everything is default seetings. When i run this code i get WebSocket connection to 'ws://127.0.0.1:1883/mqtt' failed: Connection closed before receiving a handshake response
What i am missing ?
From my personal experience with Paho MQTT JavaScript library and RabbitMQ broker on windows, here is a list of things that you need to do to be able to use MQTT from JS from within a browser:
Install rabbitmq_web_mqtt plugin (you may find latest binary here, copy it to "c:\Program Files\RabbitMQ Server\rabbitmq_server-3.6.2\plugins\", and enable from command line using "rabbitmq-plugins enable rabbitmq_web_mqtt".
Of course, MQTT plugin also needs to be enabled on broker
For me, client was not working with version 3.6.1 of RabbitMQ, while it works fine with version 3.6.2 (Windows)
Port to be used for connections is 15675, NOT 1883!
Make sure to specify all 4 parameters when making instance of Paho.MQTT.Client. In case when you omit one, you get websocket connection error which may be quite misleading.
Finally, here is a code snippet which I tested and works perfectly (just makes connection):
client = new Paho.MQTT.Client("localhost", 15675, "/ws", "client-1");
//set callback handlers
client.onConnectionLost = onConnectionLost;
client.onMessageArrived = onMessageArrived;
//connect the client
client.connect({
onSuccess : onConnect
});
//called when the client connects
function onConnect() {
console.log("Connected");
}
//called when the client loses its connection
function onConnectionLost(responseObject) {
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost:" + responseObject.errorMessage);
}
}
//called when a message arrives
function onMessageArrived(message) {
console.log("onMessageArrived:" + message.payloadString);
}
It's not clear in the question but I assume you are running the code above in a web browser.
This will be making a MQTT connection over Websockets (as shown in the error). This is different from a native MQTT over TCP connection.
The default pure MQTT port if 1883, Websocket support is likely to be on a different port.
You will need to configure RabbitMQ to accept MQTT over Websockets as well as pure MQTT, this pull request for RabbitMQ seams to talk about adding this capability. It mentions that this capability was only added in version 3.6.x and that the documentaion is still outstanding (as of 9th Feb 2016)

Prevent getting old updates from Telegram Bot API using a web hook

I'm writing a Telegram bot and I'm using the official bot API. I've got a webhook server that handles requests and sends a 200 OK response for every request.
Before the server stops, the webhook is detached so Telegram does not send updates anymore. However, whenever I turn the bot on and set the webhook URL again, Telegram starts flooding the webhook server with old updates.
Is there any way I can prevent this without requesting /getUpdates repeatedly until I reach the last update?
Here's a heavily simplified version of how my code looks like:
var http = require('http'),
unirest = require('unirest'),
token = '***';
// Attach the webhook
unirest.post('https://api.telegram.org/bot' + token + '/setWebhook')
.field('url', 'https://example.com/api/update')
.end();
process.on('exit', function() {
// Detach the webhook
unirest.post('https://api.telegram.org/bot' + token + '/setWebhook')
.field('url', '')
.end();
});
// Handle requests
var server = http.createServer(function(req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end('Thanks!');
});
server.listen(80);
Thanks in advance.
The best way is to use update_id which is a specific number that increases on every new request (i.e. update). How to implement it?
First off, let's start with the following anonymous class (using PHP7):
$lastUpdateId = new class()
{
const FILE_PATH = "last-update-id.txt";
private $value = 1;
public function __construct()
{
$this->ensureFileExists();
$this->value = filesize(self::FILE_PATH) == 0
? 0 : (int)(file_get_contents(self::FILE_PATH));
}
public function set(int $lastUpdateId)
{
$this->ensureFileExists();
file_put_contents(self::FILE_PATH, $lastUpdateId);
$this->value = $lastUpdateId;
}
public function get(): int
{
return $this->value;
}
public function isNewRequest(int $updateId): bool
{
return $updateId > $this->value;
}
private function ensureFileExists()
{
if (!file_exists(self::FILE_PATH)) {
touch(self::FILE_PATH);
}
}
};
What the class does is clear: Handling the last update_id via a plain file.
Note: The class is tried to be as short as possible. It does not provide error-checking. Use your custom implementation (e.g. use SplFileObject instead of file_{get|put}_contents() functions) instead.
Now, there are two methods of getting updates: Long Polling xor WebHooks (check Telegram bot API for more details on each methods and all JSON properties). The above code (or similar) should be used in both cases.
Note: Currently, it is impossible to use both methods at the same time.
Long Polling Method (default)
This way, you send HTTPS requests to Telegram bot API, and you'd get updates as response in a JSON-formatted object. So, the following work can be done to get new updates (API, why using offset):
$botToken = "<token>";
$updates = json_decode(file_get_contents("https://api.telegram.org/bot{$botToken}/getUpdates?offset={$lastUpdateId->get()}"), true);
// Split updates from each other in $updates
// It is considered that one sample update is stored in $update
// See the section below
parseUpdate($update);
WebHook Method (preferred)
Requiring support for HTTPS POST method from your server, the best way of getting updates at-the-moment.
Initially, you must enable WebHooks for your bot, using the following request (more details):
https://api.telegram.org/bot<token>/setWebhook?url=<file>
Replace <token> with you bot token, and <file> with the address of your file which is going to accept new requests. Again, it must be HTTPS.
OK, the last step is creating your file at the specified URL:
// The update is sent
$update = $_POST;
// See the section below
parseUpdate($update);
From now, all requests and updates your bot will be directly sent to the file.
Implementation of parseUpdate()
Its implementation is totally up to you. However, to show how to use the class above in the implementation, this is a sample and short implementation for it:
function parseUpdate($update)
{
// Validate $update, first
// Actually, you should have a validation class for it
// Here, we suppose that: $update["update_id"] !== null
if ($lastUpdateId->isNewRequest($update["update_id"])) {
$lastUpdateId->set($update["update_id"]);
// New request, go on
} else {
// Old request (or possible file error)
// You may throw exceptions here
}
}
Enjoy!
Edit: Thanks to #Amir for suggesting editions made this answer more complete and useful.
When you server starts up you can record the timestamp and then use this to compare against incoming message date values. If the date is >= the timestamp when you started...the message is ok to be processed.
I am not sure if there is a way you can tell Telegram you are only interested in new updates, their retry mechanism is a feature so that messages aren't missed...even if your bot is offline.
In the webhook mode, Telegram servers send updates every minute until receives an OK response from the webhook program.
so I recommend these steps:
Check your webhook program that you specified its address as url parameter of the setWebhook method. Call its address in a browser. It does not produce an output to view, but clears that probably there is no error in your program.
Include a command that produces a '200 OK Status' header output in your program to assure that the program sends this header to the Telegram server.
I have the same issue, then I tried to reset the default webhook with
https://api.telegram.org/bot[mybotuniqueID]/setWebhook?url=
after that, i verified the current getUpdates query were the same old updates but I sent new requests through the telegram's bot chat
https://api.telegram.org/bot[mybotuniqueID]/getUpdates
when I set up my webhook again the webhook read the same old updates. Maybe the getUpdates method is not refreshing the JSON content.
NOTE:
in my case, it was working fine until I decided to change /set privacy bot settings from botfather

Do I need to Close and/or Dispose callback channels acquired through OperationContext.Current.GetCallbackChannel?

I'm using OperationContext.Current.GetCallbackChannel to get a channel to the client that called a WCF service operation.
Do I need to worry about closing / disposing these callback channels or is this taken care of by the framework?
Well, I just tried it myself and it turns out that if you Close & Dispose the callback channel (after casting to IClientChannel) the entire Service channel becomes useless and when called throws a ProtocolException saying:
"This channel can no longer be used to send messages as the output session was auto-closed due to a server-initiated shutdown. Either disable auto-close by setting the DispatchRuntime.AutomaticInputSessionShutdown to false, or consider modifying the shutdown protocol with the remote server."
I assume that this is an unwelcome consequence or side effect of attempting to close & dispose the callback channel, meaning that this should not be done.
In my opinion you should.
The callback mechanism supplies nothing like a higher-level protocol for managing the
connection between the service and the callback endpoint. It is up to the developer to
come up with some application-level protocol or a consistent pattern for managing the
lifecycle of the connection. The service can only call back to the client if the client-side channel is still open, which is typically achieved by not closing the proxy. Keeping the proxy open will also prevent the callback object from being garbage-collected. If the service maintains a reference on a callback endpoint and the client-side proxy is closed or the client application itself is gone, when the service invokes the callback it will get an ObjectDisposedException from the service channel. It is therefore preferable for the client to inform the service when it no longer wishes to receive callbacks or when the client application is shutting down. To that end, you can add an explicit Disconnect() method to the service contract. Since every method call carries the callback reference with it, in the Disconnect() method the service can remove the callback reference from its internal store.
here is an exemple :
class MyService : IServiceContract
{
static List<IServiceContractCallback> m_Callbacks = new List<IServiceContractCallback>();
public void Connect()
{
IServiceContractCallbackcallback = OperationContext.Current.GetCallbackChannel<IServiceContractCallback>();
if(m_Callbacks.Contains(callback) == false)
{
m_Callbacks.Add(callback);
}
}
public void Disconnect()
{
IServiceContractCallback callback = OperationContext.Current.GetCallbackChannel<IServiceContractCallback>();
if(m_Callbacks.Contains(callback))
{
m_Callbacks.Remove(callback);
}
else
{
throw new InvalidOperationException("Cannot find callback");
}
}
In such a way a client can inform the service that the callback is no longer needed. Does it answer your question ?

Authorization with Websphere MQ 6

I have the server side of IBM's WebSphere MQ version 6 on a virtual machine running Windows Server 2003, sitting on a Vista desktop. The desktop has the client installed.
I've got a little test program (from their code samples) that puts a message on a queue and takes it off again. This program worked when run on the server directly with the server binding. However, I can't get it to work from the client side with the client binding.
The error I get is CompCode 2, Reason 2035, which is an authorization failure.
I suspect this has to do with the fact that the program runs under my user by default, which is on a domain that the virtual machine doesn't know about (and can't access).
I have set up a local user on the vm that I'd like to connect as (user: websphere, password: websphere), but I'm not clear on how to get this all to work. I have the code that I'm using below, and I've tried various combinations of security exit settings on the channel and endpoints, but I can't get away from 2035.
Anyone have experience with this? Help would be much appreciated!
Code:
using System;
using System.Collections;
using IBM.WMQ;
class MQSample
{
// The type of connection to use, this can be:-
// MQC.TRANSPORT_MQSERIES_BINDINGS for a server connection.
// MQC.TRANSPORT_MQSERIES_CLIENT for a non-XA client connection
// MQC.TRANSPORT_MQSERIES_XACLIENT for an XA client connection
// MQC.TRANSPORT_MQSERIES_MANAGED for a managed client connection
const String connectionType = MQC.TRANSPORT_MQSERIES_CLIENT;
// Define the name of the queue manager to use (applies to all connections)
const String qManager = "QM_vm_win2003";
// Define the name of your host connection (applies to client connections only)
const String hostName = "vm-win2003";
// Define the name of the channel to use (applies to client connections only)
const String channel = "S_vm_win2003";
/// <summary>
/// Initialise the connection properties for the connection type requested
/// </summary>
/// <param name="connectionType">One of the MQC.TRANSPORT_MQSERIES_ values</param>
static Hashtable init(String connectionType)
{
Hashtable connectionProperties = new Hashtable();
// Add the connection type
connectionProperties.Add(MQC.TRANSPORT_PROPERTY, connectionType);
// Set up the rest of the connection properties, based on the
// connection type requested
switch (connectionType)
{
case MQC.TRANSPORT_MQSERIES_BINDINGS:
break;
case MQC.TRANSPORT_MQSERIES_CLIENT:
connectionProperties.Add(MQC.HOST_NAME_PROPERTY, hostName);
connectionProperties.Add(MQC.CHANNEL_PROPERTY, channel);
connectionProperties.Add(MQC.USER_ID_PROPERTY, "websphere");
connectionProperties.Add(MQC.PASSWORD_PROPERTY, "websphere");
break;
}
return connectionProperties;
}
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static int Main(string[] args)
{
try
{
Hashtable connectionProperties = init(connectionType);
// Create a connection to the queue manager using the connection
// properties just defined
MQQueueManager qMgr = new MQQueueManager(qManager, connectionProperties);
// Set up the options on the queue we wish to open
int openOptions = MQC.MQOO_INPUT_AS_Q_DEF | MQC.MQOO_OUTPUT;
// Now specify the queue that we wish to open,and the open options
MQQueue system_default_local_queue =
qMgr.AccessQueue("clq_default_vm_sql2000", openOptions);
// Define a WebSphere MQ message, writing some text in UTF format
MQMessage hello_world = new MQMessage();
hello_world.WriteUTF("Hello World!");
// Specify the message options
MQPutMessageOptions pmo = new MQPutMessageOptions();
// accept the defaults,
// same as MQPMO_DEFAULT
// Put the message on the queue
system_default_local_queue.Put(hello_world, pmo);
// Get the message back again
// First define a WebSphere MQ message buffer to receive the message
MQMessage retrievedMessage = new MQMessage();
retrievedMessage.MessageId = hello_world.MessageId;
// Set the get message options
MQGetMessageOptions gmo = new MQGetMessageOptions(); //accept the defaults
//same as MQGMO_DEFAULT
// Get the message off the queue
system_default_local_queue.Get(retrievedMessage, gmo);
// Prove we have the message by displaying the UTF message text
String msgText = retrievedMessage.ReadUTF();
Console.WriteLine("The message is: {0}", msgText);
// Close the queue
system_default_local_queue.Close();
// Disconnect from the queue manager
qMgr.Disconnect();
}
//If an error has occurred in the above,try to identify what went wrong.
//Was it a WebSphere MQ error?
catch (MQException ex)
{
Console.WriteLine("A WebSphere MQ error occurred: {0}", ex.ToString());
}
catch (System.Exception ex)
{
Console.WriteLine("A System error occurred: {0}", ex.ToString());
}
Console.ReadLine();
return 0;
}//end of start
}//end of sample
With Windows-to-Windows connections, WMQ will pass the SID as well as the "short ID" which in this case would be "websphere". This is a little better authorization than you get with non-Windows WMQ which only uses the short ID. The problem is that someone on a non-windows server can connect using the short ID "websphere" and since there is no SID WMQ will accept the connection as thought it were the Windows account.
Two ways to address this. On the QMgr host you can run setmqaut commands to authorize the SID you are actually using to connect. The VM must be able to inquire on the domain where the Windows account lives and the setmqaut command must use -p user#domain syntax.
Alternatively, you can just use the locally defined ID in the MCAUSER of the channel like
ALTER CHL(channel name) CHLTYPE(SVRCONN) MCAUSER('webaphere#vm')
...where 'vm' is the name of the virtual machine and you've authorized the account with setmqaut commands or by putting it into the mqm or administrators group.
Keep in mind this is only for testing! Any channel with a blank or administrative MCAUSER can not only administer WMQ but also execute arbitrary commands on the underlying host server. In the real world you would create accounts with access to queues and the QMgr but not access to administer and you'd put those into all MCAUSER values, then set MCAUSER('nobody') for all the SYSTEM.DEF and SYSTEM.AUTO channels.
Lots more on this available on my web site t-rob.net in the MQ and Links pages. Also, check out:
Comment lines: T.Rob Wyatt: What you didn't know you didn’t know about WebSphere MQ security
Comment lines: T.Rob Wyatt: WebSphere MQ security heats up
I used to have the same problem. the solution, we need to assign user window account to MQA group or administrator group. Then, add user name of the window account to MCA user in the channel.
Hope this helps