class WindowClose(ActionListener): def __init__(self): from javax.swing import Timer self.timer = Timer(5000, self) self.timer.start() def actionPerformed(self, e): self.timer.stop() mframe.dispose()
class LifeGame(object): def __init__(self, numRows, numCols): self.numRows = numRows self.numCols = numCols self.timer = Timer(250, None, actionPerformed=self._step) self.gridMutator = GridMutator() def startGui(self): frame = JFrame("Life", defaultCloseOperation=JFrame.EXIT_ON_CLOSE) self.gridPanel = JPanel(GridLayout(self.numRows, self.numCols)) self.cellButtons = self._doForAllCells(self._createCellButton) self.grid = self._doForAllCells(lambda r, c: False) frame.add(self.gridPanel) buttonPanel = JPanel(FlowLayout()) stepButton = JButton("Step", actionPerformed=self._step) runButton = JToggleButton("Run", actionPerformed=self._run) buttonPanel.add(stepButton) buttonPanel.add(runButton) frame.add(buttonPanel, SOUTH) frame.pack() frame.locationRelativeTo = None frame.visible = True def _step(self, event): self.grid = self.gridMutator.generateNext( self._doForAllCells(lambda r, c: self.cellButtons[r][c].selected)) self._doForAllCells(self._selectCellButtonFromGrid) def _run(self, event): if self.timer.running: self.timer.stop() else: self.timer.start() def _createCellButton(self, r, c): button = JToggleButton() s = button.preferredSize button.preferredSize = (s.height, s.height) # Make square self.gridPanel.add(button) return button def _doForAllCells(self, fn): return [[fn(r, c) for c in range(self.numCols)] for r in range(self.numRows)] def _selectCellButtonFromGrid(self, r, c): self.cellButtons[r][c].selected = self.grid[r][c]
class _EventTimer(ActionListener): timers = {} def __init__(self, eventid): self.event = pyj2d.event.Event(eventid) self.timer = Timer(0, self) def set_timer(self, time): if self.timer.isRunning(): self.timer.stop() if time: self.timer.setInitialDelay(time) self.timer.setDelay(time) self.timer.start() def actionPerformed(self, evt): pyj2d.event.post(self.event)
class LifeGame(object): def __init__(self, numRows, numCols): self.numRows = numRows self.numCols = numCols self.timer = Timer(250, None, actionPerformed=self._step) def startGui(self): frame = JFrame("Life", defaultCloseOperation=JFrame.EXIT_ON_CLOSE) (R, C) = (self.numRows, self.numCols) gridPanel = JPanel(GridLayout(R, C)) self.checkBoxes = [[JCheckBox() for c in range(C)] for r in range(R)] self.grid = [[False for c in range(C)] for r in range(R)] for r in range(R): for c in range(C): gridPanel.add(self.checkBoxes[r][c]) frame.add(gridPanel) buttonPanel = JPanel(FlowLayout()) stepButton = JButton("Step", actionPerformed=self._step) runButton = JToggleButton("Run", actionPerformed=self._run) buttonPanel.add(stepButton) buttonPanel.add(runButton) frame.add(buttonPanel, SOUTH) frame.pack() frame.locationRelativeTo = None frame.visible = True def _getGridFromCheckBoxes(self): return [[self.checkBoxes[r][c].selected for c in range(self.numCols)] for r in range(self.numRows)] def _step(self, event): self.grid = GridMutator().generateNext(self._getGridFromCheckBoxes()) self._selectCheckBoxesFromGrid() def _run(self, event): if self.timer.running: self.timer.stop() else: self.timer.start() def _selectCheckBoxesFromGrid(self): for r in range(self.numRows): for c in range(self.numCols): self.checkBoxes[r][c].selected = self.grid[r][c]
class _EventTimer(ActionListener): def __init__(self, event): self.event = event self.timer = Timer(0, self) self.repeat = True def set_timer(self, time, repeat): if self.timer.isRunning(): self.timer.stop() if time: self.repeat = repeat self.timer.setInitialDelay(time) self.timer.setDelay(time) self.timer.start() def actionPerformed(self, evt): env.event.post(self.event) if not self.repeat: self.timer.stop()
class CommandClient(): def __init__(self, extender): self._syncTimer = Timer(1000, None) self._syncTimer.setRepeats(True) self._syncTimer.actionPerformed = self._sendCommandSync self._syncTimer.stop() self.commandListenPort = 8089; self._startTimer = Timer(1000, None) self._startTimer.setInitialDelay(1500) self._startTimer.setRepeats(False) self._startTimer.actionPerformed = self._sendCommandStart self._startTimer.stop() self._extender = extender def startCrawling(self): self._startTimer.start() def startSync(self): self._syncTimer.start() def stopCrawling(self): self._sendCommandStop(None) self._syncTimer.stop() def _sendCommandStart(self, ev): self._sendCommand("start") self.startSync() def _sendCommandStop(self, ev): self._sendCommand("stop") def _sendCommandSync(self, ev): result = self._sendCommand("sync") self._extender.syncCrawlingState(result) def _sendCommand(self, command): url = 'http://127.0.0.1:' + str(self.commandListenPort) + '/?command={0}'.format(command) # TODO: iterate through parameters response = urllib2.urlopen(url) data = json.load(response) return data
class BurpExtender(IBurpExtender, ITab, IContextMenuFactory, DocumentListener, ChangeListener): # # implement IBurpExtender # def registerExtenderCallbacks(self, callbacks): print "PhantomJS RIA Crawler extension" print "Nikolay Matyunin @autorak <*****@*****.**>" # keep a reference to our callbacks object and helpers object self._callbacks = callbacks self._helpers = callbacks.getHelpers() # extension name callbacks.setExtensionName("Phantom RIA Crawler") # Create Tab UI components self._jPanel = JPanel() self._jPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); _titleLabel = JLabel("Phantom RIA Crawler", SwingConstants.LEFT) _titleLabelFont = _titleLabel.font _titleLabelFont = _titleLabelFont.deriveFont(Font.BOLD, 12); _titleLabel.setFont(_titleLabelFont); _titleLabel.setForeground(Color(230, 142, 11)) self._addressTextField = JTextField('') self._addressTextField.setColumns(50) _addressTextLabel = JLabel("Target URL:", SwingConstants.RIGHT) self._addressTextField.getDocument().addDocumentListener(self) self._phantomJsPathField = JTextField('phantomjs') # TODO: set permanent config value self._phantomJsPathField.setColumns(50) _phantomJsPathLabel = JLabel("PhantomJS path:", SwingConstants.RIGHT) self._startButton = JToggleButton('Start', actionPerformed=self.startToggled) self._startButton.setEnabled(False) _requestsMadeLabel = JLabel("DEPs found:", SwingConstants.RIGHT) self._requestsMadeInfo = JLabel("", SwingConstants.LEFT) _statesFoundLabel = JLabel("States found:", SwingConstants.RIGHT) self._statesFoundInfo = JLabel("", SwingConstants.LEFT) _separator = JSeparator(SwingConstants.HORIZONTAL) _configLabel = JLabel("Crawling configuration:") self._configButton = JButton("Load config", actionPerformed=self.loadConfigClicked) self._configFile = "" _listenersLabel= JLabel("Burp proxy listener:", SwingConstants.RIGHT) self._listenersCombo = JComboBox() self._configTimer = Timer(5000, None) self._configTimer.actionPerformed = self._configUpdated self._configTimer.stop() self._configUpdated(None) self._commandClient = CommandClient(self) # Layout management self._groupLayout = GroupLayout(self._jPanel) self._jPanel.setLayout(self._groupLayout) self._groupLayout.setAutoCreateGaps(True) self._groupLayout.setAutoCreateContainerGaps(True) self._groupLayout.setHorizontalGroup(self._groupLayout.createParallelGroup() .addComponent(_titleLabel) .addGroup(self._groupLayout.createSequentialGroup() .addComponent(_addressTextLabel) .addGroup(self._groupLayout.createParallelGroup() .addComponent(self._addressTextField, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE) .addGroup(self._groupLayout.createSequentialGroup() .addComponent(_requestsMadeLabel) .addComponent(self._requestsMadeInfo)) .addGroup(self._groupLayout.createSequentialGroup() .addComponent(_statesFoundLabel) .addComponent(self._statesFoundInfo))) .addComponent(self._startButton)) .addComponent(_separator) .addGroup(self._groupLayout.createSequentialGroup() .addComponent(_configLabel) .addComponent(self._configButton)) .addGroup(self._groupLayout.createSequentialGroup() .addComponent(_phantomJsPathLabel) .addComponent(self._phantomJsPathField, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)) .addGroup(self._groupLayout.createSequentialGroup() .addComponent(_listenersLabel) .addComponent(self._listenersCombo, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE, GroupLayout.PREFERRED_SIZE)) ) self._groupLayout.setVerticalGroup(self._groupLayout.createSequentialGroup() .addComponent(_titleLabel) .addGroup(self._groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(_addressTextLabel) .addComponent(self._addressTextField) .addComponent(self._startButton)) .addGroup(self._groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(_requestsMadeLabel) .addComponent(self._requestsMadeInfo)) .addGroup(self._groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(_statesFoundLabel) .addComponent(self._statesFoundInfo)) .addComponent(_separator, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addGroup(self._groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(_configLabel) .addComponent(self._configButton)) .addGroup(self._groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(_phantomJsPathLabel) .addComponent(self._phantomJsPathField)) .addGroup(self._groupLayout.createParallelGroup(GroupLayout.Alignment.BASELINE) .addComponent(_listenersLabel) .addComponent(self._listenersCombo)) ) self._groupLayout.linkSize(SwingConstants.HORIZONTAL, _configLabel, _phantomJsPathLabel); self._groupLayout.linkSize(SwingConstants.HORIZONTAL, _configLabel, _listenersLabel); self._groupLayout.linkSize(SwingConstants.HORIZONTAL, _statesFoundLabel, _requestsMadeLabel); # context menu data self._contextMenuData = None; self._running = False; # register callbacks callbacks.customizeUiComponent(self._jPanel) callbacks.registerContextMenuFactory(self) callbacks.addSuiteTab(self) return # # implement ITab and Tab ChangeListener # def getTabCaption(self): return "Phantom RIA Crawler" def getUiComponent(self): return self._jPanel def stateChanged(self, ev): self._configUpdated() def _configUpdated(self, ev): config = self._callbacks.saveConfig() # update proxy listeners index = 0 listeners = DefaultComboBoxModel() while (("proxy.listener" + str(index)) in config): listenerItem = config["proxy.listener" + str(index)] listenerItems = listenerItem.split(".") if (listenerItems[0] == "1"): address = ".".join(listenerItems[2][1:].split("|")) if (len(address) == 0): address = "127.0.0.1" listeners.addElement(address + " : " + listenerItems[1]) index = index + 1 self._listenersCombo.setModel(listeners) return; # # implement button actions # def startToggled(self, ev): if (self._startButton.getModel().isSelected()): try: os.chdir(sys.path[0] + os.sep + "riacrawler" + os.sep + "scripts") except Exception as e: print >> sys.stderr, "RIA crawler scripts loading error", "I/O error({0}): {1}".format(e.errno, e.strerror) self._startButton.setSelected(False) return phantomJsPath = self._phantomJsPathField.text target = self._addressTextField.text config = "crawler.config" if (self._configFile): config = self._configFile listenerAddress = self._listenersCombo.getSelectedItem().replace(" ", "") p = Popen("{0} --proxy={3} main.js --target={1} --config={2}".format(phantomJsPath, target, config, listenerAddress), shell=True) self._running = True self._requestsMadeInfo.setText("") self._statesFoundInfo.setText("") self._commandClient.startCrawling() else: if (self._running): self._commandClient.stopCrawling() self._running = False def syncCrawlingState(self, result): print "RIA crawling state: ", result self._requestsMadeInfo.setText(str(result["requests_made"])) self._statesFoundInfo.setText(str(result["states_detected"])) if (result["running"] == False): self._commandClient.stopCrawling() self._running = False self._startButton.setSelected(False) def loadConfigClicked(self, ev): openFile = JFileChooser(); openFile.showOpenDialog(None); self._configFile = openFile.getSelectedFile() # # implement DocumentListener for _addressTextField # def removeUpdate(self, ev): self.updateStartButton() def insertUpdate(self, ev): self.updateStartButton() def updateStartButton(self): self._startButton.setEnabled(len(self._addressTextField.text) > 0) # # implement IContextMenuFactory # def createMenuItems(self, contextMenuInvocation): menuItemList = ArrayList() context = contextMenuInvocation.getInvocationContext() if (context == IContextMenuInvocation.CONTEXT_MESSAGE_VIEWER_REQUEST or context == IContextMenuInvocation.CONTEXT_MESSAGE_EDITOR_REQUEST or context == IContextMenuInvocation.CONTEXT_PROXY_HISTORY or context == IContextMenuInvocation.CONTEXT_TARGET_SITE_MAP_TABLE): self._contextMenuData = contextMenuInvocation.getSelectedMessages() menuItemList.add(JMenuItem("Send to Phantom RIA Crawler", actionPerformed = self.menuItemClicked)) return menuItemList def menuItemClicked(self, event): if (self._running == True): self._callbacks.issueAlert("Can't set data to Phantom RIA Crawler: crawling is running already.") return; dataIsSet = False; for message in self._contextMenuData: request = self._helpers.analyzeRequest(message) url = request.getUrl().toString() print url if (url): dataisSet = True; self._addressTextField.setText(url)
class TrackDevice(java.beans.PropertyChangeListener): import java import javax.swing import javax.swing.Timer delayTimer = None relayClicks = None # TrackDevice.init - Initialize a TrackDevice instance for a particular device # # aName : Device name # aDevice : JMRI device instance # aAllowedStates : Array of states we want to track, other states are ignored # def init(self, aName, aDevice, aAllowedStates, aLogFile, aParent): from javax.swing import Timer #print ('TrackDevice.init ' + aName ) self.DeviceName = aName self.Device = aDevice self.DeviceValue = self.Device.getValue() self.AllowedStates = aAllowedStates self.parent = aParent self.LogFile = aLogFile self.timeoutListener = self.TimeoutReceiver() self.timeoutListener.setCallBack(self.receiveTimeoutHandler) self.receiveTimer = Timer(1, self.timeoutListener) self.receiveTimer.stop() self.receiveTimer.setRepeats(False) self.sendTimeoutListener = self.TimeoutReceiver() self.sendTimeoutListener.setCallBack(self.sendTimeoutHandler) self.sendTimer = Timer(1, self.sendTimeoutListener) self.sendTimer.stop() self.sendTimer.setRepeats(False) self.pauseTimeoutListener = self.TimeoutReceiver() self.pauseTimeoutListener.setCallBack(self.pauseTimeoutHandler) self.pauseTimer = Timer(1, self.pauseTimeoutListener) self.pauseTimer.stop() self.pauseTimer.setRepeats(False) self.relayClicks = jmri.jmrit.Sound( "resources/sounds/Code-receive.wav") #self.relayClicks = jmri.jmrit.Sound(jmri.util.FileUtil.getExternalFilename("preference:resources/sounds/EnhancedCTCRelay.wav")) self.relaySend = jmri.jmrit.Sound("resources/sounds/Code-send.wav") return # TrackDevice.updateState - Track the device state while reading the old log # file. Note the state but don't change the device # itself and don't log the changes to the new log file # (yet). # # aNewState : New device state. # def updateState(self, aNewState): #print 'updateState ' + self.DeviceName for i in range(len(self.AllowedStates)): if (aNewState == self.AllowedStates[i]): self.DeviceValue = aNewState break # TrackDevice.propertyChange - Record state changes as a result of activities # elsewhere in JMRI # # aEvent : Event triggering the change (we don't actually look at the event...) # def propertyChange(self, aEvent): #print "Property change " + self.DeviceName newValue = self.Device.getValue() codeSendSensor = sensors.getSensor("IS16:CCK") codeSendSensor.setState(ACTIVE) self.relaySend.loop() ccdl = 5 + java.util.Random().nextInt(1) # Code transmission delay self.sendTimer.setInitialDelay(ccdl * 10) self.sendTimer.start() if (newValue == self.DeviceValue): return for i in range(len(self.AllowedStates)): if (newValue == self.AllowedStates[i]): self.DeviceValue = newValue #logStateChange2(self.DeviceName, self.DeviceValue, True) #print "state change " + self.DeviceName + " " + str(self.DeviceValue) self.LogFile.write(self.DeviceName + " " + self.DeviceValue + "\n") self.LogFile.flush() break return # TrackDevice.setInitialDeviceState - After reading all of the old tracking file we # now initialize the actual devices to their last # known states and log these states into the new # log file. # def setInitialDeviceState(self, logFile): # Uncomment the following print statement to display the list of devices being tracked. #print "In setInitDeviceState, name = " + self.DeviceName + " value = " + self.DeviceValue self.LogFile = logFile self.Device.setValue(self.DeviceValue) self.Device.addPropertyChangeListener(self) #logStateChange2(self.DeviceName, self.DeviceState, False) logFile.write(self.DeviceName + " " + self.DeviceValue + "\n") signalId = "IS" + self.DeviceName[2:3] ctcId = "CTC:TO" + self.DeviceName[2:3] # Move the switch lever to the correct position if (self.DeviceValue == "P"): #print " ctcId = " + ctcId + " state = green" turnouts.provideTurnout("NT" + self.DeviceName[2:3]).setState(CLOSED) sensors.getSensor(signalId + ":WLL").setState(INACTIVE) sensors.getSensor(signalId + ":WLR").setState(INACTIVE) sensors.getSensor(signalId + ":WLC").setState(ACTIVE) sensors.getSensor(signalId + ":WKR").setState(INACTIVE) sensors.getSensor(signalId + ":WKL").setState(INACTIVE) sensors.getSensor(signalId + ":WKC").setState(ACTIVE) sensors.getSensor(ctcId + "GK").setState(ACTIVE) sensors.getSensor(ctcId + "YK").setState(INACTIVE) sensors.getSensor(ctcId + "RK").setState(INACTIVE) sensors.getSensor(ctcId + "GS").setState(ACTIVE) sensors.getSensor(ctcId + "YS").setState(INACTIVE) sensors.getSensor(ctcId + "RS").setState(INACTIVE) sensors.getSensor(signalId + ":TOC").setState(INACTIVE) sensors.getSensor(signalId + ":TOS").setState(INACTIVE) sensors.getSensor(signalId + ":TOP").setState(ACTIVE) elif (self.DeviceValue == "C"): #print " ctcId = " + ctcId + " state = yellow" sensors.getSensor(signalId + ":WLL").setState(ACTIVE) sensors.getSensor(signalId + ":WLR").setState(INACTIVE) sensors.getSensor(signalId + ":WLC").setState(INACTIVE) sensors.getSensor(signalId + ":WKR").setState(INACTIVE) sensors.getSensor(signalId + ":WKL").setState(ACTIVE) sensors.getSensor(signalId + ":WKC").setState(INACTIVE) sensors.getSensor(ctcId + "GK").setState(INACTIVE) sensors.getSensor(ctcId + "YK").setState(ACTIVE) sensors.getSensor(ctcId + "RK").setState(INACTIVE) sensors.getSensor(ctcId + "GS").setState(INACTIVE) sensors.getSensor(ctcId + "YS").setState(ACTIVE) sensors.getSensor(ctcId + "RS").setState(INACTIVE) sensors.getSensor(signalId + ":TOC").setState(ACTIVE) sensors.getSensor(signalId + ":TOS").setState(INACTIVE) sensors.getSensor(signalId + ":TOP").setState(INACTIVE) else: #print " ctcId = " + ctcId + " state = red" turnouts.provideTurnout("NT" + self.DeviceName[2:3]).setState(THROWN) sensors.getSensor(signalId + ":WLL").setState(INACTIVE) sensors.getSensor(signalId + ":WLR").setState(ACTIVE) sensors.getSensor(signalId + ":WLC").setState(INACTIVE) sensors.getSensor(signalId + ":WKR").setState(ACTIVE) sensors.getSensor(signalId + ":WKL").setState(INACTIVE) sensors.getSensor(signalId + ":WKC").setState(INACTIVE) sensors.getSensor(ctcId + "GK").setState(INACTIVE) sensors.getSensor(ctcId + "YK").setState(INACTIVE) sensors.getSensor(ctcId + "RK").setState(ACTIVE) sensors.getSensor(ctcId + "GS").setState(INACTIVE) sensors.getSensor(ctcId + "YS").setState(INACTIVE) sensors.getSensor(ctcId + "RS").setState(ACTIVE) sensors.getSensor(signalId + ":TOC").setState(INACTIVE) sensors.getSensor(signalId + ":TOS").setState(ACTIVE) sensors.getSensor(signalId + ":TOP").setState(INACTIVE) class TimeoutReceiver(java.awt.event.ActionListener): cb = None def actionPerformed(self, event): if (self.cb != None): self.cb(event) return def setCallBack(self, cbf): self.cb = cbf return class TimeoutReceiver2(java.awt.event.ActionListener): cb = None def actionPerformed(self, event): if (self.cb != None): self.cb(event) return def setCallBack(self, cbf): self.cb = cbf return class TimeoutReceiver3(java.awt.event.ActionListener): cb = None def actionPerformed(self, event): if (self.cb != None): self.cb(event) return def setCallBack(self, cbf): self.cb = cbf return def sendTimeoutHandler(self, event): #print "In send timeout handler" self.sendTimer.stop() self.relaySend.stop() sensors.getSensor("IS16:CCK").setState(INACTIVE) #sleep(2) signalNumber = self.DeviceName[2:3] if (self.Device.getValue() == "P"): turnouts.provideTurnout("NT" + signalNumber).setState(CLOSED) elif (self.Device.getValue() == "S"): turnouts.provideTurnout("NT" + signalNumber).setState(THROWN) smdl = 5 + java.util.Random().nextInt(2) # Switch motor delay - self.pauseTimer.setInitialDelay(smdl * 10) self.pauseTimer.start() return def pauseTimeoutHandler(self, event): #print "In pause timeout handler" self.pauseTimer.stop() sensors.getSensor("IS17:ICK").setState(ACTIVE) #print "Turning on IC light" self.relayClicks.loop() newName = "IS" + self.DeviceName[2:3] sensors.getSensor(newName + ":WKC").setState(INACTIVE) sensors.getSensor(newName + ":WKL").setState(INACTIVE) sensors.getSensor(newName + ":WKR").setState(INACTIVE) ctcName = "CTC:TO" + self.DeviceName[2:3] if (sensors.getSensor(ctcName + "YK").getState() == ACTIVE): sensors.getSensor(ctcName + "YK").setState(INACTIVE) if (sensors.getSensor(ctcName + "GK").getState() == ACTIVE): sensors.getSensor(ctcName + "GK").setState(INACTIVE) if (sensors.getSensor(ctcName + "RK").getState() == ACTIVE): sensors.getSensor(ctcName + "RK").setState(INACTIVE) icdl = 5 + java.util.Random().nextInt(3) # Indicator code delay self.receiveTimer.setInitialDelay(icdl * 10) self.receiveTimer.start() return def receiveTimeoutHandler(self, event): # see which phase we think we are in #print "In receive timeout Handler" self.receiveTimer.stop() signalNumber = self.DeviceName[2:3] #print " Signal number = " + str(signalNumber) + " signal state = " + self.Device.getValue() if (self.Device.getValue() == "P"): sensors.getSensor("IS" + signalNumber + ":WKC").setState(ACTIVE) sensors.getSensor("IS" + signalNumber + ":WKR").setState(INACTIVE) sensors.getSensor("IS" + signalNumber + ":WKL").setState(INACTIVE) sensors.getSensor("IS" + signalNumber + ":TOC").setState(INACTIVE) sensors.getSensor("IS" + signalNumber + ":TOS").setState(INACTIVE) sensors.getSensor("IS" + signalNumber + ":TOP").setState(ACTIVE) #sensors.getSensor("CTC:TO" + signalNumber + "YK").setState(INACTIVE) sensors.getSensor("CTC:TO" + signalNumber + "GK").setState(ACTIVE) #sensors.getSensor("CTC:TO" + signalNumber + "RK").setState(INACTIVE) elif (self.Device.getValue() == "C"): sensors.getSensor("IS" + signalNumber + ":WKC").setState(INACTIVE) sensors.getSensor("IS" + signalNumber + ":WKR").setState(INACTIVE) sensors.getSensor("IS" + signalNumber + ":WKL").setState(ACTIVE) sensors.getSensor("IS" + signalNumber + ":TOS").setState(INACTIVE) sensors.getSensor("IS" + signalNumber + ":TOP").setState(INACTIVE) sensors.getSensor("IS" + signalNumber + ":TOC").setState(ACTIVE) sensors.getSensor("CTC:TO" + signalNumber + "YK").setState(ACTIVE) #sensors.getSensor("CTC:TO" + signalNumber + "GK").setState(INACTIVE) #sensors.getSensor("CTC:TO" + signalNumber + "RK").setState(INACTIVE) jmri.jmrit.Sound("resources/sounds/Bell.wav").play() elif (self.Device.getValue() == "S"): sensors.getSensor("IS" + signalNumber + ":WKC").setState(INACTIVE) sensors.getSensor("IS" + signalNumber + ":WKR").setState(ACTIVE) sensors.getSensor("IS" + signalNumber + ":WKL").setState(INACTIVE) sensors.getSensor("IS" + signalNumber + ":TOC").setState(INACTIVE) sensors.getSensor("IS" + signalNumber + ":TOP").setState(INACTIVE) sensors.getSensor("IS" + signalNumber + ":TOS").setState(ACTIVE) #sensors.getSensor("CTC:TO" + signalNumber + "YK").setState(INACTIVE) #sensors.getSensor("CTC:TO" + signalNumber + "GK").setState(INACTIVE) sensors.getSensor("CTC:TO" + signalNumber + "RK").setState(ACTIVE) self.relayClicks.stop() self.parent.waitMsec(1000) sensors.getSensor("IS17:ICK").setState(INACTIVE) return
class USBThrottle(Jynstrument, PropertyChangeListener, AddressListener): #Property listener part: USB value def propertyChange(self, event): # Customize bellow for throttles calls: if (event.propertyName == "Value"): # USB if (event.oldValue.getController() == self.desiredController): component = event.oldValue.getComponent().toString() value = event.newValue # Uncomment bellow line to see component name and its value # print "Component",component,"value changed to",value try: # Change current ThrottleFrame if ((component == self.driver.componentNextThrottleFrame) and (value == self.driver.valueNextThrottleFrame)): #NEXT self.getContext().nextThrottleFrame() if ((component == self.driver.componentPreviousThrottleFrame) and (value == self.driver.valuePreviousThrottleFrame) ): #PREVIOUS self.getContext().previousThrottleFrame() if ((component == self.driver.componentNextRunningThrottleFrame) and (value == self.driver.valueNextRunningThrottleFrame) ): #NEXT RUNNING self.getContext().nextRunningThrottleFrame() if ((component == self.driver.componentPreviousRunningThrottleFrame) and (value == self.driver.valuePreviousRunningThrottleFrame )): #PREVIOUS RUNNING self.getContext().previousRunningThrottleFrame() except AttributeError: pass if (self.throttle == None): try: # Browse through roster if ((component == self.driver.componentNextRosterBrowse) and (value == self.driver.valueNextRoster)): #NEXT selectedIndex = self.addressPanel.getRosterSelectedIndex( ) self.addressPanel.setVisible(True) self.addressPanel.setIcon(False) self.addressPanel.setRosterSelectedIndex( selectedIndex + 1) if ((component == self.driver.componentPreviousRosterBrowse) and (value == self.driver.valuePreviousRoster)): #PREVIOUS selectedIndex = self.addressPanel.getRosterSelectedIndex( ) self.addressPanel.setVisible(True) self.addressPanel.setIcon(False) self.addressPanel.setRosterSelectedIndex( selectedIndex - 1) except AttributeError: pass try: # Request a throttle if ((component == self.driver.componentRosterSelect) and (value == self.driver.valueRosterSelect)): self.addressPanel.selectRosterEntry() except AttributeError: pass # From there; current throttle control, hence require a throttle if (self.throttle != None): # Release current throttle try: if ((component == self.driver.componentThrottleRelease) and (value == self.driver.valueThrottleRelease)): self.addressPanel.dispatchAddress() except AttributeError: pass try: # Speed - dynamic controler (joystick going back to neutral position) if ((component == self.driver.componentSpeedIncrease) or (component == self.driver.componentSpeedDecrease) or (component == self.driver.componentSpeed)): if ((component == self.driver.componentSpeedIncrease) and (value == self.driver.valueSpeedIncrease)): self.speedAction.setSpeedIncrement(0.03) if ((component == self.driver.componentSpeedDecrease) and (value == self.driver.valueSpeedDecrease)): self.speedAction.setSpeedIncrement(-0.03) if (component == self.driver.componentSpeed): try: self.vsd = valueSpeedDivider * self.driver.componentSpeedMultiplier except AttributeError: self.vsd = valueSpeedDivider self.speedAction.setSpeedIncrement(value / self.vsd) if (abs(value) > self.driver.valueSpeedTrigger): self.speedTimer.start() else: self.speedTimer.stop() except AttributeError: self.speedTimer.stop( ) # just in case, stop it, really should never get there try: # Speed v2 - static controler (lever on RailDriver or AAR105) if (component == self.driver.componentSpeedSet): # negative is lever front, positive is lever back # limit range to only positive side of lever if (value < self.driver.valueSpeedSetMinValue): value = self.driver.valueSpeedSetMinValue if (value > self.driver.valueSpeedSetMaxValue): value = self.driver.valueSpeedSetMaxValue # convert fraction of input to speed step self.throttle.setSpeedSetting( (value - self.driver.valueSpeedSetMinValue) / (self.driver.valueSpeedSetMaxValue - self.driver.valueSpeedSetMinValue)) print "Slider Speed:", self.controlPanel.getDisplaySlider( ) except AttributeError: pass # Direction try: if ((component == self.driver.componentDirectionForward) and (value == self.driver.valueDirectionForward)): self.throttle.setIsForward(True) if ((component == self.driver.componentDirectionBackward) and (value == self.driver.valueDirectionBackward)): self.throttle.setIsForward(False) except AttributeError: pass try: if ((component == self.driver.componentDirectionSwitch) and (value == self.driver.valueDirectionSwitch)): self.throttle.setIsForward( not self.throttle.getIsForward()) except AttributeError: pass # Speed presets try: # STOP if ((component == self.driver.componentStopSpeed) and (value == self.driver.valueStopSpeed)): if (Calendar.getInstance().getTimeInMillis() - self.lastTimeStopButton < delay4doubleTap): self.throttle.setSpeedSetting( EStopSpeed) # EStop on double tap else: self.throttle.setSpeedSetting(speedStopSpeed) self.lastTimeStopButton = Calendar.getInstance( ).getTimeInMillis() except AttributeError: pass try: # EStop if ((component == self.driver.componentEStopSpeed) and (value == self.driver.valueEStopSpeed)): self.throttle.setSpeedSetting(EStopSpeed) except AttributeError: pass try: # EStop if ((component == self.driver.componentEStopSpeedBis) and (value == self.driver.valueEStopSpeedBis)): self.throttle.setSpeedSetting(EStopSpeed) except AttributeError: pass try: # SLOW if ((component == self.driver.componentSlowSpeed) and (value == self.driver.valueSlowSpeed)): self.throttle.setSpeedSetting(speedSlowSpeed) except AttributeError: pass try: # CRUISE if ((component == self.driver.componentCruiseSpeed) and (value == self.driver.valueCruiseSpeed)): if (Calendar.getInstance().getTimeInMillis() - self.lastTimeCruiseButton < delay4doubleTap): # EStop on double tap self.throttle.setSpeedSetting( speedMaxSpeed) # Max speed on double tap else: self.throttle.setSpeedSetting(speedCruiseSpeed) self.lastTimeCruiseButton = Calendar.getInstance( ).getTimeInMillis() except AttributeError: pass try: # MAX if ((component == self.driver.componentMaxSpeed) and (value == self.driver.valueMaxSpeed)): self.throttle.setSpeedSetting(speedMaxSpeed) except AttributeError: pass # Functions try: if ((component == self.driver.componentF0) and (value == self.driver.valueF0)): self.throttle.setF0(not self.throttle.getF0()) if ((self.roster != None) and (not self.roster.getFunctionLockable(0)) and (component == self.driver.componentF0) and (value == self.driver.valueF0Off)): self.throttle.setF0(not self.throttle.getF0()) except AttributeError: pass try: if ((component == self.driver.componentF1) and (value == self.driver.valueF1)): self.throttle.setF1(not self.throttle.getF1()) if ((self.roster != None) and (not self.roster.getFunctionLockable(1)) and (component == self.driver.componentF1) and (value == self.driver.valueF1Off)): self.throttle.setF1(not self.throttle.getF1()) except AttributeError: pass try: if ((component == self.driver.componentF2) and (value == self.driver.valueF2)): self.throttle.setF2(not self.throttle.getF2()) if ((self.roster != None) and (not self.roster.getFunctionLockable(2)) and (component == self.driver.componentF2) and (value == self.driver.valueF2Off)): self.throttle.setF2(not self.throttle.getF2()) except AttributeError: pass try: if ((component == self.driver.componentF3) and (value == self.driver.valueF3)): self.throttle.setF3(not self.throttle.getF3()) if ((self.roster != None) and (not self.roster.getFunctionLockable(3)) and (component == self.driver.componentF3) and (value == self.driver.valueF3Off)): self.throttle.setF3(not self.throttle.getF3()) except AttributeError: pass try: if ((component == self.driver.componentF4) and (value == self.driver.valueF4)): self.throttle.setF4(not self.throttle.getF4()) if ((self.roster != None) and (not self.roster.getFunctionLockable(4)) and (component == self.driver.componentF4) and (value == self.driver.valueF4Off)): self.throttle.setF4(not self.throttle.getF4()) except AttributeError: pass try: if ((component == self.driver.componentF5) and (value == self.driver.valueF5)): self.throttle.setF5(not self.throttle.getF5()) if ((self.roster != None) and (not self.roster.getFunctionLockable(5)) and (component == self.driver.componentF5) and (value == self.driver.valueF5Off)): self.throttle.setF5(not self.throttle.getF5()) except AttributeError: pass try: if ((component == self.driver.componentF6) and (value == self.driver.valueF6)): self.throttle.setF6(not self.throttle.getF6()) if ((self.roster != None) and (not self.roster.getFunctionLockable(6)) and (component == self.driver.componentF6) and (value == self.driver.valueF6Off)): self.throttle.setF6(not self.throttle.getF6()) except AttributeError: pass try: if ((component == self.driver.componentF7) and (value == self.driver.valueF7)): self.throttle.setF7(not self.throttle.getF7()) if ((self.roster != None) and (not self.roster.getFunctionLockable(7)) and (component == self.driver.componentF7) and (value == self.driver.valueF7Off)): self.throttle.setF7(not self.throttle.getF7()) except AttributeError: pass try: if ((component == self.driver.componentF8) and (value == self.driver.valueF8)): self.throttle.setF8(not self.throttle.getF8()) if ((self.roster != None) and (not self.roster.getFunctionLockable(8)) and (component == self.driver.componentF8) and (value == self.driver.valueF8Off)): self.throttle.setF8(not self.throttle.getF8()) except AttributeError: pass try: if ((component == self.driver.componentF9) and (value == self.driver.valueF9)): self.throttle.setF9(not self.throttle.getF9()) if ((self.roster != None) and (not self.roster.getFunctionLockable(9)) and (component == self.driver.componentF9) and (value == self.driver.valueF9Off)): self.throttle.setF9(not self.throttle.getF9()) except AttributeError: pass try: if ((component == self.driver.componentF10) and (value == self.driver.valueF10)): self.throttle.setF10(not self.throttle.getF10()) if ((self.roster != None) and (not self.roster.getFunctionLockable(10)) and (component == self.driver.componentF10) and (value == self.driver.valueF10Off)): self.throttle.setF10(not self.throttle.getF10()) except AttributeError: pass try: if ((component == self.driver.componentF11) and (value == self.driver.valueF11)): self.throttle.setF11(not self.throttle.getF11()) if ((self.roster != None) and (not self.roster.getFunctionLockable(11)) and (component == self.driver.componentF11) and (value == self.driver.valueF11Off)): self.throttle.setF11(not self.throttle.getF11()) except AttributeError: pass try: if ((component == self.driver.componentF12) and (value == self.driver.valueF12)): self.throttle.setF12(not self.throttle.getF12()) if ((self.roster != None) and (not self.roster.getFunctionLockable(12)) and (component == self.driver.componentF12) and (value == self.driver.valueF12Off)): self.throttle.setF12(not self.throttle.getF12()) except AttributeError: pass try: if ((component == self.driver.componentF13) and (value == self.driver.valueF13)): self.throttle.setF13(not self.throttle.getF13()) if ((self.roster != None) and (not self.roster.getFunctionLockable(13)) and (component == self.driver.componentF13) and (value == self.driver.valueF13Off)): self.throttle.setF13(not self.throttle.getF13()) except AttributeError: pass try: if ((component == self.driver.componentF14) and (value == self.driver.valueF14)): self.throttle.setF14(not self.throttle.getF14()) if ((self.roster != None) and (not self.roster.getFunctionLockable(14)) and (component == self.driver.componentF14) and (value == self.driver.valueF14Off)): self.throttle.setF14(not self.throttle.getF14()) except AttributeError: pass try: if ((component == self.driver.componentF15) and (value == self.driver.valueF15)): self.throttle.setF15(not self.throttle.getF15()) if ((self.roster != None) and (not self.roster.getFunctionLockable(15)) and (component == self.driver.componentF15) and (value == self.driver.valueF15Off)): self.throttle.setF15(not self.throttle.getF15()) except AttributeError: pass try: if ((component == self.driver.componentF16) and (value == self.driver.valueF16)): self.throttle.setF16(not self.throttle.getF16()) if ((self.roster != None) and (not self.roster.getFunctionLockable(16)) and (component == self.driver.componentF16) and (value == self.driver.valueF16Off)): self.throttle.setF16(not self.throttle.getF16()) except AttributeError: pass try: if ((component == self.driver.componentF17) and (value == self.driver.valueF17)): self.throttle.setF17(not self.throttle.getF17()) if ((self.roster != None) and (not self.roster.getFunctionLockable(17)) and (component == self.driver.componentF17) and (value == self.driver.valueF17Off)): self.throttle.setF17(not self.throttle.getF17()) except AttributeError: pass try: if ((component == self.driver.componentF18) and (value == self.driver.valueF18)): self.throttle.setF18(not self.throttle.getF18()) if ((self.roster != None) and (not self.roster.getFunctionLockable(18)) and (component == self.driver.componentF18) and (value == self.driver.valueF18Off)): self.throttle.setF18(not self.throttle.getF18()) except AttributeError: pass try: if ((component == self.driver.componentF19) and (value == self.driver.valueF19)): self.throttle.setF19(not self.throttle.getF19()) if ((self.roster != None) and (not self.roster.getFunctionLockable(19)) and (component == self.driver.componentF19) and (value == self.driver.valueF19Off)): self.throttle.setF19(not self.throttle.getF19()) except AttributeError: pass try: if ((component == self.driver.componentF20) and (value == self.driver.valueF20)): self.throttle.setF20(not self.throttle.getF20()) if ((self.roster != None) and (not self.roster.getFunctionLockable(20)) and (component == self.driver.componentF20) and (value == self.driver.valueF20Off)): self.throttle.setF20(not self.throttle.getF20()) except AttributeError: pass try: if ((component == self.driver.componentF21) and (value == self.driver.valueF21)): self.throttle.setF21(not self.throttle.getF21()) if ((self.roster != None) and (not self.roster.getFunctionLockable(21)) and (component == self.driver.componentF21) and (value == self.driver.valueF21Off)): self.throttle.setF21(not self.throttle.getF21()) except AttributeError: pass try: if ((component == self.driver.componentF22) and (value == self.driver.valueF22)): self.throttle.setF22(not self.throttle.getF22()) if ((self.roster != None) and (not self.roster.getFunctionLockable(22)) and (component == self.driver.componentF22) and (value == self.driver.valueF22Off)): self.throttle.setF22(not self.throttle.getF22()) except AttributeError: pass try: if ((component == self.driver.componentF23) and (value == self.driver.valueF23)): self.throttle.setF23(not self.throttle.getF23()) if ((self.roster != None) and (not self.roster.getFunctionLockable(23)) and (component == self.driver.componentF23) and (value == self.driver.valueF23Off)): self.throttle.setF23(not self.throttle.getF23()) except AttributeError: pass try: if ((component == self.driver.componentF24) and (value == self.driver.valueF24)): self.throttle.setF24(not self.throttle.getF24()) if ((self.roster != None) and (not self.roster.getFunctionLockable(24)) and (component == self.driver.componentF24) and (value == self.driver.valueF24Off)): self.throttle.setF24(not self.throttle.getF24()) except AttributeError: pass try: if ((component == self.driver.componentF25) and (value == self.driver.valueF25)): self.throttle.setF25(not self.throttle.getF25()) if ((self.roster != None) and (not self.roster.getFunctionLockable(25)) and (component == self.driver.componentF25) and (value == self.driver.valueF25Off)): self.throttle.setF25(not self.throttle.getF25()) except AttributeError: pass try: if ((component == self.driver.componentF26) and (value == self.driver.valueF26)): self.throttle.setF26(not self.throttle.getF26()) if ((self.roster != None) and (not self.roster.getFunctionLockable(26)) and (component == self.driver.componentF26) and (value == self.driver.valueF26Off)): self.throttle.setF26(not self.throttle.getF26()) except AttributeError: pass try: if ((component == self.driver.componentF27) and (value == self.driver.valueF27)): self.throttle.setF27(not self.throttle.getF27()) if ((self.roster != None) and (not self.roster.getFunctionLockable(27)) and (component == self.driver.componentF27) and (value == self.driver.valueF27Off)): self.throttle.setF27(not self.throttle.getF27()) except AttributeError: pass try: if ((component == self.driver.componentF28) and (value == self.driver.valueF28)): self.throttle.setF28(not self.throttle.getF28()) if ((self.roster != None) and (not self.roster.getFunctionLockable(28)) and (component == self.driver.componentF28) and (value == self.driver.valueF28Off)): self.throttle.setF28(not self.throttle.getF28()) except AttributeError: pass try: if ((component == self.driver.componentF29) and (value == self.driver.valueF29)): self.throttle.setF29(not self.throttle.getF29()) if ((self.roster != None) and (not self.roster.getFunctionLockable(29)) and (component == self.driver.componentF29) and (value == self.driver.valueF29Off)): self.throttle.setF29(not self.throttle.getF29()) except AttributeError: pass # Nothing to customize bellow this point if (event.propertyName == "ThrottleFrame" ): # Current throttle frame changed self.speedTimer.stop() event.oldValue.getAddressPanel().removeAddressListener(self) self.addressPanel = event.newValue.getAddressPanel() self.throttle = self.addressPanel.getThrottle() self.roster = self.addressPanel.getRosterEntry() self.speedAction.setThrottle(self.throttle) event.newValue.getAddressPanel().addAddressListener(self) #Jynstrument main and mandatory methods def getExpectedContextClassName(self): return "jmri.jmrit.throttle.ThrottleWindow" def init(self): self.getContext().addPropertyChangeListener( self) #ThrottleFrame change self.getContext().getCurrentThrottleFrame().getAddressPanel( ).addAddressListener(self) # change of throttle in Current frame self.addressPanel = self.getContext().getCurrentThrottleFrame( ).getAddressPanel() self.throttle = self.addressPanel.getThrottle() # the throttle self.roster = self.addressPanel.getRosterEntry() # roster entry if any self.speedAction = SpeedAction() #Speed increase thread self.speedAction.setThrottle(self.throttle) self.speedTimer = Timer( valueSpeedTimerRepeat, self.speedAction ) # Very important to use swing Timer object (see Swing and multithreading doc) self.speedTimer.setRepeats(True) self.label = JButton( ImageIcon(self.getFolder() + "/USBControl.png", "USBThrottle")) #label self.label.addMouseListener( self.getMouseListeners() [0]) # In order to get the popupmenu on the button too self.add(self.label) self.model = jmri.jmrix.jinput.TreeModel.instance() # USB self.desiredController = None self.ctrlMenuItem = [] self.USBDriver = None self.driver = None mi = JCheckBoxMenuItem("None") self.getPopUpMenu().add(mi) mi.addItemListener(ControllerItemListener(None, self)) self.ctrlMenuItem.append(mi) for ctrl in self.model.controllers(): mi = JCheckBoxMenuItem(ctrl.getName()) self.getPopUpMenu().add(mi) mi.addItemListener(ControllerItemListener(ctrl, self)) self.ctrlMenuItem.append(mi) if (len(self.ctrlMenuItem) == 0): print "No matching USB device found" else: self.ctrlMenuItem[0].setSelected( True) # by default connect to the first one self.model.addPropertyChangeListener(self) self.lastTimeStopButton = Calendar.getInstance().getTimeInMillis() self.lastTimeCruiseButton = Calendar.getInstance().getTimeInMillis() # On quit clean up resources def quit(self): self.speedTimer.stop() for mi in self.ctrlMenuItem: self.getPopUpMenu().remove(mi) self.ctrlMenuItem = None self.speedAction = None self.speedTimer = None self.throttle = None self.addressPanel = None self.driver = None self.USBDriver = None self.getContext().removePropertyChangeListener(self) self.model.removePropertyChangeListener(self) self.getContext().getCurrentThrottleFrame().getAddressPanel( ).removeAddressListener(self) # Menu entry changed for Current controller and update driver def setSelectedController(self, ctrl, item): for mi in self.ctrlMenuItem: if (mi != item): # Force deselection of other ones mi.setSelected(False) self.desiredController = ctrl if (ctrl != None): sys.path.append(self.getFolder()) # Load a driver try: del self.driver del self.USBDriver dd = ctrl.getName() dd = dd.replace(" ", "") dd = dd.replace(".", "") dd = dd.replace("(", "") dd = dd.replace(")", "") dd = dd.replace("{", "") dd = dd.replace("}", "") dd = dd.replace("[", "") dd = dd.replace("]", "") self.USBDriver = __import__(dd) except ImportError: # On error load a default one print "Driver \"" + dd + "\" not found in \"" + self.getFolder( ) + "\", loading default one" self.USBDriver = __import__("Default") reload(self.USBDriver) sys.path.remove(self.getFolder()) self.driver = self.USBDriver.USBDriver() def setXml(self, elt): if (elt.getChildren("USBThrottle") == None): return ctrl = elt.getChildren("USBThrottle")[0].getAttributeValue( "DesiredController") if (ctrl == None): return for mi in self.ctrlMenuItem: if (mi.getText() == ctrl): mi.setSelected(True) break def getXml(self): elt = Element("USBThrottle") for mi in self.ctrlMenuItem: if (mi.isSelected()): elt.setAttribute("DesiredController", mi.getText()) break return elt #AddressListener part: to listen for address changes in address panel (release, acquired) def notifyAddressChosen(self, address): pass def notifyAddressThrottleFound(self, throttle): self.speedTimer.stop() self.throttle = throttle self.speedAction.setThrottle(self.throttle) def notifyAddressReleased(self, address): self.speedTimer.stop() self.throttle = None self.speedAction.setThrottle(self.throttle) def notifyConsistAddressChosen(self, address, isLong): self.notifyAddressChosen(address) def notifyConsistAddressThrottleFound(self, throttle): self.notifyAddressThrottleFound(throttle) def notifyConsistAddressReleased(self, address, isLong): self.notifyAddressReleased(address)
class WiimoteThrottle2(Jynstrument, PropertyChangeListener, AddressListener, WiiDeviceDiscoveryListener, WiiRemoteListener, Runnable): #Jynstrument main and mandatory methods def getExpectedContextClassName(self): return "jmri.jmrit.throttle.ThrottleWindow" def init(self): self.getContext().addPropertyChangeListener( self) #ThrottleFrame change self.addressPanel = self.getContext().getCurrentThrottleFrame( ).getAddressPanel() self.addressPanel.addAddressListener( self) # change of throttle in Current frame self.throttle = self.getContext().getCurrentThrottleFrame( ).getAddressPanel().getThrottle() # the throttle self.speedAction = SpeedAction() #Speed increase thread self.speedAction.setThrottle(self.throttle) self.speedTimer = Timer( valueSpeedTimerRepeat, self.speedAction ) # Very important to use swing Timer object (see Swing and multithreading doc) self.speedTimer.setRepeats(True) self.label = JButton( ImageIcon(self.getFolder() + "/WiimoteThrottle2.png", "WiiMote")) #label self.label.addMouseListener( self.getMouseListeners() [0]) # In order to get the popupmenu on the button too self.add(self.label) self.lastTimeButton1 = Calendar.getInstance().getTimeInMillis() self.lastTimeButton2 = Calendar.getInstance().getTimeInMillis() self.advFunctions = AdvFunctions() self.lastTimeEStop = Calendar.getInstance().getTimeInMillis() self.wiiDevice = None self.sync = thread.allocate_lock() # A lock protecting bellow self.evt self.evt = None java.lang.System.setProperty("bluecove.jsr82.psm_minimum_off", "true") # Required for Bluecove + WiiRemoteJ WiiRemoteJ.findRemotes(self, 1) # Search for 1 Wiimote, and call back def quit(self): self.speedTimer.stop() WiiRemoteJ.stopFind() if ((self.wiiDevice != None) and (self.wiiDevice.isConnected())): self.wiiDevice.removeWiiRemoteListener(self) self.wiiDevice.disconnect() self.wiiDevice = None self.speedAction = None self.speedTimer = None self.throttle = None self.advFunctions = None self.getContext().removePropertyChangeListener(self) self.addressPanel.removeAddressListener(self) self.addressPanel = None #Wiimote discoverer events def findFinished(self, nb): print "Search finished, found ", nb, " wiimotes" def wiiDeviceDiscovered(self, evt): print "Found a Wiimote, number: ", evt.getNumber() self.wiiDevice = evt.getWiiDevice() ledLights = [False, False, False, False] ledLights[evt.getNumber() % 4] = True self.wiiDevice.setLEDLights(ledLights) self.wiiDevice.addWiiRemoteListener(self) #Wiimote events def buttonInputReceived(self, evt): # print("Wiimote Button event: ", evt) self.sync.acquire() self.evt = evt self.sync.release() SwingUtilities.invokeLater( self ) # Delegate processing to Swing thread (when we are here, we're in the WiiRemoteJ driver thread) def run(self): self.sync.acquire() evt = self.evt self.sync.release() if (self.speedTimer != None): self.speedTimer.stop() # In any case # ThrottleFrames if (evt.wasReleased(WRButtonEvent.RIGHT)): # NEXT self.getContext().nextThrottleFrame() if (evt.wasReleased(WRButtonEvent.LEFT)): # PREVIOUS self.getContext().previousThrottleFrame() if (evt.wasReleased(WRButtonEvent.UP)): # NEXT RUNNING self.getContext().nextRunningThrottleFrame() if (evt.wasReleased(WRButtonEvent.DOWN)): # PREVIOUS RUNNING self.getContext().previousRunningThrottleFrame() # No throttle assigned to current frame, browse through roster if (self.throttle == None): if (evt.wasReleased( WRButtonEvent.HOME)): # Assign selected roster entry self.addressPanel.selectRosterEntry() return if (evt.wasReleased(WRButtonEvent.PLUS)): # Next roster entry selectedIndex = self.addressPanel.getRosterSelectedIndex() self.addressPanel.setIcon(False) self.addressPanel.setVisible(True) self.addressPanel.setRosterSelectedIndex(selectedIndex + 1) return if (evt.wasReleased(WRButtonEvent.MINUS)): # Previous roster entry selectedIndex = self.addressPanel.getRosterSelectedIndex() self.addressPanel.setIcon(False) self.addressPanel.setVisible(True) self.addressPanel.setRosterSelectedIndex(selectedIndex - 1) return # Throttle assigned to current frame, control it if (self.throttle != None): # Speed control if (evt.isPressed(WRButtonEvent.B)): # SPEED - increment self.speedAction.setSpeedIncrement(valueSpeedIncrement) self.speedTimer.start() if (evt.isPressed(WRButtonEvent.A)): # SPEED - decrement self.speedAction.setSpeedIncrement(-valueSpeedIncrement) self.speedTimer.start() # EStop if (evt.isPressed(WRButtonEvent.PLUS | WRButtonEvent.MINUS)): # estop = + & - self.throttle.setSpeedSetting(speedEStopSpeed) self.lastTimeEStop = Calendar.getInstance().getTimeInMillis( ) # To cancel next inputs self.wiiDevice.vibrateFor(750) # Directions if (evt.wasReleased(WRButtonEvent.PLUS)): # FORWARD self.throttle.setIsForward(True) if (evt.wasReleased(WRButtonEvent.MINUS)): # BACKWARD self.throttle.setIsForward(False) # Home : F0 if (evt.wasReleased(WRButtonEvent.HOME)): # LIGHTS if not ((self.addressPanel.getRosterEntry() != None) and (self.advFunctions.call( self.addressPanel.getRosterEntry(), "0", False, self.throttle) != None)): self.throttle.setF0(not self.throttle.getF0()) # Wiimote 1 & 2 buttons if (evt.isPressed(WRButtonEvent.ONE)): if not ((self.addressPanel.getRosterEntry() != None) and (self.advFunctions.call( self.addressPanel.getRosterEntry(), "1", True, self.throttle) != None)): pass # default F1 not momentary (switch only on Release, do nothing here) if (evt.wasReleased(WRButtonEvent.ONE)): if not ((self.addressPanel.getRosterEntry() != None) and (self.advFunctions.call( self.addressPanel.getRosterEntry(), "1", False, self.throttle) != None)): self.throttle.setF1( not self.throttle.getF1()) # default F1 not momentary if (evt.isPressed(WRButtonEvent.TWO)): if not ((self.addressPanel.getRosterEntry() != None) and (self.advFunctions.call( self.addressPanel.getRosterEntry(), "2", True, self.throttle) != None)): self.throttle.setF2(True) # default F2 momentary if (evt.wasReleased(WRButtonEvent.TWO)): if not ((self.addressPanel.getRosterEntry() != None) and (self.advFunctions.call( self.addressPanel.getRosterEntry(), "2", False, self.throttle) != None)): self.throttle.setF2(False) def disconnected(self): self.wiiDevice = None print("Lost wiimote") def accelerationInputReceived(self, evt): pass def combinedInputReceived(self, evt): pass def extensionConnected(self, extension): pass def extensionDisconnected(self, extension): pass def extensionInputReceived(self, evt): pass def extensionPartiallyInserted(self): pass def extensionUnknown(self): pass def IRInputReceived(self, evt): pass def statusReported(self, evt): print("Wiimote status reported: ", evt) #Property listener part def propertyChange(self, event): self.speedTimer.stop() if (event.propertyName == "ThrottleFrame" ): # Current throttle frame changed event.oldValue.getAddressPanel().removeAddressListener(self) self.addressPanel = event.newValue.getAddressPanel() self.throttle = self.addressPanel.getThrottle() self.speedAction.setThrottle(self.throttle) self.addressPanel.addAddressListener(self) #AddressListener part: to listen for address changes in address panel (release, acquired) def notifyAddressChosen(self, address): pass def notifyAddressThrottleFound(self, throttle): self.speedTimer.stop() self.throttle = throttle self.speedAction.setThrottle(self.throttle) def notifyAddressReleased(self, address): self.speedTimer.stop() self.throttle = None self.speedAction.setThrottle(self.throttle) def notifyConsistAddressChosen(self, address, isLong): self.notifyAddressChosen(address) def notifyConsistAddressThrottleFound(self, throttle): self.notifyAddressThrottleFound(throttle) def notifyConsistAddressReleased(self, address, isLong): self.notifyAddressReleased(address)
class USBThrottle(Jynstrument, PropertyChangeListener, AddressListener): #Property listener part: USB value def propertyChange(self, event): # Customize bellow for throttles calls: if (event.propertyName == "Value") : # USB if (event.oldValue.getController() == self.desiredController ) : component = event.oldValue.getComponent().toString() value = event.newValue # Uncomment bellow line to see component name and its value # print "Component",component,"value changed to",value try: # Change current ThrottleFrame if ((component == self.driver.componentNextThrottleFrame) and (value == self.driver.valueNextThrottleFrame)) : #NEXT self.getContext().nextThrottleFrame() if ((component == self.driver.componentPreviousThrottleFrame) and (value == self.driver.valuePreviousThrottleFrame)) : #PREVIOUS self.getContext().previousThrottleFrame() if ((component == self.driver.componentNextRunningThrottleFrame) and (value == self.driver.valueNextRunningThrottleFrame)) : #NEXT RUNNING self.getContext().nextRunningThrottleFrame() if ((component == self.driver.componentPreviousRunningThrottleFrame) and (value == self.driver.valuePreviousRunningThrottleFrame)) : #PREVIOUS RUNNING self.getContext().previousRunningThrottleFrame() except AttributeError: pass if (self.throttle == None) : try: # Browse through roster if ((component == self.driver.componentNextRosterBrowse) and (value == self.driver.valueNextRoster)): #NEXT selectedIndex = self.addressPanel.getRosterSelectedIndex() self.addressPanel.setVisible(True) self.addressPanel.setIcon(False) self.addressPanel.setRosterSelectedIndex(selectedIndex + 1) if ((component == self.driver.componentPreviousRosterBrowse) and (value == self.driver.valuePreviousRoster)) : #PREVIOUS selectedIndex = self.addressPanel.getRosterSelectedIndex() self.addressPanel.setVisible(True) self.addressPanel.setIcon(False) self.addressPanel.setRosterSelectedIndex(selectedIndex - 1) except AttributeError: pass try: # Request a throttle if ((component == self.driver.componentRosterSelect) and (value == self.driver.valueRosterSelect)): self.addressPanel.selectRosterEntry() except AttributeError: pass # From there; current throttle control, hence require a throttle if (self.throttle != None) : # Release current throttle try: if ((component == self.driver.componentThrottleRelease) and (value == self.driver.valueThrottleRelease)): self.addressPanel.dispatchAddress() except AttributeError: pass try: # Speed - dynamic controler (joystick going back to neutral position) if ((component == self.driver.componentSpeedIncrease) or (component == self.driver.componentSpeedDecrease) or (component == self.driver.componentSpeed)): if ((component == self.driver.componentSpeedIncrease) and (value == self.driver.valueSpeedIncrease)) : self.speedAction.setSpeedIncrement( 0.03 ) if ((component == self.driver.componentSpeedDecrease) and (value == self.driver.valueSpeedDecrease)) : self.speedAction.setSpeedIncrement( -0.03 ) if (component == self.driver.componentSpeed) : try: self.vsd = valueSpeedDivider * self.driver.componentSpeedMultiplier except AttributeError: self.vsd = valueSpeedDivider self.speedAction.setSpeedIncrement(value / self.vsd) if ( abs(value) > self.driver.valueSpeedTrigger ) : self.speedTimer.start() else : self.speedTimer.stop() except AttributeError: self.speedTimer.stop() # just in case, stop it, really should never get there try: # Speed v2 - static controler (lever on RailDriver or AAR105) if (component == self.driver.componentSpeedSet): # negative is lever front, positive is lever back # limit range to only positive side of lever if (value < self.driver.valueSpeedSetMinValue) : value = self.driver.valueSpeedSetMinValue if (value > self.driver.valueSpeedSetMaxValue) : value = self.driver.valueSpeedSetMaxValue # convert fraction of input to speed step self.throttle.setSpeedSetting((value-self.driver.valueSpeedSetMinValue)/(self.driver.valueSpeedSetMaxValue-self.driver.valueSpeedSetMinValue)) print "Slider Speed:", self.controlPanel.getDisplaySlider() except AttributeError: pass # Direction try: if ((component == self.driver.componentDirectionForward) and (value == self.driver.valueDirectionForward)) : self.throttle.setIsForward(True) if ((component == self.driver.componentDirectionBackward) and (value == self.driver.valueDirectionBackward)) : self.throttle.setIsForward(False) except AttributeError: pass try: if ((component == self.driver.componentDirectionSwitch) and (value == self.driver.valueDirectionSwitch)) : self.throttle.setIsForward(not self.throttle.getIsForward()) except AttributeError: pass # Speed presets try: # STOP if ((component == self.driver.componentStopSpeed) and (value == self.driver.valueStopSpeed)) : if ( Calendar.getInstance().getTimeInMillis() - self.lastTimeStopButton < delay4doubleTap ) : self.throttle.setSpeedSetting(EStopSpeed) # EStop on double tap else: self.throttle.setSpeedSetting(speedStopSpeed) self.lastTimeStopButton = Calendar.getInstance().getTimeInMillis() except AttributeError: pass try: # EStop if ((component == self.driver.componentEStopSpeed) and (value == self.driver.valueEStopSpeed)): self.throttle.setSpeedSetting(EStopSpeed) except AttributeError: pass try: # EStop if ((component == self.driver.componentEStopSpeedBis) and (value == self.driver.valueEStopSpeedBis)): self.throttle.setSpeedSetting(EStopSpeed) except AttributeError: pass try: # SLOW if ((component == self.driver.componentSlowSpeed) and (value == self.driver.valueSlowSpeed)) : self.throttle.setSpeedSetting(speedSlowSpeed) except AttributeError: pass try: # CRUISE if ((component == self.driver.componentCruiseSpeed) and (value == self.driver.valueCruiseSpeed)) : if ( Calendar.getInstance().getTimeInMillis() - self.lastTimeCruiseButton < delay4doubleTap ) : # EStop on double tap self.throttle.setSpeedSetting(speedMaxSpeed) # Max speed on double tap else: self.throttle.setSpeedSetting(speedCruiseSpeed) self.lastTimeCruiseButton = Calendar.getInstance().getTimeInMillis() except AttributeError: pass try: # MAX if ((component == self.driver.componentMaxSpeed) and (value == self.driver.valueMaxSpeed)) : self.throttle.setSpeedSetting(speedMaxSpeed) except AttributeError: pass # Functions try: if ((component == self.driver.componentF0) and (value == self.driver.valueF0)) : self.throttle.setF0( not self.throttle.getF0() ) if ((self.roster != None) and (not self.roster.getFunctionLockable(0)) and (component == self.driver.componentF0) and (value == self.driver.valueF0Off)) : self.throttle.setF0( not self.throttle.getF0() ) except AttributeError: pass try: if ((component == self.driver.componentF1) and (value == self.driver.valueF1)) : self.throttle.setF1( not self.throttle.getF1() ) if ((self.roster != None) and (not self.roster.getFunctionLockable(1)) and (component == self.driver.componentF1) and (value == self.driver.valueF1Off)) : self.throttle.setF1( not self.throttle.getF1() ) except AttributeError: pass try: if ((component == self.driver.componentF2) and (value == self.driver.valueF2)) : self.throttle.setF2( not self.throttle.getF2() ) if ((self.roster != None) and (not self.roster.getFunctionLockable(2)) and (component == self.driver.componentF2) and (value == self.driver.valueF2Off)) : self.throttle.setF2( not self.throttle.getF2() ) except AttributeError: pass try: if ((component == self.driver.componentF3) and (value == self.driver.valueF3)) : self.throttle.setF3( not self.throttle.getF3() ) if ((self.roster != None) and (not self.roster.getFunctionLockable(3)) and (component == self.driver.componentF3) and (value == self.driver.valueF3Off)) : self.throttle.setF3( not self.throttle.getF3() ) except AttributeError: pass try: if ((component == self.driver.componentF4) and (value == self.driver.valueF4)) : self.throttle.setF4( not self.throttle.getF4() ) if ((self.roster != None) and (not self.roster.getFunctionLockable(4)) and (component == self.driver.componentF4) and (value == self.driver.valueF4Off)) : self.throttle.setF4( not self.throttle.getF4() ) except AttributeError: pass try: if ((component == self.driver.componentF5) and (value == self.driver.valueF5)) : self.throttle.setF5( not self.throttle.getF5() ) if ((self.roster != None) and (not self.roster.getFunctionLockable(5)) and (component == self.driver.componentF5) and (value == self.driver.valueF5Off)) : self.throttle.setF5( not self.throttle.getF5() ) except AttributeError: pass try: if ((component == self.driver.componentF6) and (value == self.driver.valueF6)) : self.throttle.setF6( not self.throttle.getF6() ) if ((self.roster != None) and (not self.roster.getFunctionLockable(6)) and (component == self.driver.componentF6) and (value == self.driver.valueF6Off)) : self.throttle.setF6( not self.throttle.getF6() ) except AttributeError: pass try: if ((component == self.driver.componentF7) and (value == self.driver.valueF7)) : self.throttle.setF7( not self.throttle.getF7() ) if ((self.roster != None) and (not self.roster.getFunctionLockable(7)) and (component == self.driver.componentF7) and (value == self.driver.valueF7Off)) : self.throttle.setF7( not self.throttle.getF7() ) except AttributeError: pass try: if ((component == self.driver.componentF8) and (value == self.driver.valueF8)) : self.throttle.setF8( not self.throttle.getF8() ) if ((self.roster != None) and (not self.roster.getFunctionLockable(8)) and (component == self.driver.componentF8) and (value == self.driver.valueF8Off)) : self.throttle.setF8( not self.throttle.getF8() ) except AttributeError: pass try: if ((component == self.driver.componentF9) and (value == self.driver.valueF9)) : self.throttle.setF9( not self.throttle.getF9() ) if ((self.roster != None) and (not self.roster.getFunctionLockable(9)) and (component == self.driver.componentF9) and (value == self.driver.valueF9Off)) : self.throttle.setF9( not self.throttle.getF9() ) except AttributeError: pass try: if ((component == self.driver.componentF10) and (value == self.driver.valueF10)) : self.throttle.setF10( not self.throttle.getF10() ) if ((self.roster != None) and (not self.roster.getFunctionLockable(10)) and (component == self.driver.componentF10) and (value == self.driver.valueF10Off)) : self.throttle.setF10( not self.throttle.getF10() ) except AttributeError: pass try: if ((component == self.driver.componentF11) and (value == self.driver.valueF11)) : self.throttle.setF11( not self.throttle.getF11() ) if ((self.roster != None) and (not self.roster.getFunctionLockable(11)) and (component == self.driver.componentF11) and (value == self.driver.valueF11Off)) : self.throttle.setF11( not self.throttle.getF11() ) except AttributeError: pass try: if ((component == self.driver.componentF12) and (value == self.driver.valueF12)) : self.throttle.setF12( not self.throttle.getF12() ) if ((self.roster != None) and (not self.roster.getFunctionLockable(12)) and (component == self.driver.componentF12) and (value == self.driver.valueF12Off)) : self.throttle.setF12( not self.throttle.getF12() ) except AttributeError: pass try: if ((component == self.driver.componentF13) and (value == self.driver.valueF13)) : self.throttle.setF13( not self.throttle.getF13() ) if ((self.roster != None) and (not self.roster.getFunctionLockable(13)) and (component == self.driver.componentF13) and (value == self.driver.valueF13Off)) : self.throttle.setF13( not self.throttle.getF13() ) except AttributeError: pass try: if ((component == self.driver.componentF14) and (value == self.driver.valueF14)) : self.throttle.setF14( not self.throttle.getF14() ) if ((self.roster != None) and (not self.roster.getFunctionLockable(14)) and (component == self.driver.componentF14) and (value == self.driver.valueF14Off)) : self.throttle.setF14( not self.throttle.getF14() ) except AttributeError: pass try: if ((component == self.driver.componentF15) and (value == self.driver.valueF15)) : self.throttle.setF15( not self.throttle.getF15() ) if ((self.roster != None) and (not self.roster.getFunctionLockable(15)) and (component == self.driver.componentF15) and (value == self.driver.valueF15Off)) : self.throttle.setF15( not self.throttle.getF15() ) except AttributeError: pass try: if ((component == self.driver.componentF16) and (value == self.driver.valueF16)) : self.throttle.setF16( not self.throttle.getF16() ) if ((self.roster != None) and (not self.roster.getFunctionLockable(16)) and (component == self.driver.componentF16) and (value == self.driver.valueF16Off)) : self.throttle.setF16( not self.throttle.getF16() ) except AttributeError: pass try: if ((component == self.driver.componentF17) and (value == self.driver.valueF17)) : self.throttle.setF17( not self.throttle.getF17() ) if ((self.roster != None) and (not self.roster.getFunctionLockable(17)) and (component == self.driver.componentF17) and (value == self.driver.valueF17Off)) : self.throttle.setF17( not self.throttle.getF17() ) except AttributeError: pass try: if ((component == self.driver.componentF18) and (value == self.driver.valueF18)) : self.throttle.setF18( not self.throttle.getF18() ) if ((self.roster != None) and (not self.roster.getFunctionLockable(18)) and (component == self.driver.componentF18) and (value == self.driver.valueF18Off)) : self.throttle.setF18( not self.throttle.getF18() ) except AttributeError: pass try: if ((component == self.driver.componentF19) and (value == self.driver.valueF19)) : self.throttle.setF19( not self.throttle.getF19() ) if ((self.roster != None) and (not self.roster.getFunctionLockable(19)) and (component == self.driver.componentF19) and (value == self.driver.valueF19Off)) : self.throttle.setF19( not self.throttle.getF19() ) except AttributeError: pass try: if ((component == self.driver.componentF20) and (value == self.driver.valueF20)) : self.throttle.setF20( not self.throttle.getF20() ) if ((self.roster != None) and (not self.roster.getFunctionLockable(20)) and (component == self.driver.componentF20) and (value == self.driver.valueF20Off)) : self.throttle.setF20( not self.throttle.getF20() ) except AttributeError: pass try: if ((component == self.driver.componentF21) and (value == self.driver.valueF21)) : self.throttle.setF21( not self.throttle.getF21() ) if ((self.roster != None) and (not self.roster.getFunctionLockable(21)) and (component == self.driver.componentF21) and (value == self.driver.valueF21Off)) : self.throttle.setF21( not self.throttle.getF21() ) except AttributeError: pass try: if ((component == self.driver.componentF22) and (value == self.driver.valueF22)) : self.throttle.setF22( not self.throttle.getF22() ) if ((self.roster != None) and (not self.roster.getFunctionLockable(22)) and (component == self.driver.componentF22) and (value == self.driver.valueF22Off)) : self.throttle.setF22( not self.throttle.getF22() ) except AttributeError: pass try: if ((component == self.driver.componentF23) and (value == self.driver.valueF23)) : self.throttle.setF23( not self.throttle.getF23() ) if ((self.roster != None) and (not self.roster.getFunctionLockable(23)) and (component == self.driver.componentF23) and (value == self.driver.valueF23Off)) : self.throttle.setF23( not self.throttle.getF23() ) except AttributeError: pass try: if ((component == self.driver.componentF24) and (value == self.driver.valueF24)) : self.throttle.setF24( not self.throttle.getF24() ) if ((self.roster != None) and (not self.roster.getFunctionLockable(24)) and (component == self.driver.componentF24) and (value == self.driver.valueF24Off)) : self.throttle.setF24( not self.throttle.getF24() ) except AttributeError: pass try: if ((component == self.driver.componentF25) and (value == self.driver.valueF25)) : self.throttle.setF25( not self.throttle.getF25() ) if ((self.roster != None) and (not self.roster.getFunctionLockable(25)) and (component == self.driver.componentF25) and (value == self.driver.valueF25Off)) : self.throttle.setF25( not self.throttle.getF25() ) except AttributeError: pass try: if ((component == self.driver.componentF26) and (value == self.driver.valueF26)) : self.throttle.setF26( not self.throttle.getF26() ) if ((self.roster != None) and (not self.roster.getFunctionLockable(26)) and (component == self.driver.componentF26) and (value == self.driver.valueF26Off)) : self.throttle.setF26( not self.throttle.getF26() ) except AttributeError: pass try: if ((component == self.driver.componentF27) and (value == self.driver.valueF27)) : self.throttle.setF27( not self.throttle.getF27() ) if ((self.roster != None) and (not self.roster.getFunctionLockable(27)) and (component == self.driver.componentF27) and (value == self.driver.valueF27Off)) : self.throttle.setF27( not self.throttle.getF27() ) except AttributeError: pass try: if ((component == self.driver.componentF28) and (value == self.driver.valueF28)) : self.throttle.setF28( not self.throttle.getF28() ) if ((self.roster != None) and (not self.roster.getFunctionLockable(28)) and (component == self.driver.componentF28) and (value == self.driver.valueF28Off)) : self.throttle.setF28( not self.throttle.getF28() ) except AttributeError: pass try: if ((component == self.driver.componentF29) and (value == self.driver.valueF29)) : self.throttle.setF29( not self.throttle.getF29() ) if ((self.roster != None) and (not self.roster.getFunctionLockable(29)) and (component == self.driver.componentF29) and (value == self.driver.valueF29Off)) : self.throttle.setF29( not self.throttle.getF29() ) except AttributeError: pass # Nothing to customize bellow this point if (event.propertyName == "ThrottleFrame") : # Current throttle frame changed self.speedTimer.stop() event.oldValue.getAddressPanel().removeAddressListener(self) self.addressPanel = event.newValue.getAddressPanel() self.throttle = self.addressPanel.getThrottle() self.roster = self.addressPanel.getRosterEntry() self.speedAction.setThrottle( self.throttle ) event.newValue.getAddressPanel().addAddressListener(self) #Jynstrument main and mandatory methods def getExpectedContextClassName(self): return "jmri.jmrit.throttle.ThrottleWindow" def init(self): self.getContext().addPropertyChangeListener(self) #ThrottleFrame change self.getContext().getCurrentThrottleFrame().getAddressPanel().addAddressListener(self) # change of throttle in Current frame self.addressPanel = self.getContext().getCurrentThrottleFrame().getAddressPanel() self.throttle = self.addressPanel.getThrottle() # the throttle self.roster = self.addressPanel.getRosterEntry() # roster entry if any self.speedAction = SpeedAction() #Speed increase thread self.speedAction.setThrottle( self.throttle ) self.speedTimer = Timer(valueSpeedTimerRepeat, self.speedAction ) # Very important to use swing Timer object (see Swing and multithreading doc) self.speedTimer.setRepeats(True) self.label = JButton(ImageIcon(self.getFolder() + "/USBControl.png","USBThrottle")) #label self.label.addMouseListener(self.getMouseListeners()[0]) # In order to get the popupmenu on the button too self.add(self.label) self.model = jmri.jmrix.jinput.TreeModel.instance() # USB self.desiredController = None self.ctrlMenuItem = [] self.USBDriver = None self.driver = None mi = JCheckBoxMenuItem ("None") self.getPopUpMenu().add( mi ) mi.addItemListener( ControllerItemListener(None, self) ) self.ctrlMenuItem.append(mi) for ctrl in self.model.controllers(): mi = JCheckBoxMenuItem (ctrl.getName()) self.getPopUpMenu().add( mi ) mi.addItemListener( ControllerItemListener(ctrl, self) ) self.ctrlMenuItem.append(mi) if ( len(self.ctrlMenuItem) == 0 ): print "No matching USB device found" else: self.ctrlMenuItem[0].setSelected(True) # by default connect to the first one self.model.addPropertyChangeListener(self) self.lastTimeStopButton = Calendar.getInstance().getTimeInMillis() self.lastTimeCruiseButton = Calendar.getInstance().getTimeInMillis() # On quit clean up resources def quit(self): self.speedTimer.stop() for mi in self.ctrlMenuItem : self.getPopUpMenu().remove( mi ) self.ctrlMenuItem = None self.speedAction = None self.speedTimer = None self.throttle = None self.addressPanel = None self.driver = None self.USBDriver = None self.getContext().removePropertyChangeListener(self) self.model.removePropertyChangeListener(self) self.getContext().getCurrentThrottleFrame().getAddressPanel().removeAddressListener(self) # Menu entry changed for Current controller and update driver def setSelectedController(self, ctrl, item): for mi in self.ctrlMenuItem : if ( mi != item ): # Force deselection of other ones mi.setSelected(False) self.desiredController = ctrl if (ctrl != None) : sys.path.append(self.getFolder()) # Load a driver try: del self.driver del self.USBDriver dd=ctrl.getName() dd=dd.replace(" ", "") dd=dd.replace(".", "") dd=dd.replace("(", "") dd=dd.replace(")", "") dd=dd.replace("{", "") dd=dd.replace("}", "") dd=dd.replace("[", "") dd=dd.replace("]", "") self.USBDriver = __import__(dd) except ImportError: # On error load a default one print "Driver \""+ dd +"\" not found in \""+self.getFolder()+"\", loading default one" self.USBDriver = __import__("Default") reload(self.USBDriver) sys.path.remove(self.getFolder()) self.driver = self.USBDriver.USBDriver() def setXml(self, elt): if (elt.getChildren("USBThrottle") == None): return ctrl = elt.getChildren("USBThrottle")[0].getAttributeValue("DesiredController") if (ctrl == None): return for mi in self.ctrlMenuItem : if ( mi.getText() == ctrl ): mi.setSelected(True) break def getXml(self): elt = Element("USBThrottle") for mi in self.ctrlMenuItem : if (mi.isSelected()) : elt.setAttribute("DesiredController", mi.getText()) break return elt #AddressListener part: to listen for address changes in address panel (release, acquired) def notifyAddressChosen(self, address): pass def notifyAddressThrottleFound(self, throttle): self.speedTimer.stop() self.throttle = throttle self.speedAction.setThrottle( self.throttle ) def notifyAddressReleased(self, address): self.speedTimer.stop() self.throttle = None self.speedAction.setThrottle( self.throttle ) def notifyConsistAddressChosen(self, address, isLong): self.notifyAddressChosen(address) def notifyConsistAddressThrottleFound(self, throttle): self.notifyAddressThrottleFound(throttle) def notifyConsistAddressReleased(self, address, isLong): self.notifyAddressReleased(address)
class Board(JPanel, KeyListener, ActionListener): def __init__(self): super(Board, self).__init__() self.initUI() def initUI(self): self.setBackground(Color.black) iid = ImageIcon("dot.png") self.ball = iid.getImage() iia = ImageIcon("apple.png") self.apple = iia.getImage() iih = ImageIcon("head.png") self.head = iih.getImage() self.setFocusable(True) self.addKeyListener(self) self.initGame() def initGame(self): self.left = False self.right = True self.up = False self.down = False self.inGame = True self.dots = 3 for i in range(self.dots): x[i] = 50 - i * 10 y[i] = 50 self.locateApple() self.timer = Timer(DELAY, self) self.timer.start() def paint(self, g): # due to bug, cannot call super() JPanel.paint(self, g) if self.inGame: self.drawObjects(g) else: self.gameOver(g) def drawObjects(self, g): g.drawImage(self.apple, self.apple_x, self.apple_y, self) for z in range(self.dots): if (z == 0): g.drawImage(self.head, x[z], y[z], self) else: g.drawImage(self.ball, x[z], y[z], self) Toolkit.getDefaultToolkit().sync() g.dispose() def gameOver(self, g): msg = "Game Over" small = Font("Helvetica", Font.BOLD, 14) metr = self.getFontMetrics(small) g.setColor(Color.white) g.setFont(small) g.drawString(msg, (WIDTH - metr.stringWidth(msg)) / 2, HEIGHT / 2) def checkApple(self): if x[0] == self.apple_x and y[0] == self.apple_y: self.dots = self.dots + 1 self.locateApple() def move(self): z = self.dots while z > 0: x[z] = x[(z - 1)] y[z] = y[(z - 1)] z = z - 1 if self.left: x[0] -= DOT_SIZE if self.right: x[0] += DOT_SIZE if self.up: y[0] -= DOT_SIZE if self.down: y[0] += DOT_SIZE def checkCollision(self): z = self.dots while z > 0: if z > 4 and x[0] == x[z] and y[0] == y[z]: self.inGame = False z = z - 1 if y[0] > HEIGHT - DOT_SIZE: self.inGame = False if y[0] < 0: self.inGame = False if x[0] > WIDTH - DOT_SIZE: self.inGame = False if x[0] < 0: self.inGame = False def locateApple(self): r = random.randint(0, RAND_POS) self.apple_x = r * DOT_SIZE r = random.randint(0, RAND_POS) self.apple_y = r * DOT_SIZE # public void actionPerformed(ActionEvent e) { def actionPerformed(self, e): if self.inGame: self.checkApple() self.checkCollision() self.move() else: self.timer.stop() self.repaint() def keyPressed(self, e): key = e.getKeyCode() if key == KeyEvent.VK_LEFT and not self.right: self.left = True self.up = False self.down = False if key == KeyEvent.VK_RIGHT and not self.left: self.right = True self.up = False self.down = False if key == KeyEvent.VK_UP and not self.down: self.up = True self.right = False self.left = False if key == KeyEvent.VK_DOWN and not self.up: self.down = True self.right = False self.left = False
class XYPlot(core.DataViewComponent): def __init__(self, view, name, func, args=(), filter=None, label=None): core.DataViewComponent.__init__(self, label) self.view = view self.name = name self.func = func self.indices = None self.data = self.view.watcher.watch(name, func, args=args) self.margin = 10 self.autozoom = True self.last_maxy = None self.popup_zoom = JCheckBoxMenuItem('auto-zoom', self.autozoom, stateChanged=self.toggle_autozoom) self.popup.add(self.popup_zoom) self.autohide = True self.show_axes_labels = True self.popup_hide = JCheckBoxMenuItem('auto-hide axis labels', True, actionPerformed=self.toggle_autohide) self.popup.add(self.popup_hide) self.axes_label_init_clr = 0.3 self.axes_label_clr_val = self.axes_label_init_clr self.axes_label_clr_step = (1 - self.axes_label_init_clr) / 10 self.axes_label_hide_dly = 1000 self.axes_label_hide_tmr = Timer(self.axes_label_hide_dly / 10, None, actionPerformed=self.fade_axes_labels) self.filter = filter self.setSize(200, 200) def save(self): save_info = core.DataViewComponent.save(self) save_info['sel_dim'] = self.indices save_info['autozoom'] = self.autozoom save_info['last_maxy'] = self.last_maxy save_info['autohide'] = self.autohide return save_info def restore(self, d): core.DataViewComponent.restore(self, d) self.indices = d.get('sel_dim', [0, 1]) self.autozoom = d.get('autozoom', True) self.popup_zoom.state = self.autozoom self.last_maxy = d.get('last_maxy', None) self.autohide = d.get('autohide', True) self.popup_hide.state = self.autohide self.show_axes_labels = not self.autohide self.fix_popup() def toggle_autozoom(self, event): self.autozoom = event.source.state self.repaint() def toggle_autohide(self, event): self.autohide = event.source.state if(self.autohide): self.axes_label_hide_tmr.start() else: self.disp_axes_labels() def fix_popup(self): self.popup.add(JPopupMenu.Separator()) # Add submenus for x and y axes x_menu = JMenu("X Axis") y_menu = JMenu("Y Axis") self.popup.add(x_menu) self.popup.add(y_menu) x_btngrp = ButtonGroup() y_btngrp = ButtonGroup() # Calculate number of submenu layers needed max_ind = len(self.data.get_first()) num_sub = max(1, int(ceil(log(max_ind) / log(self.max_show_dim)))) max_sub = [self.max_show_dim ** (num_sub - i) for i in range(num_sub)] x_subs = [x_menu] * num_sub y_subs = [y_menu] * num_sub for i in range(max_ind): if(i % self.max_show_dim == 0): for n in range(num_sub - 1): if(i % max_sub[n + 1] == 0): new_xmenu = JMenu("%s[%d:%d]" % ('v', i, min(max_ind, i + max_sub[n + 1]) - 1)) new_ymenu = JMenu("%s[%d:%d]" % ('v', i, min(max_ind, i + max_sub[n + 1]) - 1)) x_subs[n].add(new_xmenu) x_subs[n + 1] = new_xmenu y_subs[n].add(new_ymenu) y_subs[n + 1] = new_ymenu x_radio = JRadioButtonMenuItem('%s[%d]' % ('v', i), i == self.indices[0], actionPerformed=lambda x, index=i, self=self: self.indices.__setitem__(0, index)) y_radio = JRadioButtonMenuItem('%s[%d]' % ('v', i), i == self.indices[1], actionPerformed=lambda x, index=i, self=self: self.indices.__setitem__(1, index)) x_btngrp.add(x_radio) y_btngrp.add(y_radio) x_subs[num_sub - 1].add(x_radio) y_subs[num_sub - 1].add(y_radio) def mouseEntered(self, event): if(self.autohide): self.disp_axes_labels() core.DataViewComponent.mouseEntered(self, event) def mouseExited(self, event): if(self.autohide): self.axes_label_hide_tmr.start() core.DataViewComponent.mouseExited(self, event) def disp_axes_labels(self): self.axes_label_clr_val = self.axes_label_init_clr self.show_axes_labels = True self.axes_label_hide_tmr.stop() self.repaint() def fade_axes_labels(self, event): if(self.show_axes_labels): if(self.axes_label_clr_val >= 1 - self.axes_label_clr_step): self.axes_label_hide_tmr.stop() self.show_axes_labels = False else: self.axes_label_clr_val += self.axes_label_clr_step self.axes_label_clr_val = min(1, self.axes_label_clr_val) self.axes_label_hide_tmr.start() self.repaint() def paintComponent(self, g): core.DataViewComponent.paintComponent(self, g) xc = self.width / 2 yc = (self.height - self.label_offset) / 2 x0 = self.margin / 2.0 y0 = self.margin / 2.0 g.color = Color(0.8, 0.8, 0.8) g.drawRect(int(x0) - 1, int(y0 + self.label_offset) - 1, int(self.size.width - self.margin) + 1, int(self.size.height - self.label_offset - self.margin) + 1) g.drawLine(xc, self.margin + self.label_offset, xc, self.height - self.margin) g.drawLine(self.margin, yc + self.label_offset, self.width - self.margin, yc + self.label_offset) dt_tau = None if self.filter and self.view.tau_filter > 0: dt_tau = self.view.dt / self.view.tau_filter pts = int(self.view.time_shown / self.view.dt) try: data = self.data.get(start=self.view.current_tick - pts + 1, count=pts, dt_tau=dt_tau) except: return if data is None: return if(self.indices is None): self.indices = [0, 1] self.fix_popup() xs = [d[self.indices[0]] for d in data if d is not None] ys = [d[self.indices[1]] for d in data if d is not None] if len(xs) > 0: mx = max(max(xs), max(ys), -min(xs), -min(ys)) mx = round(mx)[1] if mx < 1.0: mx = 1.0 else: mx = 1.0 if(not self.autozoom and self.last_maxy is not None and mx < self.last_maxy): mx = self.last_maxy self.last_maxy = mx g.color = Color.black txt = '%g' % mx bounds = g.font.getStringBounds(txt, g.fontRenderContext) #g.drawString(txt,xc+self.margin,bounds.height) g.drawString(txt, xc + x0, bounds.height + self.margin + self.label_offset) g.drawString(txt, self.width - self.margin - bounds.width, yc + bounds.height + self.label_offset) txt = '%g' % (-mx) #g.drawString(txt,xc+self.margin,self.height-self.margin) g.drawString(txt, xc + x0, self.height - self.margin) g.drawString(txt, self.margin, yc + bounds.height + self.label_offset) if(self.show_axes_labels): g.color = Color(self.axes_label_clr_val, self.axes_label_clr_val, self.axes_label_clr_val) txt = '%s[%d]' % ('v', self.indices[0]) boundsl = g.font.getStringBounds(txt, g.fontRenderContext) g.drawString(txt, self.width - self.margin - boundsl.width, yc - y0 + self.label_offset) txt = '%s[%d]' % ('v', self.indices[1]) boundsl = g.font.getStringBounds(txt, g.fontRenderContext) g.drawString(txt, xc - x0 - boundsl.width, bounds.height + self.margin + self.label_offset) g.color = Color.black pdftemplate = getattr(self.view.area, 'pdftemplate', None) if pdftemplate is not None: pdf, scale = pdftemplate pdf.setLineWidth(0.5) last_color = None sx = (self.width / 2 - self.margin) / mx sy = (yc - self.margin) / mx for i in range(pts - 1): if data[i] is not None and data[i + 1] is not None: x0 = data[i][self.indices[0]] y0 = data[i][self.indices[1]] x1 = data[i + 1][self.indices[0]] y1 = data[i + 1][self.indices[1]] c = 1.0 - i / float(pts - 1) g.color = Color(c, c, c) if pdftemplate is None: g.drawLine(int(xc + x0 * sx), int(yc - y0 * sy + self.label_offset), int(xc + x1 * sx), int(yc - y1 * sy + self.label_offset)) else: c = int(c * 32) * 8 if c > 255: c = 255 if c != last_color: if last_color is not None: pdf.setRGBColorStroke(last_color, last_color, last_color) pdf.stroke() pdf.moveTo(((xc + x0 * sx) + self.x) * scale, 800 - (self.y + yc - y0 * sy + self.label_offset) * scale) last_color = c pdf.lineTo(((xc + x1 * sx) + self.x) * scale, 800 - (self.y + yc - y1 * sy + self.label_offset) * scale) if pdftemplate is not None: pdf.setRGBColorStroke(last_color, last_color, last_color) pdf.stroke()
class WiimoteThrottle(Jynstrument, PropertyChangeListener, AddressListener, WiiDeviceDiscoveryListener, WiiRemoteListener, Runnable): #Wiimote discoverer events def findFinished(self, nb): print "Search finished, found ",nb ," wiimotes" def wiiDeviceDiscovered(self, evt): print "Found a Wiimote, number: ", evt.getNumber() self.wiiDevice = evt.getWiiDevice() ledLights = [False, False, False, False] ledLights[evt.getNumber()%4] = True self.wiiDevice.setLEDLights(ledLights) self.wiiDevice.addWiiRemoteListener(self) #Wiimote events def buttonInputReceived(self, evt): # print("Wiimote Button event: ", evt) self.sync.acquire() self.evt = evt self.sync.release() SwingUtilities.invokeLater(self) # Delegate processing to Swing thread (when we are here, we're in the WiiRemoteJ driver thread) def run(self): self.sync.acquire() evt = self.evt self.sync.release() if (self.speedTimer != None): self.speedTimer.stop() # In any case # ThrottleFrames if ( evt.wasReleased(WRButtonEvent.RIGHT) ): # NEXT self.getContext().nextThrottleFrame() if ( evt.wasReleased(WRButtonEvent.LEFT) ): # PREVIOUS self.getContext().previousThrottleFrame() if ( evt.wasReleased(WRButtonEvent.UP) ): # NEXT RUNNING self.getContext().nextRunningThrottleFrame() if ( evt.wasReleased(WRButtonEvent.DOWN) ): # PREVIOUS RUNNING self.getContext().previousRunningThrottleFrame() # No throttle assigned to current frame, browse through roster if (self.throttle == None): if ( evt.wasReleased(WRButtonEvent.HOME) ): # Assign selected roster entry self.addressPanel.selectRosterEntry() return if ( evt.wasReleased(WRButtonEvent.PLUS) ): # Next roster entry selectedIndex = self.addressPanel.getRosterSelectedIndex() self.addressPanel.setIcon(False) self.addressPanel.setVisible(True) self.addressPanel.setRosterSelectedIndex(selectedIndex + 1) return if ( evt.wasReleased(WRButtonEvent.MINUS) ): # Previous roster entry selectedIndex = self.addressPanel.getRosterSelectedIndex() self.addressPanel.setIcon(False) self.addressPanel.setVisible(True) self.addressPanel.setRosterSelectedIndex(selectedIndex - 1) return # Throttle assigned to current frame, control it if (self.throttle != None): if ( evt.wasReleased(WRButtonEvent.HOME) ): # LIGHTS self.throttle.setF0( not self.throttle.getF0() ) return if ( evt.wasReleased(WRButtonEvent.PLUS) ): # FORWARD self.throttle.setIsForward(True) return if ( evt.wasReleased(WRButtonEvent.MINUS) ): # BACKWARD self.throttle.setIsForward(False) return # Speed control if ( evt.isPressed(WRButtonEvent.B) ): # SPEED - increment self.speedAction.setSpeedIncrement( valueSpeedIncrement ) self.speedTimer.start() return if ( evt.isPressed(WRButtonEvent.A) ): # SPEED - decrement self.speedAction.setSpeedIncrement( -valueSpeedIncrement ) self.speedTimer.start() return # EStop if ( evt.isPressed( WRButtonEvent.ONE | WRButtonEvent.TWO ) ): # estop = button1 + button2 self.throttle.setSpeedSetting( speedEStopSpeed ) self.lastTimeEStop = Calendar.getInstance().getTimeInMillis() # To cancel next inputs self.wiiDevice.vibrateFor(750) return # Speed presets if (Calendar.getInstance().getTimeInMillis() - self.lastTimeEStop > delay4double): # Delay for nothing after EStop if (( evt.wasReleased(WRButtonEvent.TWO) ) and #STOP = button2 x2 or (button2 and CurrentSpeed = slow speed) ( (Calendar.getInstance().getTimeInMillis() - self.lastTimeButton2 < delay4double) or ( self.throttle.getSpeedSetting() == speedSlowSpeed ))): self.throttle.setSpeedSetting( speedStopSpeed ) return if ( evt.wasReleased(WRButtonEvent.TWO) ): # SLOW SPEED = button2 self.throttle.setSpeedSetting( speedSlowSpeed ) self.lastTimeButton2 = Calendar.getInstance().getTimeInMillis() return if (( evt.wasReleased(WRButtonEvent.ONE) ) and # MAX SPEED = button1x2 or (button1 and CurrentSpeed = cruise speed) ( (Calendar.getInstance().getTimeInMillis() - self.lastTimeButton1 < delay4double) or ( self.throttle.getSpeedSetting() == speedCruiseSpeed ))): self.throttle.setSpeedSetting( speedMaxSpeed ) return if ( evt.wasReleased( WRButtonEvent.ONE) ): # CRUISE SPEED = button1 self.throttle.setSpeedSetting( speedCruiseSpeed ) self.lastTimeButton1 = Calendar.getInstance().getTimeInMillis() return def disconnected(self): self.wiiDevice = None print("Lost wiimote") def accelerationInputReceived(self, evt): pass def combinedInputReceived(self, evt): pass def extensionConnected(self, extension): pass def extensionDisconnected(self, extension): pass def extensionInputReceived(self, evt): pass def extensionPartiallyInserted(self): pass def extensionUnknown(self): pass def IRInputReceived(self, evt): pass def statusReported(self, evt): print("Wiimote status reported: ", evt) #Property listener part def propertyChange(self, event): self.speedTimer.stop() if (event.propertyName == "ThrottleFrame") : # Current throttle frame changed event.oldValue.getAddressPanel().removeAddressListener(self) self.addressPanel = event.newValue.getAddressPanel() self.throttle = self.addressPanel.getThrottle() self.speedAction.setThrottle( self.throttle ) self.addressPanel.addAddressListener(self) #Jynstrument main and mandatory methods def getExpectedContextClassName(self): return "jmri.jmrit.throttle.ThrottleWindow" def init(self): self.getContext().addPropertyChangeListener(self) #ThrottleFrame change self.addressPanel=self.getContext().getCurrentThrottleFrame().getAddressPanel(); self.addressPanel.addAddressListener(self) # change of throttle in Current frame self.throttle = self.getContext().getCurrentThrottleFrame().getAddressPanel().getThrottle() # the throttle self.speedAction = SpeedAction() #Speed increase thread self.speedAction.setThrottle( self.throttle ) self.speedTimer = Timer(valueSpeedTimerRepeat, self.speedAction ) # Very important to use swing Timer object (see Swing and multithreading doc) self.speedTimer.setRepeats(True) self.label = JButton(ImageIcon(self.getFolder() + "/WiimoteThrottle.png","WiiMote")) #label self.label.addMouseListener(self.getMouseListeners()[0]) # In order to get the popupmenu on the button too self.add(self.label) self.lastTimeButton1 = Calendar.getInstance().getTimeInMillis() self.lastTimeButton2 = Calendar.getInstance().getTimeInMillis() self.lastTimeEStop = Calendar.getInstance().getTimeInMillis() self.wiiDevice = None self.sync = thread.allocate_lock() # A lock protecting bellow self.evt self.evt = None java.lang.System.setProperty("bluecove.jsr82.psm_minimum_off", "true"); # Required for Bluecove + WiiRemoteJ WiiRemoteJ.findRemotes(self, 1) # Search for 1 Wiimote, and call back def quit(self): self.speedTimer.stop() WiiRemoteJ.stopFind() if ((self.wiiDevice != None) and (self.wiiDevice.isConnected())): self.wiiDevice.removeWiiRemoteListener(self) self.wiiDevice.disconnect() self.wiiDevice = None self.speedAction = None self.speedTimer = None self.throttle = None self.getContext().removePropertyChangeListener(self) self.addressPanel.removeAddressListener(self) self.addressPanel = None #AddressListener part: to listen for address changes in address panel (release, acquired) def notifyAddressChosen(self, address): pass def notifyAddressThrottleFound(self, throttle): self.speedTimer.stop() self.throttle = throttle self.speedAction.setThrottle( self.throttle ) def notifyAddressReleased(self, address): self.speedTimer.stop() self.throttle = None self.speedAction.setThrottle( self.throttle ) def notifyConsistAddressChosen(self, address, isLong): self.notifyAddressChosen(address) def notifyConsistAddressThrottleFound(self, throttle): self.notifyAddressThrottleFound(throttle) def notifyConsistAddressReleased(self, address, isLong): self.notifyAddressReleased(address)
class FunctionControl(core.DataViewComponent, ComponentListener): def __init__(self, view, name, func, label=None): core.DataViewComponent.__init__(self, label) self.view = view self.name = name self.func = func self.label_height = 18 self.resize_border = 2 self.popup_hide_limit = JCheckBoxMenuItem('auto-hide limits', True, actionPerformed=self.toggle_autohide) self.popup.add(self.popup_hide_limit) self.show_limits = False self.auto_hide_limits = True self.limits_font = Font("Dialog", Font.PLAIN, 10) self.limit_width = 0 self.limit_hide_delay = 1000 self.limit_color_def = 0.3 self.limit_color_val = self.limit_color_def self.limit_color_step = (1 - self.limit_color_def) / 10 self.limit_hide_timer = Timer(self.limit_hide_delay / 10, None, actionPerformed=self.hide_limits) self.limit_hide_timer.setRepeats(False) self.popup.add(JPopupMenu.Separator()) self.popup.add(JMenuItem('zero', actionPerformed=self.zero)) self.popup.add(JMenuItem('set value', actionPerformed=self.set_value)) self.filename = None self.popup.add(JMenuItem('set from file...', actionPerformed=self.set_from_file)) self.popup.add(JPopupMenu.Separator()) self.popup.add(JMenuItem('increase range', actionPerformed=self.increase_range)) self.popup.add(JMenuItem('decrease range', actionPerformed=self.decrease_range)) self.scale_factor = 0.01 self.range = 1.0 self.data = self.view.watcher.watch(name, func) values = self.data.get_first() self.sliders = [] self.labels = [] for i, v in enumerate(values): vv = int(v * 100 / self.range) if vv > 100: vv = 100 if vv < -100: vv = -100 slider = JSlider(JSlider.VERTICAL, -100, 100, vv, stateChanged=lambda event, index=i: self.slider_moved(index)) slider.background = Color.white self.add(slider) self.sliders.append(slider) label = JLabel('0.00') self.add(label) self.labels.append(label) slider.addMouseListener(self) self.setSize(len(values) * 40 + 40, 200) self.addComponentListener(self) self.componentResized(None) def increase_range(self, event): self.range *= 2.0 self.check_label_size() self.repaint() def decrease_range(self, event): self.range *= 0.5 self.check_label_size() self.repaint() def check_label_size(self): if(self.show_limits): limit_label = JLabel(("-%1.2f" % (self.range))) limit_width = limit_label.getPreferredSize().width - self.sliders[0].width / 2 if(limit_width != self.limit_width): self.setSize(self.size.width + limit_width - self.limit_width, self.size.height) self.setLocation(self.x - limit_width + self.limit_width, self.y) self.limit_width = limit_width def zero(self, event): for i in range(len(self.sliders)): self.set_slider_value(i, 0) def set_value(self, event): try: example = ','.join(['%1.1f' % random.uniform(-5, 5) for i in range(len(self.sliders))]) text = JOptionPane.showInputDialog(self.view.frame, 'Enter input value. \nExample: %s' % example, "Set value", JOptionPane.PLAIN_MESSAGE, None, None, None) v = eval(text) if isinstance(v, (int, float)): v = [v] if len(v) > len(self.sliders): v = v[:len(self.sliders)] for i, vv in enumerate(v): self.set_slider_value(i, vv) except: self.release_value(event) def set_from_file(self, event): fileChooser = JFileChooser() if self.filename is not None: fileChooser.setSelectedFile(java.io.File(self.filename)) if fileChooser.showOpenDialog(self) == JFileChooser.APPROVE_OPTION: self.filename = fileChooser.selectedFile.absolutePath #TODO: this doesn't for for nested FunctionInputs input = self.view.network.getNode(self.name) from nef.functions import Interpolator interp = Interpolator(self.filename) interp.load_into_function(input) def set_slider_value(self, index, value): sv = value / (self.scale_factor * self.range) self.sliders[index].value = int(sv) self.labels[index].text = '%1.2f' % value self.check_label_size() self.repaint() if self.view.paused: # change immediately, bypassing filter self.data.data[-1][index] = value self.view.forced_origins_prev[(self.name, 'origin', index)] = value self.view.forced_origins[(self.name, 'origin', index)] = value def slider_moved(self, index): if self.sliders[index].valueIsAdjusting: # if I moved it v = self.sliders[index].value * self.scale_factor * self.range self.labels[index].text = '%1.2f' % v if self.view.paused: # change immediately, bypassing filter self.data.data[-1][index] = v self.view.forced_origins_prev[(self.name, 'origin', index)] = v self.view.forced_origins[(self.name, 'origin', index)] = v def paintComponent(self, g): temp = self.show_label self.show_label = False core.DataViewComponent.paintComponent(self, g) self.show_label = temp if self.show_label: g.color = Color(0.3, 0.3, 0.3) bounds = g.font.getStringBounds(self.label, g.fontRenderContext) g.drawString(self.label, (self.size.width - self.limit_width) / 2 - bounds.width / 2 + self.limit_width, bounds.height) self.active = self.view.current_tick >= self.view.timelog.tick_count - 1 data = self.data.get(start=self.view.current_tick, count=1)[0] if data is None: data = self.data.get_first() if(self.show_limits): g.color = Color(self.limit_color_val, self.limit_color_val, self.limit_color_val) txt_min = "%1.2f" % (-self.range) txt_max = "%1.2f" % (self.range) temp_font = g.font g.font = self.limits_font bounds_min = g.font.getStringBounds(txt_min, g.fontRenderContext) bounds_max = g.font.getStringBounds(txt_max, g.fontRenderContext) g.drawString(txt_max, 10 + bounds_min.width - bounds_max.width, self.resize_border + self.label_offset + bounds_max.height) g.drawString(txt_min, 10, self.height - self.resize_border - self.labels[0].getPreferredSize().height - bounds_min.height) g.font = temp_font for i, v in enumerate(data): while v > self.range * 1.1: self.range *= 2 while v < -self.range * 1.1: self.range *= 2 for i, v in enumerate(data): sv = int(v * 100.0 / self.range) if sv > 100: sv = 100 if sv < -100: sv = -100 if not self.sliders[i].valueIsAdjusting: self.sliders[i].value = sv self.labels[i].text = '%1.2f' % v self.sliders[i].enabled = self.active self.componentResized(None) def componentResized(self, e): w = self.width - self.resize_border * 2 - self.limit_width dw = w / len(self.sliders) x = (dw - self.sliders[0].minimumSize.width) / 2 for i, slider in enumerate(self.sliders): slider.setLocation(self.limit_width + self.resize_border + x + i * dw, self.resize_border + self.label_offset) slider.setSize(slider.minimumSize.width, self.height - self.resize_border * 2 - 20 - self.label_offset) self.labels[i].setLocation(slider.x + slider.width / 2 - self.labels[i].width / 2, slider.y + slider.height) def componentHidden(self, e): pass def componentMoved(self, e): pass def componentShown(self, e): pass def save(self): info = core.DataViewComponent.save(self) if(self.auto_hide_limits): self.hide_limits(None) info['x'] = self.x # Overwrite x and width to account for removed limits info['width'] = self.width info['range'] = self.range info['limits'] = self.auto_hide_limits info['limits_w'] = self.limit_width return info def restore(self, d): core.DataViewComponent.restore(self, d) self.range = d.get('range', 1.0) self.auto_hide_limits = d.get('limits', True) self.limit_width = d.get('limits_w', 0) self.popup_hide_limit.state = self.auto_hide_limits self.show_limits = not self.auto_hide_limits def mouseEntered(self, event): if(self.auto_hide_limits): self.disp_limits() core.DataViewComponent.mouseEntered(self, event) def mouseExited(self, event): if(self.auto_hide_limits): self.limit_hide_timer.start() core.DataViewComponent.mouseExited(self, event) def toggle_autohide(self, event): self.auto_hide_limits = event.source.state if(self.auto_hide_limits): self.limit_hide_timer.start() else: self.disp_limits() def disp_limits(self): if(not self.show_limits): limit_label = JLabel(("-%1.2f" % (self.range))) self.limit_width = limit_label.getPreferredSize().width - self.sliders[0].width / 2 self.setSize(self.size.width + self.limit_width, self.size.height) self.setLocation(self.x - self.limit_width, self.y) self.limit_hide_timer.stop() self.limit_color_val = self.limit_color_def self.show_limits = True self.repaint() def hide_limits(self, event): if(self.show_limits): if(self.limit_color_val >= 1 - self.limit_color_step): self.limit_hide_timer.stop() self.setSize(self.size.width - self.limit_width, self.size.height) self.setLocation(self.x + self.limit_width, self.y) self.limit_width = 0 self.show_limits = False else: self.limit_color_val += self.limit_color_step self.limit_color_val = min(self.limit_color_val, 1.0) self.limit_hide_timer.start() self.repaint()
class Simbicon(java, applet, Applet, MouseListener, MouseMotionListener, KeyListener): """ generated source for class Simbicon """ bip7 = Bip7() gnd = Ground() Dt = 0.00005 DtDisp = 0.0054 timeEllapsed = 0 # we'll use this buffered image to reduce flickering tempBuffer = BufferedImage() timer = Timer() # and the controller con = Controller() Md = float() Mdd = float() DesVel = 0 # if this variable is set to true, the simulation will be running, otherwise it won't simFlag = False simButton = javax.swing.JButton() reset = javax.swing.JButton() panel = javax.swing.JPanel() speedSlider = javax.swing.JSlider() label = javax.swing.JLabel() shouldPanY = False def init(self): """ generated source for method init """ setSize(500, 500) addMouseListener(self) addMouseMotionListener(self) # initialize the biped to a valid state: state = [ 0.463, 0.98, 0.898, -0.229, 0.051, 0.276, -0.221, -1.430, -0.217, 0.086, 0.298, -3.268, -0.601, 3.167, 0.360, 0.697, 0.241, 3.532 ] self.bip7.setState(state) delay = 1 # milliseconds taskPerformer = ActionListener() self.timer = Timer(delay, taskPerformer) self.timer.start() self.tempBuffer = BufferedImage(500, 500, BufferedImage.TYPE_INT_RGB) initComponents() self.con = Controller() self.con.addWalkingController() self.con.addRunningController() self.con.addCrouchWalkController() self.addKeyListener(self) self.requestFocus() def boundRange(self, value, min, max): """ generated source for method boundRange """ if value < min: value = min if value > max: value = max return value # //////////////////////////////////////////////////////// # PROC: wPDtorq() # DOES: computes requires torque to move a joint wrt world frame # //////////////////////////////////////////////////////// def wPDtorq(self, torq, joint, dposn, kp, kd, world): """ generated source for method wPDtorq """ joint_posn = self.bip7.State[4 + joint * 2] joint_vel = self.bip7.State[4 + joint * 2 + 1] if world: # control wrt world frame? (virtual) joint_posn += self.bip7.State[4] # add body tilt joint_vel += self.bip7.State[5] # add body angular velocity torq[joint] = kp * (dposn - joint_posn) - kd * joint_vel # //////////////////////////////////////////////////////// # PROC: jointLimit() # DOES: enforces joint limits # //////////////////////////////////////////////////////// def jointLimit(self, torq, joint): """ generated source for method jointLimit """ kpL = 800 kdL = 80 minAngle = self.con.jointLimit[0][joint] maxAngle = self.con.jointLimit[1][joint] currAngle = self.bip7.State[4 + joint * 2] currOmega = self.bip7.State[4 + joint * 2 + 1] if currAngle < minAngle: torq = kpL * (minAngle - currAngle) - kdL * currOmega elif currAngle > maxAngle: torq = kpL * (maxAngle - currAngle) - kdL * currOmega return torq def bip7WalkFsm(self, torq): """ generated source for method bip7WalkFsm """ torsoIndex = 0 rhipIndex = 1 rkneeIndex = 2 lhipIndex = 3 lkneeIndex = 4 rankleIndex = 5 lankleIndex = 6 worldFrame = [False, True, False, True, False, False, False] self.con.stateTime += self.Dt s = self.con.state[self.con.fsmState] computeMdMdd() n = 0 while n < 7: target = self.boundRange(target, self.con.targetLimit[0][n], self.con.targetLimit[1][n]) self.wPDtorq(torq, n, target, self.con.kp[n], self.con.kd[n], worldFrame[n]) n += 1 self.con.advance(self.bip7) def bip7Control(self, torq): """ generated source for method bip7Control """ body = 0 stanceHip = int() swingHip = int() fallAngle = 60 n = 0 while n < 7: torq[n] = 0 n += 1 if not self.bip7.lostControl: self.bip7WalkFsm(torq) if self.con.state[self.con.fsmState].leftStance: stanceHip = 3 swingHip = 1 else: stanceHip = 1 swingHip = 3 if not self.con.state[self.con.fsmState].poseStance: torq[stanceHip] = -torq[body] - torq[swingHip] torq[0] = 0 n = 1 while n < 7: torq[n] = self.boundRange(torq[n], self.con.torqLimit[0][n], self.con.torqLimit[1][n]) self.jointLimit(torq[n], n) n += 1 def computeMdMdd(self): """ generated source for method computeMdMdd """ stanceFootX = self.bip7.getStanceFootXPos(self.con) self.Mdd = self.bip7.State[1] - self.DesVel self.Md = self.bip7.State[0] - stanceFootX def initComponents(self): """ generated source for method initComponents """ self.simButton = javax.swing.JButton() self.reset = javax.swing.JButton() self.panel = javax.swing.JPanel() self.label = javax.swing.JLabel() self.label.setText("Speed: ") self.speedSlider = javax.swing.JSlider() self.speedSlider.setMaximum(100) self.speedSlider.setMinimum(0) self.speedSlider.setToolTipText( "Adjust the speed of the simulation by adjusting this slider.") setLayout(BorderLayout()) self.panel.setLayout(FlowLayout()) add(self.panel, BorderLayout.NORTH) self.panel.add(self.label) self.panel.add(self.speedSlider) self.panel.add(self.simButton) self.panel.add(self.reset) self.speedSlider.addMouseListener(java.awt.event.MouseAdapter()) self.simButton.setText(" Start ") self.reset.setText("Reset") self.simButton.addActionListener(java.awt.event.ActionListener()) self.reset.addActionListener(java.awt.event.ActionListener()) def resetSimulation(self): """ generated source for method resetSimulation """ self.bip7.resetBiped() self.con.stateTime = 0 self.con.fsmState = 0 self.con.currentGroupNumber = 0 self.con.desiredGroupNumber = 0 repaint() def runLoop(self): """ generated source for method runLoop """ if self.simFlag == False: return self.timer.stop() i = 0 while i < 200: self.bip7.computeGroundForces(self.gnd) self.bip7Control(self.bip7.t) self.bip7.runSimulationStep(self.Dt) self.timeEllapsed += self.Dt if self.timeEllapsed > self.DtDisp: self.update(self.getGraphics()) self.timeEllapsed = 0 i += 1 self.timer.start() def update(self, g): """ generated source for method update """ if g == None: return g2 = self.tempBuffer.getGraphics() g2.setColor(Color(255, 255, 255)) g2.fillRect(0, 0, getSize().width - 1, getSize().height - 1) m = Matrix3x3.getTranslationMatrix(0, -300) m = m.multiplyBy(Matrix3x3.getScalingMatrix(float(100))) panX = self.bip7.State[0] panY = self.bip7.State[2] if self.shouldPanY == False: panY = 0 m = m.multiplyBy( Matrix3x3.getTranslationMatrix(-panX + 1.5, -panY + 0.5)) self.bip7.drawBiped(g2, m) self.gnd.draw(g2, m) g.drawImage(self.tempBuffer, 0, self.panel.getHeight(), self) self.panel.repaint() def paint(self, g): """ generated source for method paint """ self.update(g) self.panel.repaint() def keyReleased(self, e): """ generated source for method keyReleased """ def keyPressed(self, e): """ generated source for method keyPressed """ if e.getKeyCode() == e.VK_LEFT: self.bip7.PushTime = 0.2 self.bip7.PushForce = -60 if e.getKeyCode() == e.VK_RIGHT: self.bip7.PushTime = 0.2 self.bip7.PushForce = 60 if e.getKeyChar() == 'r' or e.getKeyChar() == 'R': self.con.desiredGroupNumber = 1 if e.getKeyChar() == 'w' or e.getKeyChar() == 'W': self.con.desiredGroupNumber = 0 if e.getKeyChar() == 'c' or e.getKeyChar() == 'C': self.con.desiredGroupNumber = 2 if e.getKeyChar() == '1': self.gnd.getFlatGround() self.resetSimulation() if e.getKeyChar() == '2': self.gnd.getComplexTerrain() self.resetSimulation() def keyTyped(self, e): """ generated source for method keyTyped """ def mouseDragged(self, e): """ generated source for method mouseDragged """ def mouseMoved(self, e): """ generated source for method mouseMoved """ def mousePressed(self, e): """ generated source for method mousePressed """ self.requestFocus() def mouseReleased(self, e): """ generated source for method mouseReleased """ def mouseEntered(self, e): """ generated source for method mouseEntered """ def mouseExited(self, e): """ generated source for method mouseExited """ def mouseClicked(self, e): """ generated source for method mouseClicked """ def destroy(self): """ generated source for method destroy """ removeMouseListener(self) removeMouseMotionListener(self) def getAppletInfo(self): """ generated source for method getAppletInfo """ return "Title: Simbicon\n" + "Author: Stelian Coros, Michiel van de Panne."
class TrackDevice(java.beans.PropertyChangeListener): import java import javax.swing from javax.swing import Timer delayTimer = None relayClicks = None # TrackDevice.init - Initialize a TrackDevice instance for a particular device # # aName : Device name # aDevice : JMRI device instance # aAllowedStates : Array of states we want to track, other states are ignored # def init(self, aName, aDevice, aAllowedStates, aLogFile, aParent): from javax.swing import Timer self.DeviceName = aName self.Device = aDevice self.DeviceNumber = self.DeviceName[2:self.DeviceName.find(":")] self.AllowedStates = aAllowedStates self.parent = aParent self.DeviceValue = self.AllowedStates[0] self.LogFile = aLogFile self.timeoutListener = self.TimeoutReceiver() self.timeoutListener.setCallBack(self.receiveTimeoutHandler) self.receiveTimer = Timer(100, self.timeoutListener) self.receiveTimer.setInitialDelay(10) self.receiveTimer.stop() self.receiveTimer.setRepeats(False) self.sendTimeoutListener = self.TimeoutReceiver2() self.sendTimeoutListener.setCallBack(self.sendTimeoutHandler) self.sendTimer = Timer(100, self.timeoutListener) self.sendTimer.setInitialDelay(10) self.sendTimer.stop() self.sendTimer.setRepeats(False) self.pauseTimeoutListener = self.TimeoutReceiver() self.pauseTimeoutListener.setCallBack(self.pauseTimeoutHandler) self.pauseTimer = Timer(100, self.pauseTimeoutListener) self.pauseTimer.setInitialDelay(10) self.pauseTimer.stop() self.pauseTimer.setRepeats(False) self.finalTimeoutListener = self.TimeoutReceiver() self.finalTimeoutListener.setCallBack(self.finalTimeoutHandler) self.finalTimer = Timer(100, self.finalTimeoutListener) self.finalTimer.setInitialDelay(10) self.finalTimer.stop() self.finalTimer.setRepeats(False) # self.relayClicks = jmri.jmrit.Sound(jmri.util.FileUtil.getExternalFilename("preference:resources/sounds/EnhancedCTCRelayTrimmed.wav")) self.relayClicks = jmri.jmrit.Sound( "resources/sounds/Code-receive.wav") self.relaySend = jmri.jmrit.Sound("resources/sounds/Code-send.wav") return # TrackDevice.updateState - Track the device state while reading the old log # file. Note the state but don't change the device # itself and don't log the changes to the new log file # (yet). # # aNewState : New device state. # def updateState(self, aNewState): print 'updateState ' + self.DeviceName + " to state = " + aNewState for i in range(len(self.AllowedStates)): if (aNewState == self.AllowedStates[i]): self.DeviceValue = aNewState self.Device.setValue(aNewState) break # TrackDevice.propertyChange - Record state changes as a result of activities # elsewhere in JMRI # # aEvent : Event triggering the change (we don't actually look at the event...) # def propertyChange(self, aEvent): newValue = self.Device.getValue() print("***** In propertyChange") memories.getMemory("IM5:TVC").setValue("1") # # Turn on Control Code indicator light codeSendSensor = sensors.getSensor("Code Send Indicator") codeSendSensor.setState(ACTIVE) # # Start relay clicking sound self.relaySend.loop() # # Start timer to keep code send light on and relays clicking for a while. ccdl = 15 #+ java.util.Random().nextInt(1) # Code transmission delay self.sendTimer.setDelay(ccdl * 1000) #self.sendTimer.start() self.parent.waitMsec(ccdl * 1000) self.relaySend.stop() codeSendSensor.setState(INACTIVE) if (newValue == self.DeviceValue): return for i in range(len(self.AllowedStates)): if (newValue == self.AllowedStates[i]): self.DeviceValue = newValue self.LogFile.write(self.DeviceName + " " + self.DeviceValue + "\n") self.LogFile.flush() break return # TrackDevice.setInitialDeviceState - After reading all of the old tracking file we # now initialize the actual devices to their last # known states and log these states into the new # log file. # def setInitialDeviceState(self, logFile, parent): # Uncomment the following print statement to display the list of devices being tracked. print "In setInitDeviceState, name = " + self.DeviceName + " value = " + self.DeviceValue self.LogFile = logFile ### self.Device.setState(self.DeviceValue) self.Device.addPropertyChangeListener(self) #logStateChange2(self.DeviceName, self.DeviceState, False) logFile.write(self.DeviceName + " " + self.DeviceValue + "\n") signalId = "IS:" + self.DeviceNumber # Move the switch lever to the correct position sensors.getSensor(signalId + ":CB").setState(INACTIVE) if (self.DeviceValue == "N"): turnouts.provideTurnout("NT" + self.DeviceNumber).setState(CLOSED) self.parent.waitMsec(100) sensors.getSensor(signalId + ":NK").setState(ACTIVE) sensors.getSensor(signalId + ":L").setState(ACTIVE) sensors.getSensor(signalId + ":RK").setState(INACTIVE) else: turnouts.provideTurnout("NT" + self.DeviceNumber).setState(THROWN) self.parent.waitMsec(100) sensors.getSensor(signalId + ":NK").setState(INACTIVE) sensors.getSensor(signalId + ":RK").setState(ACTIVE) sensors.getSensor(signalId + ":L").setState(INACTIVE) class TimeoutReceiver(java.awt.event.ActionListener): cb = None def actionPerformed(self, event): if (self.cb != None): self.cb(event) return def setCallBack(self, cbf): self.cb = cbf return class TimeoutReceiver2(java.awt.event.ActionListener): cb = None def actionPerformed(self, event): if (self.cb != None): self.cb(event) return def setCallBack(self, cbf): self.cb = cbf return def sendTimeoutHandler(self, event): print "In send timeout handler" self.sendTimer.stop() self.relaySend.stop() sensors.getSensor("IS16:CCK").setState(INACTIVE) smdl = 5 #+ java.util.Random().nextInt(2) # Switch motor delay - self.pauseTimer.setInitialDelay(smdl * 100) self.pauseTimer.start() return # # Timeout handler between send & receive. # Turn panel indicators off & start indication code relay clicks. def pauseTimeoutHandler(self, event): self.pauseTimer.stop() sensors.getSensor("Code Receive Indicator").setState(ACTIVE) self.relayClicks.loop() newName = "IS:" + self.DeviceNumber sensors.getSensor(newName + ":NK").setState(INACTIVE) sensors.getSensor(newName + ":RK").setState(INACTIVE) signals.getSignalHead("VH:T" + str(self.DeviceNumber) + "N").setAppearance(DARK) signals.getSignalHead("VH:T" + str(self.DeviceNumber) + "R").setAppearance(DARK) icdl = 5 #+ java.util.Random().nextInt(3) # Indicator code delay self.receiveTimer.setInitialDelay(icdl * 100) self.receiveTimer.start() return # # Final timeout handler....turn off Indication Code relay clicks and change indicator lights on panel. def receiveTimeoutHandler(self, event): # see which phase we think we are in self.receiveTimer.stop() sensors.getSensor("Code Receive Indicator").setState(INACTIVE) # # Throw the turnout. We should do this in an earlier timeout handler, but with the CTC panel lights hardwired to the tortoise motor, # the lights change too soon. if (memories.getMemory("IM1:FB").getValue() == 0): if (self.Device.getValue() == "N"): turnouts.provideTurnout("NT" + self.DeviceNumber).setState(CLOSED) else: turnouts.provideTurnout("NT" + self.DeviceNumber).setState(THROWN) self.finalTimer.setInitialDelay(6000) self.finalTimer.start() return # # Final timeout handler....turn off Indication Code relay clicks and change indicator lights on panel. def finalTimeoutHandler(self, event): # see which phase we think we are in self.finalTimer.stop() self.relayClicks.stop() sensors.getSensor("Code Receive Indicator").setState(INACTIVE) memories.getMemory("IM5:TVC").setValue("0") memories.getMemory("IM1:FB").setValue(0) return