simple_example.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import os
  2. import sys
  3. if __name__ == '__main__':
  4. if 'PIPENV_ACTIVE' not in os.environ:
  5. sys.exit(f'This script should be run in a Pipenv.\n\nRun it as:\npipenv run python {os.path.basename(__file__)}')
  6. # Place imports below this line
  7. import logging
  8. import math
  9. from smartknob_io import (
  10. ask_for_serial_port,
  11. smartknob_context
  12. )
  13. from proto_gen import smartknob_pb2
  14. def _run_example():
  15. logging.basicConfig(level=logging.INFO)
  16. p = ask_for_serial_port()
  17. with smartknob_context(p) as s:
  18. # Initialize with an empty state object
  19. last_state = smartknob_pb2.SmartKnobState()
  20. # Callback function to handle state updates
  21. def log_state(new_state):
  22. nonlocal last_state
  23. # We'll log the state if it's changed substantially since the last state we recieved
  24. config_changed = last_state.config.SerializeToString(deterministic=True) != new_state.config.SerializeToString(deterministic=True)
  25. position_changed = last_state.current_position != new_state.current_position
  26. sub_position_large_change = abs(last_state.sub_position_unit * last_state.config.position_width_radians - new_state.sub_position_unit * new_state.config.position_width_radians) > math.radians(5)
  27. press_nonce_changed = last_state.press_nonce != new_state.press_nonce
  28. if config_changed or position_changed or sub_position_large_change or press_nonce_changed:
  29. logging.info('State: ' + str(new_state))
  30. last_state = new_state
  31. # Register our state handler function
  32. s.add_handler('smartknob_state', log_state)
  33. # Run forever, set config when enter is pressed
  34. while True:
  35. input()
  36. config = smartknob_pb2.SmartKnobConfig()
  37. config.position = 0
  38. config.min_position = 0
  39. config.max_position = 5
  40. config.position_width_radians = math.radians(10)
  41. config.detent_strength_unit = 1
  42. config.endstop_strength_unit = 1
  43. config.snap_point = 1.1
  44. config.text = "From Python!"
  45. s.set_config(config)
  46. if __name__ == '__main__':
  47. _run_example()