How to stop PiCamera preview on keystroke? - camera

I made a code through python to operate a preview of my PiCamera, I have set the time to 10 seconds, then automatically turns off. However I am unsure how I would be able to have a keystroke to stop the camera and return to the previous screen?
At the moment I am able to view for 10 seconds, and nothing else, the usual ctrl-c and various other keys does not work.
How would I be able to integrate a keystroke into the code following to stop the script and return to normal screen?
from picamera import PiCamera
from time import sleep
camera = PiCamera()
camera.start_preview()
sleep(10)
camera.stop_preview()

Subprocess module you can check on the official page:
https://docs.python.org/2/library/subprocess.html#subprocess.Popen
A possible way to implement with subprocess.Popen is here on SO:
Controlling a python script from another script
Another possibility is to use multiprocesses or multithreading module. For instance creation of a thread can be done and you can take care of an ID :-)
All the possibility will lead you to learn a bit more of python!
My better suggestion will be to create easily a thread (https://docs.python.org/3/library/threading.html --> here for python 3), get the ID and leave it run.
If you want to terminate the camera running, then terminate the thread :-)

Related

What is the function to run simulation in MEL?

I would like to create a MEL script that creates a scene, setting up ncloth and passive collider objects and run the simulation up to a certain frame.
In the script editor, I can see the scene set-up but there is no function starting the simulation.
The technique that #Andreas suggests is sometimes called "command harvesting". It is a great way to learn what and how Maya is doing things. But to answer your specific question:
You can use cmds.play() to start playing back on Maya. See the docs for options.
You might want to set the start frame and end frame of the playback range using the cmds.playbackOptions() command. See the docs for options.
So you would do: (relevant explanatory comments added)
# egs. to play from frame 1 to 120
# also note that the playbackSpeed flag is used
# we need to set this to 0 to "play every frame".
# setting maxPlaybackSpeed to 0 will result in free playback, so the playback isn't clamped.
# At this point, playback wouldn't be realtime, but it will be accurate.
# Dynamics and simulations must be played back like this or the nucleus will not evaluate properly.
cmds.playbackOptions(animationStartTime=1, animationEndTime=120, playbackSpeed=0, maxPlaybackSpeed=0)
# now start playback
cmds.play(forward=True)
EDIT: I just noticed that you had asked for MEL commands. Just take the above commands and MEL-ify them, like so:
playbackOptions -e animationStartTime 1 animationEndTime 120 playbackSpeed 0;
play -f 1;
Suggestion: It is best to playblast this playback to watch it in proper fps and playback speed.
Hope that was useful.
In the Script Editor you can tell Maya to "Echo all commands". If you enable that, then do something in the UI, it will output all the MEL commands in the Script Editor.
I'd try using bakeSimulation to convert the sim to ordinary vertex animations. You can then advance time to the desired time and export your OBJ that way.
This will disable the simulation once executed - it's good for getting the results but not editing them.

Manually run GTK event loop

I am trying to integrate GTK (in a .NET application via the gtk-sharp bindings) into an application that already has a "main loop." Calling Gtk.Application.Run() results in the entire thing basically locking up while waiting on the Gtk loop. Furthermore, this app can't really be integrated into GTK in the usual sense (that is, using GTK's idle stuff to pump the app for events).
Is there a way to do the opposite and run the GTK main event loop manually?
Right now I have something like this:
def _pump_gtk():
while true:
if Gtk.Application.EventsPending():
Gtk.Application.RunIteration()
yield
(the yield is because _pump_gtk is running as a coroutine in the main application)
However, this seems to have problems because Gtk doesn't think there is a main loop running? I get a lot of Gtk-CRITICAL **: gtk_main_quit: assertion main_loops != NULL' failed errors.
Is there a way to run the GTK main loop manually?

pygtk vlc player does not play next track

I'm writing a small custom player based on libvlc. I've used much of the code from https://github.com/hartror/python-libvlc-bindings/blob/master/examples/gtkvlc.py that plays a single track just like I need.
Now I want to swtich to another track after previous has finished. To do that I catch callback "EventType.MediaPlayerEndReached" and in callback handler I write code:
<------>def endCallback(self,event):
<------><------>fname = vlc_controller.GetNextTrack()['url']
<------><------>self.w.set_title(fname)
<------><------>self.vlc.player.set_mrl(fname)
<------><------>self.w.set_title('after set_mrl')
<------><------>self.vlc.player.play()
<------><------>self.w.set_title('after play')
Now when this code gets executed it stucks on self.vlc.player.set_mrl(fname) and does not go any further and as a result I see NO NEXT TRACK.
I've tried different variations of this code using (vlc.stop(), vlc.set_media instead of vlc.set_mrl) but nothing works
Finally....
I think the best choise is to make multi threaded application on python
2 Threads:
Main thread - gtk.loop and displaying video an some other thinks
Additional thread that makes media switching.
For some time I was afraid of multithreading but now I know that this was the best way to do this task
For those facing similar issue in C# (Xamarin), per VLC documentation, calling the VLC object from an event tied to the object may freeze the application. So they said to use the code below inside the trigger event.
ThreadPool.QueueUserWorkItem(_ => PlayNext());
An example would be calling the code above inside the EndReach event.
Where PlayNext() is your own custom method to handle the next action you want to execute.
I struggled with this for about a day before seeing that portion of the documentation.

pygtk statusBar will not update from signal handler

So I have been pulling my hair out all day at this, and I am out of patience.
Basically I have a pygtk program that is built from glade. At the bottom of the main window, there is a status bar that I use to display usage errors, and status messages about the connected hardware and they use the functions below. So all of the calls to displayError come from within my object based on user interaction, and they all seem to work. In testing I tried making calls to displayCurrent and it works as well. The problem comes when the hardware process tries to use displayCurrent. The way the system works is that one of the members of my main window class is an interface object to the hardware. This has a separate process, using multiprocessing.Process, which sends a signal every time it gets data with the data being the message to output. Does anyone have any ideas? I'll be happy to explain anything in more depth if needed, it's just a LOT of code to post to get all the details.
def displayCurrent(self, message):
print message
if self.lastMess:
self.statusBar.remove(self.normalID, self.lastMess)
self.lastMess = self.statusBar.push(self.normalID, message)
def displayError(self, message, timeout = 5):
"""
Function that takes an error message and raises it to the user via the statusbar
timeout seconds later.
"""
print message
mess = self.statusBar.push(self.urgentID, message)
# clear statusbar
gobject.timeout_add_seconds(timeout, self.clearStatus, self.urgentID, mess)
def clearStatus(self, cID, mID):
#time.sleep(timeout)
self.statusBar.remove(cID, mID)
#print self.statusBar.remove_all(self.urgentID)
print 'popped'
return False
Post the whole code.
In general, this won't work if you are in a separate process. GTK (and everything else) has been forked. You need to use some form of interprocess communication. Multiprocessing module handles it for you. There are also hacks you can do in GTK such as using a window title (like Vim) or perhaps a plug and socket to communicate; don't be tempted by these.

How do I pause a function in c or objective-c on mac without using sleep()

Hi I would like to pause the execution of a function in an cocoa project. I dont want to use sleep() because the function needs to resume after user interaction. I also want to avoid doing this with multiple calls to sleep.
Thanks for your responses. Ok I started the code while waiting for some answers. I then realized that sleep or pause would not be usefull to me because it freeses my whole program. I think I might have to do some threading. Here is the situation:
I have a program that uses coreplot. I also use it to debug and develop algorithms so I do lots of plots while the data is being processed (ie in the midfle of the code but I need the flexibility to put it anywhaere so I cant separate my function). I was able to do this with NSRunAlertPanel but having a message box like that doesnt make it very presentable and I cant do much with the main window while an alert is open.
I hope I am not too confusing with my explanation but if I am ill try to one line it here:
I would like to interact with my cocoa interface while one of my functions is stopped in the middle of what it is doing.
Its sounds to me like you're looking for -NSRunLoop runUntilDate:
Apple's Docs: runUntilDate
This code will cause the execution within your method to pause but still let other events like timers and user input occur:
while ( functionShouldPause )
{
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1]];
}
Switching functionShouldPause back to false will allow the rest of the method to execute.
It seems more like you are interested in reacting to user events rather than "pausing" the function. You would probably want to put the code that you want to execute into another function that is called as a result of the user's actions.
In C you can use the pause() function in <unistd.h>. This causes the calling program to suspend until it receives a signal, at which point the pause call will return and your program will continue (or call a signal handler; depending on what signal was received).
So it sounds like you want to break the function into two parts; the bit that happens before the sleep and the bit that happens afterward. Before going to sleep, register for a notification that calls the "after" code, and can be triggered by the UI (by an IBAction connected to whatever UI element). Now instead of calling sleep(), run the run loop for the period you want to go to sleep for, then after that has returned post the "after" notification. In the "after" code, remove the object as an observer for that notification. Now, whichever happens first - the time runs out or the user interrupts you - you get to run the "after" code.
Isn't there a clock or timer function? When your button is pressed start running a loop like timeTillAction = 10 and do a loop of timeTillAction = timeTillAction - 1 until it reaches 0 then run whatever code after the 10 seconds.
Sorry if this isn't well explained.