Advertisement
Guest User

Untitled

a guest
Sep 13th, 2017
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.48 KB | None | 0 0
  1. import ubinascii, umqtt.robust as MQTTClient, time, math
  2. from machine import Pin, ADC, unique_id
  3.  
  4. pin1 = Pin(4, Pin.OUT)
  5. pin2 = Pin(15, Pin.OUT)
  6. pin3 = Pin(14, Pin.OUT)
  7. pin4 = Pin(12, Pin.OUT)
  8.  
  9. WEIGHT = 10
  10. WILDCARD_TOPIC = b"g11/#"
  11. AIR_TOPIC = b"g11/air"
  12. SENSOR_TOPIC = b"g11/sensor"
  13. PING_TOPIC = b"g11/ping"
  14.  
  15. CLIENT_ID = ubinascii.hexlify(unique_id())
  16. mqtt = MQTTClient.MQTTClient(CLIENT_ID, "broker.mqtt-cpe.ml", user="None", password="None")
  17.  
  18. _sensor_value = 0
  19.  
  20. def sensor_value():
  21.   _sensor_value = (_sensor_value * (WEIGHT - 1) + ADC(0).read()) / WEIGHT
  22.  
  23.   return _sensor_value
  24.  
  25.  
  26. def turn_on():
  27.   pin1(0)
  28.   pin2(1)
  29.  
  30.  
  31. def turn_off():
  32.   pin1(0)
  33.   pin2(0)
  34.  
  35. def beep(duty=512, period=100):
  36.   beep.duty(duty)
  37.   time.sleep_ms(period)
  38.   beep.duty(0)
  39.  
  40. def onmessage(topic, message):
  41.   message = message.decode("ascii")
  42.   topic = topic.decode("ascii")
  43.  
  44.   if topic == AIR_TOPIC and message == '1' :
  45.     turn_on()
  46.   else:
  47.     turn_off()
  48.  
  49.  
  50. simple_scheduler_timer = time.time()
  51.  
  52. def scheduler_tick(period=1):
  53.   global timesimple_scheduler_timer
  54.  
  55.   if time.time() - timesimple_scheduler_timer < period:
  56.     return False
  57.  
  58.   simple_scheduler_timer = time.time()
  59.  
  60.   return True
  61.  
  62.  
  63. def main():
  64.   mqtt.set_callback(onmessage)
  65.   mqtt.connect()
  66.   mqtt.subscribe(WILDCARD_TOPIC)
  67.  
  68.   while True:
  69.     mqtt.check_msg()
  70.     if scheduler_tick():
  71.       mqtt.publish(SENSOR_TOPIC, str(sensor_value()))
  72.     time.sleep(1000)
  73.     mqtt.publish(PING_TOPIC, "iamalive")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement