MikrofonSensor und TemperaturSenor die zwei Python programme funktionieren. mit den jeweiligen 2 json Datein. Beim TemperaturSensor wird im Terminal keine Wertre ausgegeben aber in der json Datei kann man die Temp und Hum sehen.

This commit is contained in:
Chiara 2025-05-28 14:53:44 +02:00
parent 4c654ec969
commit 1751076592
2614 changed files with 349009 additions and 0 deletions

View file

@ -0,0 +1,33 @@
# Copyright (c) 2010-2024 Emmanuel Blot <emmanuel.blot@free.fr>
# Copyright (c) 2008-2015, Neotion
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Serial modules compliant with pyserial APIs
"""
try:
from serial.serialutil import SerialException
except ImportError as exc:
raise ImportError("Python serial module not installed") from exc
try:
from serial import VERSION, serial_for_url as serial4url
version = tuple(int(x) for x in VERSION.split('.'))
if version < (3, 0):
raise ValueError
except (ValueError, IndexError, ImportError) as exc:
raise ImportError("pyserial 3.0+ is required") from exc
try:
from serial import protocol_handler_packages
protocol_handler_packages.append('pyftdi.serialext')
except ImportError as exc:
raise SerialException('Cannot register pyftdi extensions') from exc
serial_for_url = serial4url
def touch():
"""Do nothing, only for static checkers than do not like module import
with no module references
"""

View file

@ -0,0 +1,178 @@
# Copyright (c) 2010-2024 Emmanuel Blot <emmanuel.blot@free.fr>
# Copyright (c) 2008-2016, Neotion
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
# pylint: disable=broad-except
# pylint: disable=invalid-name
# pylint: disable=missing-function-docstring
# pylint: disable=missing-module-docstring
# pylint: disable=no-member
# pylint: disable=super-with-arguments
from sys import stderr
from time import time
from ..misc import hexdump
__all__ = ['SerialLogger']
class SerialLogger:
"""Serial port wrapper to log input/output data to a log file.
"""
def __init__(self, *args, **kwargs):
logpath = kwargs.pop('logfile', None)
if not logpath:
raise ValueError('Missing logfile')
try:
# pylint: disable=consider-using-with
self._logger = open(logpath, "wt")
except IOError as exc:
print(f'Cannot log data to {logpath}: {exc}', file=stderr)
self._last = time()
self._log_init(*args, **kwargs)
super(SerialLogger, self).__init__(*args, **kwargs)
def open(self,):
self._log_open()
super(SerialLogger, self).open()
def close(self):
self._log_close()
self._logger.close()
super(SerialLogger, self).close()
def read(self, size=1):
data = super(SerialLogger, self).read(size)
self._log_read(data)
return data
def write(self, data):
if data:
self._log_write(data)
super(SerialLogger, self).write(data)
def flush(self):
self._log_flush()
super(SerialLogger, self).flush()
def reset_input_buffer(self):
self._log_reset('I')
super(SerialLogger, self).reset_input_buffer()
def reset_output_buffer(self):
self._log_reset('O')
super(SerialLogger, self).reset_output_buffer()
def send_break(self, duration=0.25):
self._log_signal('BREAK', f'for {duration:.3f}')
super(SerialLogger, self).send_break()
def _update_break_state(self):
self._log_signal('BREAK', self._break_state)
super(SerialLogger, self)._update_break_state()
def _update_rts_state(self):
self._log_signal('RTS', self._rts_state)
super(SerialLogger, self)._update_rts_state()
def _update_dtr_state(self):
self._log_signal('DTR', self._dtr_state)
super(SerialLogger, self)._update_dtr_state()
@property
def cts(self):
level = super(SerialLogger, self).cts
self._log_signal('CTS', level)
return level
@property
def dsr(self):
level = super(SerialLogger, self).dsr
self._log_signal('DSR', level)
return level
@property
def ri(self):
level = super(SerialLogger, self).ri
self._log_signal('RI', level)
return level
@property
def cd(self):
level = super(SerialLogger, self).cd
self._log_signal('CD', level)
return level
def in_waiting(self):
count = super(SerialLogger, self).in_waiting()
self._log_waiting(count)
return count
def _print(self, header, string=None):
if self._logger:
now = time()
delta = (now-self._last)*1000
self._last = now
print(f'{header} ({delta:3.3f} ms):\n{string or ""}',
file=self._logger)
self._logger.flush()
def _log_init(self, *args, **kwargs):
try:
sargs = ', '.join(args)
skwargs = ', '.join({f'{it[0]}={it[1]}' for it in kwargs.items()})
self._print('NEW', f' args: {sargs} {skwargs}')
except Exception as exc:
print(f'Cannot log init ({exc})', file=stderr)
def _log_open(self):
try:
self._print('OPEN')
except Exception as exc:
print(f'Cannot log open ({exc})', file=stderr)
def _log_close(self):
try:
self._print('CLOSE')
except Exception as exc:
print(f'Cannot log close ({exc})', file=stderr)
def _log_read(self, data):
try:
self._print('READ', hexdump(data))
except Exception as exc:
print(f'Cannot log input data ({exc})', file=stderr)
def _log_write(self, data):
try:
self._print('WRITE', hexdump(data))
except Exception as exc:
print(f'Cannot log output data ({exc})', data, file=stderr)
def _log_flush(self):
try:
self._print('FLUSH')
except Exception as exc:
print(f'Cannot log flush action ({exc})', file=stderr)
def _log_reset(self, type_):
try:
self._print('RESET BUFFER', type_)
except Exception as exc:
print(f'Cannot log reset buffer ({exc})', file=stderr)
def _log_waiting(self, count):
try:
self._print('INWAITING', f'{count}')
except Exception as exc:
print(f'Cannot log inwaiting ({exc})', file=stderr)
def _log_signal(self, name, value):
try:
self._print(name.upper(), str(value))
except Exception as exc:
print(f'Cannot log {name} ({exc})', file=stderr)

View file

@ -0,0 +1,196 @@
# Copyright (c) 2008-2024, Emmanuel Blot <emmanuel.blot@free.fr>
# Copyright (c) 2008-2016, Neotion
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
# this file has not been updated for a while, so coding style needs some love
# pylint: disable=attribute-defined-outside-init
# pylint: disable=invalid-name
# pylint: disable=missing-class-docstring
# pylint: disable=missing-module-docstring
from io import RawIOBase
from time import sleep, time as now
from serial import SerialBase, SerialException, VERSION as pyserialver
from pyftdi.ftdi import Ftdi
from pyftdi.usbtools import UsbToolsError
class FtdiSerial(SerialBase):
"""Base class for Serial port implementation compatible with pyserial API
using a USB device.
"""
BAUDRATES = sorted([9600 * (x+1) for x in range(6)] +
list(range(115200, 1000000, 115200)) +
list(range(1000000, 13000000, 100000)))
PYSERIAL_VERSION = tuple(int(x) for x in pyserialver.split('.'))
def open(self):
"""Open the initialized serial port"""
if self.port is None:
raise SerialException("Port must be configured before use.")
try:
device = Ftdi.create_from_url(self.port)
except (UsbToolsError, IOError) as exc:
raise SerialException(f'Unable to open USB port {self.portstr}: '
f'{exc}') from exc
self.udev = device
self._set_open_state(True)
self._reconfigure_port()
def close(self):
"""Close the open port"""
self._set_open_state(False)
if self.udev:
self.udev.close()
self.udev = None
def read(self, size=1):
"""Read size bytes from the serial port. If a timeout is set it may
return less characters as requested. With no timeout it will block
until the requested number of bytes is read."""
data = bytearray()
start = now()
while True:
buf = self.udev.read_data(size)
data.extend(buf)
size -= len(buf)
if size <= 0:
break
if self._timeout is not None:
if buf:
break
ms = now()-start
if ms > self._timeout:
break
sleep(0.01)
return bytes(data)
def write(self, data):
"""Output the given string over the serial port."""
return self.udev.write_data(data)
def flush(self):
"""Flush of file like objects. In this case, wait until all data
is written."""
def reset_input_buffer(self):
"""Clear input buffer, discarding all that is in the buffer."""
self.udev.purge_rx_buffer()
def reset_output_buffer(self):
"""Clear output buffer, aborting the current output and
discarding all that is in the buffer."""
self.udev.purge_tx_buffer()
def send_break(self, duration=0.25):
"""Send break condition."""
self.udev.set_break(True)
sleep(duration)
self.udev.set_break(False)
def _update_break_state(self):
"""Send break condition. Not supported"""
self.udev.set_break(self._break_state)
def _update_rts_state(self):
"""Set terminal status line: Request To Send"""
self.udev.set_rts(self._rts_state)
def _update_dtr_state(self):
"""Set terminal status line: Data Terminal Ready"""
self.udev.set_dtr(self._dtr_state)
@property
def ftdi(self) -> Ftdi:
"""Return the Ftdi instance.
:return: the Ftdi instance
"""
return self.udev
@property
def usb_path(self):
"""Return the physical location as a triplet.
* bus is the USB bus
* address is the address on the USB bus
* interface is the interface number on the FTDI debice
:return: (bus, address, interface)
:rtype: tuple(int)
"""
return self.udev.usb_path
@property
def cts(self):
"""Read terminal status line: Clear To Send"""
return self.udev.get_cts()
@property
def dsr(self):
"""Read terminal status line: Data Set Ready"""
return self.udev.get_dsr()
@property
def ri(self):
"""Read terminal status line: Ring Indicator"""
return self.udev.get_ri()
@property
def cd(self):
"""Read terminal status line: Carrier Detect"""
return self.udev.get_cd()
@property
def in_waiting(self):
"""Return the number of characters currently in the input buffer."""
# not implemented
return 0
@property
def out_waiting(self):
"""Return the number of bytes currently in the output buffer."""
return 0
@property
def fifoSizes(self):
"""Return the (TX, RX) tupple of hardware FIFO sizes"""
return self.udev.fifo_sizes
def _reconfigure_port(self):
try:
self._baudrate = self.udev.set_baudrate(self._baudrate, True)
self.udev.set_line_property(self._bytesize,
self._stopbits,
self._parity)
if self._rtscts:
self.udev.set_flowctrl('hw')
elif self._xonxoff:
self.udev.set_flowctrl('sw')
else:
self.udev.set_flowctrl('')
try:
self.udev.set_dynamic_latency(12, 200, 50)
except AttributeError:
# backend does not support this feature
pass
except IOError as exc:
err = self.udev.get_error_string()
raise SerialException(f'{exc} ({err})') from exc
def _set_open_state(self, open_):
self.is_open = bool(open_)
# assemble Serial class with the platform specific implementation and the base
# for file-like behavior.
class Serial(FtdiSerial, RawIOBase):
BACKEND = 'pyftdi'
def __init__(self, *args, **kwargs):
RawIOBase.__init__(self)
FtdiSerial.__init__(self, *args, **kwargs)

View file

@ -0,0 +1,213 @@
# Copyright (c) 2008-2024, Emmanuel Blot <emmanuel.blot@free.fr>
# Copyright (c) 2016, Emmanuel Bouaziz <ebouaziz@free.fr>
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
# this file has not been updated for a while, so coding style needs some love
# pylint: disable=broad-except
# pylint: disable=attribute-defined-outside-init
# pylint: disable=redefined-outer-name
# pylint: disable=invalid-name
# pylint: disable=missing-function-docstring
# pylint: disable=missing-class-docstring
# pylint: disable=missing-module-docstring
import errno
import os
import select
import socket
from io import RawIOBase
from serial import (SerialBase, SerialException, PortNotOpenError,
VERSION as pyserialver)
from ..misc import hexdump
__all__ = ['Serial']
class SerialExceptionWithErrno(SerialException):
"""Serial exception with errno extension"""
def __init__(self, message, errno=None):
SerialException.__init__(self, message)
self.errno = errno
class SocketSerial(SerialBase):
"""Fake serial port redirected to a Unix socket.
This is basically a copy of the serialposix serial port implementation
with redefined IO for a Unix socket"""
BACKEND = 'socket'
VIRTUAL_DEVICE = True
PYSERIAL_VERSION = tuple(int(x) for x in pyserialver.split('.'))
def _reconfigure_port(self):
pass
def open(self):
"""Open the initialized serial port"""
if self._port is None:
raise SerialException("Port must be configured before use.")
if self.isOpen():
raise SerialException("Port is already open.")
self._dump = False
self.sock = None
try:
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
filename = self.portstr[self.portstr.index('://')+3:]
if filename.startswith('~/'):
home = os.getenv('HOME')
if home:
filename = os.path.join(home, filename[2:])
self._filename = filename
self.sock.connect(self._filename)
except Exception as exc:
self.close()
msg = f'Could not open port: {exc}'
if isinstance(exc, socket.error):
# pylint: disable=no-member
raise SerialExceptionWithErrno(msg, exc.errno) from exc
raise SerialException(msg) from exc
self._set_open_state(True)
self._lastdtr = None
def close(self):
if self.sock:
try:
self.sock.shutdown(socket.SHUT_RDWR)
except Exception:
pass
try:
self.sock.close()
except Exception:
pass
self.sock = None
self._set_open_state(False)
def in_waiting(self):
"""Return the number of characters currently in the input buffer."""
return 0
def read(self, size=1):
"""Read size bytes from the serial port. If a timeout is set it may
return less characters as requested. With no timeout it will block
until the requested number of bytes is read."""
if self.sock is None:
raise PortNotOpenError
read = bytearray()
if size > 0:
while len(read) < size:
ready, _, _ = select.select([self.sock], [], [], self._timeout)
if not ready:
break # timeout
buf = self.sock.recv(size-len(read))
if not buf:
# Some character is ready, but none can be read
# it is a marker for a disconnected peer
raise PortNotOpenError
read += buf
if self._timeout >= 0 and not buf:
break # early abort on timeout
return read
def write(self, data):
"""Output the given string over the serial port."""
if self.sock is None:
raise PortNotOpenError
t = len(data)
d = data
while t > 0:
try:
if self.writeTimeout is not None and self.writeTimeout > 0:
_, ready, _ = select.select([], [self.sock], [],
self.writeTimeout)
if not ready:
raise TimeoutError()
n = self.sock.send(d)
if self._dump:
print(hexdump(d[:n]))
if self.writeTimeout is not None and self.writeTimeout > 0:
_, ready, _ = select.select([], [self.sock], [],
self.writeTimeout)
if not ready:
raise TimeoutError()
d = d[n:]
t = t - n
except OSError as e:
if e.errno != errno.EAGAIN:
raise
def flush(self):
"""Flush of file like objects. In this case, wait until all data
is written."""
def reset_input_buffer(self):
"""Clear input buffer, discarding all that is in the buffer."""
def reset_output_buffer(self):
"""Clear output buffer, aborting the current output and
discarding all that is in the buffer."""
def send_break(self, duration=0.25):
"""Send break condition. Not supported"""
def _update_break_state(self):
"""Send break condition. Not supported"""
def _update_rts_state(self):
"""Set terminal status line: Request To Send"""
def _update_dtr_state(self):
"""Set terminal status line: Data Terminal Ready"""
def setDTR(self, value=1):
"""Set terminal status line: Data Terminal Ready"""
@property
def cts(self):
"""Read terminal status line: Clear To Send"""
return True
@property
def dsr(self):
"""Read terminal status line: Data Set Ready"""
return True
@property
def ri(self):
"""Read terminal status line: Ring Indicator"""
return False
@property
def cd(self):
"""Read terminal status line: Carrier Detect"""
return False
# - - platform specific - - - -
def nonblocking(self):
"""internal - not portable!"""
if self.sock is None:
raise PortNotOpenError
self.sock.setblocking(0)
def dump(self, enable):
self._dump = enable
# - - Helpers - -
def _set_open_state(self, open_):
if self.PYSERIAL_VERSION < (3, 0):
self._isOpen = bool(open_)
else:
self.is_open = bool(open_)
# assemble Serial class with the platform specifc implementation and the base
# for file-like behavior.
class Serial(SocketSerial, RawIOBase):
pass