From 612eb3db7cdb792d82454c0c8b3c30f655a2bae0 Mon Sep 17 00:00:00 2001 From: gax Date: Wed, 1 Mar 2023 18:30:51 +0000 Subject: [PATCH 01/43] cliente mqtt con docker --- clienteMqtt/Dockerfile | 11 +++++++++++ clienteMqtt/clienteMqtt.py | 30 ++++++++++++++++++++++++++++++ clienteMqtt/requirements.txt | 3 +++ 3 files changed, 44 insertions(+) create mode 100755 clienteMqtt/Dockerfile create mode 100755 clienteMqtt/clienteMqtt.py create mode 100755 clienteMqtt/requirements.txt diff --git a/clienteMqtt/Dockerfile b/clienteMqtt/Dockerfile new file mode 100755 index 00000000..52d78340 --- /dev/null +++ b/clienteMqtt/Dockerfile @@ -0,0 +1,11 @@ +FROM python:3.11-slim + +WORKDIR /app + +COPY ./requirements.txt /app/requirements.txt + +RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt + +COPY . /app + +CMD ["python", "/app/clienteMqtt.py"] \ No newline at end of file diff --git a/clienteMqtt/clienteMqtt.py b/clienteMqtt/clienteMqtt.py new file mode 100755 index 00000000..96250d84 --- /dev/null +++ b/clienteMqtt/clienteMqtt.py @@ -0,0 +1,30 @@ +import asyncio, ssl, certifi, logging +from asyncio_mqtt import Client, ProtocolVersion +from environs import Env + +env = Env() +env.read_env() #lee el archivo con las variables. por defecto .env + +logging.basicConfig(format='%(asctime)s - cliente mqtt - %(levelname)s:%(message)s', level=logging.INFO, datefmt='%d/%m/%Y %H:%M:%S') + +async def main(): + tls_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + tls_context.minimum_version = ssl.TLSVersion.TLSv1_2 + tls_context.maximum_version = ssl.TLSVersion.TLSv1_3 + tls_context.verify_mode = ssl.CERT_REQUIRED + tls_context.check_hostname = True + tls_context.load_default_certs() + + async with Client( + env("SERVIDOR"), + protocol=ProtocolVersion.V31, + port=8883, + tls_context=tls_context, + ) as client: + async with client.messages() as messages: + await client.subscribe("#") + async for message in messages: + logging.info(str(message.topic) + ": " + message.payload.decode("utf-8")) + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/clienteMqtt/requirements.txt b/clienteMqtt/requirements.txt new file mode 100755 index 00000000..84ced5d6 --- /dev/null +++ b/clienteMqtt/requirements.txt @@ -0,0 +1,3 @@ +asyncio-mqtt==0.16.1 +certifi==2022.12.7 +environs==9.5.0 \ No newline at end of file From e1feec168b0d5a34dcdce069d992ac69aa4deae9 Mon Sep 17 00:00:00 2001 From: gax Date: Wed, 1 Mar 2023 17:29:12 -0300 Subject: [PATCH 02/43] uso de ENV --- clienteMqtt/Dockerfile | 2 ++ clienteMqtt/clienteMqtt.py | 9 +++------ 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/clienteMqtt/Dockerfile b/clienteMqtt/Dockerfile index 52d78340..e3586266 100755 --- a/clienteMqtt/Dockerfile +++ b/clienteMqtt/Dockerfile @@ -8,4 +8,6 @@ RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt COPY . /app +ENV TZ="America/Argentina/Buenos_Aires" + CMD ["python", "/app/clienteMqtt.py"] \ No newline at end of file diff --git a/clienteMqtt/clienteMqtt.py b/clienteMqtt/clienteMqtt.py index 96250d84..2e17b8e9 100755 --- a/clienteMqtt/clienteMqtt.py +++ b/clienteMqtt/clienteMqtt.py @@ -1,11 +1,8 @@ -import asyncio, ssl, certifi, logging +import asyncio, ssl, certifi, logging, os from asyncio_mqtt import Client, ProtocolVersion from environs import Env -env = Env() -env.read_env() #lee el archivo con las variables. por defecto .env - -logging.basicConfig(format='%(asctime)s - cliente mqtt - %(levelname)s:%(message)s', level=logging.INFO, datefmt='%d/%m/%Y %H:%M:%S') +logging.basicConfig(format='%(asctime)s - cliente mqtt - %(levelname)s:%(message)s', level=logging.INFO, datefmt='%d/%m/%Y %H:%M:%S %z') async def main(): tls_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) @@ -16,7 +13,7 @@ async def main(): tls_context.load_default_certs() async with Client( - env("SERVIDOR"), + os.environ['SERVIDOR'], protocol=ProtocolVersion.V31, port=8883, tls_context=tls_context, From d2fad211888ad88115c17850d7795165322f9a42 Mon Sep 17 00:00:00 2001 From: gax Date: Thu, 2 Mar 2023 07:53:47 -0300 Subject: [PATCH 03/43] orden ENV --- clienteMqtt/Dockerfile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/clienteMqtt/Dockerfile b/clienteMqtt/Dockerfile index e3586266..8353d235 100755 --- a/clienteMqtt/Dockerfile +++ b/clienteMqtt/Dockerfile @@ -2,12 +2,12 @@ FROM python:3.11-slim WORKDIR /app +ENV TZ="America/Argentina/Buenos_Aires" + COPY ./requirements.txt /app/requirements.txt RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt COPY . /app -ENV TZ="America/Argentina/Buenos_Aires" - CMD ["python", "/app/clienteMqtt.py"] \ No newline at end of file From b1d71c60016beddabfe2a53ff472027e8481cb10 Mon Sep 17 00:00:00 2001 From: gax Date: Thu, 2 Mar 2023 08:44:01 -0300 Subject: [PATCH 04/43] env var TOPICO --- clienteMqtt/clienteMqtt.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clienteMqtt/clienteMqtt.py b/clienteMqtt/clienteMqtt.py index 2e17b8e9..59303557 100755 --- a/clienteMqtt/clienteMqtt.py +++ b/clienteMqtt/clienteMqtt.py @@ -19,7 +19,7 @@ async def main(): tls_context=tls_context, ) as client: async with client.messages() as messages: - await client.subscribe("#") + await client.subscribe(os.environ['TOPICO']) async for message in messages: logging.info(str(message.topic) + ": " + message.payload.decode("utf-8")) From 46b24bb0198c29d4803e83c95f431ed4831c9e8c Mon Sep 17 00:00:00 2001 From: gax Date: Thu, 2 Mar 2023 09:19:39 -0300 Subject: [PATCH 05/43] docker-compose --- docker-compose.yml | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100755 docker-compose.yml diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100755 index 00000000..c9d92ad5 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,10 @@ +version: "3" +services: + clientemqtt: + image: clientemqtt + container_name: clientemqtt + environment: + - TZ=America/Argentina/Buenos_Aires + - SERVIDOR=${SERVIDOR} #Se reemplazará por la env var SERVIDOR defineda en .env + - TOPICO=${TOPICO} + restart: unless-stopped From 8554f674eced9f8cddccf7c9a8932d5f3dcc74a6 Mon Sep 17 00:00:00 2001 From: gax Date: Thu, 2 Mar 2023 17:08:39 -0300 Subject: [PATCH 06/43] base de datos --- .gitignore | 138 +++++++++++++++++++++++++++++++++++ clienteMqtt/clienteMqtt.py | 29 +++++++- clienteMqtt/requirements.txt | 3 +- docker-compose.yml | 29 ++++++++ sensores_remotos.sql | 36 +++++++++ 5 files changed, 231 insertions(+), 4 deletions(-) create mode 100755 .gitignore create mode 100755 sensores_remotos.sql diff --git a/.gitignore b/.gitignore new file mode 100755 index 00000000..7605c880 --- /dev/null +++ b/.gitignore @@ -0,0 +1,138 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +bin/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +include/ +lib/ +lib64/ +lib64 +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST +pyvenv.cfg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +.env + +#swag related files: ignore all except NGINX conf +swag/config/* +!swag/config/nginx/site-confs/default.conf diff --git a/clienteMqtt/clienteMqtt.py b/clienteMqtt/clienteMqtt.py index 59303557..702e1a4e 100755 --- a/clienteMqtt/clienteMqtt.py +++ b/clienteMqtt/clienteMqtt.py @@ -1,4 +1,4 @@ -import asyncio, ssl, certifi, logging, os +import asyncio, ssl, certifi, logging, os, aiomysql, json, traceback from asyncio_mqtt import Client, ProtocolVersion from environs import Env @@ -12,16 +12,39 @@ async def main(): tls_context.check_hostname = True tls_context.load_default_certs() + async with Client( - os.environ['SERVIDOR'], + os.getenv("SERVIDOR"), protocol=ProtocolVersion.V31, port=8883, tls_context=tls_context, ) as client: async with client.messages() as messages: - await client.subscribe(os.environ['TOPICO']) + await client.subscribe('#') async for message in messages: logging.info(str(message.topic) + ": " + message.payload.decode("utf-8")) + datos=json.loads(message.payload.decode('utf8')) + sql = "INSERT INTO `mediciones` (`sensor_id`, `temperatura`, `humedad`) VALUES (%s, %s, %s)" + try: + conn = await aiomysql.connect(host=os.getenv("MARIADB_SERVER"), port=3306, + user=os.getenv("MARIADB_USER"), + password=os.getenv("MARIADB_USER_PASS"), + db=os.getenv("MARIADB_DB")) + except Exception as e: + logging.error(traceback.format_exc()) + + cur = await conn.cursor() + + async with conn.cursor() as cur: + try: + await cur.execute(sql, (message.topic, datos['temperatura'], datos['humedad'])) + except Exception as e: + logging.error(traceback.format_exc()) + # Logs the error appropriately. + await conn.commit() + + conn.close() + if __name__ == "__main__": asyncio.run(main()) diff --git a/clienteMqtt/requirements.txt b/clienteMqtt/requirements.txt index 84ced5d6..12dd6551 100755 --- a/clienteMqtt/requirements.txt +++ b/clienteMqtt/requirements.txt @@ -1,3 +1,4 @@ asyncio-mqtt==0.16.1 certifi==2022.12.7 -environs==9.5.0 \ No newline at end of file +environs==9.5.0 +aiomysql==0.1.1 \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml index c9d92ad5..37b9fc93 100755 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,5 +1,28 @@ version: "3" services: + mariadb: + image: mariadb + container_name: mariadb + environment: + - PUID=1000 + - PGID=1000 + - MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD} + - TZ=America/Argentina/Buenos_Aires + volumes: + - /home/iot/docker/mariadb:/config + ports: + - 3306:3306 + restart: unless-stopped + phpmyadmin: + image: phpmyadmin + container_name: phpmyadmin + restart: always + environment: + - PMA_HOST=mariadb + ports: + - 8080:80 + links: + - mariadb clientemqtt: image: clientemqtt container_name: clientemqtt @@ -7,4 +30,10 @@ services: - TZ=America/Argentina/Buenos_Aires - SERVIDOR=${SERVIDOR} #Se reemplazará por la env var SERVIDOR defineda en .env - TOPICO=${TOPICO} + - MARIADB_SERVER=${MARIADB_SERVER} + - MARIADB_USER=${MARIADB_USER} + - MARIADB_USER_PASS=${MARIADB_USER_PASS} + - MARIADB_DB=${MARIADB_DB} restart: unless-stopped + depends_on: + - mariadb diff --git a/sensores_remotos.sql b/sensores_remotos.sql new file mode 100755 index 00000000..52db7bf3 --- /dev/null +++ b/sensores_remotos.sql @@ -0,0 +1,36 @@ +-- +-- Base de datos: `sensores_remotos` +-- +CREATE DATABASE IF NOT EXISTS `sensores_remotos` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci; +USE `sensores_remotos`; + +-- -------------------------------------------------------- + +-- +-- Estructura de tabla para la tabla `mediciones` +-- + +CREATE TABLE `mediciones` ( + `id` int(11) NOT NULL, + `sensor_id` char(12) NOT NULL, + `timestamp` timestamp NOT NULL DEFAULT current_timestamp(), + `temperatura` decimal(3,1) NOT NULL, + `humedad` decimal(3,1) NOT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + +-- +-- Indices de la tabla `mediciones` +-- +ALTER TABLE `mediciones` + ADD PRIMARY KEY (`id`), + ADD KEY `timestamp` (`timestamp`); + +-- +-- AUTO_INCREMENT de la tabla `mediciones` +-- +ALTER TABLE `mediciones` + MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; +COMMIT; + +CREATE USER 'mediciones'@'%' IDENTIFIED BY 'passworddeiot';GRANT USAGE ON *.* TO 'mediciones'@'%' REQUIRE NONE WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0; +GRANT SELECT, INSERT ON `sensores\_remotos`.* TO 'mediciones'@'%'; \ No newline at end of file From 96c68b12d016209de5cad34c60c4e50e4ac218e4 Mon Sep 17 00:00:00 2001 From: gax Date: Fri, 3 Mar 2023 09:45:51 -0300 Subject: [PATCH 07/43] phpmyadmins depends_on --- docker-compose.yml | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index 37b9fc93..e9c4fcc5 100755 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -14,15 +14,15 @@ services: - 3306:3306 restart: unless-stopped phpmyadmin: - image: phpmyadmin - container_name: phpmyadmin - restart: always - environment: - - PMA_HOST=mariadb - ports: - - 8080:80 - links: - - mariadb + image: phpmyadmin + container_name: phpmyadmin + restart: always + environment: + - PMA_HOST=mariadb + ports: + - 8080:80 + depends_on: + - mariadb clientemqtt: image: clientemqtt container_name: clientemqtt From 675ee5018c01e1661fe58739502295e4f127a11d Mon Sep 17 00:00:00 2001 From: gax Date: Fri, 3 Mar 2023 10:13:25 -0300 Subject: [PATCH 08/43] grafana --- .gitignore | 2 ++ docker-compose.yml | 13 +++++++++++++ 2 files changed, 15 insertions(+) diff --git a/.gitignore b/.gitignore index 7605c880..ae0c4aeb 100755 --- a/.gitignore +++ b/.gitignore @@ -136,3 +136,5 @@ dmypy.json #swag related files: ignore all except NGINX conf swag/config/* !swag/config/nginx/site-confs/default.conf + +grafana/ \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml index e9c4fcc5..bd405a8f 100755 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -37,3 +37,16 @@ services: restart: unless-stopped depends_on: - mariadb + grafana: + image: grafana/grafana + container_name: grafana + user: "1000" + volumes: + - /home/iot/docker/grafana:/var/lib/grafana + ports: + - 3000:3000 + depends_on: + - mariadb + environment: + GF_ANALYTICS_REPORTING_ENABLED: "false" + restart: unless-stopped \ No newline at end of file From ea08a45d3fda2a0e093fdd4f0a7f00730da73f58 Mon Sep 17 00:00:00 2001 From: gax Date: Sat, 4 Mar 2023 00:31:22 +0000 Subject: [PATCH 09/43] agregar mosquitto --- docker-compose.yml | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/docker-compose.yml b/docker-compose.yml index bd405a8f..f4717a67 100755 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -37,6 +37,17 @@ services: restart: unless-stopped depends_on: - mariadb + mosquitto: + image: eclipse-mosquitto + container_name: mosquitto + user: "1000:1000" + ports: + - 1883:1883 + - 8883:8883 + restart: unless-stopped + volumes: + - ~/docker/mosquitto/config/mosquitto.conf:/mosquitto/config/mosquitto.conf + - ~/docker/mosquitto/config:/mosquitto/config grafana: image: grafana/grafana container_name: grafana From a746d97b0ea40f5ad08a16e6d1093d7c81cc640f Mon Sep 17 00:00:00 2001 From: gax Date: Mon, 6 Mar 2023 10:22:54 +0000 Subject: [PATCH 10/43] Actualizar 'docker-compose.yml' ruta relativa --- docker-compose.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index f4717a67..d7278d61 100755 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -9,7 +9,7 @@ services: - MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD} - TZ=America/Argentina/Buenos_Aires volumes: - - /home/iot/docker/mariadb:/config + - ~/docker/mariadb:/config ports: - 3306:3306 restart: unless-stopped @@ -53,7 +53,7 @@ services: container_name: grafana user: "1000" volumes: - - /home/iot/docker/grafana:/var/lib/grafana + - ~/docker/grafana:/var/lib/grafana ports: - 3000:3000 depends_on: From 5fe81cf285fcc47a76828c9c0ed666883db88d35 Mon Sep 17 00:00:00 2001 From: gax Date: Mon, 6 Mar 2023 08:55:01 -0300 Subject: [PATCH 11/43] portainer --- .gitignore | 3 ++- docker-compose.yml | 13 ++++++++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index ae0c4aeb..d8a1b09f 100755 --- a/.gitignore +++ b/.gitignore @@ -137,4 +137,5 @@ dmypy.json swag/config/* !swag/config/nginx/site-confs/default.conf -grafana/ \ No newline at end of file +grafana/ +mosquitto/ \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml index d7278d61..29052f0f 100755 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -60,4 +60,15 @@ services: - mariadb environment: GF_ANALYTICS_REPORTING_ENABLED: "false" - restart: unless-stopped \ No newline at end of file + restart: unless-stopped + portainer: + image: portainer/portainer-ce:latest + container_name: portainer + ports: + - 9443:9443 + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - portainer_data:/data + restart: unless-stopped +volumes: + portainer_data: \ No newline at end of file From bcbed1924dff7ef1613fc5c7874de610e534fd12 Mon Sep 17 00:00:00 2001 From: gax Date: Mon, 6 Mar 2023 10:34:11 -0300 Subject: [PATCH 12/43] swag --- .gitignore | 6 ++---- docker-compose.yml | 19 +++++++++++++++++++ 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/.gitignore b/.gitignore index d8a1b09f..adfbc40d 100755 --- a/.gitignore +++ b/.gitignore @@ -134,8 +134,6 @@ dmypy.json .env #swag related files: ignore all except NGINX conf -swag/config/* -!swag/config/nginx/site-confs/default.conf - +swag/ grafana/ -mosquitto/ \ No newline at end of file +mosquitto/ diff --git a/docker-compose.yml b/docker-compose.yml index 29052f0f..ca139ba3 100755 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -70,5 +70,24 @@ services: - /var/run/docker.sock:/var/run/docker.sock - portainer_data:/data restart: unless-stopped + swag: + image: linuxserver/swag + container_name: swag + cap_add: + - NET_ADMIN + environment: + - PUID=1000 + - PGID=1000 + - TZ=America/Argentina/Buenos_Aires + - URL=${DOMINIO} + - VALIDATION=duckdns + - DUCKDNSTOKEN=${DUCKDNSTOKEN} + - SUBDOMAINS= + volumes: + - ~/docker/swag:/config + ports: + - 10000:443 + - 80:80 + restart: unless-stopped volumes: portainer_data: \ No newline at end of file From a717a5aba4341feb414efb9bd1369136237ab29d Mon Sep 17 00:00:00 2001 From: gax Date: Mon, 6 Mar 2023 13:54:09 -0300 Subject: [PATCH 13/43] phpmyadmin + tls --- docker-compose.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/docker-compose.yml b/docker-compose.yml index ca139ba3..e7bc1501 100755 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -19,6 +19,7 @@ services: restart: always environment: - PMA_HOST=mariadb + - PMA_ABSOLUTE_URI=https://${DOMINIO}:10000/phpmyadmin/ ports: - 8080:80 depends_on: From d091ec925817e80ed5743b84ca6cfa3b74c3f87d Mon Sep 17 00:00:00 2001 From: gax Date: Mon, 6 Mar 2023 14:46:23 -0300 Subject: [PATCH 14/43] grafana + tls --- docker-compose.yml | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index e7bc1501..9bf340ed 100755 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -19,7 +19,7 @@ services: restart: always environment: - PMA_HOST=mariadb - - PMA_ABSOLUTE_URI=https://${DOMINIO}:10000/phpmyadmin/ + - PMA_ABSOLUTE_URI=https://${DOMINIO}:${PUERTO}/phpmyadmin/ ports: - 8080:80 depends_on: @@ -60,6 +60,10 @@ services: depends_on: - mariadb environment: + GF_SERVER_PROTOCOL: http + GF_SERVER_ROOT_URL: https://${DOMINIO}:${PUERTO}/grafana/ + GF_SERVER_SERVE_FROM_SUB_PATH: "true" + GF_SERVER_DOMAIN: ${DOMINIO} GF_ANALYTICS_REPORTING_ENABLED: "false" restart: unless-stopped portainer: @@ -87,7 +91,7 @@ services: volumes: - ~/docker/swag:/config ports: - - 10000:443 + - ${PUERTO}:443 - 80:80 restart: unless-stopped volumes: From 03df65bc645049b4e492ab174b7f25f238d4a36e Mon Sep 17 00:00:00 2001 From: gax Date: Mon, 6 Mar 2023 16:58:30 -0300 Subject: [PATCH 15/43] mosquitto + tls + pass --- clienteMqtt/clienteMqtt.py | 2 ++ docker-compose.yml | 5 +++++ 2 files changed, 7 insertions(+) diff --git a/clienteMqtt/clienteMqtt.py b/clienteMqtt/clienteMqtt.py index 702e1a4e..083fd7db 100755 --- a/clienteMqtt/clienteMqtt.py +++ b/clienteMqtt/clienteMqtt.py @@ -15,6 +15,8 @@ async def main(): async with Client( os.getenv("SERVIDOR"), + username=os.getenv("MQTT_USR"), + password=os.getenv("MQTT_PASS"), protocol=ProtocolVersion.V31, port=8883, tls_context=tls_context, diff --git a/docker-compose.yml b/docker-compose.yml index 9bf340ed..3f3ef629 100755 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -35,6 +35,8 @@ services: - MARIADB_USER=${MARIADB_USER} - MARIADB_USER_PASS=${MARIADB_USER_PASS} - MARIADB_DB=${MARIADB_DB} + - MQTT_USR=${MQTT_USR} + - MQTT_PASS=${MQTT_PASS} restart: unless-stopped depends_on: - mariadb @@ -49,6 +51,9 @@ services: volumes: - ~/docker/mosquitto/config/mosquitto.conf:/mosquitto/config/mosquitto.conf - ~/docker/mosquitto/config:/mosquitto/config + - ~/docker/swag/etc/letsencrypt:/var/tmp + - ~/docker/mosquitto/data:/mosquitto/data + - ~/docker/mosquitto/log:/mosquitto/log grafana: image: grafana/grafana container_name: grafana From e43ab360a5c51f7e0b642d24e8138101c2ab0de0 Mon Sep 17 00:00:00 2001 From: gax Date: Tue, 7 Mar 2023 14:38:50 -0300 Subject: [PATCH 16/43] mi primer bot --- telegrambot/Dockerfile | 13 +++++++++++++ telegrambot/requirements.txt | 1 + telegrambot/telegrambot.py | 36 ++++++++++++++++++++++++++++++++++++ 3 files changed, 50 insertions(+) create mode 100755 telegrambot/Dockerfile create mode 100755 telegrambot/requirements.txt create mode 100755 telegrambot/telegrambot.py diff --git a/telegrambot/Dockerfile b/telegrambot/Dockerfile new file mode 100755 index 00000000..53aaa6c7 --- /dev/null +++ b/telegrambot/Dockerfile @@ -0,0 +1,13 @@ +FROM python:3.11-slim + +WORKDIR /app + +ENV TZ="America/Argentina/Buenos_Aires" + +COPY ./requirements.txt /app/requirements.txt + +RUN pip install --no-cache-dir --upgrade -r /app/requirements.txt + +COPY . /app + +CMD ["python", "/app/telegrambot.py"] \ No newline at end of file diff --git a/telegrambot/requirements.txt b/telegrambot/requirements.txt new file mode 100755 index 00000000..939400f4 --- /dev/null +++ b/telegrambot/requirements.txt @@ -0,0 +1 @@ +python-telegram-bot==20.1 \ No newline at end of file diff --git a/telegrambot/telegrambot.py b/telegrambot/telegrambot.py new file mode 100755 index 00000000..9249b12a --- /dev/null +++ b/telegrambot/telegrambot.py @@ -0,0 +1,36 @@ +from telegram import Update +from telegram.ext import Application, CommandHandler, ContextTypes +import logging, os + +token=os.getenv("TOKEN") + +logging.basicConfig(format='%(asctime)s - TelegramBot - %(levelname)s - %(message)s', level=logging.INFO) + +async def start(update: Update, context: ContextTypes.DEFAULT_TYPE): + logging.info("se conectó: " + str(update.message.from_user.id)) + if update.message.from_user.first_name: + nombre=update.message.from_user.first_name + else: + nombre="" + if update.message.from_user.last_name: + apellido=update.message.from_user.last_name + else: + apellido="" + + await context.bot.send_message(update.message.chat.id, text="Bienvenido al Bot "+ nombre + " " + apellido) + # await update.message.reply_text("Bienvenido al Bot "+ nombre + " " + apellido) # también funciona + +async def acercade(update: Update, context): + await context.bot.send_message(update.message.chat.id, text="Este bot fue creado para el curso de IoT (2023)") + + +def main() -> None: + application = Application.builder().token(token).build() + + application.add_handler(CommandHandler('start', start)) + application.add_handler(CommandHandler('acercade', acercade)) + + application.run_polling() + +if __name__ == '__main__': + main() From dd3a2553bd2eef0077f285d10bf3834e93306f90 Mon Sep 17 00:00:00 2001 From: gax Date: Tue, 7 Mar 2023 14:43:43 -0300 Subject: [PATCH 17/43] =?UTF-8?q?m=C3=A1s=20compacto?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- telegrambot/telegrambot.py | 1 - 1 file changed, 1 deletion(-) diff --git a/telegrambot/telegrambot.py b/telegrambot/telegrambot.py index 9249b12a..518a80b5 100755 --- a/telegrambot/telegrambot.py +++ b/telegrambot/telegrambot.py @@ -23,7 +23,6 @@ async def start(update: Update, context: ContextTypes.DEFAULT_TYPE): async def acercade(update: Update, context): await context.bot.send_message(update.message.chat.id, text="Este bot fue creado para el curso de IoT (2023)") - def main() -> None: application = Application.builder().token(token).build() From d74699fdd140ab8bc002a64006e9ce3c30d4efa2 Mon Sep 17 00:00:00 2001 From: gax Date: Tue, 7 Mar 2023 14:55:49 -0300 Subject: [PATCH 18/43] sin -> --- telegrambot/telegrambot.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/telegrambot/telegrambot.py b/telegrambot/telegrambot.py index 518a80b5..e4f0e713 100755 --- a/telegrambot/telegrambot.py +++ b/telegrambot/telegrambot.py @@ -16,19 +16,16 @@ async def start(update: Update, context: ContextTypes.DEFAULT_TYPE): apellido=update.message.from_user.last_name else: apellido="" - await context.bot.send_message(update.message.chat.id, text="Bienvenido al Bot "+ nombre + " " + apellido) # await update.message.reply_text("Bienvenido al Bot "+ nombre + " " + apellido) # también funciona async def acercade(update: Update, context): await context.bot.send_message(update.message.chat.id, text="Este bot fue creado para el curso de IoT (2023)") -def main() -> None: +def main(): application = Application.builder().token(token).build() - application.add_handler(CommandHandler('start', start)) application.add_handler(CommandHandler('acercade', acercade)) - application.run_polling() if __name__ == '__main__': From 99e1001f7ea20d70a6f09bc645dcd954cd05216d Mon Sep 17 00:00:00 2001 From: gax Date: Tue, 7 Mar 2023 19:25:06 +0000 Subject: [PATCH 19/43] Actualizar 'clienteMqtt/requirements.txt' environs no es nevesario --- clienteMqtt/requirements.txt | 1 - 1 file changed, 1 deletion(-) diff --git a/clienteMqtt/requirements.txt b/clienteMqtt/requirements.txt index 12dd6551..1b040df2 100755 --- a/clienteMqtt/requirements.txt +++ b/clienteMqtt/requirements.txt @@ -1,4 +1,3 @@ asyncio-mqtt==0.16.1 certifi==2022.12.7 -environs==9.5.0 aiomysql==0.1.1 \ No newline at end of file From 59e4d110dd2e1aeea05655664f093cc6fa460b89 Mon Sep 17 00:00:00 2001 From: gax Date: Tue, 7 Mar 2023 19:29:28 +0000 Subject: [PATCH 20/43] Actualizar 'clienteMqtt/clienteMqtt.py' environs no es necesario --- clienteMqtt/clienteMqtt.py | 1 - 1 file changed, 1 deletion(-) diff --git a/clienteMqtt/clienteMqtt.py b/clienteMqtt/clienteMqtt.py index 083fd7db..34628ed8 100755 --- a/clienteMqtt/clienteMqtt.py +++ b/clienteMqtt/clienteMqtt.py @@ -1,6 +1,5 @@ import asyncio, ssl, certifi, logging, os, aiomysql, json, traceback from asyncio_mqtt import Client, ProtocolVersion -from environs import Env logging.basicConfig(format='%(asctime)s - cliente mqtt - %(levelname)s:%(message)s', level=logging.INFO, datefmt='%d/%m/%Y %H:%M:%S %z') From d6da76d9fd7084ada59cf352e401fd5259b9ca33 Mon Sep 17 00:00:00 2001 From: gax Date: Tue, 7 Mar 2023 21:46:29 +0000 Subject: [PATCH 21/43] Actualizar 'clienteMqtt/clienteMqtt.py' remove cur = await conn.cursor() --- clienteMqtt/clienteMqtt.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/clienteMqtt/clienteMqtt.py b/clienteMqtt/clienteMqtt.py index 34628ed8..47b47130 100755 --- a/clienteMqtt/clienteMqtt.py +++ b/clienteMqtt/clienteMqtt.py @@ -34,8 +34,6 @@ async def main(): except Exception as e: logging.error(traceback.format_exc()) - cur = await conn.cursor() - async with conn.cursor() as cur: try: await cur.execute(sql, (message.topic, datos['temperatura'], datos['humedad'])) From 50f839e79a9f675b3b466ec182d630ac12aa92fc Mon Sep 17 00:00:00 2001 From: gax Date: Wed, 8 Mar 2023 17:24:25 +0000 Subject: [PATCH 22/43] Actualizar 'clienteMqtt/clienteMqtt.py' environ[] --- clienteMqtt/clienteMqtt.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/clienteMqtt/clienteMqtt.py b/clienteMqtt/clienteMqtt.py index 47b47130..d2cadad3 100755 --- a/clienteMqtt/clienteMqtt.py +++ b/clienteMqtt/clienteMqtt.py @@ -13,9 +13,9 @@ async def main(): async with Client( - os.getenv("SERVIDOR"), - username=os.getenv("MQTT_USR"), - password=os.getenv("MQTT_PASS"), + os.environ["SERVIDOR"), + username=os.environ["MQTT_USR"], + password=os.environ["MQTT_PASS"], protocol=ProtocolVersion.V31, port=8883, tls_context=tls_context, @@ -27,10 +27,10 @@ async def main(): datos=json.loads(message.payload.decode('utf8')) sql = "INSERT INTO `mediciones` (`sensor_id`, `temperatura`, `humedad`) VALUES (%s, %s, %s)" try: - conn = await aiomysql.connect(host=os.getenv("MARIADB_SERVER"), port=3306, - user=os.getenv("MARIADB_USER"), - password=os.getenv("MARIADB_USER_PASS"), - db=os.getenv("MARIADB_DB")) + conn = await aiomysql.connect(host=os.environ["MARIADB_SERVER"], port=3306, + user=os.environ["MARIADB_USER"], + password=os.environ["MARIADB_USER_PASS"], + db=os.environ["MARIADB_DB"]) except Exception as e: logging.error(traceback.format_exc()) From a867882ced5a0a9d152b0870a1cdc5ccaf69cf4f Mon Sep 17 00:00:00 2001 From: gax Date: Wed, 8 Mar 2023 17:29:47 +0000 Subject: [PATCH 23/43] Actualizar 'telegrambot/telegrambot.py' environ[] --- telegrambot/telegrambot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telegrambot/telegrambot.py b/telegrambot/telegrambot.py index e4f0e713..d76305fd 100755 --- a/telegrambot/telegrambot.py +++ b/telegrambot/telegrambot.py @@ -2,7 +2,7 @@ from telegram.ext import Application, CommandHandler, ContextTypes import logging, os -token=os.getenv("TOKEN") +token=os.environ["TOKEN"] logging.basicConfig(format='%(asctime)s - TelegramBot - %(levelname)s - %(message)s', level=logging.INFO) From 43c5c0d0f2f18f7596cde45594ccc30d2a316c4d Mon Sep 17 00:00:00 2001 From: gax Date: Thu, 9 Mar 2023 12:09:23 +0000 Subject: [PATCH 24/43] Actualizar 'telegrambot/telegrambot.py' TOKEN por TB_TOKEN --- telegrambot/telegrambot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/telegrambot/telegrambot.py b/telegrambot/telegrambot.py index d76305fd..fee8f307 100755 --- a/telegrambot/telegrambot.py +++ b/telegrambot/telegrambot.py @@ -2,7 +2,7 @@ from telegram.ext import Application, CommandHandler, ContextTypes import logging, os -token=os.environ["TOKEN"] +token=os.environ["TB_TOKEN"] logging.basicConfig(format='%(asctime)s - TelegramBot - %(levelname)s - %(message)s', level=logging.INFO) From b3f1967bb7c1441c06bb53afd9a01ac19fb2d479 Mon Sep 17 00:00:00 2001 From: gax Date: Thu, 9 Mar 2023 13:48:11 +0000 Subject: [PATCH 25/43] Actualizar 'clienteMqtt/clienteMqtt.py' MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit faltó un ] --- clienteMqtt/clienteMqtt.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/clienteMqtt/clienteMqtt.py b/clienteMqtt/clienteMqtt.py index d2cadad3..bbc48c52 100755 --- a/clienteMqtt/clienteMqtt.py +++ b/clienteMqtt/clienteMqtt.py @@ -13,7 +13,7 @@ async def main(): async with Client( - os.environ["SERVIDOR"), + os.environ["SERVIDOR"], username=os.environ["MQTT_USR"], password=os.environ["MQTT_PASS"], protocol=ProtocolVersion.V31, From 15c26d89e65644ecec21e8d95416dd017f185306 Mon Sep 17 00:00:00 2001 From: gax Date: Fri, 24 Mar 2023 19:25:39 +0000 Subject: [PATCH 26/43] Actualizar 'clienteMqtt/clienteMqtt.py' ensure_closed() --- clienteMqtt/clienteMqtt.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/clienteMqtt/clienteMqtt.py b/clienteMqtt/clienteMqtt.py index bbc48c52..a4d78c36 100755 --- a/clienteMqtt/clienteMqtt.py +++ b/clienteMqtt/clienteMqtt.py @@ -37,13 +37,12 @@ async def main(): async with conn.cursor() as cur: try: await cur.execute(sql, (message.topic, datos['temperatura'], datos['humedad'])) + await conn.commit() + await cur.close() + await conn.ensure_closed() except Exception as e: logging.error(traceback.format_exc()) # Logs the error appropriately. - await conn.commit() - - conn.close() - if __name__ == "__main__": asyncio.run(main()) From c9d52aeb168bae7abf28d3bf97017f52e31875cc Mon Sep 17 00:00:00 2001 From: gax Date: Wed, 19 Apr 2023 18:58:35 +0000 Subject: [PATCH 27/43] Actualizar '.gitignore' wireguard --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index adfbc40d..d71d5879 100755 --- a/.gitignore +++ b/.gitignore @@ -137,3 +137,4 @@ dmypy.json swag/ grafana/ mosquitto/ +wireguard/ From 3367abd6b31aeb617a85f5f5313ddf94cd3a6bfb Mon Sep 17 00:00:00 2001 From: gax Date: Wed, 19 Apr 2023 19:19:52 +0000 Subject: [PATCH 28/43] Actualizar 'docker-compose.yml' MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit nueva versión de swag --- docker-compose.yml | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index 3f3ef629..fa6fa460 100755 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -81,7 +81,7 @@ services: - portainer_data:/data restart: unless-stopped swag: - image: linuxserver/swag + image: lscr.io/linuxserver/swag:latest container_name: swag cap_add: - NET_ADMIN @@ -90,13 +90,14 @@ services: - PGID=1000 - TZ=America/Argentina/Buenos_Aires - URL=${DOMINIO} - - VALIDATION=duckdns + - VALIDATION=dns + - DNSPLUGIN=duckdns - DUCKDNSTOKEN=${DUCKDNSTOKEN} - SUBDOMAINS= volumes: - ~/docker/swag:/config ports: - - ${PUERTO}:443 + - ${PUERTO}:443/tcp - 80:80 restart: unless-stopped volumes: From d7e27a70d2bdca1ce5fc335ff8ff1c6e0f83b8cb Mon Sep 17 00:00:00 2001 From: gax Date: Wed, 19 Apr 2023 19:38:18 +0000 Subject: [PATCH 29/43] =?UTF-8?q?nueva=20versi=C3=B3n=20de=20swag?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docker-compose.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/docker-compose.yml b/docker-compose.yml index fa6fa460..82e62f68 100755 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -92,7 +92,6 @@ services: - URL=${DOMINIO} - VALIDATION=dns - DNSPLUGIN=duckdns - - DUCKDNSTOKEN=${DUCKDNSTOKEN} - SUBDOMAINS= volumes: - ~/docker/swag:/config From a84e4cac8eb7a1e7468b902d49497233892c3fbd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Germ=C3=A1n=20Xander?= Date: Mon, 20 May 2024 15:32:57 -0300 Subject: [PATCH 30/43] ver2024 --- .gitignore | 1 + clienteMqtt/clienteMqtt.py | 55 +++++++++++++++--------------- clienteMqtt/requirements.txt | 7 ++-- docker-compose.yml => compose.yaml | 32 ++++++++++------- telegrambot/requirements.txt | 2 +- telegrambot/telegrambot.py | 2 +- 6 files changed, 53 insertions(+), 46 deletions(-) rename docker-compose.yml => compose.yaml (76%) diff --git a/.gitignore b/.gitignore index d71d5879..157c537e 100755 --- a/.gitignore +++ b/.gitignore @@ -138,3 +138,4 @@ swag/ grafana/ mosquitto/ wireguard/ +mariadb/ diff --git a/clienteMqtt/clienteMqtt.py b/clienteMqtt/clienteMqtt.py index a4d78c36..17fd23de 100755 --- a/clienteMqtt/clienteMqtt.py +++ b/clienteMqtt/clienteMqtt.py @@ -1,48 +1,47 @@ import asyncio, ssl, certifi, logging, os, aiomysql, json, traceback -from asyncio_mqtt import Client, ProtocolVersion +import aiomqtt logging.basicConfig(format='%(asctime)s - cliente mqtt - %(levelname)s:%(message)s', level=logging.INFO, datefmt='%d/%m/%Y %H:%M:%S %z') async def main(): + tls_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) - tls_context.minimum_version = ssl.TLSVersion.TLSv1_2 - tls_context.maximum_version = ssl.TLSVersion.TLSv1_3 tls_context.verify_mode = ssl.CERT_REQUIRED tls_context.check_hostname = True tls_context.load_default_certs() - - async with Client( + async with aiomqtt.Client( os.environ["SERVIDOR"], username=os.environ["MQTT_USR"], password=os.environ["MQTT_PASS"], - protocol=ProtocolVersion.V31, - port=8883, + port=int(os.environ["PUERTO_MQTTS"]), tls_context=tls_context, ) as client: - async with client.messages() as messages: - await client.subscribe('#') - async for message in messages: - logging.info(str(message.topic) + ": " + message.payload.decode("utf-8")) - datos=json.loads(message.payload.decode('utf8')) - sql = "INSERT INTO `mediciones` (`sensor_id`, `temperatura`, `humedad`) VALUES (%s, %s, %s)" + await client.subscribe(os.environ['TOPICO']) + async for message in client.messages: + logging.info(str(message.topic) + ": " + message.payload.decode("utf-8")) + dispositivo=str(message.topic).split('/')[-1] + datos=json.loads(message.payload.decode('utf8')) + sql = "INSERT INTO `mediciones` (`sensor_id`, `temperatura`, `humedad`) VALUES (%s, %s, %s)" + try: + conn = await aiomysql.connect(host=os.environ["MARIADB_SERVER"], port=3306, + user=os.environ["MARIADB_USER"], + password=os.environ["MARIADB_USER_PASS"], + db=os.environ["MARIADB_DB"]) + except Exception as e: + logging.error(traceback.format_exc()) + + cur = await conn.cursor() + + async with conn.cursor() as cur: try: - conn = await aiomysql.connect(host=os.environ["MARIADB_SERVER"], port=3306, - user=os.environ["MARIADB_USER"], - password=os.environ["MARIADB_USER_PASS"], - db=os.environ["MARIADB_DB"]) + await cur.execute(sql, (dispositivo, datos['temperatura'], datos['humedad'])) + await conn.commit() + await cur.close() + await conn.ensure_closed() except Exception as e: logging.error(traceback.format_exc()) - - async with conn.cursor() as cur: - try: - await cur.execute(sql, (message.topic, datos['temperatura'], datos['humedad'])) - await conn.commit() - await cur.close() - await conn.ensure_closed() - except Exception as e: - logging.error(traceback.format_exc()) - # Logs the error appropriately. + # Logs the error appropriately. if __name__ == "__main__": - asyncio.run(main()) + asyncio.run(main()) \ No newline at end of file diff --git a/clienteMqtt/requirements.txt b/clienteMqtt/requirements.txt index 1b040df2..f8b271a2 100755 --- a/clienteMqtt/requirements.txt +++ b/clienteMqtt/requirements.txt @@ -1,3 +1,4 @@ -asyncio-mqtt==0.16.1 -certifi==2022.12.7 -aiomysql==0.1.1 \ No newline at end of file +aiomqtt==2.0.1 +certifi==2024.2.2 +environs==11.0.0 +aiomysql==0.2.0 \ No newline at end of file diff --git a/docker-compose.yml b/compose.yaml similarity index 76% rename from docker-compose.yml rename to compose.yaml index 82e62f68..140a2648 100755 --- a/docker-compose.yml +++ b/compose.yaml @@ -1,4 +1,3 @@ -version: "3" services: mariadb: image: mariadb @@ -6,10 +5,10 @@ services: environment: - PUID=1000 - PGID=1000 - - MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD} + - MARIADB_ROOT_PASSWORD=${MARIADB_ROOT_PASSWORD} - TZ=America/Argentina/Buenos_Aires volumes: - - ~/docker/mariadb:/config + - ./mariadb:/config ports: - 3306:3306 restart: unless-stopped @@ -37,6 +36,7 @@ services: - MARIADB_DB=${MARIADB_DB} - MQTT_USR=${MQTT_USR} - MQTT_PASS=${MQTT_PASS} + - PUERTO_MQTTS=${PUERTO_MQTTS} restart: unless-stopped depends_on: - mariadb @@ -46,20 +46,20 @@ services: user: "1000:1000" ports: - 1883:1883 - - 8883:8883 + - ${PUERTO_MQTTS}:8883 restart: unless-stopped volumes: - - ~/docker/mosquitto/config/mosquitto.conf:/mosquitto/config/mosquitto.conf - - ~/docker/mosquitto/config:/mosquitto/config - - ~/docker/swag/etc/letsencrypt:/var/tmp - - ~/docker/mosquitto/data:/mosquitto/data - - ~/docker/mosquitto/log:/mosquitto/log + - ./mosquitto/config/mosquitto.conf:/mosquitto/config/mosquitto.conf + - ./mosquitto/config:/mosquitto/config + - ./swag/etc/letsencrypt:/var/tmp + - ./mosquitto/data:/mosquitto/data + - ./mosquitto/log:/mosquitto/log grafana: - image: grafana/grafana + image: grafana/grafana-oss container_name: grafana user: "1000" volumes: - - ~/docker/grafana:/var/lib/grafana + - ./grafana:/var/lib/grafana ports: - 3000:3000 depends_on: @@ -72,7 +72,7 @@ services: GF_ANALYTICS_REPORTING_ENABLED: "false" restart: unless-stopped portainer: - image: portainer/portainer-ce:latest + image: portainer/portainer-ce:2.20.2 container_name: portainer ports: - 9443:9443 @@ -94,10 +94,16 @@ services: - DNSPLUGIN=duckdns - SUBDOMAINS= volumes: - - ~/docker/swag:/config + - ./swag:/config ports: - ${PUERTO}:443/tcp - 80:80 restart: unless-stopped + telegrambot: + image: telegrambot + container_name: telegrambot + environment: + - TZ=America/Argentina/Buenos_Aires + - TB_TOKEN=${TB_TOKEN} volumes: portainer_data: \ No newline at end of file diff --git a/telegrambot/requirements.txt b/telegrambot/requirements.txt index 939400f4..16cf3d49 100755 --- a/telegrambot/requirements.txt +++ b/telegrambot/requirements.txt @@ -1 +1 @@ -python-telegram-bot==20.1 \ No newline at end of file +python-telegram-bot==21.2 \ No newline at end of file diff --git a/telegrambot/telegrambot.py b/telegrambot/telegrambot.py index fee8f307..d4339a5e 100755 --- a/telegrambot/telegrambot.py +++ b/telegrambot/telegrambot.py @@ -20,7 +20,7 @@ async def start(update: Update, context: ContextTypes.DEFAULT_TYPE): # await update.message.reply_text("Bienvenido al Bot "+ nombre + " " + apellido) # también funciona async def acercade(update: Update, context): - await context.bot.send_message(update.message.chat.id, text="Este bot fue creado para el curso de IoT (2023)") + await context.bot.send_message(update.message.chat.id, text="Este bot fue creado para el curso de IoT FIO") def main(): application = Application.builder().token(token).build() From 709e5efa71b7226f933028ecff387956ac3f46af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Germ=C3=A1n=20Xander?= Date: Mon, 20 May 2024 15:43:30 -0300 Subject: [PATCH 31/43] ver2024 --- telegrambot/telegrambot.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/telegrambot/telegrambot.py b/telegrambot/telegrambot.py index d4339a5e..0d0e398d 100755 --- a/telegrambot/telegrambot.py +++ b/telegrambot/telegrambot.py @@ -22,10 +22,20 @@ async def start(update: Update, context: ContextTypes.DEFAULT_TYPE): async def acercade(update: Update, context): await context.bot.send_message(update.message.chat.id, text="Este bot fue creado para el curso de IoT FIO") +async def kill(update: Update, context): + logging.info(context.args) + if context.args and context.args[0] == '@e': + await context.bot.send_animation(update.message.chat.id, "CgACAgEAAxkBAANXZAiWvDIEfGNVzodgTgH1o5z3_WEAAmUCAALrx0lEZ8ytatzE5X0uBA") + await asyncio.sleep(6) + await context.bot.send_message(update.message.chat.id, text="¡¡¡Ahora estan todos muertos!!!") + else: + await context.bot.send_message(update.message.chat.id, text="☠️ ¡¡¡Esto es muy peligroso!!! ☠️") + def main(): application = Application.builder().token(token).build() application.add_handler(CommandHandler('start', start)) application.add_handler(CommandHandler('acercade', acercade)) + application.add_handler(CommandHandler('kill', kill)) application.run_polling() if __name__ == '__main__': From 40d7c67c0ddf69954fadedb5fd229a22d10346a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Germ=C3=A1n=20Xander?= Date: Mon, 20 May 2024 16:09:06 -0300 Subject: [PATCH 32/43] ver2024b --- telegrambot/telegrambot.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/telegrambot/telegrambot.py b/telegrambot/telegrambot.py index 0d0e398d..c8f9bc7b 100755 --- a/telegrambot/telegrambot.py +++ b/telegrambot/telegrambot.py @@ -1,6 +1,6 @@ from telegram import Update from telegram.ext import Application, CommandHandler, ContextTypes -import logging, os +import logging, os, asyncio token=os.environ["TB_TOKEN"] @@ -25,7 +25,7 @@ async def acercade(update: Update, context): async def kill(update: Update, context): logging.info(context.args) if context.args and context.args[0] == '@e': - await context.bot.send_animation(update.message.chat.id, "CgACAgEAAxkBAANXZAiWvDIEfGNVzodgTgH1o5z3_WEAAmUCAALrx0lEZ8ytatzE5X0uBA") + await context.bot.send_animation(update.message.chat.id, "CgACAgEAAxkBAAOPZkuctzsWZVlDSNoP9PavSZmH5poAAmUCAALrx0lEVKaX7K-68Ns1BA") await asyncio.sleep(6) await context.bot.send_message(update.message.chat.id, text="¡¡¡Ahora estan todos muertos!!!") else: From 674bf9132d142496bf7218e01b801da9468b2de8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Germ=C3=A1n=20Xander?= Date: Thu, 23 May 2024 10:08:51 -0300 Subject: [PATCH 33/43] ver2024 --- compose.yaml | 7 +++++++ telegrambot/requirements.txt | 3 ++- telegrambot/telegrambot.py | 31 ++++++++++++++++++++++++++----- 3 files changed, 35 insertions(+), 6 deletions(-) diff --git a/compose.yaml b/compose.yaml index 140a2648..d1059898 100755 --- a/compose.yaml +++ b/compose.yaml @@ -105,5 +105,12 @@ services: environment: - TZ=America/Argentina/Buenos_Aires - TB_TOKEN=${TB_TOKEN} + - MARIADB_SERVER=${MARIADB_SERVER} + - MARIADB_USER=${MARIADB_USER} + - MARIADB_USER_PASS=${MARIADB_USER_PASS} + - MARIADB_DB=${MARIADB_DB} + restart: unless-stopped + depends_on: + - mariadb volumes: portainer_data: \ No newline at end of file diff --git a/telegrambot/requirements.txt b/telegrambot/requirements.txt index 16cf3d49..25ab6bb1 100755 --- a/telegrambot/requirements.txt +++ b/telegrambot/requirements.txt @@ -1 +1,2 @@ -python-telegram-bot==21.2 \ No newline at end of file +python-telegram-bot==21.2 +aiomysql==0.2.0 diff --git a/telegrambot/telegrambot.py b/telegrambot/telegrambot.py index c8f9bc7b..4dda5820 100755 --- a/telegrambot/telegrambot.py +++ b/telegrambot/telegrambot.py @@ -1,6 +1,6 @@ -from telegram import Update -from telegram.ext import Application, CommandHandler, ContextTypes -import logging, os, asyncio +from telegram import Update, ReplyKeyboardMarkup +from telegram.ext import Application, CommandHandler, ContextTypes, MessageHandler, filters +import logging, os, asyncio, aiomysql, traceback, locale token=os.environ["TB_TOKEN"] @@ -16,8 +16,8 @@ async def start(update: Update, context: ContextTypes.DEFAULT_TYPE): apellido=update.message.from_user.last_name else: apellido="" - await context.bot.send_message(update.message.chat.id, text="Bienvenido al Bot "+ nombre + " " + apellido) - # await update.message.reply_text("Bienvenido al Bot "+ nombre + " " + apellido) # también funciona + kb = [["temperatura"],["humedad"]] + await context.bot.send_message(update.message.chat.id, text="Bienvenido al Bot "+ nombre + " " + apellido,reply_markup=ReplyKeyboardMarkup(kb)) async def acercade(update: Update, context): await context.bot.send_message(update.message.chat.id, text="Este bot fue creado para el curso de IoT FIO") @@ -31,11 +31,32 @@ async def kill(update: Update, context): else: await context.bot.send_message(update.message.chat.id, text="☠️ ¡¡¡Esto es muy peligroso!!! ☠️") +async def medicion(update: Update, context): + logging.info(update.message.text) + sql = f"SELECT timestamp, {update.message.text} FROM mediciones ORDER BY timestamp DESC LIMIT 1" + conn = await aiomysql.connect(host=os.environ["MARIADB_SERVER"], port=3306, + user=os.environ["MARIADB_USER"], + password=os.environ["MARIADB_USER_PASS"], + db=os.environ["MARIADB_DB"]) + async with conn.cursor() as cur: + await cur.execute(sql) + r = await cur.fetchone() + if update.message.text == 'temperatura': + unidad = 'ºC' + else: + unidad = '%' + await context.bot.send_message(update.message.chat.id, + text="La última {} es de {} {},\nregistrada a las {:%H:%M:%S %d/%m/%Y}" + .format(update.message.text, str(r[1]).replace('.',','), unidad, r[0])) + logging.info("La última {} es de {} {}, medida a las {:%H:%M:%S %d/%m/%Y}".format(update.message.text, r[1], unidad, r[0])) + conn.close() + def main(): application = Application.builder().token(token).build() application.add_handler(CommandHandler('start', start)) application.add_handler(CommandHandler('acercade', acercade)) application.add_handler(CommandHandler('kill', kill)) + application.add_handler(MessageHandler(filters.Regex("^(temperatura|humedad)$"), medicion)) application.run_polling() if __name__ == '__main__': From 0a2284b9291a9de08687c1b3f35ad806e392dfa0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Germ=C3=A1n=20Xander?= Date: Thu, 23 May 2024 14:39:01 -0300 Subject: [PATCH 34/43] ver2024 --- telegrambot/requirements.txt | 1 + telegrambot/telegrambot.py | 31 ++++++++++++++++++++++++++++++- 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/telegrambot/requirements.txt b/telegrambot/requirements.txt index 25ab6bb1..3256d9a6 100755 --- a/telegrambot/requirements.txt +++ b/telegrambot/requirements.txt @@ -1,2 +1,3 @@ python-telegram-bot==21.2 aiomysql==0.2.0 +matplotlib==3.9.0 diff --git a/telegrambot/telegrambot.py b/telegrambot/telegrambot.py index 4dda5820..56ddd91b 100755 --- a/telegrambot/telegrambot.py +++ b/telegrambot/telegrambot.py @@ -1,6 +1,8 @@ from telegram import Update, ReplyKeyboardMarkup from telegram.ext import Application, CommandHandler, ContextTypes, MessageHandler, filters import logging, os, asyncio, aiomysql, traceback, locale +import matplotlib.pyplot as plt +from io import BytesIO token=os.environ["TB_TOKEN"] @@ -16,7 +18,7 @@ async def start(update: Update, context: ContextTypes.DEFAULT_TYPE): apellido=update.message.from_user.last_name else: apellido="" - kb = [["temperatura"],["humedad"]] + kb = [["temperatura"],["humedad"],["gráfico temperatura"],["gráfico humedad"]] await context.bot.send_message(update.message.chat.id, text="Bienvenido al Bot "+ nombre + " " + apellido,reply_markup=ReplyKeyboardMarkup(kb)) async def acercade(update: Update, context): @@ -51,12 +53,39 @@ async def medicion(update: Update, context): logging.info("La última {} es de {} {}, medida a las {:%H:%M:%S %d/%m/%Y}".format(update.message.text, r[1], unidad, r[0])) conn.close() +async def graficos(update: Update, context): + logging.info(update.message.text) + sql = f"SELECT timestamp, {update.message.text.split()[1]} FROM mediciones where id mod 2 = 0 AND timestamp >= NOW() - INTERVAL 1 DAY ORDER BY timestamp" + conn = await aiomysql.connect(host=os.environ["MARIADB_SERVER"], port=3306, + user=os.environ["MARIADB_USER"], + password=os.environ["MARIADB_USER_PASS"], + db=os.environ["MARIADB_DB"]) + async with conn.cursor() as cur: + await cur.execute(sql) + filas = await cur.fetchall() + + fig, ax = plt.subplots(figsize=(7, 4)) + fecha,var=zip(*filas) + ax.plot(fecha,var) + ax.grid(True, which='both') + ax.set_title(update.message.text, fontsize=14, verticalalignment='bottom') + ax.set_xlabel('fecha') + ax.set_ylabel('unidad') + + buffer = BytesIO() + fig.tight_layout() + fig.savefig(buffer, format='png') + buffer.seek(0) + await context.bot.send_photo(chat_id=update.effective_chat.id, photo=buffer) + conn.close() + def main(): application = Application.builder().token(token).build() application.add_handler(CommandHandler('start', start)) application.add_handler(CommandHandler('acercade', acercade)) application.add_handler(CommandHandler('kill', kill)) application.add_handler(MessageHandler(filters.Regex("^(temperatura|humedad)$"), medicion)) + application.add_handler(MessageHandler(filters.Regex("^(gráfico temperatura|gráfico humedad)$"), graficos)) application.run_polling() if __name__ == '__main__': From 78752bedad989894dac00d25d13a163a41e39cdf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Germ=C3=A1n=20Xander?= Date: Fri, 9 May 2025 10:57:04 -0300 Subject: [PATCH 35/43] ver2025. set sensor_id to sensor_1 --- compose.yaml | 6 +++--- telegrambot/requirements.txt | 6 +++--- telegrambot/telegrambot.py | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/compose.yaml b/compose.yaml index d1059898..17923aee 100755 --- a/compose.yaml +++ b/compose.yaml @@ -67,12 +67,12 @@ services: environment: GF_SERVER_PROTOCOL: http GF_SERVER_ROOT_URL: https://${DOMINIO}:${PUERTO}/grafana/ - GF_SERVER_SERVE_FROM_SUB_PATH: "true" - GF_SERVER_DOMAIN: ${DOMINIO} + # GF_SERVER_SERVE_FROM_SUB_PATH: "true" + GF_SERVER_DOMAIN: https://${DOMINIO} GF_ANALYTICS_REPORTING_ENABLED: "false" restart: unless-stopped portainer: - image: portainer/portainer-ce:2.20.2 + image: portainer/portainer-ce container_name: portainer ports: - 9443:9443 diff --git a/telegrambot/requirements.txt b/telegrambot/requirements.txt index 3256d9a6..625f480e 100755 --- a/telegrambot/requirements.txt +++ b/telegrambot/requirements.txt @@ -1,3 +1,3 @@ -python-telegram-bot==21.2 -aiomysql==0.2.0 -matplotlib==3.9.0 +python-telegram-bot +aiomysql +matplotlib diff --git a/telegrambot/telegrambot.py b/telegrambot/telegrambot.py index 56ddd91b..304458b5 100755 --- a/telegrambot/telegrambot.py +++ b/telegrambot/telegrambot.py @@ -55,7 +55,7 @@ async def medicion(update: Update, context): async def graficos(update: Update, context): logging.info(update.message.text) - sql = f"SELECT timestamp, {update.message.text.split()[1]} FROM mediciones where id mod 2 = 0 AND timestamp >= NOW() - INTERVAL 1 DAY ORDER BY timestamp" + sql = f"SELECT timestamp, {update.message.text.split()[1]} FROM mediciones where id mod 2 = 0 AND timestamp >= NOW() - INTERVAL 1 DAY AND sensor_id LIKE 'sensor_1' ORDER BY timestamp" conn = await aiomysql.connect(host=os.environ["MARIADB_SERVER"], port=3306, user=os.environ["MARIADB_USER"], password=os.environ["MARIADB_USER_PASS"], From 841a6018ee2458c7b9233299fb81f9c2cfa963a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Germ=C3=A1n=20Xander?= Date: Mon, 12 May 2025 16:33:38 -0300 Subject: [PATCH 36/43] ver2025b --- clienteMqtt/requirements.txt | 8 ++++---- telegrambot/telegrambot.py | 1 + 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/clienteMqtt/requirements.txt b/clienteMqtt/requirements.txt index f8b271a2..9c15641c 100755 --- a/clienteMqtt/requirements.txt +++ b/clienteMqtt/requirements.txt @@ -1,4 +1,4 @@ -aiomqtt==2.0.1 -certifi==2024.2.2 -environs==11.0.0 -aiomysql==0.2.0 \ No newline at end of file +aiomqtt +certifi +environs +aiomysql diff --git a/telegrambot/telegrambot.py b/telegrambot/telegrambot.py index 304458b5..05887c30 100755 --- a/telegrambot/telegrambot.py +++ b/telegrambot/telegrambot.py @@ -77,6 +77,7 @@ async def graficos(update: Update, context): fig.savefig(buffer, format='png') buffer.seek(0) await context.bot.send_photo(chat_id=update.effective_chat.id, photo=buffer) + buffer.close() conn.close() def main(): From e4040454e127a76b79f0e8e75f8b5c24d03c7d67 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Germ=C3=A1n=20Xander?= Date: Mon, 12 May 2025 16:57:55 -0300 Subject: [PATCH 37/43] ver2025b --- telegrambot/telegrambot.py | 1 + 1 file changed, 1 insertion(+) diff --git a/telegrambot/telegrambot.py b/telegrambot/telegrambot.py index 05887c30..2a326ce8 100755 --- a/telegrambot/telegrambot.py +++ b/telegrambot/telegrambot.py @@ -75,6 +75,7 @@ async def graficos(update: Update, context): buffer = BytesIO() fig.tight_layout() fig.savefig(buffer, format='png') + plt.close() buffer.seek(0) await context.bot.send_photo(chat_id=update.effective_chat.id, photo=buffer) buffer.close() From 0e609837c045b3c728047a02496cb6b9ed59967b Mon Sep 17 00:00:00 2001 From: LAV419 Date: Tue, 20 May 2025 13:25:54 -0300 Subject: [PATCH 38/43] prueba1 --- telegrambot/telegrambot.py | 55 +++++++++++++++++++++++++++++++++++--- 1 file changed, 51 insertions(+), 4 deletions(-) diff --git a/telegrambot/telegrambot.py b/telegrambot/telegrambot.py index 2a326ce8..38e30de6 100755 --- a/telegrambot/telegrambot.py +++ b/telegrambot/telegrambot.py @@ -18,7 +18,7 @@ async def start(update: Update, context: ContextTypes.DEFAULT_TYPE): apellido=update.message.from_user.last_name else: apellido="" - kb = [["temperatura"],["humedad"],["gráfico temperatura"],["gráfico humedad"]] + kb = [["Destello"],["Modo"],["Relé"]] await context.bot.send_message(update.message.chat.id, text="Bienvenido al Bot "+ nombre + " " + apellido,reply_markup=ReplyKeyboardMarkup(kb)) async def acercade(update: Update, context): @@ -32,7 +32,53 @@ async def kill(update: Update, context): await context.bot.send_message(update.message.chat.id, text="¡¡¡Ahora estan todos muertos!!!") else: await context.bot.send_message(update.message.chat.id, text="☠️ ¡¡¡Esto es muy peligroso!!! ☠️") - + +async def setpoint(update: Update, context): + logging.info(context.args) + + if not context.args: + await context.bot.send_message(chat_id=update.message.chat.id, text="Por favor ingresa un valor numérico.") + return + try: + setpoint=float(context.args[0]) + await context.bot.send_message(chat_id=update.message.chat.id, text=f"Cambiando el setpoint a: {setpoint}") + except ValueError: + await context.bot.send_message(chat_id=update.message.chat.id, text="El valor ingresado no es un número válido.") + + +async def periodo(update: Update, context): + logging.info(context.args) + + if not context.args: + await context.bot.send_message(chat_id=update.message.chat.id, text="Por favor ingresa un valor numérico.") + return + try: + await context.bot.send_message(chat_id=update.message.chat.id, text=f"Cambiando el periodo a: {float(context.args[0])}") + except ValueError: + await context.bot.send_message(chat_id=update.message.chat.id, text="El valor ingresado no es un número válido.") + + +async def publicacion(client, publish_topic, valor): + logger = logging.getLogger("publisher") + while True: + await client.publish(publish_topic, str(valor)) + logger.info(f"Publicado: {valor}") + await asyncio.sleep(5) + + + async with asyncio.TaskGroup() as tg: + tg.create_task(publicacion(client, publish_topic)) + +async def DMR(update: Update, context): + if update.message.text == 'Destello': + await context.bot.send_message(chat_id=update.message.chat.id, text=f"Brilla como el sol cuando amanece") + elif update.message.text == 'Modo': + await context.bot.send_message(chat_id=update.message.chat.id, text=f"Flaco cambiaste el modo") + elif update.message.text == 'Relé': + await context.bot.send_message(chat_id=update.message.chat.id, text=f"Se activo el rele (creo)") + else: + await context.bot.send_message(chat_id=update.message.chat.id, text=f"Que tocaste flaco?") + async def medicion(update: Update, context): logging.info(update.message.text) sql = f"SELECT timestamp, {update.message.text} FROM mediciones ORDER BY timestamp DESC LIMIT 1" @@ -86,8 +132,9 @@ def main(): application.add_handler(CommandHandler('start', start)) application.add_handler(CommandHandler('acercade', acercade)) application.add_handler(CommandHandler('kill', kill)) - application.add_handler(MessageHandler(filters.Regex("^(temperatura|humedad)$"), medicion)) - application.add_handler(MessageHandler(filters.Regex("^(gráfico temperatura|gráfico humedad)$"), graficos)) + application.add_handler(CommandHandler('setpoint', setpoint)) + application.add_handler(CommandHandler('periodo', periodo)) + application.add_handler(MessageHandler(filters.Regex("^(Destello|Modo|Relé)$"), DMR)) application.run_polling() if __name__ == '__main__': From 850492350ea75edcefc61d80a71ea86c7f850f27 Mon Sep 17 00:00:00 2001 From: LAV419 Date: Tue, 20 May 2025 16:33:26 -0300 Subject: [PATCH 39/43] Prueba2 --- telegrambot/requirements.txt | 1 + telegrambot/telegrambot.py | 61 ++++++++++++++++++++++-------------- 2 files changed, 39 insertions(+), 23 deletions(-) diff --git a/telegrambot/requirements.txt b/telegrambot/requirements.txt index 625f480e..e3494dd8 100755 --- a/telegrambot/requirements.txt +++ b/telegrambot/requirements.txt @@ -1,3 +1,4 @@ python-telegram-bot aiomysql +aiomqtt matplotlib diff --git a/telegrambot/telegrambot.py b/telegrambot/telegrambot.py index 38e30de6..07557404 100755 --- a/telegrambot/telegrambot.py +++ b/telegrambot/telegrambot.py @@ -1,6 +1,6 @@ from telegram import Update, ReplyKeyboardMarkup from telegram.ext import Application, CommandHandler, ContextTypes, MessageHandler, filters -import logging, os, asyncio, aiomysql, traceback, locale +import logging, os, asyncio, aiomysql, traceback, locale, aiomqtt, ssl, certifi, json import matplotlib.pyplot as plt from io import BytesIO @@ -56,28 +56,41 @@ async def periodo(update: Update, context): await context.bot.send_message(chat_id=update.message.chat.id, text=f"Cambiando el periodo a: {float(context.args[0])}") except ValueError: await context.bot.send_message(chat_id=update.message.chat.id, text="El valor ingresado no es un número válido.") - - -async def publicacion(client, publish_topic, valor): - logger = logging.getLogger("publisher") - while True: - await client.publish(publish_topic, str(valor)) - logger.info(f"Publicado: {valor}") - await asyncio.sleep(5) - - - async with asyncio.TaskGroup() as tg: - tg.create_task(publicacion(client, publish_topic)) - -async def DMR(update: Update, context): - if update.message.text == 'Destello': - await context.bot.send_message(chat_id=update.message.chat.id, text=f"Brilla como el sol cuando amanece") - elif update.message.text == 'Modo': - await context.bot.send_message(chat_id=update.message.chat.id, text=f"Flaco cambiaste el modo") - elif update.message.text == 'Relé': - await context.bot.send_message(chat_id=update.message.chat.id, text=f"Se activo el rele (creo)") - else: - await context.bot.send_message(chat_id=update.message.chat.id, text=f"Que tocaste flaco?") + +from aiomqtt import MqttError + +async def DMR(update: Update, context: ContextTypes.DEFAULT_TYPE): + text = update.message.text + + tls_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + tls_context.verify_mode = ssl.CERT_REQUIRED + tls_context.check_hostname = True + tls_context.load_default_certs() + + try: + async with aiomqtt.Client( + "vellbach.duckdns.org", + port=23417, + username="lav", + password="alejandro", + tls_context=tls_context, + ) as client: + if text == 'Destello': + action_description = "Brilla como el sol cuando amanece ✨" + await client.publish("destello", payload=1) + elif text == 'Modo': + action_description = "Flaco cambiaste el modo ⚙️" + await client.publish("modo", payload=1) + elif text == 'Relé': + action_description = "Se activó el relé (creo) 💡" + await client.publish("relé", payload=1) + else: + await context.bot.send_message(update.message.chat.id,text="Qué tocaste flaco? 🤔") + return + await context.bot.send_message(update.message.chat.id, text=action_description) + except MqttError as e: + logging.error(f"Error al conectar con MQTT: {e}") + await context.bot.send_message(update.message.chat.id, text="❌ No se pudo conectar con el servidor MQTT.") async def medicion(update: Update, context): logging.info(update.message.text) @@ -129,12 +142,14 @@ async def graficos(update: Update, context): def main(): application = Application.builder().token(token).build() + application.add_handler(CommandHandler('start', start)) application.add_handler(CommandHandler('acercade', acercade)) application.add_handler(CommandHandler('kill', kill)) application.add_handler(CommandHandler('setpoint', setpoint)) application.add_handler(CommandHandler('periodo', periodo)) application.add_handler(MessageHandler(filters.Regex("^(Destello|Modo|Relé)$"), DMR)) + application.run_polling() if __name__ == '__main__': From 691100ae8aeeaf36b72b08ceba7f9ff7603c9b52 Mon Sep 17 00:00:00 2001 From: LAV419 Date: Tue, 20 May 2025 17:22:37 -0300 Subject: [PATCH 40/43] Prueba3 --- telegrambot/telegrambot.py | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/telegrambot/telegrambot.py b/telegrambot/telegrambot.py index 07557404..7fe7a43b 100755 --- a/telegrambot/telegrambot.py +++ b/telegrambot/telegrambot.py @@ -69,11 +69,8 @@ async def DMR(update: Update, context: ContextTypes.DEFAULT_TYPE): try: async with aiomqtt.Client( - "vellbach.duckdns.org", - port=23417, - username="lav", - password="alejandro", - tls_context=tls_context, + "fiounam.duckdns.org", + port=8883, ) as client: if text == 'Destello': action_description = "Brilla como el sol cuando amanece ✨" From 054a34d085c9d8afad8152c68d54d83559076254 Mon Sep 17 00:00:00 2001 From: LAV419 Date: Tue, 20 May 2025 21:08:15 -0300 Subject: [PATCH 41/43] Final1 --- compose.yaml | 4 ++ telegrambot/telegrambot.py | 98 +++++++++++++++++++++++--------------- 2 files changed, 63 insertions(+), 39 deletions(-) diff --git a/compose.yaml b/compose.yaml index 17923aee..78d07243 100755 --- a/compose.yaml +++ b/compose.yaml @@ -109,6 +109,10 @@ services: - MARIADB_USER=${MARIADB_USER} - MARIADB_USER_PASS=${MARIADB_USER_PASS} - MARIADB_DB=${MARIADB_DB} + - DOMINIO=${DOMINIO} + - MQTT_USR=${MQTT_USR} + - MQTT_PASS=${MQTT_PASS} + - PUERTO_MQTTS=${PUERTO_MQTTS} restart: unless-stopped depends_on: - mariadb diff --git a/telegrambot/telegrambot.py b/telegrambot/telegrambot.py index 7fe7a43b..46af49f9 100755 --- a/telegrambot/telegrambot.py +++ b/telegrambot/telegrambot.py @@ -57,37 +57,30 @@ async def periodo(update: Update, context): except ValueError: await context.bot.send_message(chat_id=update.message.chat.id, text="El valor ingresado no es un número válido.") -from aiomqtt import MqttError -async def DMR(update: Update, context: ContextTypes.DEFAULT_TYPE): - text = update.message.text +async def publicar(context: ContextTypes.DEFAULT_TYPE, topico: str): + client = context.application.bot_data["mqtt_client"] + if not client: + logging.error("MQTT client no disponible en el contexto.") + return + try: + await client.publish(topico, topico) + logging.info(f"Publicado en MQTT: {topico}") + except Exception as e: + logging.error(f"Error al publicar en MQTT: {e}") + traceback.print_exc() - tls_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) - tls_context.verify_mode = ssl.CERT_REQUIRED - tls_context.check_hostname = True - tls_context.load_default_certs() - try: - async with aiomqtt.Client( - "fiounam.duckdns.org", - port=8883, - ) as client: - if text == 'Destello': - action_description = "Brilla como el sol cuando amanece ✨" - await client.publish("destello", payload=1) - elif text == 'Modo': - action_description = "Flaco cambiaste el modo ⚙️" - await client.publish("modo", payload=1) - elif text == 'Relé': - action_description = "Se activó el relé (creo) 💡" - await client.publish("relé", payload=1) - else: - await context.bot.send_message(update.message.chat.id,text="Qué tocaste flaco? 🤔") - return - await context.bot.send_message(update.message.chat.id, text=action_description) - except MqttError as e: - logging.error(f"Error al conectar con MQTT: {e}") - await context.bot.send_message(update.message.chat.id, text="❌ No se pudo conectar con el servidor MQTT.") +async def DMR(update: Update, context: ContextTypes.DEFAULT_TYPE): + text = update.message.text.lower() + acciones = { + "destello": "Brilla como el sol cuando amanece ✨", + "modo": "Flaco cambiaste el modo ⚙️", + "relé": "Se activó el relé (creo) 💡" + } + + await publicar(context,text) + await context.bot.send_message(update.message.chat.id, text=acciones[text]) async def medicion(update: Update, context): logging.info(update.message.text) @@ -137,17 +130,44 @@ async def graficos(update: Update, context): buffer.close() conn.close() -def main(): - application = Application.builder().token(token).build() +async def main(): - application.add_handler(CommandHandler('start', start)) - application.add_handler(CommandHandler('acercade', acercade)) - application.add_handler(CommandHandler('kill', kill)) - application.add_handler(CommandHandler('setpoint', setpoint)) - application.add_handler(CommandHandler('periodo', periodo)) - application.add_handler(MessageHandler(filters.Regex("^(Destello|Modo|Relé)$"), DMR)) + tls_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + tls_context.verify_mode = ssl.CERT_REQUIRED + tls_context.check_hostname = True + tls_context.load_default_certs() - application.run_polling() -if __name__ == '__main__': - main() + async with aiomqtt.Client( + os.environ["DOMINIO"], + username=os.environ["MQTT_USR"], + password=os.environ["MQTT_PASS"], + port=int(os.environ["PUERTO_MQTTS"]), + tls_context=tls_context, + ) as client: + + application = Application.builder().token(token).build() + + application.add_handler(CommandHandler('start', start)) + application.add_handler(CommandHandler('about', acercade)) + application.add_handler(CommandHandler('setpoint', setpoint)) + application.add_handler(MessageHandler(filters.Regex("^(Destello|Modo|Relé)$"), DMR)) + + application.bot_data["mqtt_client"] = client + + # Inicializar la aplicación Telegram + async with application: # Calls initialize and shutdown + await application.start() + await application.updater.start_polling() + # Start other asyncio frameworks here + # Add some logic that keeps the event loop running until you want to shutdown + while True: + try: + await asyncio.sleep(1) + except Exception: + # Stop the other asyncio frameworks here + await application.updater.stop() + await application.stop() + +if __name__ == "__main__": + asyncio.run(main()) \ No newline at end of file From 30fd17b160e75b2941c948bb083cb8ef0bb40b28 Mon Sep 17 00:00:00 2001 From: LAV419 Date: Tue, 20 May 2025 21:25:32 -0300 Subject: [PATCH 42/43] Final --- telegrambot/telegrambot.py | 37 +++++++++++++++++++++++-------------- 1 file changed, 23 insertions(+), 14 deletions(-) diff --git a/telegrambot/telegrambot.py b/telegrambot/telegrambot.py index 46af49f9..c7567e14 100755 --- a/telegrambot/telegrambot.py +++ b/telegrambot/telegrambot.py @@ -40,12 +40,15 @@ async def setpoint(update: Update, context): await context.bot.send_message(chat_id=update.message.chat.id, text="Por favor ingresa un valor numérico.") return try: - setpoint=float(context.args[0]) - await context.bot.send_message(chat_id=update.message.chat.id, text=f"Cambiando el setpoint a: {setpoint}") + setpoint_value = float(context.args[0]) + await context.bot.send_message(chat_id=update.message.chat.id, text=f"Cambiando el setpoint a: {setpoint_value}") + + payload = json.dumps({"setpoint": setpoint_value}) + await publicar(context, "setpoint", payload) + except ValueError: await context.bot.send_message(chat_id=update.message.chat.id, text="El valor ingresado no es un número válido.") - async def periodo(update: Update, context): logging.info(context.args) @@ -53,33 +56,38 @@ async def periodo(update: Update, context): await context.bot.send_message(chat_id=update.message.chat.id, text="Por favor ingresa un valor numérico.") return try: - await context.bot.send_message(chat_id=update.message.chat.id, text=f"Cambiando el periodo a: {float(context.args[0])}") + periodo_value = float(context.args[0]) + await context.bot.send_message(chat_id=update.message.chat.id, text=f"Cambiando el periodo a: {periodo_value}") + + payload = json.dumps({"periodo": periodo_value}) + await publicar(context, "periodo", payload) + except ValueError: await context.bot.send_message(chat_id=update.message.chat.id, text="El valor ingresado no es un número válido.") - -async def publicar(context: ContextTypes.DEFAULT_TYPE, topico: str): - client = context.application.bot_data["mqtt_client"] +async def publicar(context: ContextTypes.DEFAULT_TYPE, topico: str, payload: str): + client = context.application.bot_data.get("mqtt_client") if not client: logging.error("MQTT client no disponible en el contexto.") return try: - await client.publish(topico, topico) - logging.info(f"Publicado en MQTT: {topico}") + await client.publish(topico, payload) + logging.info(f"Publicado en MQTT: {topico} -> {payload}") except Exception as e: logging.error(f"Error al publicar en MQTT: {e}") traceback.print_exc() + async def DMR(update: Update, context: ContextTypes.DEFAULT_TYPE): text = update.message.text.lower() acciones = { - "destello": "Brilla como el sol cuando amanece ✨", - "modo": "Flaco cambiaste el modo ⚙️", - "relé": "Se activó el relé (creo) 💡" + "destello": "Encendiendo el LED", + "modo": "Cambiando el modo", + "relé": "Activando el relé" } - - await publicar(context,text) + + await publicar(context, text, text) await context.bot.send_message(update.message.chat.id, text=acciones[text]) async def medicion(update: Update, context): @@ -151,6 +159,7 @@ async def main(): application.add_handler(CommandHandler('start', start)) application.add_handler(CommandHandler('about', acercade)) application.add_handler(CommandHandler('setpoint', setpoint)) + application.add_handler(CommandHandler('periodo', periodo)) application.add_handler(MessageHandler(filters.Regex("^(Destello|Modo|Relé)$"), DMR)) application.bot_data["mqtt_client"] = client From 41a275970bf21a4123c38d69b449ee4cff5d55e6 Mon Sep 17 00:00:00 2001 From: LAV419 <73648857+LAV419@users.noreply.github.com> Date: Tue, 20 May 2025 21:27:20 -0300 Subject: [PATCH 43/43] Update README.md --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index b5710abe..d037f849 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,4 @@ -# docker +# Ejercicio Telegram bot + +Vellbach, Lucas Alejandro