Serial.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. # NanoVNASaver
  2. #
  3. # A python program to view and export Touchstone data from a NanoVNA
  4. # Copyright (C) 2019, 2020 Rune B. Broberg
  5. # Copyright (C) 2020 NanoVNA-Saver Authors
  6. #
  7. # This program is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  19. import logging
  20. from threading import Lock
  21. import serial
  22. logger = logging.getLogger(__name__)
  23. def drain_serial(serial_port: serial.Serial):
  24. """drain up to 64k outstanding data in the serial incoming buffer"""
  25. # logger.debug("Draining: %s", serial_port)
  26. timeout = serial_port.timeout
  27. serial_port.timeout = 0.05
  28. for _ in range(512):
  29. cnt = len(serial_port.read(128))
  30. if not cnt:
  31. serial_port.timeout = timeout
  32. return
  33. serial_port.timeout = timeout
  34. logger.warning("unable to drain all data")
  35. class Interface(serial.Serial):
  36. def __init__(self, interface_type: str, comment, *args, **kwargs):
  37. super().__init__(*args, **kwargs)
  38. assert interface_type in ('serial', 'usb', 'bt', 'network')
  39. self.type = interface_type
  40. self.comment = comment
  41. self.port = None
  42. self.baudrate = 115200
  43. self.timeout = 0.05
  44. self.lock = Lock()
  45. def __str__(self):
  46. return f"{self.port} ({self.comment})"