def __init__(self, imageManager, imageNames, view, visible=True, robotName=None): self.view = view self.imageManager = imageManager self.robotName = robotName self.imageNames = imageNames self.visible = visible self.widgetWidth = 400 self.showNonMainImages = True # if false, show only imageNames[0] self.updateUtime = 0 self.initialized = False # these two data structures are initialized when data is received self.imageWidgets = [None for i in range(0, len(self.imageNames))] self.flips = [None for i in range(0, len(self.imageNames))] self.eventFilter = PythonQt.dd.ddPythonEventFilter() self.view.installEventFilter(self.eventFilter) self.eventFilter.addFilteredEventType(QtCore.QEvent.Resize) self.eventFilter.connect("handleEvent(QObject*, QEvent*)", self.onResizeEvent) self.timerCallback = TimerCallback() self.timerCallback.targetFps = 60 self.timerCallback.callback = self.updateView self.timerCallback.start()
def __init__(self, view): TimerCallback.__init__(self) self.view = view self.flyTime = 0.5 self.startTime = 0.0 self.maintainViewDirection = False self.positionZoom = 0.7
def initView(self, view): # Must call the createview function with the robot name so that the view can be associated, but cannot pass # keyword arguments to python_qt functions so need to also pass the -1 to add the tab to the end of the list # rather than insert it. self.view = view or app.getViewManager().createView( self.viewName, "VTK View", -1, self.robotName) app.getRobotSelector().associateViewWithRobot(self.view, self.robotName) self.view.installImageInteractor() # self.interactorStyle = self.view.renderWindow().GetInteractor().GetInteractorStyle() # self.interactorStyle.AddObserver('SelectionChangedEvent', self.onRubberBandPick) self.imageActor = vtk.vtkImageActor() self.imageActor.SetInputData(self.getImage()) self.imageActor.SetVisibility(False) self.view.renderer().AddActor(self.imageActor) self.view.orientationMarkerWidget().Off() self.view.backgroundRenderer().SetBackground(0, 0, 0) self.view.backgroundRenderer().SetBackground2(0, 0, 0) self.timerCallback = TimerCallback() self.timerCallback.targetFps = 60 self.timerCallback.callback = self.updateView self.timerCallback.start()
def __init__(self, spindleMonitor): self.spindleMonitor = spindleMonitor self.timer = TimerCallback(targetFps=3) self.timer.callback = self.update self.warningButton = None self.action = None
def __init__(self, propertySet, propertiesPanel, propertyNamesToAdd=None): self.propertySet = propertySet self.propertyNamesToAdd = propertyNamesToAdd self.propertiesPanel = propertiesPanel self.connections = [] self.connections.append( self.propertySet.connectPropertyAdded(self._onPropertyAdded) ) self.connections.append( self.propertySet.connectPropertyChanged(self._onPropertyChanged) ) self.connections.append( self.propertySet.connectPropertyAttributeChanged( self._onPropertyAttributeChanged ) ) self.propertiesPanel.connect( "propertyValueChanged(QtVariantProperty*)", self._onPanelPropertyChanged ) self.timer = TimerCallback() self.timer.callback = self._rebuildNow self._blockSignals = True PropertyPanelHelper.addPropertiesToPanel( self.propertySet, self.propertiesPanel, self.propertyNamesToAdd ) self._blockSignals = False
def start(enableAutomaticQuit=True): ''' In testing mode, the application will quit automatically after starting unless enableAutomaticQuit is set to False. Tests that need to perform work after the QApplication has started can set this flag to False and call quit or exit themselves. In testing mode, this function will register an exception hook so that tests will return on error code if an unhandled exception is raised. ''' if enableAutomaticQuit: ConsoleApp.startTestingModeQuitTimer() if ConsoleApp.getTestingEnabled() and not ConsoleApp.getTestingInteractiveEnabled(): sys.excepthook = _consoleAppExceptionHook def onStartup(): for func in ConsoleApp._startupCallbacks: try: func() except: print traceback.format_exc() startTimer = TimerCallback(callback=onStartup) startTimer.singleShot(0) result = ConsoleApp.applicationInstance().exec_() if ConsoleApp.getTestingEnabled() and not ConsoleApp.getTestingInteractiveEnabled(): print 'TESTING PROGRAM RETURNING EXIT CODE:', result sys.exit(result) return result
def __init__(self): self.timer = TimerCallback(targetFps=10) #self.timer.disableScheduledTimer() self.app = ConsoleApp() self.robotModel, self.jointController = roboturdf.loadRobotModel( 'robot model') self.fpsCounter = simpletimer.FPSCounter() self.drakePoseJointNames = robotstate.getDrakePoseJointNames() self.fpsCounter.printToConsole = True self.timer.callback = self._tick self._initialized = False self.publishChannel = 'JOINT_POSITION_GOAL' # self.lastCommandMessage = newAtlasCommandMessageAtZero() self._numPositions = len(robotstate.getDrakePoseJointNames()) self._previousElapsedTime = 100 self._baseFlag = 0 self.jointLimitsMin = np.array([ self.robotModel.model.getJointLimits(jointName)[0] for jointName in robotstate.getDrakePoseJointNames() ]) self.jointLimitsMax = np.array([ self.robotModel.model.getJointLimits(jointName)[1] for jointName in robotstate.getDrakePoseJointNames() ]) self.useControllerFlag = False self.drivingGainsFlag = False self.applyDefaults()
def onRobotPlan(self, msg): playback = planplayback.PlanPlayback() playback.interpolationMethod = 'pchip' poseTimes, poses = playback.getPlanPoses(msg) f = playback.getPoseInterpolator(poseTimes, poses) jointController = self.robotSystem.teleopJointController timer = simpletimer.SimpleTimer() def setPose(pose): jointController.setPose('plan_playback', pose) self.jointTeleopPanel.endPose = pose self.jointTeleopPanel.updateSliders() commandStream.setGoalPose(pose) def updateAnimation(): tNow = timer.elapsed() if tNow > poseTimes[-1]: pose = poses[-1] setPose(pose) return False pose = f(tNow) setPose(pose) self.animationTimer = TimerCallback() self.animationTimer.targetFps = 60 self.animationTimer.callback = updateAnimation self.animationTimer.start()
def main(): app = consoleapp.ConsoleApp() meshCollection = lcmobjectcollection.LCMObjectCollection('MESH_COLLECTION_COMMAND') affordanceCollection = lcmobjectcollection.LCMObjectCollection('AFFORDANCE_COLLECTION_COMMAND') meshCollection.sendEchoRequest() affordanceCollection.sendEchoRequest() def printCollection(): print print '----------------------------------------------------' print datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') print '%d affordances' % len(affordanceCollection.collection) for desc in affordanceCollection.collection.values(): print print 'name:', desc['Name'] print 'type:', desc['classname'] timer = TimerCallback(targetFps=0.2) timer.callback = printCollection timer.start() #app.showPythonConsole() app.start()
class AnimateRobot(object): def __init__(self, obj, view): self.obj = obj self.view = view self.timer = TimerCallback(targetFps=60) self.timer.callback = self.tick def start(self): self.startTime = time.time() self.timer.start() def stop(self): self.timer.stop() def tick(self): tNow = time.time() elapsed = tNow - self.startTime x, y = np.sin(elapsed), np.cos(elapsed) angle = -elapsed t = vtk.vtkTransform() t.PostMultiply() t.RotateZ(np.degrees(angle)) t.Translate(x, y, 0) self.obj.getChildFrame().copyFrame(t) self.view.render()
def __init__(self, view): self.view = view self.depthImage = None self.pointCloudObj = None self.renderObserver = None self.windowToDepthBuffer = vtk.vtkWindowToImageFilter() self.windowToDepthBuffer.SetInput(self.view.renderWindow()) self.windowToDepthBuffer.SetInputBufferTypeToZBuffer() self.windowToDepthBuffer.ShouldRerenderOff() self.windowToColorBuffer = vtk.vtkWindowToImageFilter() self.windowToColorBuffer.SetInput(self.view.renderWindow()) self.windowToColorBuffer.SetInputBufferTypeToRGB() self.windowToColorBuffer.ShouldRerenderOff() useBackBuffer = False if useBackBuffer: self.windowToDepthBuffer.ReadFrontBufferOff() self.windowToColorBuffer.ReadFrontBufferOff() self.initDepthImageView() self.initPointCloudView() self._block = False self.singleShotTimer = TimerCallback() self.singleShotTimer.callback = self.update
def __init__(self, minValue=0.0, maxValue=1.0, resolution=1000): self._value = 0.0 self.spinbox = QtGui.QDoubleSpinBox() self.spinbox.setSuffix('s') self.slider = QtGui.QSlider(QtCore.Qt.Horizontal) self.playButton = QtGui.QPushButton('Play') self.setValueRange(minValue, maxValue) self.setResolution(resolution) self.slider.connect('valueChanged(int)', self._onSliderValueChanged) self.spinbox.connect('valueChanged(double)', self._onSpinboxValueChanged) self.playButton.connect('clicked()', self._onPlayClicked) self.widget = QtGui.QWidget() layout = QtGui.QHBoxLayout(self.widget) layout.addWidget(self.playButton) layout.addWidget(self.spinbox) layout.addWidget(self.slider) self.animationPrevTime = 0.0 self.animationRate = 1.0 self.animationRateTarget = 1.0 self.animationRateAlpha = 1.0 self.animationTimer = TimerCallback(callback=self._tick, targetFps=60) self.useRealTime = True self.callbacks = callbacks.CallbackRegistry(self.events._fields) self.eventFilter = PythonQt.dd.ddPythonEventFilter() self.eventFilter.connect('handleEvent(QObject*, QEvent*)', self._filterEvent) self.eventFilter.addFilteredEventType(QtCore.QEvent.MouseButtonPress) self.eventFilter.addFilteredEventType(QtCore.QEvent.MouseMove) self.slider.installEventFilter(self.eventFilter)
def __init__(self, image_handler): self._name = 'Image View' self._view = PythonQt.dd.ddQVTKWidgetView() self._image_handler = image_handler self._image = vtk.vtkImageData() self._prev_attrib = None # Initialize the view. self._view.installImageInteractor() # Add actor. self._image_actor = vtk.vtkImageActor() vtk_SetInputData(self._image_actor, self._image) self._image_actor.SetVisibility(False) self._view.renderer().AddActor(self._image_actor) self._view.orientationMarkerWidget().Off() self._view.backgroundRenderer().SetBackground(0, 0, 0) self._view.backgroundRenderer().SetBackground2(0, 0, 0) self._depth_mapper = None # Add timer. self._render_timer = TimerCallback(targetFps=60, callback=self.render) self._render_timer.start()
class LCMForceDisplay(object): ''' Displays foot force sensor signals in a status bar widget or label widget ''' def onRobotState(self,msg): self.l_foot_force_z = msg.force_torque.l_foot_force_z self.r_foot_force_z = msg.force_torque.r_foot_force_z def __init__(self, channel, statusBar=None): self.sub = lcmUtils.addSubscriber(channel, lcmbotcore.robot_state_t, self.onRobotState) self.label = QtGui.QLabel('') statusBar.addPermanentWidget(self.label) self.timer = TimerCallback(targetFps=10) self.timer.callback = self.showRate self.timer.start() self.l_foot_force_z = 0 self.r_foot_force_z = 0 def __del__(self): lcmUtils.removeSubscriber(self.sub) def showRate(self): global leftInContact, rightInContact self.label.text = '%.2f | %.2f' % (self.l_foot_force_z,self.r_foot_force_z)
def main(): app = consoleapp.ConsoleApp() meshCollection = lcmobjectcollection.LCMObjectCollection( 'MESH_COLLECTION_COMMAND') affordanceCollection = lcmobjectcollection.LCMObjectCollection( 'AFFORDANCE_COLLECTION_COMMAND') meshCollection.sendEchoRequest() affordanceCollection.sendEchoRequest() def printCollection(): print print '----------------------------------------------------' print datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') print '%d affordances' % len(affordanceCollection.collection) for desc in affordanceCollection.collection.values(): print print 'name:', desc['Name'] print 'type:', desc['classname'] timer = TimerCallback(targetFps=0.2) timer.callback = printCollection timer.start() #app.showPythonConsole() app.start()
def __init__(self, obj, propertyName, targetValue, animationTime=1.0): self.obj = obj self.propertyName = propertyName self.animationTime = animationTime self.targetValue = targetValue self.timer = TimerCallback()
def playPoses(self, poseTimes, poses, jointController): f = self.getPoseInterpolator(poseTimes, poses) timer = SimpleTimer() def updateAnimation(): tNow = timer.elapsed() * self.playbackSpeed if tNow > poseTimes[-1]: pose = poses[-1] jointController.setPose("plan_playback", pose) if self.animationCallback: self.animationCallback() return False pose = f(tNow) jointController.setPose("plan_playback", pose) if self.animationCallback: self.animationCallback() self.animationTimer = TimerCallback() self.animationTimer.targetFps = 60 self.animationTimer.callback = updateAnimation self.animationTimer.start() updateAnimation()
def startApplication(enableQuitTimer=False): appInstance = QtGui.QApplication.instance() if enableQuitTimer: quitTimer = TimerCallback() quitTimer.callback = appInstance.quit quitTimer.singleShot(0.1) appInstance.exec_()
def __init__(self, imageManager, imageName, view, visible=True): self.view = view self.imageManager = imageManager self.imageName = imageName self.visible = visible self.updateUtime = 0 self.initialized = False self.imageWidget = vtk.vtkLogoWidget() imageRep = self.imageWidget.GetRepresentation() self.imageWidget.ResizableOff() self.imageWidget.SelectableOn() imageRep.GetImageProperty().SetOpacity(1.0) self.imageWidget.SetInteractor( self.view.renderWindow().GetInteractor()) self.flip = vtk.vtkImageFlip() self.flip.SetFilteredAxis(1) self.flip.SetInput(imageManager.getImage(imageName)) imageRep.SetImage(self.flip.GetOutput()) self.eventFilter = PythonQt.dd.ddPythonEventFilter() self.view.installEventFilter(self.eventFilter) self.eventFilter.addFilteredEventType(QtCore.QEvent.Resize) self.eventFilter.connect('handleEvent(QObject*, QEvent*)', self.onResizeEvent) self.timerCallback = TimerCallback() self.timerCallback.targetFps = 60 self.timerCallback.callback = self.updateView self.timerCallback.start()
class LCMForceDisplay(object): ''' Displays foot force sensor signals in a status bar widget or label widget ''' def onRobotState(self, msg): self.l_foot_force_z = msg.force_torque.l_foot_force_z self.r_foot_force_z = msg.force_torque.r_foot_force_z def __init__(self, channel, statusBar=None): self.sub = lcmUtils.addSubscriber(channel, lcmbotcore.robot_state_t, self.onRobotState) self.label = QtGui.QLabel('') statusBar.addPermanentWidget(self.label) self.timer = TimerCallback(targetFps=10) self.timer.callback = self.showRate self.timer.start() self.l_foot_force_z = 0 self.r_foot_force_z = 0 def __del__(self): lcmUtils.removeSubscriber(self.sub) def showRate(self): global leftInContact, rightInContact self.label.text = '%.2f | %.2f' % (self.l_foot_force_z, self.r_foot_force_z)
def __init__(self, view): self.view = view loader = QtUiTools.QUiLoader() uifile = QtCore.QFile(':/ui/ddFrameVisualization.ui') assert uifile.open(uifile.ReadOnly) self.widget = loader.load(uifile) self.ui = WidgetDict(self.widget.children()) self.botFrameUpdater = BotFrameUpdater(self.ui.botFramesListWidget) robotModel = om.findObjectByName('robot state model') self.linkFrameUpdater = LinkFrameUpdater(robotModel, self.ui.linkFramesListWidget) self.eventFilter = PythonQt.dd.ddPythonEventFilter() self.ui.scrollArea.installEventFilter(self.eventFilter) self.eventFilter.addFilteredEventType(QtCore.QEvent.Resize) self.eventFilter.connect('handleEvent(QObject*, QEvent*)', self.onEvent) PythonQt.dd.ddGroupBoxHider(self.ui.botFramesGroup) PythonQt.dd.ddGroupBoxHider(self.ui.linkFramesGroup) self.updateTimer = TimerCallback(targetFps=60) self.updateTimer.callback = self.updateFrames self.updateTimer.start()
def _initTaskPanel(self): self.lastStatusMessage = '' self.nextStepTask = None self.completedTasks = [] self.taskQueue = atq.AsyncTaskQueue() self.taskQueue.connectQueueStarted(self.onQueueStarted) self.taskQueue.connectQueueStopped(self.onQueueStopped) self.taskQueue.connectTaskStarted(self.onTaskStarted) self.taskQueue.connectTaskEnded(self.onTaskEnded) self.taskQueue.connectTaskPaused(self.onTaskPaused) self.taskQueue.connectTaskFailed(self.onTaskFailed) self.taskQueue.connectTaskException(self.onTaskException) self.timer = TimerCallback(targetFps=2) self.timer.callback = self.updateTaskStatus self.timer.start() self.taskTree = tmw.TaskTree() self.ui.taskFrame.layout().insertWidget(0, self.taskTree.treeWidget) l = QtGui.QVBoxLayout(self.ui.taskPropertiesGroupBox) l.addWidget(self.taskTree.propertiesPanel) PythonQt.dd.ddGroupBoxHider(self.ui.taskPropertiesGroupBox) self.ui.taskStepButton.connect('clicked()', self.onStep) self.ui.taskContinueButton.connect('clicked()', self.onContinue) self.ui.taskPauseButton.connect('clicked()', self.onPause) self.ui.promptAcceptButton.connect('clicked()', self.onAcceptPrompt) self.ui.promptRejectButton.connect('clicked()', self.onRejectPrompt) self.clearPrompt() self.updateTaskButtons()
def __init__(self, frameProvider): vis.PolyDataItem.__init__(self, 'spindle axis', vtk.vtkPolyData(), view=None) self.frameProvider = frameProvider self.timer = TimerCallback() self.timer.callback = self.update self.setProperty('Color', QtGui.QColor(0, 255, 0)) self.setProperty('Visible', False)
def __init__(self, view, channelName, coordinateFrame, sensorName, intensityRange): TimerCallback.__init__(self) self.view = view self.channelName = channelName self.reader = None self.displayedRevolution = -1 self.lastScanLine = 0 self.numberOfScanLines = 1000 self.nextScanLineId = 0 self.scanLines = [] self.pointSize = 1 self.alpha = 0.5 self.visible = True self.colorBy = 'Solid Color' self.initScanLines() self.sensorName = sensorName self.coordinateFrame = coordinateFrame self.revPolyData = vtk.vtkPolyData() self.polyDataObj = vis.PolyDataItem('Lidar Sweep', self.revPolyData, view) self.polyDataObj.actor.SetPickable(1) self.polyDataObj.setRangeMap('intensity', intensityRange) self.setPointSize(self.pointSize) self.setAlpha(self.alpha) self.targetFps = 60 self.colorizeCallback = None
def start(enableAutomaticQuit=True): """ In testing mode, the application will quit automatically after starting unless enableAutomaticQuit is set to False. Tests that need to perform work after the QApplication has started can set this flag to False and call quit or exit themselves. In testing mode, this function will register an exception hook so that tests will return on error code if an unhandled exception is raised. """ if enableAutomaticQuit: ConsoleApp.startTestingModeQuitTimer() if (ConsoleApp.getTestingEnabled() and not ConsoleApp.getTestingInteractiveEnabled()): sys.excepthook = _consoleAppExceptionHook def onStartup(): for func in ConsoleApp._startupCallbacks: try: func() except: print traceback.format_exc() startTimer = TimerCallback(callback=onStartup) startTimer.singleShot(0) result = ConsoleApp.applicationInstance().exec_() if (ConsoleApp.getTestingEnabled() and not ConsoleApp.getTestingInteractiveEnabled()): print "TESTING PROGRAM RETURNING EXIT CODE:", result sys.exit(result) return result
def __init__( self, view, channelName, coordinateFrame, sensorName, intensityRange=(400, 4000) ): TimerCallback.__init__(self) self.view = view self.channelName = channelName self.reader = None self.displayedRevolution = -1 self.lastScanLine = 0 self.numberOfScanLines = 100 self.nextScanLineId = 0 self.scanLines = [] self.pointSize = 1 self.alpha = 0.5 self.visible = True self.colorBy = "Solid Color" self.intensityRange = intensityRange self.initScanLines() self.sensorName = sensorName self.coordinateFrame = coordinateFrame self.revPolyData = vtk.vtkPolyData() self.polyDataObj = vis.PolyDataItem("Lidar Sweep", self.revPolyData, view) self.polyDataObj.actor.SetPickable(1) self.polyDataObj.setRangeMap("intensity", intensityRange) self.setPointSize(self.pointSize) self.setAlpha(self.alpha) self.targetFps = 60 self.colorizeCallback = None
def __init__(self, robotStateJointController, view, cameraview, mapServerSource): self.robotStateJointController = robotStateJointController self.view = view self.cameraview = cameraview self.mapServerSource = mapServerSource self.lastCameraMessageTime = 0 self.lastScanBundleMessageTime = 0 self.lastBlackoutLengths = [] self.lastBlackoutLength = 0 self.inBlackout = False self.averageBlackoutLength = 0.0 self.txt = vis.updateText("DATA AGE: 0 sec", "Data Age Text", view=self.view) self.txt.addProperty('Show Avg Duration', False) self.txt.setProperty('Visible', False) self.updateTimer = TimerCallback(self.UPDATE_RATE) self.updateTimer.callback = self.update self.updateTimer.start()
class RosSubscriberManager(object): """A helper class for managing rospy subscribers and dispatching callbacks.""" def __init__(self): self.msgs = {} self.pending_msgs = {} self.counters = {} self.subs = OrderedDict() self.callbacks = OrderedDict() def init_node(self): rospy.init_node('director_rospy_node', anonymous=True) def on_idle(): time.sleep(0.0001) self.idle_timer = TimerCallback(callback=on_idle, targetFps=100) self.idle_timer.start() self.dispatch_timer = TimerCallback(targetFps=30) self.dispatch_timer.callback = self.on_dispatch_timer self.dispatch_timer.start() def get_estimated_topic_hz(self, topic_name): assert topic_name in self.counters return self.counters[topic_name].getAverageFPS() def get_latest_msg(self, topic_name): return self.msgs.get(topic_name) def subscribe(self, topic_name, message_type, message_function=None, call_on_thread=False): def on_message(msg): self.msgs[topic_name] = msg self.counters[topic_name].tick() if call_on_thread and message_function: message_function(topic_name, msg) else: self.pending_msgs[topic_name] = msg self.counters[topic_name] = FPSCounter() self.callbacks[topic_name] = message_function self.subs[topic_name] = rospy.Subscriber(topic_name, message_type, on_message) def handle_pending_message(self, topic_name): msg = self.pending_msgs.pop(topic_name, None) if msg is not None: callback = self.callbacks.get(topic_name) if callback: callback(topic_name, msg) def handle_pending_messages(self): for topic_name in list(self.pending_msgs.keys()): self.handle_pending_message(topic_name) def on_dispatch_timer(self): self.handle_pending_messages()
def __init__(self, imageManager, view=None, robotName=""): self.imageManager = imageManager self.updateUtimes = {} self.robotModel = None self.sphereObjects = {} self.robotName = robotName try: if self.robotName: self.images = [ camera["name"] for camera in drcargs.getRobotConfig( self.robotName)["sensors"]["camera"]["color"] ] except KeyError as e: raise Exception( "CameraView requires color cameras to be defined at sensors/camera/color." " Check your director config.") for name in self.images: imageManager.addImage(name, self.robotName) self.updateUtimes[name] = 0 self.initView(view) self.initEventFilter() self.rayCallback = rayDebug self.timerCallback = TimerCallback() self.timerCallback.targetFps = 60 self.timerCallback.callback = self.updateView self.timerCallback.start()
def start(self): if self.reader is None: self.reader = drc.vtkMultisenseSource() self.reader.InitBotConfig(drcargs.args().config_file) self.reader.SetDistanceRange(0.25, 4.0) self.reader.Start() TimerCallback.start(self)
def __init__(self, atlasDriver, statusBar): self.atlasDriver = atlasDriver self.label = QtGui.QLabel('') statusBar.addPermanentWidget(self.label) self.timer = TimerCallback(targetFps=1) self.timer.callback = self.showRate self.timer.start()
def __init__(self, lDriver, rDriver, robotStateModel, robotStateJointController, view): self.robotStateModel = robotStateModel self.robotStateJointController = robotStateJointController self.drivers = {} self.drivers['left'] = lDriver self.drivers['right'] = rDriver self.storedCommand = {'left': None, 'right': None} loader = QtUiTools.QUiLoader() uifile = QtCore.QFile(':/ui/ddHandControl.ui') assert uifile.open(uifile.ReadOnly) self.widget = loader.load(uifile) self.ui = WidgetDict(self.widget.children()) self._updateBlocked = True self.widget.advanced.sendButton.setEnabled(True) # Store calibration for wrist f/t sensors self.wristftvis = WristForceTorqueVisualizer(robotStateModel, robotStateJointController, view) # connect the callbacks self.widget.basic.openButton.clicked.connect(self.openClicked) self.widget.basic.closeButton.clicked.connect(self.closeClicked) self.widget.basic.waitOpenButton.clicked.connect(self.waitOpenClicked) self.widget.basic.waitCloseButton.clicked.connect(self.waitCloseClicked) self.widget.advanced.sendButton.clicked.connect(self.sendClicked) self.widget.advanced.calibrateButton.clicked.connect(self.calibrateClicked) self.widget.advanced.setModeButton.clicked.connect(self.setModeClicked) self.widget.advanced.regraspButton.clicked.connect(self.regraspClicked) self.widget.advanced.dropButton.clicked.connect(self.dropClicked) self.widget.advanced.repeatRateSpinner.valueChanged.connect(self.rateSpinnerChanged) self.ui.fingerControlButton.clicked.connect(self.fingerControlButton) self.widget.sensors.rightTareButton.clicked.connect(self.wristftvis.tareRightFT) self.widget.sensors.leftTareButton.clicked.connect(self.wristftvis.tareLeftFT) self.widget.sensors.rightCalibButton.clicked.connect(self.wristftvis.calibRightFT) self.widget.sensors.leftCalibButton.clicked.connect(self.wristftvis.calibLeftFT) self.widget.sensors.rightCalibClearButton.clicked.connect(self.wristftvis.calibRightClearFT) self.widget.sensors.leftCalibClearButton.clicked.connect(self.wristftvis.calibLeftClearFT) self.widget.sensors.rightVisCheck.clicked.connect(self.updateWristFTVis) self.widget.sensors.leftVisCheck.clicked.connect(self.updateWristFTVis) self.widget.sensors.torqueVisCheck.clicked.connect(self.updateWristFTVis) PythonQt.dd.ddGroupBoxHider(self.ui.sensors) PythonQt.dd.ddGroupBoxHider(self.ui.fingerControl) # Bug fix... for some reason one slider is set as disabled self.ui.fingerASlider.setEnabled(True) # create a timer to repeat commands self.updateTimer = TimerCallback() self.updateTimer.callback = self.updatePanel self.updateTimer.targetFps = 3 self.updateTimer.start()
def start(self): if self.reader is None: self.reader = drc.vtkLidarSource() self.reader.InitBotConfig(drcargs.args().config_file) self.reader.SetDistanceRange(0.25, 80.0) self.reader.SetHeightRange(-80.0, 80.0) self.reader.Start() TimerCallback.start(self)
def __init__(self): self.interval = 1 / 60.0 sys.setcheckinterval(1000) #sys.setswitchinterval(self.interval) # sys.setswitchinterval is only Python 3 self.taskQueue = asynctaskqueue.AsyncTaskQueue() self.pendingTasks = [] self.threads = [] self.timer = TimerCallback(callback=self._onTimer, targetFps=1 / self.interval)
class BlackoutMonitor(object): UPDATE_RATE = 5 AVERAGE_N = 5 def __init__(self, robotStateJointController, view, cameraview, mapServerSource): self.robotStateJointController = robotStateJointController self.view = view self.cameraview = cameraview self.mapServerSource = mapServerSource self.lastCameraMessageTime = 0 self.lastScanBundleMessageTime = 0 self.lastBlackoutLengths = [] self.lastBlackoutLength = 0 self.inBlackout = False self.averageBlackoutLength = 0.0 self.txt = vis.updateText("DATA AGE: 0 sec", "Data Age Text", view=self.view) self.txt.addProperty('Show Avg Duration', False) self.txt.setProperty('Visible', False) self.updateTimer = TimerCallback(self.UPDATE_RATE) self.updateTimer.callback = self.update self.updateTimer.start() def update(self): self.lastCameraMessageTime = self.cameraview.imageManager.queue.getCurrentImageTime('CAMERA_LEFT') self.lastScanBundleMessageTime = self.mapServerSource.reader.GetLastScanBundleUTime() if self.robotStateJointController.lastRobotStateMessage: elapsedCam = max((self.robotStateJointController.lastRobotStateMessage.utime - self.lastCameraMessageTime) / (1000*1000), 0.0) elapsedScan = max((self.robotStateJointController.lastRobotStateMessage.utime - self.lastScanBundleMessageTime) / (1000*1000), 0.0) # can't be deleted, only hidden, so this is ok if (self.txt.getProperty('Visible')): if (self.txt.getProperty('Show Avg Duration')): textstr = "CAM AGE: %02d sec\nSCAN AGE: %02d sec AVG: %02d sec" % (math.floor(elapsedCam), math.floor(elapsedScan), math.floor(self.averageBlackoutLength)) else: textstr = "CAM AGE: %02d sec\nSCAN AGE: %02d sec" % (math.floor(elapsedCam), math.floor(elapsedScan)) ssize = self.view.size self.txt.setProperty('Text', textstr) self.txt.setProperty('Position', [10, 10]) # count out blackouts if elapsedCam > 1.0: self.inBlackout = True self.lastBlackoutLength = elapsedCam else: if (self.inBlackout): # Don't count huge time jumps due to init if (self.lastBlackoutLength < 100000): self.lastBlackoutLengths.append(self.lastBlackoutLength) if len(self.lastBlackoutLengths) > self.AVERAGE_N: self.lastBlackoutLengths.pop(0) if len(self.lastBlackoutLengths) > 0: self.averageBlackoutLength = sum(self.lastBlackoutLengths) / float(len(self.lastBlackoutLengths)) self.inBlackout = False
def init_node(self): rospy.init_node('director_rospy_node', anonymous=True) def on_idle(): time.sleep(0.0001) self.idle_timer = TimerCallback(callback=on_idle, targetFps=100) self.idle_timer.start() self.dispatch_timer = TimerCallback(targetFps=30) self.dispatch_timer.callback = self.on_dispatch_timer self.dispatch_timer.start()
def start(self): if self.reader is None: self.reader = drc.vtkLidarSource() self.reader.subscribe(self.channelName) self.reader.setCoordinateFrame(self.coordinateFrame) self.reader.InitBotConfig(drcargs.args().config_file) self.reader.SetDistanceRange(0.25, 80.0) self.reader.SetHeightRange(-80.0, 80.0) self.reader.Start() TimerCallback.start(self)
def start(self): if self.reader is None: self.reader = drc.vtkMultisenseSource() self.reader.InitBotConfig(drcargs.args().config_file) self.reader.SetDistanceRange(0.25, 4.0) self.reader.SetHeightRange(-80.0, 80.0) self.reader.Start() self.setIntensityRange(400, 4000) TimerCallback.start(self)
def __init__(self, view, callbackFunc=None): TimerCallback.__init__(self) self.reader = None self.folder = None self.view = view self.displayedMapIds = {} self.polyDataObjects = {} self.targetFps = 10 self.callbackFunc = callbackFunc self.colorizeCallback = None self.useMeshes = True
class TriggerFingerPublisher(): def __init__(self, lcmChannel): self.lcmChannel = lcmChannel self.reader = midi.MidiReader() self.timer = TimerCallback() self.timer.callback = self.tick self.msg = lcmdrc.trigger_finger_t() def startPublishing(self): print 'Publishing on ' + self.lcmChannel self.timer.start() def publish(self): messages = self.reader.getMessages() for message in messages: channel = message[2] val = message[3] / 127.0 if channel is 102: self.msg.slider1 = val elif channel is 103: self.msg.slider2 = val elif channel is 104: self.msg.slider3 = val elif channel is 105: self.msg.slider4 = val elif channel is 106: self.msg.knob1 = val elif channel is 107: self.msg.knob2 = val elif channel is 108: self.msg.knob3 = val elif channel is 109: self.msg.knob4 = val elif channel is 110: self.msg.knob5 = val elif channel is 111: self.msg.knob6 = val elif channel is 112: self.msg.knob7 = val elif channel is 113: self.msg.knob8 = val if len(messages) is not 0: self.msg.utime = getUtime() lcmUtils.publish(self.lcmChannel, self.msg) def tick(self): self.publish()
class CommittedRobotPlanListener(object): def __init__(self): self.sub = lcmUtils.addSubscriber('COMMITTED_ROBOT_PLAN', lcmdrc.robot_plan_t, self.onRobotPlan) lcmUtils.addSubscriber('COMMITTED_PLAN_PAUSE', lcmdrc.plan_control_t, self.onPause) self.animationTimer = None def onPause(self, msg): commandStream.stopStreaming() if self.animationTimer: self.animationTimer.stop() def onRobotPlan(self, msg): playback = planplayback.PlanPlayback() playback.interpolationMethod = 'pchip' poseTimes, poses = playback.getPlanPoses(msg) f = playback.getPoseInterpolator(poseTimes, poses) print 'received robot plan, %.2f seconds' % (poseTimes[-1] - poseTimes[0]) commandStream.applyPlanDefaults() commandStream.startStreaming() timer = simpletimer.SimpleTimer() def setPose(pose): commandStream.setGoalPose(pose) def updateAnimation(): tNow = timer.elapsed() if tNow > poseTimes[-1]: pose = poses[-1] setPose(pose) commandStream.applyDefaults() print 'plan ended.' return False pose = f(tNow) setPose(pose) self.animationTimer = TimerCallback() self.animationTimer.targetFps = 1000 self.animationTimer.callback = updateAnimation self.animationTimer.start()
class PropertyPanelConnector(object): def __init__(self, propertySet, propertiesPanel, propertyNamesToAdd=None): self.propertySet = propertySet self.propertyNamesToAdd = propertyNamesToAdd self.propertiesPanel = propertiesPanel self.connections = [] self.connections.append(self.propertySet.connectPropertyAdded(self._onPropertyAdded)) self.connections.append(self.propertySet.connectPropertyChanged(self._onPropertyChanged)) self.connections.append(self.propertySet.connectPropertyAttributeChanged(self._onPropertyAttributeChanged)) self.propertiesPanel.connect('propertyValueChanged(QtVariantProperty*)', self._onPanelPropertyChanged) self.timer = TimerCallback() self.timer.callback = self._rebuildNow self._blockSignals = True PropertyPanelHelper.addPropertiesToPanel(self.propertySet, self.propertiesPanel, self.propertyNamesToAdd) self._blockSignals = False def cleanup(self): self.timer.callback = None self.propertiesPanel.disconnect('propertyValueChanged(QtVariantProperty*)', self._onPanelPropertyChanged) for connection in self.connections: self.propertySet.callbacks.disconnect(connection) def _rebuild(self): if not self.timer.singleShotTimer.isActive(): self.timer.singleShot(0) def _rebuildNow(self): self._blockSignals = True self.propertiesPanel.clear() PropertyPanelHelper.addPropertiesToPanel(self.propertySet, self.propertiesPanel) self._blockSignals = False def _onPropertyAdded(self, propertySet, propertyName): self._rebuild() def _onPropertyAttributeChanged(self, propertySet, propertyName, propertyAttribute): self._rebuild() def _onPropertyChanged(self, propertySet, propertyName): self._blockSignals = True PropertyPanelHelper.onPropertyValueChanged(self.propertiesPanel, propertySet, propertyName) self._blockSignals = False def _onPanelPropertyChanged(self, panelProperty): if not self._blockSignals: PropertyPanelHelper.setPropertyFromPanel(panelProperty, self.propertiesPanel, self.propertySet)
def __init__(self, image_handler): self._name = 'Image View' self._view = PythonQt.dd.ddQVTKWidgetView() self._image_handler = image_handler self._image = vtk.vtkImageData() self._prev_attrib = None # Initialize the view. self._view.installImageInteractor() # Add actor. self._image_actor = vtk.vtkImageActor() vtk_SetInputData(self._image_actor, self._image) self._image_actor.SetVisibility(False) self._view.renderer().AddActor(self._image_actor) self._view.orientationMarkerWidget().Off() self._view.backgroundRenderer().SetBackground(0, 0, 0) self._view.backgroundRenderer().SetBackground2(0, 0, 0) self._depth_mapper = None # Add timer. self._render_timer = TimerCallback( targetFps=60, callback=self.render) self._render_timer.start()
def __init__(self, multisenseDriver): self.multisenseDriver = multisenseDriver self.multisenseChanged = False loader = QtUiTools.QUiLoader() uifile = QtCore.QFile(":/ui/ddMultisense.ui") assert uifile.open(uifile.ReadOnly) self.widget = loader.load(uifile) self.ui = WidgetDict(self.widget.children()) self.updateTimer = TimerCallback(targetFps=2) self.updateTimer.callback = self.updatePanel self.updateTimer.start() self.widget.headCamGainSpinner.setEnabled(False) self.widget.headCamExposureSpinner.setEnabled(False) # connect the callbacks self.widget.spinRateSpinner.valueChanged.connect(self.spinRateChange) self.widget.scanDurationSpinner.valueChanged.connect(self.scanDurationChange) self.widget.headCamFpsSpinner.valueChanged.connect(self.headCamFpsChange) self.widget.headCamGainSpinner.valueChanged.connect(self.headCamGainChange) self.widget.headCamExposureSpinner.valueChanged.connect(self.headCamExposureChange) self.widget.headAutoGainCheck.clicked.connect(self.headCamAutoGainChange) self.widget.ledOnCheck.clicked.connect(self.ledOnCheckChange) self.widget.ledBrightnessSpinner.valueChanged.connect(self.ledBrightnessChange) self.widget.sendButton.clicked.connect(self.sendButtonClicked) self.updatePanel()
def __init__(self, imageManager, imageName, view, visible=True): self.view = view self.imageManager = imageManager self.imageName = imageName self.visible = visible self.updateUtime = 0 self.initialized = False self.imageWidget = vtk.vtkLogoWidget() imageRep = self.imageWidget.GetRepresentation() self.imageWidget.ResizableOff() self.imageWidget.SelectableOn() imageRep.GetImageProperty().SetOpacity(1.0) self.imageWidget.SetInteractor(self.view.renderWindow().GetInteractor()) self.flip = vtk.vtkImageFlip() self.flip.SetFilteredAxis(1) self.flip.SetInput(imageManager.getImage(imageName)) imageRep.SetImage(self.flip.GetOutput()) self.eventFilter = PythonQt.dd.ddPythonEventFilter() self.view.installEventFilter(self.eventFilter) self.eventFilter.addFilteredEventType(QtCore.QEvent.Resize) self.eventFilter.connect("handleEvent(QObject*, QEvent*)", self.onResizeEvent) self.timerCallback = TimerCallback() self.timerCallback.targetFps = 60 self.timerCallback.callback = self.updateView self.timerCallback.start()
def playPoses(self, poseTimes, poses, jointController): f = self.getPoseInterpolator(poseTimes, poses) timer = SimpleTimer() def updateAnimation(): tNow = timer.elapsed() * self.playbackSpeed if tNow > poseTimes[-1]: pose = poses[-1] jointController.setPose('plan_playback', pose) if self.animationCallback: self.animationCallback() return False pose = f(tNow) jointController.setPose('plan_playback', pose) if self.animationCallback: self.animationCallback() self.animationTimer = TimerCallback() self.animationTimer.targetFps = 60 self.animationTimer.callback = updateAnimation self.animationTimer.start() updateAnimation()
class SpindleSpinChecker(object): def __init__(self, spindleMonitor): self.spindleMonitor = spindleMonitor self.timer = TimerCallback(targetFps=3) self.timer.callback = self.update self.warningButton = None self.action = None def update(self): if abs(self.spindleMonitor.getAverageSpindleVelocity()) < 0.2: self.notifyUserStatusBar() else: self.clearStatusBarWarning() def start(self): self.action.checked = True self.timer.start() def stop(self): self.action.checked = False self.timer.stop() def setupMenuAction(self): self.action = app.addMenuAction('Tools', 'Spindle Stuck Warning') self.action.setCheckable(True) self.action.checked = self.timer.isActive() self.action.connect('triggered()', self.onActionChanged) def onActionChanged(self): if self.action.checked: self.start() else: self.stop() def clearStatusBarWarning(self): if self.warningButton: self.warningButton.deleteLater() self.warningButton = None def notifyUserStatusBar(self): if self.warningButton: return self.warningButton = QtGui.QPushButton('Spindle Stuck Warning') self.warningButton.setStyleSheet("background-color:red") app.getMainWindow().statusBar().insertPermanentWidget(0, self.warningButton)