Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

No es que sea inteligencia.... pero algo hace #13

Open
wants to merge 16 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ status.json
.session

*.ignore

**/data/*
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
Expand Down
9 changes: 4 additions & 5 deletions Bots/BaseMQTTNode/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,12 @@ WORKDIR /app

# Copia el archivo de requerimientos al contenedor
COPY requirements.txt .
# Instala las dependencias
RUN pip install -r requirements.txt

# Copia el archivo node.py al contenedor
COPY gladosMQTT.py .
COPY node.py .

# Instala las dependencias
RUN pip install -r requirements.txt
COPY main.py .

# Ejecuta el programa cuando el contenedor se inicie
CMD ["python", "node.py"]
CMD ["python", "main.py"]
6 changes: 3 additions & 3 deletions Bots/BaseMQTTNode/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ version: '3'
services:
glados_node:
build: .
image: makespacemadrid/glados-base-node:1.0
image: makespacemadrid/glados-base-node:1.5
hostname: base-node
# ports:
# - "8080:8080" # Cambia el puerto si es necesario
environment:
- MQTT_PORT = 1883
- MQTT_HOST = mqtt.makespacemadrid.org
- MQTT_PORT=1883
- MQTT_HOST=mqtt.makespacemadrid.org
202 changes: 69 additions & 133 deletions Bots/BaseMQTTNode/gladosMQTT.py
Original file line number Diff line number Diff line change
@@ -1,138 +1,74 @@
# -*- coding: utf-8 -*-

import paho.mqtt.client as mqtt
import platform
import time
import os
import json



#Carga inicial de variables, aunque el valor de estas se reescribira al ejecutar initMQTT
mqttServer = "192.168.1.1"
mqttPort = 1883
nodeName = "test-node"
baseTopic = "node/test-node"
debugTopic = baseTopic+"debug"
mqttClient = mqtt.Client()


def dummy() :
debug(dummy)

nodeConnectedCallback = dummy
nodeMsgCallback = dummy
nodeDisconnectedCallback = dummy

def subscribe(topic) :
mqttClient.subscribe(topic)


def publish(topic,msg,persist = False) :
mqttClient.publish(topic,msg,persist)

def debug(msg) :
print(msg)
publish(debugTopic,str(msg))

def on_connect(client, userdata, rc,arg):
global mqttServer
global mqttPort
global nodeName
global baseTopic
global debugTopic

debug("[GladosNode] Connected with result code "+str(rc))
debug("[GladosNode] Node name : " + nodeName)
debug("[GladosNode] Base topic : " + baseTopic)
debug("[GladosNode] Debug topic : " + debugTopic)
debug("[GladosNode] mosquitto_sub -h " + mqttServer + " -t " + debugTopic)


publish("node/hello", "Hello! Im "+ nodeName)
nodeConnectedCallback(client, userdata, rc,arg)


# The callback for when a PUBLISH message is received from the server.
# Aqui recibimos los mensajes, y si no hay que hacer nada con ellos se lo pasamos al callback del nodo para que los procese
def on_message(client, userdata, msg):

try:
debug("[GladosNode] mqtt_rcv: { "+msg.topic + " - " +msg.payload+ " }")
except:
debug("[GladosNode] mqtt_rcv: not str ")
nodeMsgCallback(client, userdata, msg)

def on_disconnect(client, userdata, rc):
nodeDisconnectedCallback(client, userdata, rc)

#Inicia mqtt y devuelve el control
def initMQTT(host,port,name,connectedCallback,msgCallback,disconnectedCallback) :
global mqttServer
global mqttPort
global nodeName
global baseTopic
global debugTopic
global mqttClient

global nodeConnectedCallback
global nodeMsgCallback
global nodeDisconnectedCallback

mqttServer = host
mqttPort = port
nodeName = name
baseTopic = "node/"+nodeName+"/"
debugTopic = baseTopic+"debug"


nodeConnectedCallback = connectedCallback
nodeMsgCallback = msgCallback
nodeDisconnectedCallback = disconnectedCallback

mqttClient.on_connect = on_connect
mqttClient.on_message = on_message
mqttClient.on_disconnect = on_disconnect

print("[GladosNode] Connecting : "+str(mqttServer)+" Port:"+str(mqttPort)+ " node: " + str(name))

try:
mqttClient.connect(mqttServer,port=mqttPort,keepalive=120)
except:
print("Cant connect, will retry automatically")
mqttClient.loop_start()

#Inicia mqtt y captura la ejecucion
def initMQTTandLoopForever(host,port,name,connectedCallback,msgCallback,disconnectedCallback) :
global mqttServer
global mqttPort
global nodeName
global baseTopic
global debugTopic

global nodeConnectedCallback
global nodeMsgCallback
global nodeDisconnectedCallback

mqttServer = host
mqttPort = port
nodeName = name
baseTopic = "node/"+nodeName+"/"
debugTopic = baseTopic+"debug"


nodeConnectedCallback = connectedCallback
nodeMsgCallback = msgCallback
nodeDisconnectedCallback = disconnectedCallback

mqttClient.on_connect = on_connect
mqttClient.on_message = on_message
mqttClient.on_disconnect = on_disconnect

print("[GladosNode] Connecting : "+str(mqttServer)+" Port:"+str(mqttPort)+ " node: " + str(name))

try:
mqttClient.connect(mqttServer,port=mqttPort,keepalive=120)
except:
print("Cant connect, will retry automatically")
mqttClient.loop_forever()
class GladosMQTT:
def __init__(self, host="192.168.1.1", port=1883, name="test-node", msg_callback=None):
self.mqttServer = host
self.mqttPort = port
self.nodeName = name
self.baseTopic = "node/" + self.nodeName
self.statusTopic = self.baseTopic+'/status'
self.debugTopic = self.baseTopic + "/debug"
self.mqttClient = mqtt.Client()
self.topics = []
self.nodeMsgCallback = msg_callback if msg_callback is not None else self.dummy

self.mqttClient.on_connect = self.on_connect
self.mqttClient.on_message = self.on_message
self.mqttClient.on_disconnect = self.on_disconnect
self.mqttClient.will_set(self.statusTopic,'OFFLINE', int(2), True)



def set_topics(self, topics):
self.topics = topics

def dummy(self, *args, **kwargs):
self.debug("Dummy function called")

def publish(self, topic, msg,qos=2,persist=False):
self.mqttClient.publish(topic, msg,qos, persist)

def debug(self, msg):
if not isinstance(msg, str):
try:
msg = json.dumps(msg)
except (TypeError, ValueError):
msg = str(msg)

print(msg)
self.publish(self.debugTopic, msg)

def on_connect(self, client, userdata, flags, rc):
self.debug("[GladosNode] Connected with result code " + str(rc))
self.mqttClient.publish(self.statusTopic,'ONLINE', int(2))
for topic in self.topics:
self.mqttClient.subscribe(topic,int(2))

def on_message(self, client, userdata, msg):
# try:
# self.debug("[GladosNode] mqtt_rcv: { " + msg.topic + " - " + msg.payload.decode() + " }")
# except Exception as e:
# self.debug("[GladosNode] mqtt_rcv error: " + str(e))
self.nodeMsgCallback(client, userdata, msg)

def on_disconnect(self, client, userdata, rc):
self.debug("[GladosNode] Disconnected with result code " + str(rc))

def init_mqtt(self):
self.debug("[GladosNode] Connecting : " + str(self.mqttServer) + " Port:" + str(self.mqttPort) + " node: " + str(self.nodeName))
try:
self.mqttClient.connect(self.mqttServer, port=self.mqttPort, keepalive=120)
except Exception as e:
self.debug("Cannot connect: " + str(e))
self.mqttClient.loop_start()

def init_mqtt_and_loop_forever(self):
self.debug("[GladosNode] Connecting : " + str(self.mqttServer) + " Port:" + str(self.mqttPort) + " node: " + str(self.nodeName))
try:
self.mqttClient.connect(self.mqttServer, port=self.mqttPort, keepalive=120)
except Exception as e:
self.debug("Cannot connect: " + str(e))
self.mqttClient.loop_forever()
33 changes: 33 additions & 0 deletions Bots/BaseMQTTNode/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# -*- coding: utf-8 -*-

import os
import platform
import time
from gladosMQTT import GladosMQTT

# Variables
mqHost = os.environ.get("MQTT_HOST")
mqPort = int(os.environ.get("MQTT_PORT"))
nodeName = platform.node()

# Definición de los callbacks
def on_mqtt_message(client, userdata, msg):
if msg.topic == "my_topic":
glados_mqtt.debug("msg:" + str(msg.payload))

# Instanciación de la clase GladosMQTT
glados_mqtt = GladosMQTT(host=mqHost, port=mqPort, name=nodeName, msg_callback=on_mqtt_message)

# Suscripción a tópicos
glados_mqtt.set_topics(["node/topic", "my_topic"]) # Asegúrate de incluir los tópicos correctos aquí

# Inicialización de MQTT
glados_mqtt.init_mqtt_and_loop_forever()

#glados_mqtt.init_mqtt
#try:
# while True:
# Loop principal del programa
# time.sleep(10)
#except KeyboardInterrupt:
# print('Interrupted!')
41 changes: 0 additions & 41 deletions Bots/BaseMQTTNode/node.py

This file was deleted.

21 changes: 21 additions & 0 deletions Bots/Calendar/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Utiliza una imagen base que ya tiene el cliente mqtt
FROM makespacemadrid/glados-base-node:1.0

# Establece el directorio de trabajo en /app
WORKDIR /app
VOLUME [ "/data" ]

# Copia el archivo de requerimientos al contenedor
COPY requirements.txt .
RUN pip install -r requirements.txt


# Copia el archivo node.py al contenedor
COPY node.py .

# Instala las dependencias

USER 1000

# Ejecuta el programa cuando el contenedor se inicie
CMD ["python", "node.py"]
43 changes: 43 additions & 0 deletions Bots/Calendar/GoogleCalendar.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# google_calendar.py
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
import os.path
import pickle
import datetime

class GoogleCalendarClient:
def __init__(self):
self.creds = None
self.scopes = ['https://www.googleapis.com/auth/calendar']

# El archivo token.pickle almacena los tokens de acceso y actualización del usuario
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
self.creds = pickle.load(token)

# Si no hay credenciales válidas disponibles, deja que el usuario inicie sesión.
if not self.creds or not self.creds.valid:
if self.creds and self.creds.expired and self.creds.refresh_token:
self.creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'/data/`credentials.json', self.scopes)
self.creds = flow.run_local_server(port=0)
with open('token.pickle', 'wb') as token:
pickle.dump(self.creds, token)

self.service = build('calendar', 'v3', credentials=self.creds)

def get_events(self, calendar_id='primary', time_min=None, time_max=None, max_results=10):
# Lógica para obtener eventos de Google Calendar
events_result = self.service.events().list(calendarId=calendar_id, timeMin=time_min,
timeMax=time_max, maxResults=max_results,
singleEvents=True, orderBy='startTime').execute()
return events_result.get('items', [])

def create_event(self, calendar_id='primary', event_data=None):
# Lógica para crear un nuevo evento en Google Calendar
event = self.service.events().insert(calendarId=calendar_id, body=event_data).execute()
return event
Loading