how to get bluetooth connected device data in read,write,notify methods using react-native-ble-plx or ble-manager - reactjs

const monitorchars = DeviceManager.monitorCharacteristicForDevice(
device.id,
"00001800-0000-1000-8000-00805f9b34fb",
"00002a01-0000-1000-8000-00805f9b34fb",
function (err, result) {
if(err) {
console.log(err)
return;
}
console.log(result);
});
console.log(monitorchars)
I am using the react-native-ble-plx package.
I get read characteristics, read descriptors, and I am trying to write and notify props in react-native code. But, values are showing errors.
Can anyone can help to write and notify in ble-plx?
BleError: Characteristic X notify change failed for device Y and service Z
We are working on a device by using this we got services and their respective characteristics,among those characteristics we have one characteristic with notify property(isNotifiable:true,isNotifying:false) and a client characteristic configuration descriptor. now we want to make this isNotifying property value to true so that we can get some data stream from the device i refered this document ,in this there is a statement like "to set the notification value, we need to tell the sensor to enables us this notification mode. We will write to the characteristic’s descriptor to set the right value: Notify or Indicate." in ble-plx there is a method bleManager.writeDescriptorForDevice(), we tried using this but ended up with an error,
so,help me in getting the device data by making isNotifying property value true

Related

What does the error "Exceeded maximum allowed number of Trackers" mean?

I'm following this tutorial to implement object tracking on iOS 11. I'm able to track objects perfectly, until a certain point, then this error appears in the console.
Throws: Error Domain=com.apple.vis Code=9 "Internal error: Exceeded maximum allowed number of Trackers for a tracker type: VNObjectTrackerType" UserInfo={NSLocalizedDescription=Internal error: Exceeded maximum allowed number of Trackers for a tracker type: VNObjectTrackerType}
Am I using the API incorrectly, or perhaps Vision has trouble handling too many consecutive object tracking tasks? Curious if anyone has insight into why this is happening.
It appears that you hit the limit on the number of trackers that can be active in the system. First thing to note is that a new tracker is created every time a new observation, with new -uuid property is used. You should be recycling the initial observation you use when you started the tracker, until you no longer want to use it, by feeding what you got from “results” for time T into the subsequent request you make for time T+1. When you no longer want to use that tracker (maybe the confidence score gets too low), there is a “lastFrame” property that can be set, which lets the Vision framework know that you are done with that tracker. Trackers also get released when the sequence request handler is released.
To track the rectangle you feed consequent observations to the same VNSequenceRequestHandler instance, say, handler. When the rectangle is lost, i.e. the new observation is nil in your handler function / callback, or you are getting some other tracking error, just re-instantiate the handler and continue, e.g. (sample code to show the idea):
private var handler = VNSequenceRequestHandler()
// <...>
func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
guard
let pixelBuffer: CVPixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer),
let lastObservation = self.lastObservation
else {
self.handler = VNSequenceRequestHandler()
return
}
let request = VNTrackObjectRequest(detectedObjectObservation: lastObservation, completionHandler: self.handleVisionRequestUpdate)
request.trackingLevel = .accurate
do {
try self.handler.perform([request], on: pixelBuffer)
} catch {
print("Throws: \(error)")
}
}
Note that handler is var, not a constant.
Also, you may re-instantiate the handler in actual handler function (like func handleVisionRequestUpdate(_ request: VNRequest, error: Error?)) in case new observation object is invalid.
My problem with this was that I had a function that called perform... on the same VNSequenceRequestHandler that the tracking was also calling perform on, because of that I was processing too many try self.visionSequenceHandler.perform(trackRequests, on: ciimage) concurrently. Make sure the VNSequenceRequestHandler is not getting hit at the same time by multiple performs....

How to capture keyboard in linux kernel module?

I am trying to write a Linux kernel module to work similar to a 'MouseKeys' application - to grab certain keys and then output mouse events. I'm currently struggling trying to grab input in such a way that I can discard or passthrough keys based on some internal state of my module - what I want is something like:
int keyboard_callback(event) {
if (active) {
processKey(event); // this would output mouse events
return BLOCK_KEY_EVENT; // input is not visible to any applications
}
// input would be processed downstream as normal
return PASSTHROUGH_KEY_EVENT;
}
....
register_input_handler(keyboard_callback);

Download File (using Thread class)

Ok, I understand that maybe very stupid question, but i never did it before, so i ask this question. How can i download file (let's say, from the internet) using Thread class?
What do you mean with "using Thread class"? I guess you want to download a file threaded so it does not block your UI or some other part of your program.
Ill assume that your using C++ and WINAPI.
First create a thread. This tutorial provides good information about WIN32 threads.
This thread will be responsible for downloading the file. To do this you simply connect to the webserver on port 80 and send a HTTP GET request for the file you want. It could look similar to this (note the newline characters):
GET /path/to/your/file.jpg HTTP/1.1\r\n
Host: www.host.com\r\n
Connection: close\r\n
\r\n
\r\n
The server will then answer with a HTTP response containing the file with a preceding header. Parse this header and read the contents.
More information on HTTP can be found here.
If would suggest that you do not use threads for downloading files. It's better to use asynchronous constructs that are more targeted towards I/O, since they will incur a lower overhead than threads. I don't know what version of the .NET Framework you are working with, but in 4.5, something like this should work:
private static Task DownloadFileAsync(string uri, string localPath)
{
// Get the http request
HttpWebRequest webRequest = WebRequest.CreateHttp(uri);
// Get the http response asynchronously
return webRequest.GetResponseAsync()
.ContinueWith(task =>
{
// When the GetResponseAsync task is finished, we will come
// into this contiuation (which is an anonymous method).
// Check if the GetResponseAsync task failed.
if (task.IsFaulted)
{
Console.WriteLine(task.Exception);
return null;
}
// Get the web response.
WebResponse response = task.Result;
// Open a file stream for the local file.
FileStream localStream = File.OpenWrite(localPath);
// Copy the contents from the response stream to the
// local file stream asynchronously.
return response.GetResponseStream().CopyToAsync(localStream)
.ContinueWith(streamTask =>
{
// When the CopyToAsync task is finished, we come
// to this continuation (which is also an anonymous
// method).
// Flush and dispose the local file stream. There
// is a FlushAsync method that will flush
// asychronously, returning yet another task, but
// for the sake of brevity I use the synchronous
// method here.
localStream.Flush();
localStream.Dispose();
// Don't forget to check if the previous task
// failed or not.
// All Task exceptions must be observed.
if (streamTask.IsFaulted)
{
Console.WriteLine(streamTask.Exception);
}
});
// since we end up with a task returning a task we should
// call Unwrap to return a single task representing the
// entire operation
}).Unwrap();
}
You would want to elaborate a bit on the error handling. What this code does is in short:
See the code comments for more detailed explanations of how it works.

Windows Phone 7 Push Notifications Not Showing Up On My Phone

UPDATE: The plot thickens. I changed my channel name and it is suddenly working (which means it wasn't a problem with my push service, since I'm getting the same HTTP response from the Microsoft Push Notification server).
To me, however, this is not a solution. How will I be able to test this and KNOW my users are getting their push notifications if I'm getting the same response when it's not working as I do when it is?
[ORIGINAL POST]
I've been trying to get push notifications sent to my Windows Phone 7 device, but I'm having very big problems that I can't find any answers for. I'll start with the c# code.
I set up push notifications using the following C# code.
private HttpNotificationChannel channel;
private static string PUSH_CHANNEL = "MySpecialPushChannel";
private Uri PushUri = null;
private bool IsPushRegistered = false;
public void StartPushSubscription()
{
try
{
channel = HttpNotificationChannel.Find(PUSH_CHANNEL);
}
catch
{}
if (channel != null)
{
PushUri = channel.ChannelUri;
if (!channel.IsShellTileBound)
channel.BindToShellTile();
}
else
{
channel = new HttpNotificationChannel(PUSH_CHANNEL);
channel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(channel_ChannelUriUpdated);
channel.HttpNotificationReceived += new EventHandler<HttpNotificationEventArgs>(channel_HttpNotificationReceived);
channel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(channel_ErrorOccurred);
try
{
channel.Open();
channel.BindToShellTile();
}
catch (Exception err)
{
channel = null;
IsPushRegistered = false;
// Code to try again
}
}
}
void channel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
{
PushUri = e.ChannelUri;
IsPushRegistered = true;
}
I'm following the standard WP7 push structure:
Find the HttpNotificationChannel (or start a new one)
Register event handler to get the push notification uri back
Open the channel
Bind to the tile
Handle the channel Uri (which we send to our service to await the happy day when we send the push notification
OK... so far so good. No errors, I get my Uri, send it to my service just fine. I pin my app to the start screen and my service sends a push request to the Uri (sending just the count so that I get a little push count number in the upper right hand corner). I get back an HTTP 200 status with the following:
DeviceConnectionStatus => Connected
NotificationStatus => Received
SubscriptionStatus => Active
And then... nothing. No push status shows up on my app. I've now tried it on my device, in the emulator, on another device, and with multiple servers and the result is always the same. Everything looks like it is working except for the fact that it doesn't work.
To me, however, this is not a solution. How will I be able to test this and KNOW my users are getting their push notifications if I'm getting the same response when it's not working as I do when it is?
The answer is, you can't. It's a limitation of how WP7 handles notifications.
For structured notifications like Tile and Toast, if you get the Connected/Active/Received/200 response, then you can know that MPNS accepted your notification request. However, this does not mean that you have sent a valid XML payload.
The component that handles parsing XML is the Push Client, the process running on the phone that accepts push notifications and deals them out to appropriate applications, displays the toast, etc.
If you have sent invalid XML, there is absolutely no indication that you've done so. At most, if you try to send the notification again to that same push channel URI, you'll get a 404 in response. Apparently getting an invalid XML payload for a specific application makes that application's push channel close, requiring you to go through the whole procedure again.
I've discovered this while debugging with our server team, and through trying to get the phone to display an alternate live tile. The only advice I can offer you is to quadruple-check your XML.
You will get errors in your error event handler for your push notification channel for Toast notifications that have invalid XML, since you are able to send/receive toast notifications while the application is active.
If anyone from Microsoft is reading this, PLEASE provide more thorough documentation on possible error states in the push notification system. We also need an event handler for Tile notifications, or at least allow us to receive tile notifications while the app is in the foreground and fire the notification channel error event so that we can be aware that our XML payload is invalid.
Especially if your web service isn't built with WCF, .NET, Azure, and whatever, working with Push Notifications on WP7 is like wandering blind.
Documentation for an exception message reading "InvalidOperationException(Failed to open channel)" should not read: "This exception is raised when the notification channel failed to open. Try opening the notification channel again." (reference)
are you getting the URL from each device? you need to get a URL from the push notification sevice for each device everytime your device connects,
when it does you need to find a way of retrieving the url from each client,
once you do that and your still not receiving push notifications then I would write to microsoft to see if they can see anything to do with the push notifications

Runtime debugging tips for Windows Service?

I have a Windows Service that monitors a COM port connected to a vendors hardware. This is a very busy piece of hardware that is constantly polling other devices on the wire (this is a twisted-pair RS485 "network"). My software needs to emulate X number of hardware devices on this wire, so I've got a multi-threaded thing going on with a multi-tiered state machine to keep track of where the communications protocol is at any moment.
Problem is with a Windows Service (this is my first one, BTW) is that you need some debugging to let you know if stuff is working properly. When I was first developing this state machine/multi-thread code I had a windows form with a RichTextBox that displayed the ASCII chars going back-n-forth on the line. Seems like I can't really have that GUI niceness with a service. I tried opening a form in the service via another program that sent the service messages that are received via the OnCustomCommand() handler but it didn't seem to work. I had "Allow service to interact with desktop" checked and everything. I was using the Show() and Hide() methods of my debug form.
I guess I don't need to see all of the individual characters going on the line but man that sure would be nice (I think I really need to see them :-) ). So does anyone have any crazy ideas that could help me out? I don't want to bog down the system with some IPC that isn't meant for the voluminous amount of data that is sure to come through. It will only be very short-term debugging though, just confirmation that the program, the RS485-to-USB dongle, and hardware is all working.
Use OutputDebugString to write to the debugging buffer and then use DebugView to watch it. If you're running on Windows XP or earlier, then you can use PortMon to see the raw bytes going through the serial port. The advantage over a log file is that there's very little overhead, particularly when you're not watching it. You can even run DebugView from another machine and monitor your service remotely.
I dunno if it will work for you, but I always build my services with a extra Main that build them as console app to get debug output.
Edit:
Some example:
class Worker : ServiceBase
{
#if(RELEASE)
/// <summary>
/// The Main Thread where the Service is Run.
/// </summary>
static void Main()
{
ServiceBase.Run(new Worker());
}
#endif
#if(DEBUG)
public static void Main(String[] args)
{
Worker worker = new Worker();
worker.OnStart(null);
Console.ReadLine();
worker.OnStop();
}
#endif
// Other Service code
}
You could write the output to a log file and then use another application to watch that file. This question about "tail" outlines several options for watching log files with windows.
What I usually do when working on a Windows Service is to create it so that it can be run either as a service, or as a plain old command-line application. You can easily check whether you are running as a service by checking Environment.UserInteractive. If this property is true, then you are running from the command line. If the property is false, then you are running as a service. Add this code to Program.cs, and use it where you would normally call ServiceBase.Run(servicesToRun)
/// <summary>Runs the provided service classes.</summary>
/// <param name="servicesToRun">The service classes to run.</param>
/// <param name="args">The command-line arguments to pass to the service classes.</param>
private static void RunServices(IEnumerable<ServiceBase> servicesToRun, IEnumerable args)
{
var serviceBaseType = typeof(ServiceBase);
var onStartMethod = serviceBaseType.GetMethod("OnStart", BindingFlags.Instance | BindingFlags.NonPublic);
foreach (var service in servicesToRun)
{
onStartMethod.Invoke(service, new object[] { args });
Console.WriteLine(service.ServiceName + " started.");
}
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
var onStopMethod = serviceBaseType.GetMethod("OnStop", BindingFlags.Instance | BindingFlags.NonPublic);
foreach (var service in servicesToRun)
{
onStopMethod.Invoke(service, null);
Console.WriteLine(service.ServiceName + " stopped.");
}
}
Now you can debug your service, set breakpoints, anything you want. When you run your application, you'll get a console window, appropriate for displaying console messages, and it will stay open until you hit a key.
I'm answering my own question here. I tried a couple of suggestions here but here's what I ended up doing...
I created a Windows Form application with a single Button and RichTextBox. This application constructed a NamedPipeServerStream on it's end. The Button's job was to send either "debug on" (command 128) or "debug off" (129) to the Windows Service. The initial value was "debug off". When the button was clicked, a command of 128 was sent to the Windows Service to turn debugging on. In the Windows Service this triggered an internal variable to be true, plus it connected to the Form application with a NamedPipeClientStream and started sending characters with a BinaryWriter as they were received or sent on the COM port. On the Form side, a BackgroundWorker was created to WaitForConnection() on the pipe. When it got a connection, a BinaryReader.ReadString() was used to read the data off of the pipe and shoot it to the RichTextBox.
I'm almost there. I'm breaking my pipe when I click the debug button again and a subsequent click doesn't correctly redo the pipe. All in all I'm happy with it. I can post any code if anyone is interested. Thanks for the responses!

Resources