Skip to content

Instantly share code, notes, and snippets.

@RWaltersMA
Last active September 3, 2018 23:58
Show Gist options
  • Save RWaltersMA/c7ca51ad55e332e41be84ec5450520f6 to your computer and use it in GitHub Desktop.
Save RWaltersMA/c7ca51ad55e332e41be84ec5450520f6 to your computer and use it in GitHub Desktop.
Main.py file for Implementing an end-to-end IoT Solution in MongoDB. Used with NodeMCU and MicroPython
from umqtt.simple import MQTTClient
import network
import machine
import time
import socket
import utime
ssid=#Put your SSID name here
pwd=#Put your WiFi password here
device_name='TempSensor1' #Put the name of the device here
mqqt_server=#Put the IP address of your MQTT
mqqt_port=1883 #Change if needed, default port for MQQT
# **** Set variables and define functions that support grabbing current time from an NTP server
# borrowed from https://github.com/micropython/micropython/blob/master/ports/esp8266/modules/ntptime.py
# (date(2000, 1, 1) - date(1900, 1, 1)).days * 24*60*60
NTP_DELTA = 3155673600
host="pool.ntp.org"
try:
import usocket as socket
except:
import socket
try:
import ustruct as struct
except:
import struct
def time():
NTP_QUERY = bytearray(48)
NTP_QUERY[0] = 0x1b
addr = socket.getaddrinfo(host, 123)[0][-1]
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(1)
res = s.sendto(NTP_QUERY, addr)
msg = s.recv(48)
s.close()
val = struct.unpack("!I", msg[40:44])[0]
return val - NTP_DELTA
def settime():
t = time()
import machine
import utime
tm = utime.localtime(t)
tm = tm[0:3] + (0,) + tm[3:6] + (0,)
machine.RTC().datetime(tm)
def do_connect():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('connecting to ' + ssid)
wlan.connect(ssid, pwd)
while not wlan.isconnected():
pass
print('network config:', wlan.ifconfig())
settime()
print('current time=%s' % (machine.RTC().datetime(),))
def start_sampling():
client = MQTTClient(device_name, mqqt_server,mqqt_port)
client.connect()
adc = machine.ADC(0)
i=adc.read()
c=(i/10)
f = (c * (9/5)) + 32
#Note: message contents are the value in F and time in unix timestamp
d=machine.RTC().datetime()
s='{ "device":"' + str(device_name) + '","value": ' + str(f) + ', "time":"' + str(d) + '"}'
client.publish('/iotdemo/temp',s)
client.disconnect()
def set_led(v):
led = machine.Pin(5, machine.Pin.OUT)
if v==1:
led.on()
else:
led.off()
do_connect()
while True:
set_led(1)
start_sampling()
set_led(0)
utime.sleep(5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment