lazar00

main.py

May 20th, 2018
500
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import dht
  2. import machine
  3. import time
  4. import network
  5. from simple import MQTTClient
  6. from machine import Timer
  7. # from umqtt_simple import MQTTClient
  8. def blink():
  9.     led.off()
  10.     time.sleep(0.1)
  11.     led.on()
  12.     time.sleep(0.1)
  13.     led.off()
  14.     time.sleep(0.1)
  15.     led.on()
  16. isLedOn = False
  17.  
  18. # Modify below section as required
  19. CONFIG = {
  20.      # Configuration details of the MQTT broker
  21.      "MQTT_BROKER": "192.168.1.6",
  22.      "USER": "",
  23.      "PASSWORD": "",
  24.      "PORT": 1883,
  25.      "TOPIC1": "/room/light",
  26.      "TOPIC2": "/dnevna/led",
  27.      # unique identifier of the chip
  28.      "CLIENT_ID": b"esp8266_lazar"
  29. }
  30.  
  31.  
  32.  
  33. #Create an instannt(CONFIG['CLIENT_ID'], CONFIG['MQTT_BROKER'], user=CONFIG['USER'], password=CONFIG['PASSWORD'], port=CONFIG['PORT'])
  34.  
  35.  
  36. def onMessage(topic, msg):
  37.    print("msg:"+msg.decode('UTF-8'))
  38.    message = str(msg.decode('UTF-8'))
  39.    topicStr=str(topic.decode('UTF-8'))
  40.    if(topicStr == "/dnevna/led"):
  41.        if(message == "on"):
  42.            led.off()
  43.            global isLedOn = True
  44.            print("LED ON")
  45.            client.publish("/dnevna/ledStatus", str(isLedOn))
  46.        elif(message == "off"):
  47.            print("LED OFF")
  48.            led.on()
  49.            global isLedOn = False
  50.            client.publish("/dnevna/ledStatus", str(isLedOn))
  51.        else:
  52.            print("command not found")
  53.            client.publish("/dnevna/status","command not found...")
  54.  
  55. def listen():
  56.     # Attach call back handler to be called on receiving messages
  57.     client.set_callback(onMessage)
  58.     client.connect()
  59.     client.subscribe(CONFIG['TOPIC1'])
  60.     client.subscribe(CONFIG['TOPIC2'])
  61.     # client.subscribe("/dnevna/led")
  62.     print("ESP8266 is Connected to %s and subscribed to %s topic" % (CONFIG['MQTT_BROKER'], CONFIG['TOPIC1']))
  63.     print("ESP8266 is Connected to %s and subscribed to %s topic" % (CONFIG['MQTT_BROKER'], CONFIG['TOPIC2']))
  64.     blink()
  65.  
  66.  
  67.  
  68. REBOOT_TIMEOUT = 86400000
  69. tim = Timer(-1)
  70. #import webrepl_setup
  71.  
  72. sta_if = network.WLAN(network.STA_IF)
  73. print("connecting to network, please wait...")
  74. sta_if.active(True)
  75. sta_if.connect('mw-net', 'Kravataokovrata')
  76. time.sleep(1)
  77.  
  78. led = machine.Pin(2, machine.Pin.OUT)
  79. sensor = dht.DHT22(machine.Pin(16))
  80.  
  81. led.off()
  82. time.sleep(1)
  83. led.on()
  84. time.sleep(1)
  85. try:
  86.     listen()
  87. except:
  88.     tim.init(period=1000, mode=Timer.PERIODIC, callback=lambda t:machine.reset())
  89. tim.init(period=REBOOT_TIMEOUT, mode=Timer.PERIODIC, callback=lambda t:machine.reset())
  90.  
  91.  
  92.  
  93. if(sta_if.isconnected()):
  94.     print("connected!")
  95.     print(sta_if.ifconfig())
  96.     while True:
  97.         try:
  98.             sensor.measure()
  99.             print("TEMP: "+ str(sensor.temperature()))
  100.             print("HUM: "+ str(sensor.humidity()))
  101.             client.check_msg()
  102.             time.sleep(0.5)
  103.             client.publish("/dnevna/temp",str(sensor.temperature()))
  104.             client.publish("/dnevna/hum",str(sensor.humidity()))
  105.             time.sleep(2)
  106.             #message1=0;
  107.         except Exception as e:
  108.             print(e)
  109.  
  110. else:
  111.     while (not sta_if.isconnected()):
  112.         print("connection failure, trying to reconnect...")
  113.         sta_if.active(True)
  114.         sta_if.connect('mw-net', 'Kravataokovrata')
  115.         time.sleep(1)ce of MQTTClient
  116. client = MQTTClient(CONFIG['CLIENT_ID'], CONFIG['MQTT_BROKER'], user=CONFIG['USER'], password=CONFIG['PASSWORD'], port=CONFIG['PORT'])
  117.  
  118.  
  119. def onMessage(topic, msg):
  120.    print("msg:"+msg.decode('UTF-8'))
  121.    message = str(msg.decode('UTF-8'))
  122.    topicStr=str(topic.decode('UTF-8'))
  123.    if(topicStr == "/dnevna/led"):
  124.        if(message == "on"):
  125.            led.off()
  126.            isLedOn = True
  127.            print("LED ON")
  128.            client.publish("/dnevna/ledStatus", str(isLedOn))
  129.        elif(message == "off"):
  130.            print("LED OFF")
  131.            led.on()
  132.            isLedOn = False
  133.            client.publish("/dnevna/ledStatus", str(isLedOn))
  134.        else:
  135.            print("command not found")
  136.            client.publish("/dnevna/status","command not found...")
  137.  
  138. def listen():
  139.     # Attach call back handler to be called on receiving messages
  140.     client.set_callback(onMessage)
  141.     client.connect()
  142.     client.subscribe(CONFIG['TOPIC1'])
  143.     client.subscribe(CONFIG['TOPIC2'])
  144.     # client.subscribe("/dnevna/led")
  145.     print("ESP8266 is Connected to %s and subscribed to %s topic" % (CONFIG['MQTT_BROKER'], CONFIG['TOPIC1']))
  146.     print("ESP8266 is Connected to %s and subscribed to %s topic" % (CONFIG['MQTT_BROKER'], CONFIG['TOPIC2']))
  147.     blink()
  148.  
  149.  
  150.  
  151. REBOOT_TIMEOUT = 86400000
  152. tim = Timer(-1)
  153. #import webrepl_setup
  154.  
  155. sta_if = network.WLAN(network.STA_IF)
  156. print("connecting to network, please wait...")
  157. sta_if.active(True)
  158. sta_if.connect('mw-net', 'Kravataokovrata')
  159. time.sleep(1)
  160.  
  161. led = machine.Pin(2, machine.Pin.OUT)
  162. sensor = dht.DHT22(machine.Pin(16))
  163.  
  164. led.off()
  165. time.sleep(1)
  166. led.on()
  167. time.sleep(1)
  168. try:
  169.     listen()
  170. except:
  171.     tim.init(period=1000, mode=Timer.PERIODIC, callback=lambda t:machine.reset())
  172. tim.init(period=REBOOT_TIMEOUT, mode=Timer.PERIODIC, callback=lambda t:machine.reset())
  173.  
  174.  
  175.  
  176. if(sta_if.isconnected()):
  177.     print("connected!")
  178.     print(sta_if.ifconfig())
  179.     while True:
  180.         try:
  181.             sensor.measure()
  182.             print("TEMP: "+ str(sensor.temperature()))
  183.             print("HUM: "+ str(sensor.humidity()))
  184.             client.check_msg()
  185.             time.sleep(0.5)
  186.             client.publish("/dnevna/temp",str(sensor.temperature()))
  187.             client.publish("/dnevna/hum",str(sensor.humidity()))
  188.             time.sleep(2)
  189.             #message1=0;
  190.         except Exception as e:
  191.             print(e)
  192.  
  193. else:
  194.     while (not sta_if.isconnected()):
  195.         print("connection failure, trying to reconnect...")
  196.         sta_if.active(True)
  197.         sta_if.connect('mw-net', 'Kravataokovrata')
  198.         time.sleep(1)
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×