Show value in progressbar from native method - java-native-interface

I have some native code and want to update the progressbar from the native code. There isn't no return value because it is a long duration task.
I found a small example http://developer.android.com/reference/android/widget/ProgressBar.html but when I move the update part in a extra method I get a NullPointerException.
It seems that this part must be in the thread of the progressbar.
I tried another way by using the AsyncTask as nested class, but I haven't access on the method publishProgress from anywhere outside the class itself.
Is there any possibility to get it working?

If it is possible to break your long task into multiple incremental calls then I'd recommend doing that. Then you can make those calls from a loop inside AsyncTask.doInBackground(), just like in the SDK examples.
If that's not possible, you'll need a progress variable in your native code that can safely be accessed from multiple threads: Write to it from your worker code and read it from a new "getProgress()" JNI function, with the appropriate synchronisation done in native code. You would then be able to call your getProgress() function from AsyncTask.doInBackground(), or whatever UI scheme you choose to use.

Related

N-API Continuous callbacks for c++ media stream

I'm trying to create a node interface for a c++ media player. Upon decoding of a frame, there is an event which allows me to access the frame data, which I'm trying to funnel into node. But I can't seem to figure out how to get that kind of functionality to work with the functions available in the node api. My approach, for the time being, is to figure out a push mechanism to get the data from c++ to javascript where all i need is to initialize a callback in javascript, since it seems more elegant. If that fails I could create a polling loop in js to check if there is new frame data, but it seems less efficient.
I've tried with napi_create_async_work, by creating a lambda function in the execute parameter function, which would allow me to call napi_make_callback for every frame callback, but then I get the following error :
Fatal error in HandleScope::HandleScope
Entering the V8 API without proper locking in place
I'm likely approaching this incorrectly, its the first time I use n-api.
Any help is welcome, thank you!
The issue is mainly pertaining to the fact you can’t access V8 (JavaScript) memory outside the event-loop’s main thread. If you're creating an async thread, by default you're also creating a new memory stack.
Fortunately, a fix is on the way which should allow thread safe access with
napi_create_threadsafe_function (example here)
Until then
There is a header only C++ package which integrates great with the C++ N-API wrapper
Napi-addon-api is update. These is a good way that use the Napi::ThreadSafeFunction.
Doc and example.

User Interface doesn't update output with position data

I am creating a user interface using (Qt) and I am attaching it to my C/C++ motion application using shared memory as my form of Inter Process Communication.
I currently have a class which I created in my motion application that has many members. Most of these members are used to update data on the UI and some of them get updated about 20 to 50 times a second, so it is pretty fast (the reason being because it is tracking motion). My problem is that the data is not getting updated on the UI frequently. It gets updated every few seconds. I was able to get it work using other variables made in structures from my application by using "volatile" however it does not seem to be working for members of my class. I know that the problem is not on the UI (Qt) side, because I saw that the actual member data was not being updated in my application, even though I have commands every cycle to update the data.
I was pretty sure the problem is that some optimization is occurring since I do not have my members declared as volatile as in my structures, but when I made them volatile it still did not work. I found that when I through a comment to print out in the function that updates my motion data within my motion application, the UI updates much more frequently as if the command to print out the comment deters the compiler form optimizing out some stuff.
Has anyone experienced this problem or have a possible solution?
Your help is greatly appreciated. Thanks ahead of time!
EDIT:
The interface does not freeze completely. I just updates every few seconds instead of continuously as I intended for it to do. Using various tests I know that the problem is not on the GUI or shared memory side. The problem lies strictly on the motion application side. The function that I am calling is below: int
`motionUpdate(MOTION_STAT * stat)
{
positionUpdate(&stat->traj);
}
`
where
positionUpdate(){stat->Position = motStatus.pos_fb;}
Position is a class member that contains x, y, and z. The function does not seem to update the position values unless I put a printed out comment before positionUpdate(). I don't track the change in shared memory to update the UI, but instead just update the UI every cycle.
Especially Given you are using Qt, I would strongly advise not using "native" shared memory, but to use signals instead. Concurrency using message-passing (signals/slots is one such way) is much, much easier to reason about and debug than trying to share memory.
I would expect your problem with updating is that the UI isn't being called enough of the time, so there is a backlog of updating to do.
Try putting in some code that throws away updates if they happen less than 0.3 seconds apart and see if that helps. You may wish to tune that number but start at the larger end.
Secondly, make sure there aren't any "notspots" in your app, in which the GUI thread is not being given the chance to run. If there are, consider putting code into another thread or, alternatively, calling processEvents() within that part of the code.
If the above really isn't what's happening, I would suggest adding more info about the architecture of your program.

C++ Output: GUI or Console?

I am making an application in C++ that runs a simulation for a health club. The user simply enters the simulation data at the beginning (3 integer values) and presses run. After that there is no user input - so very simple.
After starting the simulation a lot of the logic is deep down in lower classes but a lot of them need to print simple output messages to the UI. Returning a message is not possible as objects need to print to the UI but keep working.
I was going to pass a reference to the UI object to all classes that need it but I end up passing it around quite a lot - there must be a better way.
What I really need is something that can make calling the UI's printOutput(string) function as easy (or not much more difficult) than cout << string;
The UI also has a displayConnectionStatus(bool[] connections) method.
Bear in mind the UI inherits an abstract 'UserInterface' class so simple console UIs and GUIs can be changed in and out easily.
How do you suggest I implement this link to the UI?
If I were to use a global function, how can I redirect it to call methods of the UserInterface implementation that I selected to use?
Don't be afraid of globals.
Global objects hurt encapsulation, but for a targeted solution with no concern for immediate reusability, globals are just fine.
Expose a global object that processes events from your simulation. You can then choose to print the events, send them by e-mail, render them with OpenGL or whatever you fancy. Make a uniform interface that catches what happens inside the simulation via report callbacks, and then you can subclass this global object to suit your needs.
If the object wasn't global, you'd be passing a pointer around all the codebase.
I would suggest to go for logging framework i.e. your own class LogMessages, which got functions which get data and log the data, it can be to a UI, file, over network or anything.
And each class which needs logging, can use your logging class.
This way you can avoid globals and a generic solution , also have a look at http://www.pantheios.org/ which is open source C/C++ Diagnostic Logging API library, you may use that also...

Calling a function after another function is called

I'm programming a controller for use with Ableton Live 8 using the Python-based API. In my code I use a method provided in the API to watch for changes in a property's value, and call a function whenever the value changes. My goal is to change the color of the clip when the value change is noticed.
I have my code completed, and it compiles without error. From Ableton's log:
742234 ms. RemoteScriptError: RuntimeError
742234 ms. RemoteScriptError: :
742234 ms. RemoteScriptError: Changes cannot be triggered by notifications
742234 ms. RemoteScriptError:
It appears this is the result of using the built-in notification system to make a change to the live set during notification. Triggering the actual change AFTER the listening function has finished executing should work. Is this possible using Python?
Edit for clarification:
currently we have
value change noticed, function called
function attempts to change the clips color (results in error)
we need
listener notices value change, function called
function finds the new color value
function execution ends
another function is called outside the listener's scope, and changes the clips color
I did a lot in M4L and know this error by heart :)
I'm afraid you can't do anything about that - to my noob eyes it looks like a built-in security mechanism so you can't loop (Something changed? Change it! Something changed...).
In M4L i used Javascript Tasks to separate the steps (Tasks forget nearly everything),
something like
Observer -> Something changed
Create a Task that reacts
task.execute() or task.schedule(time)
Maybe the python threading module can achieve something similar?
BTW, if you happen to understand anything about the _Framework-Tasks, let me know.
I was having the same issue trying to delete a track from a clip stop listener, then I found this thread and followed #user2323980 suggestion.
There seems to be a "_tasks" object on every Framework class (I found it throught log_message inside ClipSlotComponent and ControlSurface) that handles concurrency between tasks. And it's really simple to use it:
self._tasks.add(Task.run(func, args))
I found some uses of it on Push and MK2 scripts, those are good references.

How do I create a timer run my program repeatedly? C++

I want create timer in my program so that I can cause it to rerun every minute and I don't know how to do it in a C++ Application. In C# I could just create a timer but I'm struggling here now...
sleep(); is not an option because as far as I know it makes your program inactive for X seconds, I need my app to be active and working, calculating all the time. This is because my code is used to constantly input information into a MS Access table. I was able to create the necessary components of my code to connect and perform the insert/update to the table but this is just on of the many components to the code that I am creating. Please help me with this little (or big?) problem, I'm very new to C++ and learning ATM, but I am developing a fast learning curve. Thanks
I suppose you work on Windows, since you mentioned C#. So take a look at SetTimer, and if it is a MFC app, then look at CWnd::SetTimer.
Every platform provides api for creating a timer, which will give you a callback usually after timer expires. You can just search for the api available on your platform.
If you are using windows use setTimer function.
If you're using C++ .NET, you can use the same Timer class(es) as C#, just use the C++ syntax (using gcnew instead of new, use the ^ for GC references).
Otherwise you could just have a loop:
while (should_keep_looping) {
// do what you need to do
// if necessary:
sleep(1);
}
See here: http://www.cplusplus.com/forum/beginner/317/
There is on built in "timer" in C++, and you are correct about the behavior of sleep(). The above thread describes a custom implementation.
if you have a window you can use its message queue, as suggested by Als and Marius in their answers
you can use some task dispatcher and some timer to register a callback, e.g. functionality provided by Boost.Asio and its deadline_timer (example)
you can check if timer expired between your tasks manually as proposed in BlackJack's link
or you can create separate thread and make it call your callback when time came. Pros: you can use sleep() there and you callback will be called in parallel with your main thread. Cons: worry about synchronization