| 1 | from kivy.app import App |
| 2 | from kivy.clock import Clock |
| 3 | from kivy.lang import Builder |
| 4 | from kivy.uix.boxlayout import BoxLayout |
| 5 | |
| 6 | from plyer import gravity |
| 7 | |
| 8 | |
| 9 | Builder.load_string(''' |
| 10 | <GravityInterface>: |
| 11 | orientation: 'vertical' |
| 12 | |
| 13 | Label: |
| 14 | id: x_label |
| 15 | text: 'X: ' |
| 16 | |
| 17 | Label: |
| 18 | id: y_label |
| 19 | text: 'Y: ' |
| 20 | |
| 21 | Label: |
| 22 | id: z_label |
| 23 | text: 'Z: ' |
| 24 | |
| 25 | Label: |
| 26 | id: status |
| 27 | text: '' |
| 28 | |
| 29 | BoxLayout: |
| 30 | size_hint_y: None |
| 31 | height: '48dp' |
| 32 | padding: '4dp' |
| 33 | |
| 34 | ToggleButton: |
| 35 | id: toggle_button |
| 36 | text: 'Start Gravity Sensor' |
| 37 | on_press: root.do_toggle() |
| 38 | |
| 39 | ''') |
| 40 | |
| 41 | |
| 42 | class GravityInterface(BoxLayout): |
| 43 | def __init__(self): |
| 44 | super().__init__() |
| 45 | self.sensorEnabled = False |
| 46 | |
| 47 | def do_toggle(self): |
| 48 | try: |
| 49 | if not self.sensorEnabled: |
| 50 | gravity.enable() |
| 51 | Clock.schedule_interval(self.get_gravity, 1 / 20.) |
| 52 | |
| 53 | self.sensorEnabled = True |
| 54 | self.ids.toggle_button.text = "Stop Gravity Sensor" |
| 55 | else: |
| 56 | gravity.disable() |
| 57 | Clock.unschedule(self.get_gravity) |
| 58 | |
| 59 | self.sensorEnabled = False |
| 60 | self.ids.toggle_button.text = "Start Gravity Sensor" |
| 61 | except NotImplementedError: |
| 62 | import traceback |
| 63 | traceback.print_exc() |
| 64 | status = "Gravity sensor is not implemented " \ |
| 65 | "for your platform" |
| 66 | self.ids.status.text = status |
| 67 | |
| 68 | def get_gravity(self, dt): |
| 69 | val = gravity.gravity |
| 70 | |
| 71 | if not val == (None, None, None): |
| 72 | self.ids.x_label.text = "X: " + str(val[0]) |
| 73 | self.ids.y_label.text = "Y: " + str(val[1]) |
| 74 | self.ids.z_label.text = "Z: " + str(val[2]) |
| 75 | |
| 76 | |
| 77 | class GravityApp(App): |
| 78 | def build(self): |
| 79 | return GravityInterface() |
| 80 | |
| 81 | |
| 82 | if __name__ == '__main__': |
| 83 | GravityApp().run() |