Advertisement
Guest User

Untitled

a guest
Sep 13th, 2017
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.51 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.   topic = topic.decode("ascii")
  44.  
  45.   if topic == AIR_TOPIC and message == 'on' :
  46.     turn_on()
  47.   else:
  48.     turn_off()
  49.  
  50.  
  51. simple_scheduler_timer = time.time()
  52.  
  53. def scheduler_tick(period=1):
  54.   global timesimple_scheduler_timer
  55.  
  56.   if time.time() - timesimple_scheduler_timer < period:
  57.     return False
  58.  
  59.   simple_scheduler_timer = time.time()
  60.  
  61.   return True
  62.  
  63.  
  64. def main():
  65.   mqtt.set_callback(onmessage)
  66.   mqtt.connect()
  67.   mqtt.subscribe(WILDCARD_TOPIC)
  68.  
  69.   while True:
  70.     mqtt.check_msg()
  71.     if scheduler_tick():
  72.       mqtt.publish(SENSOR_TOPIC, str(sensor_value()))
  73.     time.sleep(1000)
  74.     mqtt.publish(PING_TOPIC, "iamalive")
  75.     beep()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement