Internet of Things/Testprogramma MQTT

Uit Lab
< Internet of Things
Versie door Eelco (overleg | bijdragen) op 4 jun 2015 om 12:08 (Nieuwe pagina aangemaakt met 'import time import grovepi import grove_barometer_lib import paho.mqtt.client as mqtt led = 4 # led-relais op grovepi D4 valve = 3 # klep-relais op grovepi ...')
(wijz) ← Oudere versie | Huidige versie (wijz) | Nieuwere versie → (wijz)
Naar navigatie springen Naar zoeken springen

import time import grovepi import grove_barometer_lib import paho.mqtt.client as mqtt

led = 4 # led-relais op grovepi D4 valve = 3 # klep-relais op grovepi D3 valveOn = 1 # klep aan (initieel) ledOn = 0 # lamp uit (initeel)

moisturePin = 0 # grovepi A0

  1. barometer op grovepi I2C-2

now = 0

grovepi.pinMode(led, "OUTPUT") grovepi.pinMode(valve, "OUTPUT")

    1. MQTT Callbacks

def on_connect(client, userdata, flags, rc):

   if rc != 0:
       print "Connection failed. RC: {}".format(rc)
   else:
       print "Connected successfully"

def on_publish(client, userdata, mid):

   print "Message {} published.".format(mid)

def on_disconnect(client, userdata, rc):

   if rc != 0:
       print "Client disconnected unexpectedly, trying to reconnect."
       hasDisconnected = True
       mqttClient.reconnect()

def init_mqtt():

   mqttClient = mqtt.Client("testClient123") # je eigen ID
   mqttClient.on_connect = on_connect
   mqttClient.on_publish = on_publish
   mqttClient.on_disconnect = on_disconnect
   mqttClient.loop_start()
   mqttClient.connect("129.168.178.130", 1883) # local: 129.168.178.130, global: 82.161.55.218

def send_sensordata(sensorValues):

   mqttClient.publish("test/123", json.dumps(sensorValues))

sensorValues = dict()

  1. The main loop:

while True:

 try:
   print("hi")
   b = grove_barometer_lib.barometer()
   print("Pressure: " + str(b.pressure) + " temperature: " + str(b.temperature))
   sensorValues["Pressure"] = b.pressure
   sensorValues["Temperature"] = b.temperature
   moisture = grovepi.analogRead(moisturePin)
   print("Moisture: " + str(moisture))
   sensorValues["Moisture"] = moisture
   send_sensordata(sensorValues)
   # grovepi.digitalWrite(led, ledOn)
   # ledOn = 1 - ledOn
   # grovepi.digitalWrite(valve, valveOn)
   # valveOn = 1 - valveOn
   time.sleep(10)
   now += 10
 except KeyboardInterrupt:
   # reset outputs
   grovepi.digitalWrite(led, 0)
   grovepi.digitalWrite(valve, 0)
   break
 except IOError:
   print("error")