command_queue.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. """
  2. # TOP2049 Open Source programming suite
  3. #
  4. # Generic command queue.
  5. #
  6. # Copyright (c) 2012-2022 Michael Buesch <m@bues.ch>
  7. #
  8. # This program is free software; you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License as published by
  10. # the Free Software Foundation; either version 2 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # This program is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License along
  19. # with this program; if not, write to the Free Software Foundation, Inc.,
  20. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  21. """
  22. from .util import *
  23. import time
  24. class CommandQueue(object):
  25. "Generic hardware-command queue. Needs to be subclassed."
  26. def __init__(self, maxPacketBytes, synchronous=False):
  27. self.maxPacketBytes = maxPacketBytes
  28. self.synchronous = synchronous
  29. self.commandQueue = []
  30. def queueCommand(self, command):
  31. """Queue a raw command for transmission."""
  32. if isinstance(command, str):
  33. # Compat for old code
  34. command = b"".join(int2byte(ord(c)) for c in command)
  35. assert isinstance(command, (bytes, bytearray))
  36. assert(len(command) <= self.maxPacketBytes)
  37. if self.synchronous:
  38. self.send(command)
  39. else:
  40. self.commandQueue.append(command)
  41. def runCommandSync(self, command):
  42. """Run a command synchronously.
  43. This is slow. Don't use it without a very good reason."""
  44. self.flushCommands()
  45. self.queueCommand(command)
  46. self.flushCommands()
  47. def flushCommands(self, sleepSeconds=0):
  48. """Flush the command queue."""
  49. command = b""
  50. commandQueue = self.commandQueue
  51. self.commandQueue = []
  52. for oneCommand in commandQueue:
  53. assert(len(oneCommand) <= self.maxPacketBytes)
  54. if len(command) + len(oneCommand) > self.maxPacketBytes:
  55. self.send(command)
  56. command = b""
  57. command += oneCommand
  58. if command:
  59. self.send(command)
  60. if sleepSeconds:
  61. time.sleep(sleepSeconds)
  62. def send(self, data):
  63. raise NotImplementedError # Reimplement in subclass.
  64. def receive(self, size):
  65. raise NotImplementedError # Reimplement in subclass.