| 1 |
# |
| 2 |
# This file is part of the PyMeasure package. |
| 3 |
# |
| 4 |
# Copyright (c) 2013-2024 PyMeasure Developers |
| 5 |
# |
| 6 |
# Permission is hereby granted, free of charge, to any person obtaining a copy |
| 7 |
# of this software and associated documentation files (the "Software"), to deal |
| 8 |
# in the Software without restriction, including without limitation the rights |
| 9 |
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 10 |
# copies of the Software, and to permit persons to whom the Software is |
| 11 |
# furnished to do so, subject to the following conditions: |
| 12 |
# |
| 13 |
# The above copyright notice and this permission notice shall be included in |
| 14 |
# all copies or substantial portions of the Software. |
| 15 |
# |
| 16 |
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 17 |
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 18 |
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 19 |
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 20 |
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 21 |
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
| 22 |
# THE SOFTWARE. |
| 23 |
# |
| 24 |
|
| 25 |
from enum import IntFlag |
| 26 |
import logging |
| 27 |
|
| 28 |
from pyvisa import VisaIOError |
| 29 |
from pymeasure.adapters import SerialAdapter, VISAAdapter |
| 30 |
from pymeasure.instruments import Instrument |
| 31 |
|
| 32 |
|
| 33 |
log = logging.getLogger(__name__) |
| 34 |
log.addHandler(logging.NullHandler()) |
| 35 |
|
| 36 |
|
| 37 |
class VellemanK8090Switches(IntFlag): |
| 38 |
"""Use to identify switch channels.""" |
| 39 |
|
| 40 |
NONE = 0 |
| 41 |
CH1 = 1 << 0 |
| 42 |
CH2 = 1 << 1 |
| 43 |
CH3 = 1 << 2 |
| 44 |
CH4 = 1 << 3 |
| 45 |
CH5 = 1 << 4 |
| 46 |
CH6 = 1 << 5 |
| 47 |
CH7 = 1 << 6 |
| 48 |
CH8 = 1 << 7 |
| 49 |
ALL = CH1 | CH2 | CH3 | CH4 | CH5 | CH6 | CH7 | CH8 |
| 50 |
|
| 51 |
|
| 52 |
def _parse_channels(channels) -> str: |
| 53 |
"""Convert array of channel numbers into mask if needed.""" |
| 54 |
if isinstance(channels, list): |
| 55 |
mask = VellemanK8090Switches.NONE |
| 56 |
for ch in channels: |
| 57 |
mask |= 1 << (ch - 1) |
| 58 |
else: |
| 59 |
mask = channels |
| 60 |
|
| 61 |
return hex(mask) |
| 62 |
|
| 63 |
|
| 64 |
def _get_process_status(items): |
| 65 |
"""Process the result of a 0x51 status message. |
| 66 |
|
| 67 |
:param items: List of 4 integers: [CMD, MASK, Param1, Param2] |
| 68 |
""" |
| 69 |
if len(items) < 4 or items[0] != 0x51: |
| 70 |
return None, None, None |
| 71 |
|
| 72 |
return [VellemanK8090Switches(it) for it in items[1:]] |
| 73 |
|
| 74 |
|
| 75 |
class VellemanK8090(Instrument): |
| 76 |
"""For usage with the K8090 relay board, by Velleman. |
| 77 |
|
| 78 |
View the "K8090/VM8090 PROTOCOL MANUAL" for the serial command instructions. |
| 79 |
|
| 80 |
The communication is done by serial USB. The IO settings are fixed: |
| 81 |
|
| 82 |
================== ================== |
| 83 |
Baud rate 19200 |
| 84 |
Data bits 8 |
| 85 |
Parity None |
| 86 |
Stop bits 1 |
| 87 |
Flow control None |
| 88 |
================== ================== |
| 89 |
|
| 90 |
A short timeout is recommended, since the device is not consistent in giving status messages |
| 91 |
and serial timeouts will occur also in normal operation. |
| 92 |
|
| 93 |
Use the class like: |
| 94 |
|
| 95 |
.. code-block:: python |
| 96 |
|
| 97 |
from pymeasure.instruments.velleman import VellemanK8090, VellemanK8090Switches as Switches |
| 98 |
|
| 99 |
instrument = VellemanK8090("ASRL1::INSTR") |
| 100 |
|
| 101 |
# Get status update from device |
| 102 |
last_on, curr_on, time_on = instrument.status |
| 103 |
|
| 104 |
# Toggle a selection of channels on |
| 105 |
instrument.switch_on = Switches.CH3 | Switches.CH4 | Switches.CH5 |
| 106 |
|
| 107 |
""" |
| 108 |
|
| 109 |
def __init__(self, adapter, name="Velleman K8090", timeout=100, **kwargs): |
| 110 |
super().__init__( |
| 111 |
adapter, |
| 112 |
name=name, |
| 113 |
asrl={"baud_rate": 19200}, |
| 114 |
write_termination="", |
| 115 |
read_termination="", |
| 116 |
timeout=timeout, |
| 117 |
includeSCPI=False, |
| 118 |
**kwargs, |
| 119 |
) |
| 120 |
|
| 121 |
BYTE_STX = 0x04 |
| 122 |
BYTE_ETX = 0x0F |
| 123 |
|
| 124 |
version = Instrument.measurement( |
| 125 |
"0x71", |
| 126 |
""" |
| 127 |
Get firmware version, as (year - 2000, week). E.g. ``(10, 1)`` |
| 128 |
""", |
| 129 |
cast=int, |
| 130 |
get_process=lambda v: (v[2], v[3]) if len(v) > 3 and v[0] == 0x71 else None, |
| 131 |
) |
| 132 |
|
| 133 |
status = Instrument.measurement( |
| 134 |
"0x18", |
| 135 |
""" |
| 136 |
Get current relay status. |
| 137 |
The reply has a different command byte than the request. |
| 138 |
|
| 139 |
Three items (:class:`VellemanK8090Switches` flags) are returned: |
| 140 |
|
| 141 |
* Previous state: the state of each relay before this event |
| 142 |
* Current state: the state of each relay now |
| 143 |
* Timer state: the state of each relay timer |
| 144 |
""", |
| 145 |
cast=int, |
| 146 |
get_process=_get_process_status, |
| 147 |
) |
| 148 |
|
| 149 |
switch_on = Instrument.setting( |
| 150 |
"0x11,%s", |
| 151 |
""" |
| 152 |
Set channels to on state. Other channels are unaffected. |
| 153 |
Pass either a list or set of channel numbers (starting at 1), or pass a bitmask. |
| 154 |
|
| 155 |
After switching this waits for a reply from the device. This is only send when |
| 156 |
a relay actually toggles, otherwise expect a blocking time equal to the |
| 157 |
communication timeout |
| 158 |
If speed is important, avoid calling `switch_` unnecessarily. |
| 159 |
""", |
| 160 |
set_process=_parse_channels, |
| 161 |
check_set_errors=True, |
| 162 |
) |
| 163 |
|
| 164 |
switch_off = Instrument.setting( |
| 165 |
"0x12,%s", |
| 166 |
""" |
| 167 |
Set channels to off state. See :attr:`switch_on` for more details. |
| 168 |
""", |
| 169 |
set_process=_parse_channels, |
| 170 |
check_set_errors=True, |
| 171 |
) |
| 172 |
|
| 173 |
id = None # No identification available |
| 174 |
|
| 175 |
def _make_checksum(self, command, mask, param1, param2): |
| 176 |
# The formula from the sheet requires twos-complement negation, |
| 177 |
# this works |
| 178 |
return 1 + 0xFF - ((self.BYTE_STX + command + mask + param1 + param2) & 0xFF) |
| 179 |
|
| 180 |
def write(self, command, **kwargs): |
| 181 |
"""The write command specifically for the protocol of the K8090. |
| 182 |
|
| 183 |
This overrides the method from the ``Instrument`` class. |
| 184 |
|
| 185 |
Each packet to the device is 7 bytes: |
| 186 |
|
| 187 |
STX (0x04) - CMD - MASK - PARAM1 - PARAM2 - CHK - ETX (0x0F) |
| 188 |
|
| 189 |
Where `CHK` is checksum of the package. |
| 190 |
|
| 191 |
:param command: String like "CMD[, MASK, PARAM1, PARAM2]" - only CMD is mandatory |
| 192 |
:type command: str |
| 193 |
""" |
| 194 |
|
| 195 |
# The device can give status updates when we don't expect it, |
| 196 |
# drop anything from the buffer first |
| 197 |
if isinstance(self.adapter, VISAAdapter): |
| 198 |
self.adapter.flush_read_buffer() |
| 199 |
elif isinstance(self.adapter, SerialAdapter): |
| 200 |
# The SerialAdapter does not have `flush_read_buffer` implemented |
| 201 |
self.adapter.connection.flush() |
| 202 |
|
| 203 |
items_str = command.split(",") |
| 204 |
|
| 205 |
items = [int(it, 16) for it in items_str] |
| 206 |
|
| 207 |
cmd = items[0] |
| 208 |
mask = items[1] if len(items) > 1 else 0 |
| 209 |
param1 = items[2] if len(items) > 2 else 0 |
| 210 |
param2 = items[3] if len(items) > 3 else 0 |
| 211 |
|
| 212 |
checksum = self._make_checksum(cmd, mask, param1, param2) |
| 213 |
|
| 214 |
content = [ |
| 215 |
self.BYTE_STX, |
| 216 |
cmd, |
| 217 |
mask, |
| 218 |
param1, |
| 219 |
param2, |
| 220 |
checksum, |
| 221 |
self.BYTE_ETX, |
| 222 |
] |
| 223 |
|
| 224 |
self.write_bytes(bytes(content)) |
| 225 |
|
| 226 |
def read(self, **kwargs): |
| 227 |
"""The read command specifically for the protocol of the K8090. |
| 228 |
|
| 229 |
This overrides the method from the ``instrument`` class. |
| 230 |
|
| 231 |
See :meth:`write`, replies from the machine use the same format. |
| 232 |
|
| 233 |
A read will return a list of CMD, MASK, PARAM1 and PARAM2. |
| 234 |
""" |
| 235 |
# A message is always 7 bytes |
| 236 |
# (there is also a termination char, but since it is not exclusive it cannot be |
| 237 |
# reliably used) |
| 238 |
response = self.read_bytes(7) |
| 239 |
|
| 240 |
if len(response) < 7: |
| 241 |
raise ConnectionError(f"Incoming packet was {len(response)} bytes instead of 7") |
| 242 |
|
| 243 |
# Only consider the most recent block |
| 244 |
stx, command, mask, param1, param2, checksum, etx = list(response[-7:]) |
| 245 |
|
| 246 |
if stx != self.BYTE_STX or etx != self.BYTE_ETX: |
| 247 |
raise ConnectionError(f"Received invalid start and stop bytes `{stx}` and `{etx}`") |
| 248 |
|
| 249 |
if command == 0x00: |
| 250 |
raise ConnectionError(f"Received invalid command byte `{command}`") |
| 251 |
|
| 252 |
real_checksum = self._make_checksum(command, mask, param1, param2) |
| 253 |
if real_checksum != checksum: |
| 254 |
raise ConnectionError( |
| 255 |
f"Packet checksum was not correct, got {hex(checksum)} " |
| 256 |
f"instead of {hex(real_checksum)}" |
| 257 |
) |
| 258 |
|
| 259 |
values_str = [str(v) for v in [command, mask, param1, param2]] |
| 260 |
|
| 261 |
return ",".join(values_str) |
| 262 |
|
| 263 |
def check_set_errors(self): |
| 264 |
"""Check for errors after having set a property and log them. |
| 265 |
|
| 266 |
Called if :code:`check_set_errors=True` is set for that property. |
| 267 |
|
| 268 |
The K8090 replies with a status after a switch command, but |
| 269 |
**only** after any switch actually changed. In order to guarantee |
| 270 |
the buffer is empty, we attempt to read it fully here. |
| 271 |
No actual error checking is done here! |
| 272 |
|
| 273 |
:return: List of error entries. |
| 274 |
""" |
| 275 |
try: |
| 276 |
self.read() |
| 277 |
except (VisaIOError, ConnectionError): |
| 278 |
pass # Ignore a timeout |
| 279 |
except Exception as exc: |
| 280 |
log.exception("Setting a property failed.", exc_info=exc) |
| 281 |
raise |
| 282 |
else: |
| 283 |
return [] |