I'm currently trying to make a small module in python that can move the position of a VR headset / controller (physical or virtual). I have been searching for near a month now, and have even tried making my own hardware drivers but the closest thing I can find for what I need is pyopenvr.
I've been trying some of it's samples but I always get this error:
Here is the error (It is detecting an HMD):
Exception has occurred: InitError_Init_HmdNotFound
exception: no description
File "C:\Users\USERNAME\Desktop\HMDmodule\vr\test.py", line 15, in <module>
vr_system = openvr.init(openvr.VRApplication_Scene)
Here is my code:
import sys
import time
import openvr
print("OpenVR test program")
try:
if openvr.isHmdPresent(): print("VR head set found")
if openvr.isRuntimeInstalled(): print("Runtime is installed")
vr_system = openvr.init(openvr.VRApplication_Scene)
print(openvr.getRuntimePath())
print(vr_system.getRecommendedRenderTargetSize())
print(vr_system.isDisplayOnDesktop())
for i in range(10):
xform = vr_system.getEyeToHeadTransform(openvr.Eye_Left)
print(xform)
sys.stdout.flush()
time.sleep(0.2)
openvr.shutdown()
except Exception as e:
print(e)
...
I'm not entirely sure how to fix this as I am relatively new to openvr and am still trying to get it to function properly.
also, if there is a way to create a VR headset and controllers, as in creating an emulated headset without connecting a physical device that would help too. And if there is anything else that could/would be better than this, I will try it as well.
Related
I'm trying to plot netCDF data using cartopy + matplotlib (contourf) call, however on some occasions the data generate invalid polygon instances through contourf and the following error is thrown (Sample), followed by other exceptions:
TopologyException: side location conflict at -83.68749999996696 36.937499999989356
When running the code using contour (not contourf), the plot works, and I can see the invalid geometry in the contours. I am able to address this issue in the contourf call by NAN-ing the value of the point at the location of the side-location conflict.
aLatName = "PRISM_Latitude"
aLonName = "PRISM_Longitude"
tLat = 36.937499999989356
tLon = -83.68749999996696
aLat = np.abs(array[aLatName] - tLat)
aLon = np.abs(array[aLonName] - tLon)
c = np.maximum(aLon, aLat)
([xloc], [yloc]) = np.where(c == np.min(c))
array["data"][yloc, xloc] = np.nan
I'm wondering if there is a way to capture the coordinates of the side location conflict in a try-except block so I can then try the nan approach to fix the issue.
5/30 Edit: I did some rabbit hole digging through the call stack to find out more information and it seems like the error message shown above is not a python exception being thrown but an exception being thrown in C++ and then passed along through the python interpreter, specifically the GEOS library (https://github.com/libgeos/geos/blob/70b1662e9b8f5118f9eef26529e9eeb9eb466544/src/geomgraph/EdgeEndStar.cpp#L312). From what I know about C++ / Python exceptions, I cannot directly "catch" this exception in python unless it exists as a python object already so it looks like this is a dead end, but perhaps this may provide some information to others who may be stuck with a similar problem.
Sometimes an error happens but I don't notice because I may be running multiple cells at once.
I'd like errors to play a sound.
In other words, play a sound when the execution fails, an Exception is raised, when execution errors are found, etc.
Many people would like long running cells to play a sound when completed.
COLAB
I mixed the solutions I found in some places 1 2 3 4
a) Create a global exception handler that beeps on errors
b) Create a simple function that you place at the end of the long-running cell (some other approaches on links)
You can change the sounds to anything you like.
Note: The sounds inside the Exception Handler and the beep_completed() are very different and with reason. The first is short and non-annoying and the second is long and pleasant (in case you are away from computer so you clearly hear that the task is completed). In any case you can replace them.
Note: There is a line that only applies to Colab. If you can provide the one for Jupyter I will gladly update the answer.
# This line is specific for Colab (please provide alternative for Jupyter)
from google.colab import output
from IPython.core.ultratb import AutoFormattedTB
# Catch any Exception, play error sound and re-raise the Exception
#-------------------------------------------------
# initialize the formatter for making the tracebacks into strings
itb = AutoFormattedTB(mode = 'Plain', tb_offset = 1)
# this function will be called on exceptions in any cell
def custom_exc(shell, etype, evalue, tb, tb_offset=None):
# still show the error within the notebook, don't just swallow it
shell.showtraceback((etype, evalue, tb), tb_offset=tb_offset)
# Play an audio beep. Any audio URL will do.
output.eval_js('new Audio("http://soundbible.com/grab.php?id=419&type=wav").play()')
# # grab the traceback and make it into a list of strings
# stb = itb.structured_traceback(etype, evalue, tb)
# sstb = itb.stb2text(stb)
# print (sstb) # <--- this is the variable with the traceback string
# print ("sending mail")
# send_mail_to_myself(sstb)
# this registers a custom exception handler for the whole current notebook
get_ipython().set_custom_exc((Exception,), custom_exc)
#------------------------------------------
# Function to play a sound (to put at the end of a long job)
def beep_completed():
#url_sound="http://soundbible.com/grab.php?id=1795&type=mp3";
output.eval_js('new Audio("http://soundbible.com/grab.php?id=1795&type=mp3").play()')
# Just play it with
beep_completed()
Jupyter
Comment out as needed. If you want to use a local file, you have to download it first and maybe adjust the path.
from IPython.display import Audio, display
# ----- error sound --------
def play_sound_error(self, etype, value, tb, tb_offset=None):
self.showtraceback((etype, value, tb), tb_offset=tb_offset)
v1="http://soundbible.com/grab.php?id=419&type=wav" # Short Error Beep sound
v2="https://wav-sounds.com/wp-content/uploads/2017/09/Various-02.wav" # Short Baby cry
display(Audio(url=v1, autoplay=True))
v1="../sound_error_beep.wav" # Short Error Beep sound
v2="../sound_baby_cry.wav" # Short Baby cry
display(Audio(filename=v1, autoplay=True))
# ----- atach it to all Exceptions
get_ipython().set_custom_exc((Exception,), play_sound_error)
# ----- success sound --------
def play_sound_success():
v1='http://soundbible.com/grab.php?id=1795&type=wav'
#display(Audio(url=v1, autoplay=True))
display(Audio(filename='../sound_success.wav', autoplay=True))
Since in my use cases, the set_custom_exc solution was not acceptable as it did override the previously established custom exceptions, I have created a small notification package that works for both regular scripts (using sys.excepthook) and jupyter notebooks (using post_run_cell).
Furthermore, since I did not like to have a Jingle Bell situation when the cells crash immediately, I have added a customizable minimum time interval based on either the total execution time (when in scripts) or the cell execution time (when in notebooks).
The package comes both as import oneliners such as:
import ringbell.auto
Which will play a sound if the execution takes more than a minute.
Or for immediate notification:
import ringbell.immediate
Or, for notifications exclusively on exceptions:
import ringbell.all_exceptions
You can also use it to play a sound whenever you like, by importing the RingBell class and going:
from ringbell import RingBell
RingBell(
sample = "microwave",
minimum_execution_time = 0,
verbose = True
)
You can get it from PyPi by running:
pip install ringbell
I am writing a python tool that will store attributes of the stereoscopic camera in a scene into a JSON file.
I use this code to get the selected plane with the attributes I need to store
import maya.OpenMaya as om
selected = om.MSelectionList()
om.MGlobal.getActiveSelectionList(selected)
obj = om.MObject()
selected.getDependNode(0,obj)
sel = om.MFnDependencyNode(obj).name()
if sel != "npl_Near_ZP":
cmds.confirmDialog(title= 'Error:', message = 'Error: Please Select the correct plane', button =['OK'])
else:
jsonCreate(sel)
It was working perfectly before but now when I try to the script, I get the following runtime error and I 've sort of hit a wall here cause I don't understand what the problem is
Error: RuntimeError: file S:\Maya_2018_DI\build\Release\runTime\Python\Lib\site-packages\maya\OpenMaya.py line 18296: (kInvalidParameter): Index not in valid range #
I m still new to Maya so any help will be greatly appreciated
update I restarted my computer and the script is now running as it should. Can anyone explain this behaviour in case it happens again
I'm referencing this old thread:
system wide shortcut for Mac OS X
I have been attempting to use this to create a global hotkey for osx since my old method of using pyglobalshortcuts no longer works with PyQt5.
The trouble is that when I listen for 'kCGEventKeyUp' or 'kCGEventKeyDown' in the 'CGEventTapCreate' function, the program exits with code '-11'.
Here's the code I was trying:
import Quartz
from AppKit import NSKeyUp, NSSystemDefined, NSEvent
def keyboardTapCallback(proxy, type_, event, refcon):
keyEvent = NSEvent.eventWithCGEvent_(event)
if keyEvent is None:
pass
else:
print keyEvent
tap = Quartz.CGEventTapCreate(
Quartz.kCGSessionEventTap,
Quartz.kCGHeadInsertEventTap,
Quartz.kCGEventTapOptionListenOnly,
# Quartz.kCGEventMaskForAllEvents,
Quartz.CGEventMaskBit(Quartz.kCGEventKeyUp),
keyboardTapCallback,
None
)
runLoopSource = Quartz.CFMachPortCreateRunLoopSource(None, tap, 0)
Quartz.CFRunLoopAddSource(
Quartz.CFRunLoopGetCurrent(),
runLoopSource,
Quartz.kCFRunLoopDefaultMode
)
Quartz.CGEventTapEnable(tap, True)
try:
Quartz.CFRunLoopRun()
except Exception as e:
print e, "<<<<<<<<<<<<<<<"
I also tried replacing 'Quartz.kCGEventMaskBit(Quartz.kCGEventKeyUp)' with 'Quartz.kCGEventMaskForAllEvents' and while this did not fail it also isn't returning any alphanumeric keys (I need to be able to use 'ctrl+shift+d' as my shortcut).
Am I terribly far off with being able to detect this shortcut in Quartz or is there a better method in OSX?
Thanks,
-Mark
I think I just figured it out. I'm using a shared keyboard through Synergy. When I went back to my mac keyboard, it could detect the key events.
Thanks!
-Mark
I have been trying to use the Python GPIO PWM to control a set of LEDs connected to my RPi. When I run the Python script, I get the following error:
Traceback (most recent call last):
File "cycle.py", line 12, in <module>
r = GPIO.PWM(f, RED)
RuntimeError: No access to /dev/mem. Try running as root!
I have tried running the script as root (both with sudo and with actually logging in as root). All of the other GPIO functions work correctly and I have tried doing an update and uninstalling/reinstalling python-rpi.gpio through apt. Here is the code I have been running.
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
RED = 11
f = 100
r = GPIO.PWM(RED, f) <== Where it crashes
r.start(0)
try:
while 1:
for dc in range(0, 101, 5):
r.ChangeDutyCycle(dc)
time.sleep(0.1)
for dc in range(100, -1, 5):
r.ChangeDutyCycle(dc)
time.sleep(0.1)
except:
pass
r.stop()
GPIO.cleanup()
It is based off of the example found here, but there could still be bugs. I have been struggling with this for quite a bit now so any help provided would be greatly appreciated. Thanks!
The problem is with the code above is that I forgot to set RED to at output before trying to use it. The error message did not help resolve this problem. Next time, I need to remember to setup PWM pins as outputs before trying to use them.