Add serial and Arduino file

This commit is contained in:
2022-06-24 15:55:13 -07:00
parent 27fc1f5e16
commit 0e638e51bf
12 changed files with 133 additions and 73 deletions

6
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,6 @@
{
"cSpell.enabled": false,
"files.exclude": {
"**/.git": false
}
}

View File

@ -1,19 +0,0 @@
# Docker image for barcode-server
FROM python:3.9
WORKDIR /app
COPY . .
RUN apt-get update \
&& apt-get -y install sudo
RUN pip install --upgrade pip;\
pip install pipenv;\
pipenv install --system --deploy;\
pip install .
ENV PUID=1000 PGID=1000
ENTRYPOINT [ "docker/entrypoint.sh", "barcode-server" ]
CMD [ "run" ]

View File

@ -1,35 +0,0 @@
PROJECT=barcode_server
current-version:
set -ex
@echo "Current version is `cat ${PROJECT}/__init__.py | grep '__version__' | cut -d ' ' -f3 | sed s/\\\"//g`"
build:
git stash
python setup.py sdist
- git stash pop
test:
pipenv run pytest
git-release:
set -ex
git add ${PROJECT}/__init__.py
git commit -m "Bumped version to `cat ${PROJECT}/__init__.py | grep '__version__' | cut -d ' ' -f3 | sed s/\\\"//g`"
git tag v`cat ${PROJECT}/__init__.py | grep '__version__' | cut -d ' ' -f3 | sed s/\"//g`
git push
git push --tags
_release-patch:
@echo "__version__ = \"`cat ${PROJECT}/__init__.py | awk -F '("|")' '{ print($$2)}' | awk -F. '{$$NF = $$NF + 1;} 1' | sed 's/ /./g'`\"" > ${PROJECT}/__init__.py
release-patch: test _release-patch git-release current-version
_release-minor:
@echo "__version__ = \"`cat ${PROJECT}/__init__.py | awk -F '("|")' '{ print($$2)}' | awk -F. '{$$(NF-1) = $$(NF-1) + 1;} 1' | sed 's/ /./g' | awk -F. '{$$(NF) = 0;} 1' | sed 's/ /./g' `\"" > ${PROJECT}/__init__.py
release-minor: test _release-minor git-release current-version
_release-major:
@echo "__version__ = \"`cat ${PROJECT}/__init__.py | awk -F '("|")' '{ print($$2)}' | awk -F. '{$$(NF-2) = $$(NF-2) + 1;} 1' | sed 's/ /./g' | awk -F. '{$$(NF-1) = 0;} 1' | sed 's/ /./g' | awk -F. '{$$(NF) = 0;} 1' | sed 's/ /./g' `\"" > ${PROJECT}/__init__.py
release-major: test _release-major git-release current-version
release: release-patch

View File

@ -0,0 +1,64 @@
/**
* Displays text sent over the serial port (e.g. from the Serial Monitor) on
* an attached LCD.
* https://wiki.52pi.com/index.php?title=Z-0234
*/
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
String topLine;
String bottomLine;
String incomingString;
// Set the LCD address to 0x27 for a 16 chars and 2 line display
LiquidCrystal_I2C lcd(0x27, 16, 2);
void setup()
{
lcd.begin();
lcd.backlight();
// Initialize the serial port at a speed of 9600 baud
Serial.begin(9600);
}
void loop()
{
// If characters arrived over the serial port...
if (Serial.available())
{
// Wait a bit for the entire message to arrive
delay(100);
// Clear the screen
lcd.clear();
lcd.setCursor(0, 0);
// Write all characters received with the serial port to the LCD.
while (Serial.available() > 0)
{
incomingString = Serial.readString();
Serial.println(incomingString);
if (incomingString[0] != '1')
{
topLine = incomingString;
}
else
{
if (incomingString != "123456" && (incomingString.length() < 2 || (incomingString[1] != 't' && incomingString[1] != 'T')))
{
bottomLine = "";
}
else
{
bottomLine = incomingString;
bottomLine[0] = ' ';
bottomLine[1] = ' ';
}
}
lcd.print(topLine);
lcd.setCursor(0, 1);
lcd.print(bottomLine);
}
}
}

View File

@ -22,33 +22,38 @@ barcode_server:
retry_interval: 2s retry_interval: 2s
# (optional) HTTP push configuration # (optional) HTTP push configuration
http: serial:
# URL to send events to using a request # URL to send events to using a request
url: "http://dummy.restapiexample.com/api/v1/create" path: "/dev/ttyUSB0"
# (optional) HTTP push configuration
# http:
# URL to send events to using a request
# url: "http://dummy.restapiexample.com/api/v1/create"
# The request method to use # The request method to use
method: POST # method: POST
# Headers to set on each request # Headers to set on each request
headers: # headers:
- "X-Auth-Token: MY_HEADERS" # - "X-Auth-Token: MY_HEADERS"
# (optional) MQTT push configuration # (optional) MQTT push configuration
mqtt: # mqtt:
# MQTT server host address # MQTT server host address
host: "mqtt.mydomain.com" # host: "mqtt.mydomain.com"
# (optional) MQTT server port # (optional) MQTT server port
port: 1883 # port: 1883
# (optional) Client ID of this barcode-server instance to provide to the MQTT server # (optional) Client ID of this barcode-server instance to provide to the MQTT server
client_id: "barcode-server" # client_id: "barcode-server"
# MQTT topic to push events to # MQTT topic to push events to
topic: "barcode-server/barcode" # topic: "barcode-server/barcode"
# Username to use when connecting to the MQTT server # Username to use when connecting to the MQTT server
user: "myuser" # user: "myuser"
# Password to use when connecting to the MQTT server # Password to use when connecting to the MQTT server
password: "mypassword" # password: "mypassword"
# (optional) QoS value of event messages # (optional) QoS value of event messages
qos: 2 # qos: 2
# (optional) Whether to instruct the MQTT server to remember event messages between restarts (of the MQTT server) # (optional) Whether to instruct the MQTT server to remember event messages between restarts (of the MQTT server)
retain: True # retain: True
# A list of regex patterns to match USB device names against # A list of regex patterns to match USB device names against
devices: devices:

View File

@ -1 +1 @@
__version__ = "2.3.0" __version__ = "2.3.1"

View File

@ -213,6 +213,15 @@ class AppConfig(ConfigBase):
required=True required=True
) )
SERIAL_PATH = StringConfigEntry(
key_path=[
CONFIG_NODE_ROOT,
CONFIG_NODE_SERIAL,
"path"
],
required=False
)
DEVICE_PATTERNS = ListConfigEntry( DEVICE_PATTERNS = ListConfigEntry(
item_type=RegexConfigEntry, item_type=RegexConfigEntry,
item_args={ item_args={

View File

@ -22,6 +22,7 @@ CONFIG_NODE_ROOT = "barcode_server"
CONFIG_NODE_SERVER = "server" CONFIG_NODE_SERVER = "server"
CONFIG_NODE_HTTP = "http" CONFIG_NODE_HTTP = "http"
CONFIG_NODE_MQTT = "mqtt" CONFIG_NODE_MQTT = "mqtt"
CONFIG_NODE_SERIAL = "serial"
CONFIG_NODE_STATS = "stats" CONFIG_NODE_STATS = "stats"
CONFIG_NODE_PORT = "port" CONFIG_NODE_PORT = "port"

View File

@ -0,0 +1,23 @@
import serial
import logging
# import time as sleep
from prometheus_async.aio import time
from barcode_server.barcode import BarcodeEvent
from barcode_server.notifier import BarcodeNotifier
from barcode_server.stats import SERIAL_NOTIFIER_TIME
LOGGER = logging.getLogger(__name__)
class SerialNotifier(BarcodeNotifier):
def __init__(self, path: str, usb: serial):
super().__init__()
self.path = path
self.usb = usb
@time(SERIAL_NOTIFIER_TIME)
async def _send_event(self, event: BarcodeEvent):
self.usb.write(event.barcode.encode())
LOGGER.debug(f"Notified {self.path}: {event.barcode}")

View File

@ -25,4 +25,5 @@ REST_TIME_DEVICES = REST_TIME.labels(endpoint=ENDPOINT_DEVICES)
NOTIFIER_TIME = Summary('notifier_processing_seconds', 'Time spent in a notifier', ['type']) NOTIFIER_TIME = Summary('notifier_processing_seconds', 'Time spent in a notifier', ['type'])
WEBSOCKET_NOTIFIER_TIME = NOTIFIER_TIME.labels(type='websocket') WEBSOCKET_NOTIFIER_TIME = NOTIFIER_TIME.labels(type='websocket')
HTTP_NOTIFIER_TIME = NOTIFIER_TIME.labels(type='http') HTTP_NOTIFIER_TIME = NOTIFIER_TIME.labels(type='http')
SERIAL_NOTIFIER_TIME = NOTIFIER_TIME.labels(type='serial')
MQTT_NOTIFIER_TIME = NOTIFIER_TIME.labels(type='mqtt') MQTT_NOTIFIER_TIME = NOTIFIER_TIME.labels(type='mqtt')

View File

@ -1,3 +1,4 @@
import serial
import asyncio import asyncio
import logging import logging
from typing import Dict from typing import Dict
@ -13,6 +14,7 @@ from barcode_server.const import *
from barcode_server.notifier import BarcodeNotifier from barcode_server.notifier import BarcodeNotifier
from barcode_server.notifier.http import HttpNotifier from barcode_server.notifier.http import HttpNotifier
from barcode_server.notifier.mqtt import MQTTNotifier from barcode_server.notifier.mqtt import MQTTNotifier
from barcode_server.notifier.serial import SerialNotifier
from barcode_server.notifier.ws import WebsocketNotifier from barcode_server.notifier.ws import WebsocketNotifier
from barcode_server.stats import REST_TIME_DEVICES, WEBSOCKET_CLIENT_COUNT from barcode_server.stats import REST_TIME_DEVICES, WEBSOCKET_CLIENT_COUNT
from barcode_server.util import input_device_to_dict from barcode_server.util import input_device_to_dict
@ -33,6 +35,8 @@ class Webserver:
self.barcode_reader = barcode_reader self.barcode_reader = barcode_reader
self.barcode_reader.add_listener(self.on_barcode) self.barcode_reader.add_listener(self.on_barcode)
self.usb = {}
self.notifiers: Dict[str, BarcodeNotifier] = {} self.notifiers: Dict[str, BarcodeNotifier] = {}
if config.HTTP_URL.value is not None: if config.HTTP_URL.value is not None:
http_notifier = HttpNotifier( http_notifier = HttpNotifier(
@ -54,6 +58,11 @@ class Webserver:
) )
self.notifiers["mqtt"] = mqtt_notifier self.notifiers["mqtt"] = mqtt_notifier
if config.SERIAL_PATH.value is not None:
self.usb = serial.Serial(config.SERIAL_PATH.value, 9600, timeout=2)
serial_notifier = SerialNotifier(config.SERIAL_PATH.value, self.usb)
self.notifiers["serial"] = serial_notifier
async def start(self): async def start(self):
# start detecting and reading barcode scanners # start detecting and reading barcode scanners
await self.barcode_reader.start() await self.barcode_reader.start()

View File

@ -1,4 +0,0 @@
#!/bin/sh
set -eu
sudo -E -u "#${PUID}" -g "#${PGID}" "$@"