]> sigrok.org Git - libsigrokdecode.git/blob - decoders/jitter/pd.py
jitter: Factor out handle_clk() and handle_sig().
[libsigrokdecode.git] / decoders / jitter / pd.py
1 ##
2 ## This file is part of the libsigrokdecode project.
3 ##
4 ## Copyright (C) 2014 Sebastien Bourdelin <sebastien.bourdelin@savoirfairelinux.com>
5 ##
6 ## This program is free software; you can redistribute it and/or modify
7 ## it under the terms of the GNU General Public License as published by
8 ## the Free Software Foundation; either version 2 of the License, or
9 ## (at your option) any later version.
10 ##
11 ## This program is distributed in the hope that it will be useful,
12 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 ## GNU General Public License for more details.
15 ##
16 ## You should have received a copy of the GNU General Public License
17 ## along with this program; if not, write to the Free Software
18 ## Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
19 ##
20
21 import sigrokdecode as srd
22
23 # Helper dictionary for edge detection.
24 edge_detector = {
25     'rising':  lambda x, y: bool(not x and y),
26     'falling': lambda x, y: bool(x and not y),
27     'both':    lambda x, y: bool(x ^ y),
28 }
29
30 class SamplerateError(Exception):
31     pass
32
33 class Decoder(srd.Decoder):
34     api_version = 2
35     id = 'jitter'
36     name = 'Jitter'
37     longname = 'Timing jitter calculation'
38     desc = 'Retrieves the timing jitter between two digital signals.'
39     license = 'gplv2+'
40     inputs = ['logic']
41     outputs = ['jitter']
42     channels = (
43         {'id': 'clk', 'name': 'Clock', 'desc': 'Clock reference channel'},
44         {'id': 'sig', 'name': 'Resulting signal', 'desc': 'Resulting signal controlled by the clock'},
45     )
46     options = (
47         {'id': 'clk_polarity', 'desc': 'Clock edge polarity',
48             'default': 'rising', 'values': ('rising', 'falling', 'both')},
49         {'id': 'sig_polarity', 'desc': 'Resulting signal edge polarity',
50             'default': 'rising', 'values': ('rising', 'falling', 'both')},
51     )
52     annotations = (
53         ('jitter', 'Jitter value'),
54         ('clk_missed', 'Clock missed'),
55         ('sig_missed', 'Signal missed'),
56     )
57     annotation_rows = (
58         ('jitter', 'Jitter values', (0,)),
59         ('clk_missed', 'Clock missed', (1,)),
60         ('sig_missed', 'Signal missed', (2,)),
61     )
62
63     def __init__(self, **kwargs):
64         self.state = 'CLK'
65         self.samplerate = None
66         self.oldpin = None
67         self.oldclk = self.oldsig = None
68         self.clk_start = None
69         self.sig_start = None
70         self.clk_missed = 0
71         self.sig_missed = 0
72
73     def start(self):
74         self.clk_edge = edge_detector[self.options['clk_polarity']]
75         self.sig_edge = edge_detector[self.options['sig_polarity']]
76         self.out_ann = self.register(srd.OUTPUT_ANN)
77         self.out_clk_missed = self.register(srd.OUTPUT_META,
78             meta=(int, 'Clock missed', 'Clock transition missed'))
79         self.out_sig_missed = self.register(srd.OUTPUT_META,
80             meta=(int, 'Signal missed', 'Resulting signal transition missed'))
81
82     def metadata(self, key, value):
83         if key == srd.SRD_CONF_SAMPLERATE:
84             self.samplerate = value
85
86     # Helper function for jitter time annotations.
87     def putx(self, delta):
88         # Adjust granularity.
89         if delta == 0 or delta >= 1:
90             delta_s = u"%us" % (delta)
91         elif delta <= 1e-12:
92             delta_s = u"%.1ffs" % (delta * 1e15)
93         elif delta <= 1e-9:
94             delta_s = u"%.1fps" % (delta * 1e12)
95         elif delta <= 1e-6:
96             delta_s = u"%.1fns" % (delta * 1e9)
97         elif delta <= 1e-3:
98             delta_s = u"%.1fμs" % (delta * 1e6)
99         else:
100             delta_s = u"%.1fms" % (delta * 1e3)
101
102         self.put(self.clk_start, self.sig_start, self.out_ann, [0, [delta_s]])
103
104     # Helper function for missed clock and signal annotations.
105     def putm(self, data):
106         self.put(self.samplenum, self.samplenum, self.out_ann, data)
107
108     def handle_clk(self, clk, sig):
109         if self.clk_start == self.samplenum:
110             # Clock transition already treated.
111             # We have done everything we can with this sample.
112             return True
113
114         if self.clk_edge(self.oldclk, clk):
115             # Clock edge found.
116             # We note the sample and move to the next state.
117             self.clk_start = self.samplenum
118             self.state = 'SIG'
119             return False
120         else:
121             if self.sig_start is not None \
122                and self.sig_start != self.samplenum \
123                and self.sig_edge(self.oldsig, sig):
124                 # If any transition in the resulting signal
125                 # occurs while we are waiting for a clock,
126                 # we increase the missed signal counter.
127                 self.sig_missed += 1
128                 self.put(ss, self.samplenum, self.out_sig_missed, self.sig_missed)
129                 self.putm([2, ['Missed signal', 'MS']])
130             # No clock edge found, we have done everything we
131             # can with this sample.
132             return True
133
134     def handle_sig(self, clk, sig):
135         if self.sig_start == self.samplenum:
136             # Signal transition already treated.
137             # We have done everything we can with this sample.
138             return True
139
140         if self.sig_edge(self.oldsig, sig):
141             # Signal edge found.
142             # We note the sample, calculate the jitter
143             # and move to the next state.
144             self.sig_start = self.samplenum
145             self.state = 'CLK'
146             # Calculate and report the timing jitter.
147             self.putx((self.sig_start - self.clk_start) / self.samplerate)
148             return False
149         else:
150             if self.clk_start != self.samplenum \
151                and self.clk_edge(self.oldclk, clk):
152                 # If any transition in the clock signal
153                 # occurs while we are waiting for a resulting
154                 # signal, we increase the missed clock counter.
155                 self.clk_missed += 1
156                 self.put(ss, self.samplenum, self.out_clk_missed, self.clk_missed)
157                 self.putm([1, ['Missed clock', 'MC']])
158             # No resulting signal edge found, we have done
159             # everything we can with this sample.
160             return True
161
162     def decode(self, ss, es, data):
163         if not self.samplerate:
164             raise SamplerateError('Cannot decode without samplerate.')
165
166         for (self.samplenum, pins) in data:
167             # We are only interested in transitions.
168             if self.oldpin == pins:
169                 continue
170
171             self.oldpin, (clk, sig) = pins, pins
172
173             if self.oldclk is None and self.oldsig is None:
174                 self.oldclk, self.oldsig = clk, sig
175
176             # State machine:
177             # For each sample we can move 2 steps forward in the state machine.
178             while True:
179                 # Clock state has the lead.
180                 if self.state == 'CLK':
181                     if self.handle_clk(clk, sig):
182                         break
183                 if self.state == 'SIG':
184                     if self.handle_sig(clk, sig):
185                         break
186
187             # Save current CLK/SIG values for the next round.
188             self.oldclk, self.oldsig = clk, sig