Completed
Push — master ( cd7f61...8e95c5 )
by Jeffrey
04:02
created

NonrepeatingBuffer.read()   B

Complexity

Conditions 5

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 5
c 3
b 0
f 0
dl 0
loc 13
rs 8.5454
1
# These imports are for python3 compatibility inside python2
2
from __future__ import absolute_import
3
from __future__ import division
4
from __future__ import print_function
5
6
import threading
7
import cachetools
8
9
import apex.aprs.util
10
11
12
class NonrepeatingBuffer(object):
13
    def __init__(self, base_tnc, base_name, base_port=None, echo_packets=True, buffer_size=10000, buffer_time=30):
14
        self.packet_cache = cachetools.TTLCache(buffer_size, buffer_time)
15
        self.lock = threading.Lock()
16
        self.base_tnc = base_tnc
17
        self.base_port = base_port
18
        self.base_name = base_name
19
        self.echo_packets = echo_packets
20
21
    @property
22
    def port(self):
23
        return self.base_port
24
25
    @property
26
    def name(self):
27
        return self.base_name
28
29
    def connect(self, *args, **kwargs):
30
        self.base_tnc.connect(*args, **kwargs)
31
32
    def close(self, *args, **kwargs):
33
        self.base_tnc.close(*args, **kwargs)
34
35
    def write(self, frame, *args, **kwargs):
36
        with self.lock:
37
            frame_hash = str(apex.aprs.util.hash_frame(frame))
38
            if frame_hash not in self.packet_cache:
39
                self.packet_cache[frame_hash] = frame
40
                if self.base_port:
41
                    self.base_tnc.write(frame, self.base_port)
42
                else:
43
                    self.base_tnc.write(frame)
44
45
                if self.echo_packets:
46
                    apex.echo_colorized_frame(frame, self.base_name, False)
47
48
    def read(self, *args, **kwargs):
49
        with self.lock:
50
            frame = self.base_tnc.read(*args, **kwargs)
51
            if not frame:
52
                return frame
53
            frame_hash = str(apex.aprs.util.hash_frame(frame))
54
            if frame_hash not in self.packet_cache:
55
                self.packet_cache[frame_hash] = frame
56
                if self.echo_packets:
57
                    apex.echo_colorized_frame(frame, self.base_name, True)
58
                return frame
59
            else:
60
                return None
61