Skip to content

Device dataclass

Class to represent a device.

Source code in src/stm32reader.py
@dataclass
class Device:
    """Class to represent a device."""

    #: Universal ID of the device
    uid: str

    #: Position In Chain of the device.
    pic: int

    #: Size, in bytes, of the device's SRAM.
    sram_size: int

    def __eq__(self, other):
        return self.uid == other.uid and self.pic == other.pic

    def __hash__(self):
        return hash(("uid", self.uid, "pic", self.pic))

    def __str__(self):
        return f"{self.pic:03d}:{format_uid(self.uid)}"

    def __repr__(self):
        return f"<Device {self.pic:03d}:{format_uid(self.uid)} 0x{self.sram_size:08X}>"

STM32Reader

Bases: Reader

Reader implementation for STM32 boards.

The functionaly of the reader is implemented in the methods called handle_{command}.

Attributes:

Name Type Description
name

Descriptive name of the Reader.

devices List[Device]

List of managed devices.

port

State of the devices and the serial port.

Source code in src/stm32reader.py
 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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
class STM32Reader(Reader):
    """Reader implementation for STM32 boards.

    The functionaly of the reader is implemented in the methods called `handle_{command}`.

    Attributes:
        name: Descriptive name of the Reader.
        devices: List of managed devices.
        port: State of the devices and the serial port.
    """

    def __init__(self, board_type: str, port: str, baudrate: int, data_size: int):
        super(STM32Reader, self).__init__(board_type)
        self.devices: List[Device] = []
        self.name = board_type
        self.data_size = data_size

        port_path = Path(port)
        if not port_path.exists():
            print(f"Port {port_path} does not exist")
            sys.exit(1)

        ser = Serial(port_path.as_posix(), baudrate, timeout=None)
        self.port = {"state": "ON", "serial": ser, "path": port_path}

    def send(self, data: bytes):
        """Transmit data through the serial port.

        Args:
            data: Bytes to sent.
        """
        ser = self.port["serial"]
        ser.flushInput()
        ser.write(data)
        ser.flushOutput()

    def receive(self, timeout: float = 0.2, tries=200) -> List[Packet]:
        """Received data from the serial port.

        Args:
            timeout: Time to wait until start receiving information.

        Returns:
            List of packets received.
        """
        packet_size = Packet.full_size(self.data_size)

        ser = self.port["serial"]
        ser.flushInput()
        packets = []
        msg = b""

        time.sleep(timeout)
        checks = deque(maxlen=tries // 2)
        for _ in range(tries):
            checks.appendleft(ser.in_waiting)
            while ser.in_waiting:
                while len(msg) < packet_size:
                    msg += ser.read()
                packets.append(Packet.from_bytes(self.data_size, msg))
                msg = b""

            if all(num == 0 for num in checks) and packets:
                return packets
            time.sleep(0.05)

        return packets

    def handle_status(self, props: Dict[str, Any], logger, db_session):
        """Show the status of the reader.

        Args:
            props: Dict[str, Any] from the dispatcher
            logger: Logger instance to log data.
            db_session: DBManager instance to query and insert data.

        Returns:
            Status of the operation
        """
        logger.results(
            json.dumps(
                {
                    "state": self.port["state"],
                    "devices": [d.__dict__ for d in self.devices],
                }
            )
        )

    def handle_power_off(self, props: Dict[str, Any], logger, db_session):
        """Power off the serial port.

        Args:
            props: Dictionary containing the message from the dispatcher.

        Returns:
            Dictionary with the status of the operation and metadata if needed.
        """
        try:
            p = run(["ykushcmd", "-d", "a"])
            if p.returncode == 0:
                self.port["state"] = "OFF"
                logger.info("Port powered off")
            else:
                raise CommandError("Could not power off port")
        except Exception as excep:
            raise CommandError(f"Problem powering off port {self.port['path']}: {excep}") from excep

    def handle_power_on(self, props: Dict[str, Any], logger, db_session):
        """Power on the serial port.

        Args:
            props: Dictionary containing the message from the dispatcher.

        Returns:
            Dictionary with the status of the operation and metadata if needed.
        """
        try:
            p = run(["ykushcmd", "-u", "a"])
            if p.returncode == 0:
                self.port["state"] = "ON"
                logger.info("Port powered on")
            else:
                raise CommandError("Could not power on port")
        except Exception as excep:
            raise CommandError(f"Problem powering on port {self.port['path']}: {excep}") from excep

    def handle_ping(self, props: Dict[str, Any], logger, db_session):
        """Register the devices connected to the reader.

        Args:
            props: Dictionary containing the message from the dispatcher.

        Returns:
            Dictionary with the status of the operation and metadata if needed.
        """
        status_correct: Optional[bool] = None
        prev_devices = self.devices

        packet = Packet(self.data_size)
        packet.with_command(Command.PING)
        packet.craft()
        self.send(packet.to_bytes())
        packets = self.receive()

        if self.port["state"] == "OFF":
            raise CommandError(
                "Serial port is off. Please turn on the serial port first"
            )

        if prev_devices and not packets:
            raise CommandError(
                "There were devices connected but now no devices could be identified"
            )

        if not packets:
            raise CommandError("No devices could be identified")

        devices: List[Device] = []
        for packet in packets:
            if not packet.check_crc():
                logger.warning(f"Packet {packet!s} is corrupted")
                status_correct = False
            else:
                devices.append(
                    Device(format_uid(packet.uid), packet.pic, packet.options)
                )

        self.devices = devices
        if status_correct is None:
            logger.results(json.dumps([d.__dict__ for d in self.devices]))

    def handle_sensors(self, props: Dict[str, Any], logger, db_session):
        """Register the devices connected to the reader.

        Args:
            props: Dictionary containing the message from the dispatcher.

        Returns:
            Dictionary with the status of the operation and metadata if needed.
        """
        if self.port["state"] == "OFF":
            raise CommandError("Serial port is off. Turn on the serial port first")

        if not self.devices:
            raise CommandError("No devices managed")

        current_day = datetime.now()
        current_day = current_day.replace(hour=12, minute=0, second=0)
        for dev in self.devices:
            packet = Packet(self.data_size)
            packet.with_command(Command.SENSORS)
            packet.with_uid(dev.uid)
            packet.craft()
            self.send(packet.to_bytes())
            res = next(iter(self.receive()), None)
            if res is None:
                logger.error(f"Problem reading sensors for device {dev}")
                continue

            if not packet.check_crc() or packet.command == Command.ERR:
                logger.warning(
                    f"Packet {packet!s} for device {dev} is corrupted"
                )
                continue

            sensors_data = res.extract_sensors()

            logger.results(
                json.dumps(
                    {
                        "device": {"uid": dev.uid, "pic": dev.pic},
                        "temperature": sensors_data["temperature"],
                        "voltage": sensors_data["voltage"],
                    }
                )
            )

            db_session.add(
                Sensor(
                    uid=format_uid(res.uid),
                    pic=dev.pic,
                    board_type=self.name,
                    temperature=sensors_data["temperature"],
                    voltage=sensors_data["voltage"],
                    created_at=current_day,
                )
            )
            db_session.commit()

    def handle_read(self, props: Dict[str, Any], logger, db_session):
        """ """
        if self.port["state"] == "OFF":
            raise CommandError("Serial port is off. Turn on the serial port first")

        if not self.devices:
            raise CommandError("No devices managed")

        # Only store the day the read is done
        current_day = datetime.now()
        current_day = current_day.replace(hour=12, minute=0, second=0)

        for dev in self.devices:
            for offset in range(dev.sram_size // self.data_size):
                address = offset_to_address(self.data_size, offset)
                packet = Packet(self.data_size)
                packet.with_command(Command.READ)
                packet.with_uid(dev.uid)
                packet.with_options(offset)
                packet.craft()
                self.send(packet.to_bytes())
                res = next(iter(self.receive()), None)
                if res is None:
                    logger.error(
                        f"Problem reading memory of device {dev} at offset {offset}"
                    )
                    continue

                if not packet.check_crc() or packet.command == Command.ERR:
                    logger.warning(f"Packet {packet!s} is corrupted")
                    continue

                db_session.add(
                    Sample(
                        board_type=self.name,
                        uid=format_uid(res.uid),
                        pic=dev.pic,
                        address=address,
                        data=",".join([str(d) for d in res.data]),
                        created_at=current_day,
                    )
                )
                db_session.commit()
                logger.debug(f"Read memory of device {dev} at offset {offset}")

            logger.info(f"Finished reading memory of {dev}")

    def handle_write(self, props: Dict[str, Any], logger, db_session):
        """ """
        if self.port["state"] == "OFF":
            raise CommandError("Serial port is off. Turn on the serial port first")

        if not self.devices:
            raise CommandError("No devices managed")

        offset = props["offset"]
        dev_id = props["device"]
        dev = next(filter(lambda d: d.uid == dev_id, self.devices), None)

        if not dev:
            raise CommandError(f"Device {dev.id} is not managed")

        max_offset = dev.sram_size // self.data_size

        if offset < 0 or offset > max_offset:
            raise CommandError(
                f"Offset {offset} for device {dev_id} must be in range [0, {max_offset}]"
            )

        packet = Packet(self.data_size)
        packet.with_command(Command.WRITE)
        packet.with_uid(dev.uid)
        packet.with_options(offset)
        packet.with_data([int(b) for b in props["data"]])
        packet.craft()

        self.send(packet.to_bytes())
        res = next(iter(self.receive()), None)
        if res is None:
            raise CommandError(
                f"Problem writing to memory of device {dev.pic}{dev.uid} at offset {offset}"
            )

        if not res.check_crc() or res.command == Command.ERR:
            raise CommandError(f"Packet {packet!s} is corrupted")

        logger.info("Data written correctly")

    def handle_write_invert(self, props: Dict[str, Any], logger, db_session):
        """
        We assume that a reader handles only one type of device,
        So all devices *should* have the same memory regions.

        Get first all different regions and later check that a device
        has at least one sample of all of them.
        """
        if self.port["state"] == "OFF":
            raise CommandError("Serial port is off. Turn on the serial port first")

        if not self.devices:
            raise CommandError("No devices managed")

        device_list = list(self.devices)
        for dev in device_list[: len(self.devices) // 2]:
            num_addresses = dev.sram_size // self.data_size
            samples = (
                db_session.query(Sample)
                .filter(Sample.uid == dev.uid)
                .order_by(Sample.address.asc(), Sample.created_at.asc())
                .limit(num_addresses)
                .all()
            )

            if not samples:
                logger.warning(
                    f"At least one full memory sample has to be read from device {dev}"
                )
                continue

            if len(samples) != num_addresses:
                logger.warning(
                    f"The memory sample for device {dev} is not complete"
                )
                continue

            end_offset = (num_addresses) - READ_ONLY_REGIONS
            for offset in range(READ_ONLY_REGIONS, end_offset):
                sample = samples[offset]
                packet = Packet(self.data_size)
                packet.with_command(Command.WRITE)
                packet.with_uid(dev.uid)
                packet.with_options(offset)
                packet.with_data([0xFF ^ int(d) for d in sample.data.split(",")])
                packet.craft()

                self.send(packet.to_bytes())
                res = next(iter(self.receive()), None)
                if res is None:
                    logger.error(
                        f"Problem writing inverted values of device {dev.pic}{dev.uid} at offset {offset}"
                    )
                    continue

                if not res.check_crc() or res.command == Command.ERR:
                    logger.warning(f"Packet {packet!s} is corrupted")
                    continue
                logger.debug(f"Inverted memory of device {dev} at offset {offset}")

            logger.info(f"Finished inverting memory of device {dev}")

    def handle_write_const(self, props: Dict[str, Any], logger, db_session):
        """
        """
        if self.port["state"] == "OFF":
            raise CommandError("Serial port is off. Turn on the serial port first")

        if not self.devices:
            raise CommandError("No devices managed")

        value = props["value"]
        dev_id = props["device"]
        dev = next(filter(lambda d: d.uid == dev_id, self.devices), None)

        if not dev:
            raise CommandError(f"Device {dev.id} is not managed")

        end_offset = (num_addresses) - READ_ONLY_REGIONS
        for offset in range(READ_ONLY_REGIONS, end_offset):
            sample = samples[offset]
            packet = Packet(self.data_size)
            packet.with_command(Command.WRITE)
            packet.with_uid(dev.uid)
            packet.with_options(offset)
            packet.with_data([value] * self.data_size)
            packet.craft()

            self.send(packet.to_bytes())
            res = next(iter(self.receive()), None)
            if res is None:
                logger.error(
                    f"Problem writing constant value of device {dev} at offset {offset}"
                )
                continue

            if not res.check_crc() or res.command == Command.ERR:
                logger.warning(f"Packet {packet!s} is corrupted")
                continue
            logger.debug(f"Wrote constant in memory of device {dev} at offset {offset}")

        logger.info(f"Finished writing constant to memory of device {dev}")


    def handle_load(self, props: Dict[str, Any], logger, db_session):
        """ """
        if self.port["state"] == "OFF":
            raise CommandError("Serial port is off. Turn on the serial port first")

        if not self.devices:
            raise CommandError("No devices managed")

        dev_uid = props["device"]
        dev = next(filter(lambda d: d.uid == dev_uid, self.devices), None)

        if not dev:
            raise CommandError(f"Device {dev.uid} is not managed")

        source = props["source"]
        len_code = len(source)
        data_buf = [ord(c) for c in source] + [ord("\x00")] * (
            self.data_size - len_code
        )

        packet = Packet(self.data_size)
        packet.with_command(Command.LOAD)
        packet.with_uid(dev_uid)
        packet.with_data(data_buf)
        packet.craft()
        self.send(packet.to_bytes())
        res = next(iter(self.receive()), None)
        if res is None:
            raise CommandError(f"Problem loading code for device {dev}")

        if not res.check_crc() or res.command == Command.ERR:
            raise CommandError(f"Packet {packet!s} is corrupted")

        logger.info(f"Code loaded on device {dev} correctly")

    def handle_exec(self, props: Dict[str, Any], logger, db_session):
        """ """
        if self.port["state"] == "OFF":
            raise CommandError("Serial port is off. Turn on the serial port first")

        if not self.devices:
            raise CommandError("No devices managed")

        dev_uid = props["device"]
        dev = next(filter(lambda d: d.uid == dev_uid, self.devices), None)

        if not dev:
            raise CommandError(f"Device {dev_uid} is not managed")

        packet = Packet(self.data_size)
        packet.with_command(Command.EXEC)
        packet.with_uid(dev_uid)
        packet.with_options(int(props.get("reset", 0)))
        packet.craft()
        self.send(packet.to_bytes())
        res = next(iter(self.receive()), None)

        if res is None:
            raise CommandError(f"Problem executing code on device {dev.pic}{dev.uid}")

        if not res.check_crc() or res.command == Command.ERR:
            raise CommandError(f"Packet {packet!s} is corrupted")

        if res.options != 0:
            raise CommandError(
                f"Code on device {dev} executed with error code {res.options}"
            )
        logger.info(f"Code on device {dev} executed correctly")

    def handle_retr(self, props: Dict[str, Any], logger, db_session):
        """ """
        if self.port["state"] == "OFF":
            raise CommandError("Serial port is off. Turn on the serial port first")

        if not self.devices:
            raise CommandError("No devices managed")

        dev_uid = props["device"]
        dev = next(filter(lambda d: d.uid == dev_uid, self.devices), None)

        if not dev:
            raise CommandError(f"Device {dev_uid} is not managed")

        packet = Packet(self.data_size)
        packet.with_command(Command.RETR)
        packet.with_uid(dev.uid)
        packet.craft()
        self.send(packet.to_bytes())
        res = next(iter(self.receive()), None)
        if res is None:
            raise CommandError(
                f"Problem retrieving results from device {dev}"
            )

        if not res.check_crc() or res.command == Command.ERR:
            raise CommandError(f"Packet {packet!s} is corrupted")

        numbers = struct.unpack(f"<{self.data_size // 4}i", bytes(res.data))
        numbers_str = map(str, numbers)
        numbers_str = map(
            lambda n: n.replace("10", "\n").replace("32", " "), numbers_str
        )
        logger.info(f"Results retrieved correctly from device {dev_uid}")

        logger.results(
            json.dumps(
                {
                    "raw_bytes": res.data,
                    "int": numbers,
                    "string": "".join(numbers_str),
                }
            )
        )

handle_ping(props, logger, db_session)

Register the devices connected to the reader.

Parameters:

Name Type Description Default
props Dict[str, Any]

Dictionary containing the message from the dispatcher.

required

Returns:

Type Description

Dictionary with the status of the operation and metadata if needed.

Source code in src/stm32reader.py
def handle_ping(self, props: Dict[str, Any], logger, db_session):
    """Register the devices connected to the reader.

    Args:
        props: Dictionary containing the message from the dispatcher.

    Returns:
        Dictionary with the status of the operation and metadata if needed.
    """
    status_correct: Optional[bool] = None
    prev_devices = self.devices

    packet = Packet(self.data_size)
    packet.with_command(Command.PING)
    packet.craft()
    self.send(packet.to_bytes())
    packets = self.receive()

    if self.port["state"] == "OFF":
        raise CommandError(
            "Serial port is off. Please turn on the serial port first"
        )

    if prev_devices and not packets:
        raise CommandError(
            "There were devices connected but now no devices could be identified"
        )

    if not packets:
        raise CommandError("No devices could be identified")

    devices: List[Device] = []
    for packet in packets:
        if not packet.check_crc():
            logger.warning(f"Packet {packet!s} is corrupted")
            status_correct = False
        else:
            devices.append(
                Device(format_uid(packet.uid), packet.pic, packet.options)
            )

    self.devices = devices
    if status_correct is None:
        logger.results(json.dumps([d.__dict__ for d in self.devices]))

handle_power_off(props, logger, db_session)

Power off the serial port.

Parameters:

Name Type Description Default
props Dict[str, Any]

Dictionary containing the message from the dispatcher.

required

Returns:

Type Description

Dictionary with the status of the operation and metadata if needed.

Source code in src/stm32reader.py
def handle_power_off(self, props: Dict[str, Any], logger, db_session):
    """Power off the serial port.

    Args:
        props: Dictionary containing the message from the dispatcher.

    Returns:
        Dictionary with the status of the operation and metadata if needed.
    """
    try:
        p = run(["ykushcmd", "-d", "a"])
        if p.returncode == 0:
            self.port["state"] = "OFF"
            logger.info("Port powered off")
        else:
            raise CommandError("Could not power off port")
    except Exception as excep:
        raise CommandError(f"Problem powering off port {self.port['path']}: {excep}") from excep

handle_power_on(props, logger, db_session)

Power on the serial port.

Parameters:

Name Type Description Default
props Dict[str, Any]

Dictionary containing the message from the dispatcher.

required

Returns:

Type Description

Dictionary with the status of the operation and metadata if needed.

Source code in src/stm32reader.py
def handle_power_on(self, props: Dict[str, Any], logger, db_session):
    """Power on the serial port.

    Args:
        props: Dictionary containing the message from the dispatcher.

    Returns:
        Dictionary with the status of the operation and metadata if needed.
    """
    try:
        p = run(["ykushcmd", "-u", "a"])
        if p.returncode == 0:
            self.port["state"] = "ON"
            logger.info("Port powered on")
        else:
            raise CommandError("Could not power on port")
    except Exception as excep:
        raise CommandError(f"Problem powering on port {self.port['path']}: {excep}") from excep

handle_sensors(props, logger, db_session)

Register the devices connected to the reader.

Parameters:

Name Type Description Default
props Dict[str, Any]

Dictionary containing the message from the dispatcher.

required

Returns:

Type Description

Dictionary with the status of the operation and metadata if needed.

Source code in src/stm32reader.py
def handle_sensors(self, props: Dict[str, Any], logger, db_session):
    """Register the devices connected to the reader.

    Args:
        props: Dictionary containing the message from the dispatcher.

    Returns:
        Dictionary with the status of the operation and metadata if needed.
    """
    if self.port["state"] == "OFF":
        raise CommandError("Serial port is off. Turn on the serial port first")

    if not self.devices:
        raise CommandError("No devices managed")

    current_day = datetime.now()
    current_day = current_day.replace(hour=12, minute=0, second=0)
    for dev in self.devices:
        packet = Packet(self.data_size)
        packet.with_command(Command.SENSORS)
        packet.with_uid(dev.uid)
        packet.craft()
        self.send(packet.to_bytes())
        res = next(iter(self.receive()), None)
        if res is None:
            logger.error(f"Problem reading sensors for device {dev}")
            continue

        if not packet.check_crc() or packet.command == Command.ERR:
            logger.warning(
                f"Packet {packet!s} for device {dev} is corrupted"
            )
            continue

        sensors_data = res.extract_sensors()

        logger.results(
            json.dumps(
                {
                    "device": {"uid": dev.uid, "pic": dev.pic},
                    "temperature": sensors_data["temperature"],
                    "voltage": sensors_data["voltage"],
                }
            )
        )

        db_session.add(
            Sensor(
                uid=format_uid(res.uid),
                pic=dev.pic,
                board_type=self.name,
                temperature=sensors_data["temperature"],
                voltage=sensors_data["voltage"],
                created_at=current_day,
            )
        )
        db_session.commit()

handle_status(props, logger, db_session)

Show the status of the reader.

Parameters:

Name Type Description Default
props Dict[str, Any]

Dict[str, Any] from the dispatcher

required
logger

Logger instance to log data.

required
db_session

DBManager instance to query and insert data.

required

Returns:

Type Description

Status of the operation

Source code in src/stm32reader.py
def handle_status(self, props: Dict[str, Any], logger, db_session):
    """Show the status of the reader.

    Args:
        props: Dict[str, Any] from the dispatcher
        logger: Logger instance to log data.
        db_session: DBManager instance to query and insert data.

    Returns:
        Status of the operation
    """
    logger.results(
        json.dumps(
            {
                "state": self.port["state"],
                "devices": [d.__dict__ for d in self.devices],
            }
        )
    )

handle_write_invert(props, logger, db_session)

We assume that a reader handles only one type of device, So all devices should have the same memory regions.

Get first all different regions and later check that a device has at least one sample of all of them.

Source code in src/stm32reader.py
def handle_write_invert(self, props: Dict[str, Any], logger, db_session):
    """
    We assume that a reader handles only one type of device,
    So all devices *should* have the same memory regions.

    Get first all different regions and later check that a device
    has at least one sample of all of them.
    """
    if self.port["state"] == "OFF":
        raise CommandError("Serial port is off. Turn on the serial port first")

    if not self.devices:
        raise CommandError("No devices managed")

    device_list = list(self.devices)
    for dev in device_list[: len(self.devices) // 2]:
        num_addresses = dev.sram_size // self.data_size
        samples = (
            db_session.query(Sample)
            .filter(Sample.uid == dev.uid)
            .order_by(Sample.address.asc(), Sample.created_at.asc())
            .limit(num_addresses)
            .all()
        )

        if not samples:
            logger.warning(
                f"At least one full memory sample has to be read from device {dev}"
            )
            continue

        if len(samples) != num_addresses:
            logger.warning(
                f"The memory sample for device {dev} is not complete"
            )
            continue

        end_offset = (num_addresses) - READ_ONLY_REGIONS
        for offset in range(READ_ONLY_REGIONS, end_offset):
            sample = samples[offset]
            packet = Packet(self.data_size)
            packet.with_command(Command.WRITE)
            packet.with_uid(dev.uid)
            packet.with_options(offset)
            packet.with_data([0xFF ^ int(d) for d in sample.data.split(",")])
            packet.craft()

            self.send(packet.to_bytes())
            res = next(iter(self.receive()), None)
            if res is None:
                logger.error(
                    f"Problem writing inverted values of device {dev.pic}{dev.uid} at offset {offset}"
                )
                continue

            if not res.check_crc() or res.command == Command.ERR:
                logger.warning(f"Packet {packet!s} is corrupted")
                continue
            logger.debug(f"Inverted memory of device {dev} at offset {offset}")

        logger.info(f"Finished inverting memory of device {dev}")

receive(timeout=0.2, tries=200)

Received data from the serial port.

Parameters:

Name Type Description Default
timeout float

Time to wait until start receiving information.

0.2

Returns:

Type Description
List[Packet]

List of packets received.

Source code in src/stm32reader.py
def receive(self, timeout: float = 0.2, tries=200) -> List[Packet]:
    """Received data from the serial port.

    Args:
        timeout: Time to wait until start receiving information.

    Returns:
        List of packets received.
    """
    packet_size = Packet.full_size(self.data_size)

    ser = self.port["serial"]
    ser.flushInput()
    packets = []
    msg = b""

    time.sleep(timeout)
    checks = deque(maxlen=tries // 2)
    for _ in range(tries):
        checks.appendleft(ser.in_waiting)
        while ser.in_waiting:
            while len(msg) < packet_size:
                msg += ser.read()
            packets.append(Packet.from_bytes(self.data_size, msg))
            msg = b""

        if all(num == 0 for num in checks) and packets:
            return packets
        time.sleep(0.05)

    return packets

send(data)

Transmit data through the serial port.

Parameters:

Name Type Description Default
data bytes

Bytes to sent.

required
Source code in src/stm32reader.py
def send(self, data: bytes):
    """Transmit data through the serial port.

    Args:
        data: Bytes to sent.
    """
    ser = self.port["serial"]
    ser.flushInput()
    ser.write(data)
    ser.flushOutput()

Database

Bases: TableBase

Source code in src/database.py
class Sample(TableBase):
    __tablename__ = "CRPs"
    # Internal id of the sample.
    id = Column(Integer, primary_key=True)
    # Type of device connected in the chain.
    board_type = Column(String, nullable=False)
    # Universal ID of the device.
    uid = Column(String, nullable=False)
    # Position In Chain of the device.
    pic = Column(Integer, nullable=False)
    # Region of SRAM. Formated as 0x00000000
    address = Column(String, nullable=False)
    # Comma separated list of values from the memory.
    data = Column(String, nullable=False)
    # Timestamp when the sample was gathered.
    created_at = Column(DateTime, server_default=func.now(), nullable=False)

Bases: TableBase

Source code in src/database.py
class Sensor(TableBase):
    __tablename__ = "Sensors"
    # Internal id of the sensor data.
    id = Column(Integer, primary_key=True)
    # Type of device connected in the chain.
    board_type = Column(String, nullable=False)
    # Universal ID of the device.
    uid = Column(String, nullable=False)
    # Temperature value in degrees celsius.
    temperature = Column(Float, nullable=False)
    # Internal VDD in volts.
    voltage = Column(Float, nullable=False)
    # Timestamp when the sensor data was obtained.
    created_at = Column(DateTime, server_default=func.now(), nullable=False)