Advertisement
Guest User

Untitled

a guest
Sep 13th, 2017
125
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.   global _sensor_value
  22.   _sensor_value = (_sensor_value * (WEIGHT - 1) + ADC(0).read()) / WEIGHT
  23.  
  24.   return _sensor_value
  25.  
  26.  
  27. def turn_on():
  28.   pin1(0)
  29.   pin2(1)
  30.  
  31.  
  32. def turn_off():
  33.   pin1(0)
  34.   pin2(0)
  35.  
  36. def beep(duty=512, period=100):
  37.   beep.duty(duty)
  38.   time.sleep_ms(period)
  39.   beep.duty(0)
  40.  
  41. def onmessage(topic, message):
  42.   message = message.decode("ascii")
  43.  
  44.   if topic == AIR_TOPIC and message == 'on' :
  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")
  74.     beep()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement