]> sigrok.org Git - libsigrokdecode.git/blob - decoders/timing/pd.py
timing: break long options lines, rename samples identifier
[libsigrokdecode.git] / decoders / timing / pd.py
1 ##
2 ## This file is part of the libsigrokdecode project.
3 ##
4 ## Copyright (C) 2014 Torsten Duwe <duwe@suse.de>
5 ## Copyright (C) 2014 Sebastien Bourdelin <sebastien.bourdelin@savoirfairelinux.com>
6 ##
7 ## This program is free software; you can redistribute it and/or modify
8 ## it under the terms of the GNU General Public License as published by
9 ## the Free Software Foundation; either version 2 of the License, or
10 ## (at your option) any later version.
11 ##
12 ## This program is distributed in the hope that it will be useful,
13 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 ## GNU General Public License for more details.
16 ##
17 ## You should have received a copy of the GNU General Public License
18 ## along with this program; if not, see <http://www.gnu.org/licenses/>.
19 ##
20
21 import sigrokdecode as srd
22 from collections import deque
23
24 class SamplerateError(Exception):
25     pass
26
27 def normalize_time(t):
28     if abs(t) >= 1.0:
29         return '%.3f s  (%.3f Hz)' % (t, (1/t))
30     elif abs(t) >= 0.001:
31         if 1/t/1000 < 1:
32             return '%.3f ms (%.3f Hz)' % (t * 1000.0, (1/t))
33         else:
34             return '%.3f ms (%.3f kHz)' % (t * 1000.0, (1/t)/1000)
35     elif abs(t) >= 0.000001:
36         if 1/t/1000/1000 < 1:
37             return '%.3f μs (%.3f kHz)' % (t * 1000.0 * 1000.0, (1/t)/1000)
38         else:
39             return '%.3f μs (%.3f MHz)' % (t * 1000.0 * 1000.0, (1/t)/1000/1000)
40     elif abs(t) >= 0.000000001:
41         if 1/t/1000/1000/1000:
42             return '%.3f ns (%.3f MHz)' % (t * 1000.0 * 1000.0 * 1000.0, (1/t)/1000/1000)
43         else:
44             return '%.3f ns (%.3f GHz)' % (t * 1000.0 * 1000.0 * 1000.0, (1/t)/1000/1000/1000)
45     else:
46         return '%f' % t
47
48 def terse_times(t):
49     if abs(t) >= 1e0:
50         t *= 1e0
51         return ['{:.0f}s'.format(t), '{:.0f}'.format(t)]
52     if abs(t) >= 1e-3:
53         t *= 1e3
54         return ['{:.0f}ms'.format(t), '{:.0f}'.format(t)]
55     if abs(t) >= 1e-6:
56         t *= 1e6
57         return ['{:.0f}us'.format(t), '{:.0f}'.format(t)]
58     if abs(t) >= 1e-9:
59         t *= 1e9
60         return ['{:.0f}ns'.format(t), '{:.0f}'.format(t)]
61     return ['{:f}'.format(t = t)]
62
63 class Pin:
64     (DATA,) = range(1)
65
66 class Ann:
67     (TIME, TERSE, AVG, DELTA,) = range(4)
68
69 class Decoder(srd.Decoder):
70     api_version = 3
71     id = 'timing'
72     name = 'Timing'
73     longname = 'Timing calculation with frequency and averaging'
74     desc = 'Calculate time between edges.'
75     license = 'gplv2+'
76     inputs = ['logic']
77     outputs = []
78     tags = ['Clock/timing', 'Util']
79     channels = (
80         {'id': 'data', 'name': 'Data', 'desc': 'Data line'},
81     )
82     annotations = (
83         ('time', 'Time'),
84         ('terse', 'Terse'),
85         ('average', 'Average'),
86         ('delta', 'Delta'),
87     )
88     annotation_rows = (
89         ('times', 'Times', (Ann.TIME, Ann.TERSE,)),
90         ('averages', 'Averages', (Ann.AVG,)),
91         ('deltas', 'Deltas', (Ann.DELTA,)),
92     )
93     options = (
94         { 'id': 'avg_period', 'desc': 'Averaging period', 'default': 100 },
95         { 'id': 'edge', 'desc': 'Edges to check',
96           'default': 'any', 'values': ('any', 'rising', 'falling') },
97         { 'id': 'delta', 'desc': 'Show delta from last',
98           'default': 'no', 'values': ('yes', 'no') },
99         { 'id': 'terse', 'desc': 'Show periods in terse format',
100           'default': 'no', 'values': ('yes', 'no') },
101     )
102
103     def __init__(self):
104         self.reset()
105
106     def reset(self):
107         self.samplerate = None
108
109     def metadata(self, key, value):
110         if key == srd.SRD_CONF_SAMPLERATE:
111             self.samplerate = value
112
113     def start(self):
114         self.out_ann = self.register(srd.OUTPUT_ANN)
115
116     def decode(self):
117         if not self.samplerate:
118             raise SamplerateError('Cannot decode without samplerate.')
119         edge = self.options['edge']
120         avg_period = self.options['avg_period']
121         delta = self.options['delta'] == 'yes'
122         terse = self.options['terse'] == 'yes'
123         ss = None
124         last_n = deque()
125         last_t = None
126         while True:
127             if edge == 'rising':
128                 pin = self.wait({Pin.DATA: 'r'})
129             elif edge == 'falling':
130                 pin = self.wait({Pin.DATA: 'f'})
131             else:
132                 pin = self.wait({Pin.DATA: 'e'})
133
134             if not ss:
135                 ss = self.samplenum
136                 continue
137             es = self.samplenum
138             sa = es - ss
139             t = sa / self.samplerate
140
141             if terse:
142                 cls, txt = Ann.TERSE, terse_times(t)
143                 self.put(ss, es, self.out_ann, [cls, txt])
144             else:
145                 cls, txt = Ann.TIME, [normalize_time(t)]
146                 self.put(ss, es, self.out_ann, [cls, txt])
147
148             if avg_period > 0:
149                 if t > 0:
150                     last_n.append(t)
151                 if len(last_n) > avg_period:
152                     last_n.popleft()
153                 average = sum(last_n) / len(last_n)
154                 cls, txt = Ann.AVG, normalize_time(average)
155                 self.put(ss, es, self.out_ann, [cls, [txt]])
156             if last_t and delta:
157                 cls, txt = Ann.DELTA, normalize_time(t - last_t)
158                 self.put(ss, es, self.out_ann, [cls, [txt]])
159
160             last_t = t
161             ss = es