]> sigrok.org Git - sigrok-meter.git/blame - datamodel.py
README: Bump libsigrok requirement to 0.4.0.
[sigrok-meter.git] / datamodel.py
CommitLineData
48723bbb
JS
1##
2## This file is part of the sigrok-meter project.
3##
4## Copyright (C) 2014 Jens Steinhauser <jens.steinhauser@gmail.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
f76b9df8 21import collections
3010b5a0 22import itertools
5baa1f4b 23import math
48723bbb
JS
24import qtcompat
25import sigrok.core as sr
f76b9df8 26import util
48723bbb 27
3010b5a0
JS
28try:
29 from itertools import izip
30except ImportError:
31 izip = zip
32
48723bbb
JS
33QtCore = qtcompat.QtCore
34QtGui = qtcompat.QtGui
35
d0aa45b4
JS
36class Trace(object):
37 '''Class to hold the measured samples.'''
38
39 def __init__(self):
40 self.samples = []
41 self.new = False
42
43 def append(self, sample):
44 self.samples.append(sample)
45 self.new = True
46
48723bbb
JS
47class MeasurementDataModel(QtGui.QStandardItemModel):
48 '''Model to hold the measured values.'''
49
50 '''Role used to identify and find the item.'''
f76b9df8 51 idRole = QtCore.Qt.UserRole + 1
48723bbb
JS
52
53 '''Role used to store the device vendor and model.'''
54 descRole = QtCore.Qt.UserRole + 2
55
d0aa45b4
JS
56 '''Role used to store a dictionary with the traces'''
57 tracesRole = QtCore.Qt.UserRole + 3
f76b9df8 58
3010b5a0
JS
59 '''Role used to store the color to draw the graph of the channel.'''
60 colorRole = QtCore.Qt.UserRole + 4
61
48723bbb
JS
62 def __init__(self, parent):
63 super(self.__class__, self).__init__(parent)
64
65 # Use the description text to sort the items for now, because the
f76b9df8 66 # idRole holds tuples, and using them to sort doesn't work.
48723bbb
JS
67 self.setSortRole(MeasurementDataModel.descRole)
68
3010b5a0
JS
69 # A generator for the colors of the channels.
70 self._colorgen = self._make_colorgen()
71
72 def _make_colorgen(self):
73 cols = [
74 QtGui.QColor(0x8F, 0x52, 0x02), # brown
86862cb4 75 QtGui.QColor(0x73, 0xD2, 0x16), # green
3010b5a0 76 QtGui.QColor(0xCC, 0x00, 0x00), # red
86862cb4 77 QtGui.QColor(0x34, 0x65, 0xA4), # blue
3010b5a0
JS
78 QtGui.QColor(0xF5, 0x79, 0x00), # orange
79 QtGui.QColor(0xED, 0xD4, 0x00), # yellow
3010b5a0
JS
80 QtGui.QColor(0x75, 0x50, 0x7B) # violet
81 ]
82
83 def myrepeat(g, n):
84 '''Repeats every element from 'g' 'n' times'.'''
85 for e in g:
86 for f in itertools.repeat(e, n):
87 yield f
88
89 colorcycle = itertools.cycle(cols)
90 darkness = myrepeat(itertools.count(100, 10), len(cols))
91
92 for c, d in izip(colorcycle, darkness):
93 yield QtGui.QColor(c).darker(d)
94
48723bbb
JS
95 def format_mqflags(self, mqflags):
96 if sr.QuantityFlag.AC in mqflags:
97 return 'AC'
98 elif sr.QuantityFlag.DC in mqflags:
99 return 'DC'
100 else:
101 return ''
102
103 def format_value(self, mag):
5baa1f4b 104 if math.isinf(mag):
48723bbb
JS
105 return u'\u221E'
106 return '{:f}'.format(mag)
107
108 def getItem(self, device, channel):
480cdb7b
UH
109 '''Return the item for the device + channel combination from the
110 model, or create a new item if no existing one matches.'''
48723bbb 111
480cdb7b
UH
112 # Unique identifier for the device + channel.
113 # TODO: Isn't there something better?
48723bbb
JS
114 uid = (
115 device.vendor,
116 device.model,
117 device.serial_number(),
118 device.connection_id(),
119 channel.index
120 )
121
480cdb7b 122 # Find the correct item in the model.
48723bbb
JS
123 for row in range(self.rowCount()):
124 item = self.item(row)
f76b9df8 125 rid = item.data(MeasurementDataModel.idRole)
480cdb7b 126 rid = tuple(rid) # PySide returns a list.
48723bbb
JS
127 if uid == rid:
128 return item
129
480cdb7b 130 # Nothing found, create a new item.
0e810ddf 131 desc = '{} {}, {}'.format(
48723bbb
JS
132 device.vendor, device.model, channel.name)
133
134 item = QtGui.QStandardItem()
f76b9df8 135 item.setData(uid, MeasurementDataModel.idRole)
48723bbb 136 item.setData(desc, MeasurementDataModel.descRole)
d0aa45b4 137 item.setData(collections.defaultdict(Trace), MeasurementDataModel.tracesRole)
3010b5a0 138 item.setData(next(self._colorgen), MeasurementDataModel.colorRole)
48723bbb
JS
139 self.appendRow(item)
140 self.sort(0)
141 return item
142
6c05c913
JS
143 @QtCore.Slot(float, sr.classes.Device, sr.classes.Channel, tuple)
144 def update(self, timestamp, device, channel, data):
480cdb7b 145 '''Update the data for the device (+channel) with the most recent
48723bbb
JS
146 measurement from the given payload.'''
147
148 item = self.getItem(device, channel)
149
150 value, unit, mqflags = data
151 value_str = self.format_value(value)
f76b9df8 152 unit_str = util.format_unit(unit)
48723bbb
JS
153 mqflags_str = self.format_mqflags(mqflags)
154
02862990
JS
155 # The display role is a tuple containing the value and the unit/flags.
156 disp = (value_str, ' '.join([unit_str, mqflags_str]))
48723bbb
JS
157 item.setData(disp, QtCore.Qt.DisplayRole)
158
f76b9df8
JS
159 # The samples role is a dictionary that contains the old samples for each unit.
160 # Should be trimmed periodically, otherwise it grows larger and larger.
5baa1f4b
JS
161 if not math.isinf(value) and not math.isnan(value):
162 sample = (timestamp, value)
163 traces = item.data(MeasurementDataModel.tracesRole)
164 traces[unit].append(sample)
f76b9df8 165
48723bbb
JS
166class MultimeterDelegate(QtGui.QStyledItemDelegate):
167 '''Delegate to show the data items from a MeasurementDataModel.'''
168
169 def __init__(self, parent, font):
480cdb7b 170 '''Initialize the delegate.
48723bbb 171
32b16651 172 :param font: Font used for the text.
48723bbb
JS
173 '''
174
175 super(self.__class__, self).__init__(parent)
176
177 self._nfont = font
48723bbb
JS
178
179 fi = QtGui.QFontInfo(self._nfont)
180 self._nfontheight = fi.pixelSize()
181
32b16651 182 fm = QtGui.QFontMetrics(self._nfont)
48723bbb 183 r = fm.boundingRect('-XX.XXXXXX X XX')
02862990 184
32b16651
JS
185 w = 1.4 * r.width() + 2 * self._nfontheight
186 h = 2.6 * self._nfontheight
187 self._size = QtCore.QSize(w, h)
48723bbb
JS
188
189 def sizeHint(self, option=None, index=None):
190 return self._size
191
32b16651
JS
192 def _color_rect(self, outer):
193 '''Returns the dimensions of the clickable rectangle.'''
194 x1 = (outer.height() - self._nfontheight) / 2
195 r = QtCore.QRect(x1, x1, self._nfontheight, self._nfontheight)
196 r.translate(outer.topLeft())
197 return r
198
48723bbb 199 def paint(self, painter, options, index):
02862990 200 value, unit = index.data(QtCore.Qt.DisplayRole)
48723bbb 201 desc = index.data(MeasurementDataModel.descRole)
32b16651 202 color = index.data(MeasurementDataModel.colorRole)
48723bbb 203
48723bbb 204 painter.setFont(self._nfont)
32b16651
JS
205
206 # Draw the clickable rectangle.
207 painter.fillRect(self._color_rect(options.rect), color)
208
209 # Draw the text
210 h = options.rect.height()
48723bbb 211 p = options.rect.topLeft()
32b16651 212 p += QtCore.QPoint(h, (h + self._nfontheight) / 2 - 2)
0e810ddf 213 painter.drawText(p, desc + ': ' + value + ' ' + unit)
32b16651
JS
214
215 def editorEvent(self, event, model, options, index):
216 if type(event) is QtGui.QMouseEvent:
217 if event.type() == QtCore.QEvent.MouseButtonPress:
218 rect = self._color_rect(options.rect)
219 if rect.contains(event.x(), event.y()):
220 c = index.data(MeasurementDataModel.colorRole)
221 c = QtGui.QColorDialog.getColor(c, None,
222 'Choose new color for channel')
223
224 item = model.itemFromIndex(index)
225 item.setData(c, MeasurementDataModel.colorRole)
226
227 return True
228
229 return False