summaryrefslogtreecommitdiff
path: root/decoders/i2cfilter/pd.py
blob: 877c4676a0fe895679dab96c00cac862dff4fdd1 (plain)
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
##
## This file is part of the libsigrokdecode project.
##
## Copyright (C) 2012 Bert Vermeulen <bert@biot.com>
## Copyright (C) 2012 Uwe Hermann <uwe@hermann-uwe.de>
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; if not, see <http://www.gnu.org/licenses/>.
##

# TODO
# - Accept other slave address forms than decimal numbers?
# - Support for filtering out multiple slave/direction pairs?
# - Support 10bit slave addresses?

import copy
import sigrokdecode as srd

class Decoder(srd.Decoder):
    api_version = 3
    id = 'i2cfilter'
    name = 'I²C filter'
    longname = 'I²C filter'
    desc = 'Filter out addresses/directions in an I²C stream.'
    license = 'gplv3+'
    inputs = ['i2c']
    outputs = ['i2c']
    tags = ['Util']
    options = (
        {'id': 'address', 'desc': 'Slave address to filter (decimal)',
            'default': 0},
        {'id': 'direction', 'desc': 'Direction to filter', 'default': 'both',
            'values': ('read', 'write', 'both')}
    )

    def __init__(self):
        self.reset()

    def reset(self):
        self.seen_packets = []
        self.do_forward = None

    def start(self):
        self.out_python = self.register(srd.OUTPUT_PYTHON, proto_id='i2c')
        if self.options['address'] not in range(0, 127 + 1):
            raise Exception('Invalid slave (must be 0..127).')
        self.want_addrs = []
        if self.options['address']:
            self.want_addrs.append(self.options['address'])
        self.want_dir = {
            'read': 'READ', 'write': 'WRITE',
        }.get(self.options['direction'], None)

    def _need_to_forward(self, slave_addr, direction):
        if self.want_addrs and slave_addr not in self.want_addrs:
            return False
        if self.want_dir and direction != self.want_dir:
            return False
        return True

    # Accumulate observed I2C packets until a STOP or REPEATED START
    # condition is seen. These are conditions where transfers end or
    # where direction potentially changes. Forward all previously
    # accumulated traffic if it passes the slave address and direction
    # filter. This assumes that the slave address as well as the read
    # or write direction was part of the observed traffic. There should
    # be no surprise when incomplete traffic does not match the filter
    # condition.
    def decode(self, ss, es, data):

        # Unconditionally accumulate every lower layer packet we see.
        # Keep deep copies for later, only reference caller's values
        # as long as this .decode() invocation executes.
        self.seen_packets.append([ss, es, copy.deepcopy(data)])
        cmd, _ = data

        # Check the slave address and transfer direction early when
        # we see them. Keep accumulating packets while it's already
        # known here whether to forward them. This simplifies other
        # code paths. Including future handling of 10bit addresses.
        if cmd in ('ADDRESS READ', 'ADDRESS WRITE'):
            direction = cmd[len('ADDRESS '):]
            _, slave_addr = data
            self.do_forward = self._need_to_forward(slave_addr, direction)
            return

        # Forward previously accumulated packets as we see their
        # completion, and when they pass the filter condition. Prepare
        # to handle the next transfer (the next read/write part of it).
        if cmd in ('STOP', 'START REPEAT'):
            if self.do_forward:
                for ss, es, data in self.seen_packets:
                    self.put(ss, es, self.out_python, data)
            self.seen_packets.clear()
            self.do_forward = None
            return