-
Notifications
You must be signed in to change notification settings - Fork 5
/
datamodel.py
243 lines (193 loc) · 8.25 KB
/
datamodel.py
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
##
## This file is part of the sigrok-meter project.
##
## Copyright (C) 2014 Jens Steinhauser <[email protected]>
##
## 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 2 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/>.
##
import itertools
import math
import qtcompat
import sigrok.core as sr
import util
try:
from itertools import izip
except ImportError:
izip = zip
QtCore = qtcompat.QtCore
QtGui = qtcompat.QtGui
class Trace(object):
'''Class to hold the measured samples.'''
def __init__(self):
self.samples = []
self.new = False
def append(self, sample):
self.samples.append(sample)
self.new = True
class MeasurementDataModel(QtGui.QStandardItemModel):
'''Model to hold the measured values.'''
'''Role used to identify and find the item.'''
idRole = QtCore.Qt.UserRole + 1
'''Role used to store the device vendor and model.'''
descRole = QtCore.Qt.UserRole + 2
'''Role used to store a dictionary with the traces.'''
tracesRole = QtCore.Qt.UserRole + 3
'''Role used to store the color to draw the graph of the channel.'''
colorRole = QtCore.Qt.UserRole + 4
def __init__(self, parent):
super(self.__class__, self).__init__(parent)
# Use the description text to sort the items for now, because the
# idRole holds tuples, and using them to sort doesn't work.
self.setSortRole(MeasurementDataModel.descRole)
# A generator for the colors of the channels.
self._colorgen = self._make_colorgen()
def _make_colorgen(self):
cols = [
QtGui.QColor(0x8F, 0x52, 0x02), # brown
QtGui.QColor(0x73, 0xD2, 0x16), # green
QtGui.QColor(0xCC, 0x00, 0x00), # red
QtGui.QColor(0x34, 0x65, 0xA4), # blue
QtGui.QColor(0xF5, 0x79, 0x00), # orange
QtGui.QColor(0xED, 0xD4, 0x00), # yellow
QtGui.QColor(0x75, 0x50, 0x7B) # violet
]
def myrepeat(g, n):
'''Repeats every element from 'g' 'n' times'.'''
for e in g:
for f in itertools.repeat(e, n):
yield f
colorcycle = itertools.cycle(cols)
darkness = myrepeat(itertools.count(100, 10), len(cols))
for c, d in izip(colorcycle, darkness):
yield QtGui.QColor(c).darker(d)
def format_mqflags(self, mqflags):
if sr.QuantityFlag.AC in mqflags:
return 'AC'
elif sr.QuantityFlag.DC in mqflags:
return 'DC'
else:
return ''
def format_value(self, mag):
if math.isinf(mag):
return u'\u221E'
return '{:f}'.format(mag)
def getItem(self, device, channel):
'''Return the item for the device + channel combination from the
model, or create a new item if no existing one matches.'''
# Unique identifier for the device + channel.
# TODO: Isn't there something better?
uid = (
device.vendor,
device.model,
device.serial_number(),
device.connection_id(),
channel.index
)
# Find the correct item in the model.
for row in range(self.rowCount()):
item = self.item(row)
rid = item.data(MeasurementDataModel.idRole)
rid = tuple(rid) # PySide returns a list.
if uid == rid:
return item
# Nothing found, create a new item.
desc = '{} {}, {}'.format(
device.vendor, device.model, channel.name)
item = QtGui.QStandardItem()
item.setData(uid, MeasurementDataModel.idRole)
item.setData(desc, MeasurementDataModel.descRole)
item.setData({}, MeasurementDataModel.tracesRole)
item.setData(next(self._colorgen), MeasurementDataModel.colorRole)
self.appendRow(item)
self.sort(0)
return item
@QtCore.Slot(float, sr.classes.Device, sr.classes.Channel, tuple)
def update(self, timestamp, device, channel, data):
'''Update the data for the device (+channel) with the most recent
measurement from the given payload.'''
item = self.getItem(device, channel)
value, unit, mqflags = data
value_str = self.format_value(value)
unit_str = util.format_unit(unit)
mqflags_str = self.format_mqflags(mqflags)
# The display role is a tuple containing the value and the unit/flags.
disp = (value_str, ' '.join([unit_str, mqflags_str]))
item.setData(disp, QtCore.Qt.DisplayRole)
# The samples role is a dictionary that contains the old samples for each unit.
# Should be trimmed periodically, otherwise it grows larger and larger.
if not math.isinf(value) and not math.isnan(value):
sample = (timestamp, value)
traces = item.data(MeasurementDataModel.tracesRole)
# It's not possible to use 'collections.defaultdict' here, because
# PySide doesn't return the original type that was passed in.
if not (unit in traces):
traces[unit] = Trace()
traces[unit].append(sample)
item.setData(traces, MeasurementDataModel.tracesRole)
def clear_samples(self):
'''Removes all old samples from the model.'''
for row in range(self.rowCount()):
idx = self.index(row, 0)
self.setData(idx, {},
MeasurementDataModel.tracesRole)
class MultimeterDelegate(QtGui.QStyledItemDelegate):
'''Delegate to show the data items from a MeasurementDataModel.'''
def __init__(self, parent, font):
'''Initialize the delegate.
:param font: Font used for the text.
'''
super(self.__class__, self).__init__(parent)
self._nfont = font
fi = QtGui.QFontInfo(self._nfont)
self._nfontheight = fi.pixelSize()
fm = QtGui.QFontMetrics(self._nfont)
r = fm.boundingRect('-XX.XXXXXX X XX')
w = 1.4 * r.width() + 2 * self._nfontheight
h = 2.6 * self._nfontheight
self._size = QtCore.QSize(w, h)
def sizeHint(self, option=None, index=None):
return self._size
def _color_rect(self, outer):
'''Returns the dimensions of the clickable rectangle.'''
x1 = (outer.height() - self._nfontheight) / 2
r = QtCore.QRect(x1, x1, self._nfontheight, self._nfontheight)
r.translate(outer.topLeft())
return r
def paint(self, painter, options, index):
value, unit = index.data(QtCore.Qt.DisplayRole)
desc = index.data(MeasurementDataModel.descRole)
color = index.data(MeasurementDataModel.colorRole)
painter.setFont(self._nfont)
# Draw the clickable rectangle.
painter.fillRect(self._color_rect(options.rect), color)
# Draw the text
h = options.rect.height()
p = options.rect.topLeft()
p += QtCore.QPoint(h, (h + self._nfontheight) / 2 - 2)
painter.drawText(p, desc + ': ' + value + ' ' + unit)
def editorEvent(self, event, model, options, index):
if type(event) is QtGui.QMouseEvent:
if event.type() == QtCore.QEvent.MouseButtonPress:
rect = self._color_rect(options.rect)
if rect.contains(event.x(), event.y()):
c = index.data(MeasurementDataModel.colorRole)
c = QtGui.QColorDialog.getColor(c, None,
'Choose new color for channel')
if c.isValid():
# False if cancel is pressed (resulting in a black
# color).
item = model.itemFromIndex(index)
item.setData(c, MeasurementDataModel.colorRole)
return True
return False