2 ## This file is part of the libsigrok project.
4 ## Copyright (C) 2013 Martin Ling <martin-sigrok@earth.li>
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 3 of the License, or
9 ## (at your option) any later version.
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.
16 ## You should have received a copy of the GNU General Public License
17 ## along with this program. If not, see <http://www.gnu.org/licenses/>.
20 from functools import partial
21 from fractions import Fraction
22 from .lowlevel import *
23 from . import lowlevel
26 __all__ = ['Error', 'Context', 'Driver', 'Device', 'Session', 'Packet', 'Log',
27 'LogLevel', 'PacketType', 'Quantity', 'Unit', 'QuantityFlag', 'ConfigKey',
28 'ProbeType', 'Probe', 'ProbeGroup']
30 class Error(Exception):
33 return sr_strerror(self.args[0])
39 def gvariant_to_python(value):
40 type_string = g_variant_get_type_string(value)
41 if type_string == 't':
42 return g_variant_get_uint64(value)
43 if type_string == 'b':
44 return g_variant_get_bool(value)
45 if type_string == 'd':
46 return g_variant_get_double(value)
47 if type_string == 's':
48 return g_variant_get_string(value, None)
49 if type_string == '(tt)':
51 g_variant_get_uint64(g_variant_get_child_value(value, 0)),
52 g_variant_get_uint64(g_variant_get_child_value(value, 1)))
53 raise NotImplementedError(
54 "Can't convert GVariant type '%s' to a Python type." % type_string)
56 def python_to_gvariant(value):
57 if isinstance(value, int):
58 return g_variant_new_uint64(value)
59 if isinstance(value, bool):
60 return g_variant_new_boolean(value)
61 if isinstance(value, float):
62 return g_variant_new_double(value)
63 if isinstance(value, str):
64 return g_variant_new_string(value)
65 if isinstance(value, Fraction):
66 array = new_gvariant_ptr_array(2)
67 gvariant_ptr_array_setitem(array, 0,
68 g_variant_new_uint64(value.numerator))
69 gvariant_ptr_array_setitem(array, 1,
70 g_variant_new_uint64(value.denominator))
71 result = g_variant_new_tuple(array, 2)
72 delete_gvariant_ptr_array(array)
74 raise NotImplementedError(
75 "Can't convert Python '%s' to a GVariant." % type(value))
77 def callback_wrapper(session, callback, device_ptr, packet_ptr):
78 device = session.context._devices[int(device_ptr.this)]
79 packet = Packet(session, packet_ptr)
80 callback(device, packet)
82 class Context(object):
85 context_ptr_ptr = new_sr_context_ptr_ptr()
86 check(sr_init(context_ptr_ptr))
87 self.struct = sr_context_ptr_ptr_value(context_ptr_ptr)
99 driver_list = sr_driver_list()
100 for i in itertools.count():
101 driver_ptr = sr_dev_driver_ptr_array_getitem(driver_list, i)
103 self._drivers[driver_ptr.name] = Driver(self, driver_ptr)
108 class Driver(object):
110 def __init__(self, context, struct):
111 self.context = context
113 self._initialized = False
117 return self.struct.name
119 def scan(self, **kwargs):
120 if not self._initialized:
121 check(sr_driver_init(self.context.struct, self.struct))
122 self._initialized = True
124 for name, value in kwargs.items():
125 key = getattr(ConfigKey, name.upper())
128 src.data = python_to_gvariant(value)
129 options.append(src.this)
130 option_list = python_to_gslist(options)
131 device_list = sr_driver_scan(self.struct, option_list)
132 g_slist_free(option_list)
133 devices = [Device(self, gpointer_to_sr_dev_inst_ptr(ptr))
134 for ptr in gslist_to_python(device_list)]
135 g_slist_free(device_list)
138 class Device(object):
140 def __new__(cls, driver, struct):
141 address = int(struct.this)
142 if address not in driver.context._devices:
143 device = super(Device, cls).__new__(cls, driver, struct)
144 driver.context._devices[address] = device
145 return driver.context._devices[address]
147 def __init__(self, driver, struct):
151 self._probe_groups = None
153 def __getattr__(self, name):
154 key = getattr(ConfigKey, name.upper())
155 data = new_gvariant_ptr_ptr()
157 check(sr_config_get(self.driver.struct, self.struct, None,
159 except Error as error:
160 if error.errno == SR_ERR_NA:
161 raise NotImplementedError(
162 "Device does not implement %s" % name)
165 value = gvariant_ptr_ptr_value(data)
166 return gvariant_to_python(value)
168 def __setattr__(self, name, value):
170 key = getattr(ConfigKey, name.upper())
171 except AttributeError:
172 super(Device, self).__setattr__(name, value)
174 check(sr_config_set(self.struct, None, key.id, python_to_gvariant(value)))
178 return self.struct.vendor
182 return self.struct.model
186 return self.struct.version
190 if self._probes is None:
192 probe_list = self.struct.probes
194 probe_ptr = void_ptr_to_sr_probe_ptr(probe_list.data)
195 self._probes[probe_ptr.name] = Probe(self, probe_ptr)
196 probe_list = probe_list.next
200 def probe_groups(self):
201 if self._probe_groups is None:
202 self._probe_groups = {}
203 probe_group_list = self.struct.probe_groups
204 while (probe_group_list):
205 probe_group_ptr = void_ptr_to_sr_probe_group_ptr(
206 probe_group_list.data)
207 self._probe_groups[probe_group_ptr.name] = ProbeGroup(self,
209 probe_group_list = probe_group_list.next
210 return self._probe_groups
214 def __init__(self, device, struct):
220 return ProbeType(self.struct.type)
224 return self.struct.enabled
228 return self.struct.name
230 class ProbeGroup(object):
232 def __init__(self, device, struct):
238 return iter(self.probes)
240 def __getattr__(self, name):
241 key = config_key(name)
242 data = new_gvariant_ptr_ptr()
244 check(sr_config_get(self.device.driver.struct, self.device.struct,
245 self.struct, key.id, data))
246 except Error as error:
247 if error.errno == SR_ERR_NA:
248 raise NotImplementedError(
249 "Probe group does not implement %s" % name)
252 value = gvariant_ptr_ptr_value(data)
253 return gvariant_to_python(value)
255 def __setattr__(self, name, value):
257 key = config_key(name)
258 except AttributeError:
259 super(ProbeGroup, self).__setattr__(name, value)
261 check(sr_config_set(self.device.struct, self.struct,
262 key.id, python_to_gvariant(value)))
266 return self.struct.name
270 if self._probes is None:
272 probe_list = self.struct.probes
274 probe_ptr = void_ptr_to_sr_probe_ptr(probe_list.data)
275 self._probes.append(Probe(self, probe_ptr))
276 probe_list = probe_list.next
279 class Session(object):
281 def __init__(self, context):
282 assert context.session is None
283 self.context = context
284 self.struct = sr_session_new()
285 context.session = self
288 check(sr_session_destroy())
290 def add_device(self, device):
291 check(sr_session_dev_add(device.struct))
293 def open_device(self, device):
294 check(sr_dev_open(device.struct))
296 def add_callback(self, callback):
297 wrapper = partial(callback_wrapper, self, callback)
298 check(sr_session_datafeed_python_callback_add(wrapper))
301 check(sr_session_start())
304 check(sr_session_run())
307 check(sr_session_stop())
309 class Packet(object):
311 def __init__(self, session, struct):
312 self.session = session
318 return PacketType(self.struct.type)
322 if self._payload is None:
323 pointer = self.struct.payload
324 if self.type == PacketType.LOGIC:
325 self._payload = Logic(self,
326 void_ptr_to_sr_datafeed_logic_ptr(pointer))
327 elif self.type == PacketType.ANALOG:
328 self._payload = Analog(self,
329 void_ptr_to_sr_datafeed_analog_ptr(pointer))
331 raise NotImplementedError(
332 "No Python mapping for packet type %s" % self.struct.type)
337 def __init__(self, packet, struct):
344 if self._data is None:
345 self._data = cdata(self.struct.data, self.struct.length)
348 class Analog(object):
350 def __init__(self, packet, struct):
356 def num_samples(self):
357 return self.struct.num_samples
361 return Quantity(self.struct.mq)
365 return Unit(self.struct.unit)
369 return QuantityFlag.set_from_mask(self.struct.mqflags)
373 if self._data is None:
374 self._data = float_array.frompointer(self.struct.data)
381 return LogLevel(sr_log_loglevel_get())
385 check(sr_log_loglevel_set(l.id))
389 return sr_log_logdomain_get()
393 check(sr_log_logdomain_set(d))
395 class EnumValue(object):
399 def __new__(cls, id):
400 if cls not in cls._enum_values:
401 cls._enum_values[cls] = {}
402 if id not in cls._enum_values[cls]:
403 value = super(EnumValue, cls).__new__(cls)
405 cls._enum_values[cls][id] = value
406 return cls._enum_values[cls][id]
408 class LogLevel(EnumValue):
411 class PacketType(EnumValue):
414 class Quantity(EnumValue):
417 class Unit(EnumValue):
420 class QuantityFlag(EnumValue):
423 def set_from_mask(cls, mask):
426 new_mask = mask & (mask - 1)
427 result.add(cls(mask ^ new_mask))
431 class ConfigKey(EnumValue):
434 class ProbeType(EnumValue):
437 for symbol_name in dir(lowlevel):
439 ('SR_LOG_', LogLevel),
440 ('SR_DF_', PacketType),
441 ('SR_MQ_', Quantity),
443 ('SR_MQFLAG_', QuantityFlag),
444 ('SR_CONF_', ConfigKey),
445 ('SR_PROBE_', ProbeType)]:
446 if symbol_name.startswith(prefix):
447 name = symbol_name[len(prefix):]
448 value = getattr(lowlevel, symbol_name)
449 setattr(cls, name, cls(value))