mapid/mapid.py

78 lines
1.3 KiB
Python
Raw Permalink Normal View History

2023-10-26 15:32:53 +02:00
"""MAPID utility library.
This module contains an utility class to control MAPID/CP using pyserial.
"""
2023-10-15 18:01:09 +02:00
import os
import time
import dotenv #
import serial
DOTENV_LOADED = False
2023-10-26 15:32:53 +02:00
"""bool: Is .env loaded?
Prevents loading .env multiple times for speed.
"""
2023-10-15 18:01:09 +02:00
def load_dotenv():
2023-10-26 15:32:53 +02:00
"""Load .env file
"""
2023-10-15 18:01:09 +02:00
basedir = os.path.abspath(os.path.dirname(__file__))
dotenv.load_dotenv(os.path.join(basedir, ".env"))
global DOTENV_LOADED
DOTENV_LOADED = True
def get_serial_dev():
2023-10-26 15:32:53 +02:00
"""Get SERIAL_DEV setting from dotenv.
Returns:
str: The device file.
"""
2023-10-15 18:01:09 +02:00
global DOTENV_LOADED
if not DOTENV_LOADED:
load_dotenv()
return os.environ.get("SERIAL_DEV")
def get_serial_speed():
2023-10-26 15:32:53 +02:00
"""Get SERIAL_SPEED setting from dotenv.
Returns:
int: Serial speed in baud.
"""
2023-10-15 18:01:09 +02:00
global DOTENV_LOADED
if not DOTENV_LOADED:
load_dotenv()
return os.environ.get("SERIAL_SPEED")
class MAPIDCP:
arduino = None
def __init__(self):
self.arduino = serial.Serial(port=get_serial_dev(), baudrate=get_serial_speed(), timeout=.1)
def _cmd(self, cmd: str):
self.arduino.write(bytes(cmd + "\r\n", "utf8"))
time.sleep(0.1)
def cls(self):
self._cmd("CLS")
def led(self, state: bool):
if state:
self._cmd("ON")
else:
self._cmd("OFF")
def line(self, line_no: int):
self._cmd("LINE " + str(line_no))
def echo(self, text: str):
self._cmd("ECHO " + text)