File: _parser_queue.py

package info (click to toggle)
python-mido 1.3.3-0.3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 920 kB
  • sloc: python: 4,006; makefile: 127; sh: 4
file content (61 lines) | stat: -rw-r--r-- 1,373 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# SPDX-FileCopyrightText: 2017 Ole Martin Bjorndalen <ombdalen@gmail.com>
#
# SPDX-License-Identifier: MIT

import queue
from threading import RLock

from ..parser import Parser


class ParserQueue:
    """
    Thread safe message queue with built in MIDI parser.

    This should be avaiable to other backend implementations and perhaps
    also in the public API, but the API needs a bit of review. (Ideally This
    would replace the parser.)

    q = ParserQueue()

    q.put(msg)
    q.put_bytes([0xf8, 0, 0])

    msg = q.get()
    msg = q.poll()
    """
    def __init__(self):
        self._queue = queue.Queue()
        self._parser = Parser()
        self._parser_lock = RLock()

    def put(self, msg):
        self._queue.put(msg)

    def put_bytes(self, msg_bytes):
        with self._parser_lock:
            self._parser.feed(msg_bytes)
            for msg in self._parser:
                self.put(msg)

    # TODO: add timeout?
    def get(self):
        return self._queue.get()

    def poll(self):
        try:
            return self._queue.get_nowait()
        except queue.Empty:
            return None

    def __iter__(self):
        while True:
            return self.get()

    def iterpoll(self):
        while True:
            msg = self.poll()
            if msg is None:
                return
            else:
                yield msg