command_queue.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. """
  2. # TOP2049 Open Source programming suite
  3. #
  4. # Generic command queue.
  5. #
  6. # Copyright (c) 2012 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. assert(len(command) <= self.maxPacketBytes)
  33. if self.synchronous:
  34. self.send(command)
  35. else:
  36. self.commandQueue.append(command)
  37. def runCommandSync(self, command):
  38. """Run a command synchronously.
  39. This is slow. Don't use it without a very good reason."""
  40. self.flushCommands()
  41. self.queueCommand(command)
  42. self.flushCommands()
  43. def flushCommands(self, sleepSeconds=0):
  44. """Flush the command queue."""
  45. command = b""
  46. for oneCommand in self.commandQueue:
  47. assert(len(oneCommand) <= self.maxPacketBytes)
  48. if len(command) + len(oneCommand) > self.maxPacketBytes:
  49. self.send(command)
  50. command = b""
  51. command += oneCommand
  52. if command:
  53. self.send(command)
  54. self.commandQueue = []
  55. if sleepSeconds:
  56. time.sleep(sleepSeconds)
  57. def send(self, data):
  58. raise NotImplementedError # Reimplement in subclass.
  59. def receive(self, size):
  60. raise NotImplementedError # Reimplement in subclass.