Completed
Push — master ( 22a6c5...9eb1b4 )
by Jeffrey
04:55
created

NonrepeatingBuffer.write()   A

Complexity

Conditions 4

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
c 1
b 0
f 0
dl 0
loc 10
rs 9.2
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, 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
20
    @property
21
    def port(self):
22
        return self.base_port
23
24
    @property
25
    def name(self):
26
        return self.base_name
27
28
    def connect(self, *args, **kwargs):
29
        self.base_tnc.connect(*args, **kwargs)
30
31
    def close(self, *args, **kwargs):
32
        self.base_tnc.close(*args, **kwargs)
33
34
    def write(self, frame, *args, **kwargs):
35
        with self.lock:
36
            frame_hash = str(apex.aprs.util.hash_frame(frame))
37
            if frame_hash not in self.packet_cache:
38
                self.packet_cache[frame_hash] = frame
39
                if self.base_port:
40
                    self.base_tnc.write(frame, self.base_port)
41
                else:
42
                    self.base_tnc.write(frame)
43
                apex.echo_colorized_frame(frame, self.base_name, False)
44
45
    def read(self, *args, **kwargs):
46
        with self.lock:
47
            frame = self.base_tnc.read(*args, **kwargs)
48
            if not frame:
49
                return frame
50
            frame_hash = str(apex.aprs.util.hash_frame(frame))
51
            self.packet_cache[frame_hash] = frame
52
            apex.echo_colorized_frame(frame, self.base_name, True)
53
            return frame
54