Created
November 30, 2018 09:43
-
-
Save SLAAMER/3a054816a4e7a8c54bb4d1cbebda9b33 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import paho.mqtt.client as mqttClient | |
import requests | |
import serial | |
import json | |
import os | |
arduino = serial.Serial() | |
arduino.port = '/dev/ttyACM0' | |
arduino.baudrate = 9600 | |
arduino.open() | |
dispenserId = 4 | |
host="dsd-api.herokuapp.com" | |
def dispense(result): | |
try: | |
jsonDict = json.loads(result) | |
print(jsonDict) | |
# Activar motor | |
pussy = jsonDict['motor'] | |
arduino.write(bytes(pussy, 'utf-8')) | |
# # guardar en bd | |
payload = dict(quantity=1) | |
url = 'http://{}/api/v1/dispenser/{}/item/{}/dispense'.format(host, jsonDict['dispenser'], jsonDict['item']) | |
print(url) | |
response = requests.post(url, data=payload) | |
if(response.status_code == 200): | |
print(response.json()) | |
except Exception as e: | |
print("Error en algo: " + str(e)) | |
def on_connect(client, userdata, flags, rc): | |
if rc == 0: | |
print("connected OK Returned code=", rc) | |
else: | |
print("Bad connection Returned code=", rc) | |
def on_subscribe(client, userdata, mid, granted_qos): | |
print("subscrito") | |
def on_message(client, userdata, message): | |
#print("mensaje: ", str(message.payload.decode("utf-8"))) | |
result = str(message.payload.decode("utf-8")) | |
dispense(result) | |
class MQTT: | |
hostname = "test.mosquitto.org" | |
port = 8080 | |
client = mqttClient.Client(transport='websockets') | |
def __init__(self, **kwargs): | |
self.client.on_connect = on_connect | |
self.client.on_subscribe = on_subscribe | |
self.client.on_message = on_message | |
self.client.connect(self.hostname, port=self.port) | |
print("conectado a: ", self.hostname, " en puerto: ", self.port) | |
self.client.loop_start() | |
def subscribe(self, topic): | |
print("subscrito en: " + topic) | |
self.client.subscribe(topic, 2) | |
def publish(self, topic, payload): | |
self.client.publish(topic, payload=payload, qos=2) | |
print("Publishing to " + topic) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment