⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 joystick.py

📁 用wxPython编写GUI程序的样例代码
💻 PY
📖 第 1 页 / 共 3 页
字号:

        self.stick = stick

        #
        # token represents the type of axis we're displaying.
        #
        self.token = token

        #
        # Create a call to the 'Has*()' method for the stick.
        # X and Y are always there, so we tie the Has* method
        # to a hardwired True value.
        #
        if token not in ['X', 'Y']:
            self.HasFunc = eval('stick.Has%s' % token)
        else:
            self.HasFunc = self.alwaysTrue

        # Now init the panel.
        wx.Panel.__init__(self, parent, -1)

        sizer = wx.BoxSizer(wx.HORIZONTAL)

        if self.HasFunc():
            #
            # Tie our calibration functions to the appropriate
            # stick method. If we don't have the axis in question,
            # we won't need them.
            #
            self.GetMin = eval('stick.Get%sMin' % token)
            self.GetMax = eval('stick.Get%sMax' % token)

            # Create our displays and set them up.
            self.Min = wx.StaticText(self, -1, str(self.GetMin()), style=wx.ALIGN_RIGHT)
            self.Max = wx.StaticText(self, -1, str(self.GetMax()), style=wx.ALIGN_LEFT)
            self.bar = AxisBar(self)

            sizer.Add(self.Min, 0, wx.ALL | wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL, 1)
            sizer.Add(self.bar, 1, wx.ALL | wx.ALIGN_CENTER | wx.ALIGN_CENTER_VERTICAL, 1)
            sizer.Add(self.Max, 0, wx.ALL | wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL, 1)

        else:
            # We go here if the axis in question is not available.
            self.control = wx.StaticText(self, -1, '       *** Not Present ***')
            sizer.Add(self.control, 1, wx.ALL | wx.ALIGN_CENTER | wx.ALIGN_CENTER_VERTICAL, 1)

        #----------------------------------------------------------------------------

        self.SetSizer(sizer)
        sizer.Fit(self)
        wx.CallAfter(self.Update)


    def Calibrate(self):
        if not self.HasFunc():
            return

        self.Min.SetLabel(str(self.GetMin()))
        self.Max.SetLabel(str(self.GetMax()))


    def Update(self):
        # Don't bother if the axis doesn't exist.
        if not self.HasFunc():
            return

        min = int(self.Min.GetLabel())
        max = int(self.Max.GetLabel())

        #
        # Not all values are available from a wx.JoystickEvent, so I've elected
        # to not use it at all. Therefore, we are getting our values direct from
        # the stick. These values also seem to be more stable and reliable than
        # those received from the event itself, so maybe it's a good idea to
        # use the stick directly for your program.
        #
        # Here we either select the appropriate member of stick.GetPosition() or
        # apply the appropriate Get*Position method call.
        #
        if self.token == 'X':
            val = self.stick.GetPosition().x
        elif self.token == 'Y':
            val = self.stick.GetPosition().y
        else:
            val = eval('self.stick.Get%sPosition()' % self.token)


        #
        # While we might be able to rely on a range of 0-FFFFFF on Win, that might
        # not be true of all drivers on all platforms. Thus, calc the actual full
        # range first.
        #
        if min < 0:
            max += abs(min)
            val += abs(min)
            min = 0        
        range = float(max - min)
        
        #
        # The relative value is used by the derived wx.Gauge since it is a
        # positive-only control.
        #
        relative = 0
        if range:
            relative = int( val / range * 1000)

        #
        # Pass both the raw and relative values to the derived Gauge
        #
        self.bar.Update(relative, val)


    def alwaysTrue(self):
        # a dummy method used for X and Y axis.
        return True


#----------------------------------------------------------------------------

class AxisPanel(wx.Panel):
    #
    # Contained herein is a panel that offers a graphical display
    # of the levels for all axes supported by wx.Joystick. If
    # your system doesn't have a particular axis, it will be
    # 'dummied' for transparent use.
    #
    def __init__(self, parent, stick):

        self.stick = stick

        # Defines labels and 'tokens' to identify each
        # supporte axis.
        axesList = [
            ('X Axis ', 'X'),   ('Y Axis ', 'Y'),
            ('Z Axis ', 'Z'),   ('Rudder ', 'Rudder'),
            ('U Axis ', 'U'),   ('V Axis ', 'V')
            ]

        # Contains a list of all axis initialized.
        self.axes = []

        wx.Panel.__init__(self, parent, -1)

        sizer = wx.FlexGridSizer(3, 4, 1, 1)
        sizer.AddGrowableCol(1)
        sizer.AddGrowableCol(3)

        #----------------------------------------------------------------------------

        # Go through the list of labels and tokens and add a label and
        # axis display to the sizer for each.
        for label, token in axesList:
            sizer.Add(Label(self, label), 0, wx.ALL | wx.ALIGN_RIGHT, 2)
            t = Axis(self, token, self.stick)
            self.axes.append(t)
            sizer.Add(t, 1, wx.ALL | wx.EXPAND | wx.ALIGN_LEFT, 2)

        #----------------------------------------------------------------------------

        self.SetSizer(sizer)
        sizer.Fit(self)
        wx.CallAfter(self.Update)

    def Calibrate(self):
        for i in self.axes:
            i.Calibrate()

    def Update(self):
        for i in self.axes:
            i.Update()


#----------------------------------------------------------------------------

class JoystickDemoPanel(wx.Panel):

    def __init__(self, parent, log):

        self.log = log

        wx.Panel.__init__(self, parent, -1)

        # Try to grab the control. If we get it, capture the stick.
        # Otherwise, throw up an exception message and play stupid.
        try:
            self.stick = wx.Joystick()
            self.stick.SetCapture(self)
            # Calibrate our controls
            wx.CallAfter(self.Calibrate)
            wx.CallAfter(self.OnJoystick)
        except NotImplementedError, v:
            wx.MessageBox(str(v), "Exception Message")
            self.stick = None

        # One Sizer to Rule Them All...
        sizer = wx.GridBagSizer(2,2)

        self.info = InfoPanel(self, self.stick)
        sizer.Add(self.info, (0, 0), (1, 3), wx.ALL | wx.GROW, 2)

        self.info.Bind(wx.EVT_BUTTON, self.Calibrate)

        self.joy = JoyPanel(self, self.stick)
        sizer.Add(self.joy, (1, 0), (1, 1), wx.ALL | wx.GROW, 2)
                  
        self.pov = POVPanel(self, self.stick)
        sizer.Add(self.pov, (1, 1), (1, 2), wx.ALL | wx.GROW, 2)
        
        self.axes = AxisPanel(self, self.stick)
        sizer.Add(self.axes, (2, 0), (1, 3), wx.ALL | wx.GROW, 2)

        self.buttons = JoyButtons(self, self.stick)
        sizer.Add(self.buttons, (3, 0), (1, 3), wx.ALL | wx.EXPAND | wx.ALIGN_CENTER | wx.ALIGN_CENTER_VERTICAL, 1)

        self.SetSizer(sizer)
        sizer.Fit(self)

        # Capture Joystick events (if they happen)
        self.Bind(wx.EVT_JOYSTICK_EVENTS, self.OnJoystick)
        self.stick.SetMovementThreshold(10)


    def Calibrate(self, evt=None):
        # Do not try this without a stick
        if not self.stick:
            return

        self.info.Calibrate()
        self.axes.Calibrate()
        self.pov.Calibrate()
        self.buttons.Calibrate()


    def OnJoystick(self, evt=None):
        if not self.stick:
            return

        self.axes.Update()
        self.joy.Update()
        self.pov.Update()
        if evt is not None and evt.IsButton():
            self.buttons.Update()


    def ShutdownDemo(self):
        if self.stick:
            self.stick.ReleaseCapture()
        self.stick = None
        
#----------------------------------------------------------------------------

def runTest(frame, nb, log):
    if haveJoystick:
        win = JoystickDemoPanel(nb, log)
        return win
    else:
        from Main import MessagePanel
        win = MessagePanel(nb, 'wx.Joystick is not available on this platform.',
                           'Sorry', wx.ICON_WARNING)
        return win
    

#----------------------------------------------------------------------------

overview = """\
<html>
<body>
<h1>wx.Joystick</h1>
This demo illustrates the use of the wx.Joystick class, which is an interface to
one or more joysticks attached to your system.

<p>The data that can be retrieved from the joystick comes in four basic flavors.
All of these are illustrated in the demo. In fact, this demo illustrates everything
you <b>can</b> get from the wx.Joystick control.

<ul>
<li>Static information such as Manufacturer ID and model name,
<li>Analog input from up to six axes, including X and Y for the actual stick,
<li>Button input from the fire button and any other buttons that the stick has,
<li>and the POV control (a kind of mini-joystick on top of the joystick) that many sticks come with.
</ul>

<p>Getting data from the joystick can be event-driven thanks to four event types associated
with wx.JoystickEvent, or the joystick can be polled programatically to get data on
a regular basis.

<h2>Data types</h2>

Data from the joystick comes in two flavors: that which defines the boundaries, and that
which defines the current state of the stick. Thus, we have Get*Max() and Get*Min() 
methods for all axes, the max number of axes, the max number of buttons, and so on. In
general, this data can be read once and stored to speed computation up.

<h3>Analog Input</h3>

Analog input (the axes) is delivered as a whole, positive number. If you need to know 
if the axis is at zero (centered) or not, you will first have to calculate that center
based on the max and min values. The demo shows a bar graph for each axis expressed
in native numerical format, plus a 'centered' X-Y axis compass showing the relationship
of that input to the calculated stick position.

Analog input may be jumpy and spurious, so the control has a means of 'smoothing' the
analog data by setting a movement threshold. This demo sets the threshold to 10, but
you can set it at any valid value between the min and max.

<h3>Button Input</h3>

Button state is retrieved as one int that contains each button state mapped to a bit.
You get the state of a button by AND-ing its bit against the returned value, in the form

<pre>
     # assume buttonState is what the stick returned, and buttonBit 
     # is the bit you want to examine
     
     if (buttonState & ( 1 &lt;&lt; buttonBit )) :
         # button pressed, do something with it
</pre>

<p>The problem here is that some OSs return a 32-bit value for up to 32 buttons 
(imagine <i>that</i> stick!). Python V2.3 will generate an exception for bit 
values over 30. For that reason, this demo is limited to 16 buttons.

<p>Note that more than one button can be pressed at a time, so be sure to check all of them!
     

<h3>POV Input</h3>

POV hats come in two flavors: four-way, and continuous. four-way POVs are restricted to
the cardinal points of the compass; continuous, or CTS POV hats can deliver input in
.01 degree increments, theoreticaly. The data is returned as a whole number; the last
two digits are considered to be to the right of the decimal point, so in order to 
use this information, you need to divide by 100 right off the bat. 

<p>Different methods are provided to retrieve the POV data for a CTS hat 
versus a four-way hat.

<h2>Caveats</h2>

The wx.Joystick control is in many ways incomplete at the C++ library level, but it is
not insurmountable.  In short, while the joystick interface <i>can</i> be event-driven,
the wx.JoystickEvent class lacks event binders for all event types. Thus, you cannot
rely on wx.JoystickEvents to tell you when something has changed, necessarilly.

<ul>
<li>There are no events associated with the POV control.
<li>There are no events associated with the Rudder
<li>There are no events associated with the U and V axes.
</ul>

<p>Fortunately, there is an easy workaround. In the top level frame, create a wx.Timer
that will poll the stick at a set interval. Of course, if you do this, you might as
well forgo catching wxEVT_JOYSTICK_* events at all and rely on the timer to do the
polling. 

<p>Ideally, the timer should be a one-shot; after it fires, collect and process data as 
needed, then re-start the timer, possibly using wx.CallAfter().

</body>
</html>
"""

#----------------------------------------------------------------------------

if __name__ == '__main__':
    import sys,os
    import run
    run.main(['', os.path.basename(sys.argv[0])] + sys.argv[1:])

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -