simple_example.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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. last_state = smartknob_pb2.SmartKnobState()
  19. def log_state(message):
  20. nonlocal last_state
  21. if last_state.config.SerializeToString(deterministic=True) != message.config.SerializeToString(deterministic=True):
  22. logging.info('State: ' + str(message))
  23. last_state = message
  24. s.add_handler('smartknob_state', log_state)
  25. s.request_state()
  26. # Run forever, set config when enter is pressed
  27. while True:
  28. input()
  29. config = smartknob_pb2.SmartKnobConfig()
  30. config.position = 0
  31. config.min_position = 0
  32. config.max_position = 5
  33. config.position_width_radians = math.radians(10)
  34. config.detent_strength_unit = 1
  35. config.endstop_strength_unit = 1
  36. config.snap_point = 1.1
  37. config.text = "From Python!"
  38. s.set_config(config)
  39. if __name__ == '__main__':
  40. _run_example()