We use NodeMCU (ESP8266) ,a micro-controller chip , it includes on-board Wi-Fi. sensors are connected to this NodeMCU .
Pre-requisite to use NodeMCU -
Python is one of the most widely used, simple and easy-to-learn programming languages around. So, the emergence of MicroPython makes it extremely easy and simple to program digital electronics. If you’ve never programmed digital electronics before, MicroPython is a good starting point.
I'm using the esp8266-12 version board. To install micropython you will need esptool you will need to download and install python and pip, to install the esptool.
Run the below command on a terminal or cmd to install esptool
Next you can visit micropython website and download the latest firmware for the esp8266, after downloading it open up a terminal in the same directory as the firmware file and then run the below command
You will need to change the port based on you PC.
After this you should have successfully installed micropython.
Sensor code :
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import utime
import time
import json
import machine
import network
from umqtt.robust import MQTTClient
from hcsr04 import HCSR04
sensor1 = HCSR04(trigger_pin=5, echo_pin=4, echo_timeout_us=10000)
sensor2 = HCSR04(trigger_pin=14, echo_pin=12, echo_timeout_us=10000)
machine.Pin(13, machine.Pin.OUT).off()
machine.Pin(15, machine.Pin.OUT).off()
#################
def blinkLed(number):
led = machine.Pin(number, machine.Pin.OUT)
for i in range(3):
led.on()
time.sleep(0.5)
led.off()
time.sleep(0.5)
###############
def TaskTwo():
blinkLed(13)
changeStatus2 = False
while True:
machine.Pin(13, machine.Pin.OUT).on()
print("Slot 2 thread running")
distance2 = sensor2.distance_cm()
machine.Pin(13, machine.Pin.OUT).off()
if distance2 > 1 and distance2 < 10:
if not changeStatus2:
currentTime = time.time()
send_Two("BLOCK")
changeStatus2 = True
print('object in Slot 2 at:', distance2, 'cm')
else:
if changeStatus2:
send_Two("RELEASE")
changeStatus2 = False
yield None
utime.sleep(2)
def send_Two(t):
print('Slot 2 thread : sending message', t)
payload = {"Slot": "2", "status": t}
sta_if = network.WLAN(network.STA_IF)
if not sta_if.isconnected():
print('No network conencted , connecting to network...')
sta_if.active(True)
sta_if.connect('RailWire1', '8drowssap')
while not sta_if.isconnected():
pass
c = MQTTClient('send_Two', 'iot.eclipse.org')
c.connect()
c.publish('aaaparking/Slotsensor', json.dumps(payload))
blinkLed(13)
print('Slot 2 thread : message sent')
c.disconnect()
#################
def send_One(t):
print('Slot 1 thread : sending message', t)
payload = {"Slot": "1", "status": t}
sta_if = network.WLAN(network.STA_IF)
if not sta_if.isconnected():
print('No network conencted , connecting to network...')
sta_if.active(True)
sta_if.connect('RailWire1', '8drowssap')
while not sta_if.isconnected():
pass
c = MQTTClient('send_One', 'iot.eclipse.org')
c.connect()
c.publish('aaaparking/Slotsensor', json.dumps(payload))
blinkLed(15)
print('Slot 1 thread : message sent')
c.disconnect()
def TaskOne():
blinkLed(15)
changeStatus1 = False
while True:
machine.Pin(15, machine.Pin.OUT).on()
print("Slot 1 thread : running")
distance1 = sensor1.distance_cm()
machine.Pin(15, machine.Pin.OUT).off()
if distance1 > 1 and distance1 < 10:
if not changeStatus1:
currentTime = time.time()
send_One("BLOCK")
changeStatus1 = True
print('object in Slot 1 at :', distance1, 'cm')
else:
if changeStatus1:
send_One("RELEASE")
changeStatus1 = False
yield None
utime.sleep(2)
#################
TaskQueue = [TaskOne(), TaskTwo()]
while True:
for task in TaskQueue:
next(task)
2. MQTT Code:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import machine
import time
import urequests
import json
import network
from umqtt.robust import MQTTClient
print("main class running")
url = "https://iotmmsp1942289005trial.hanatrial.ondemand.com/com.sap.iotservices.mms/v1/api/http/data/2fb8bd57-78d4-4027-a204-6801009e6c9c"
headers = {'Authorization': 'Bearer ' + '711f4cdfd921cecc225f2f518ed2294',
'content-type': 'application/json;charset=utf-8'}
machine.Pin(13, machine.Pin.OUT).off()
machine.Pin(12, machine.Pin.OUT).off()
machine.Pin(5, machine.Pin.OUT).off()
machine.Pin(4, machine.Pin.OUT).off()
#################
def blinkLed(number):
led = machine.Pin(number, machine.Pin.OUT)
for i in range(3):
led.on()
time.sleep(0.5)
led.off()
time.sleep(0.5)
#################
def callback(topic, message):
print(topic, message)
d = {}
if topic == b'aaaparking/Slotsensor':
try:
d = json.loads(message)
except:
print("exception in reading json message")
if d['Slot'] and d['Slot'] == '1':
currentTime = time.time()
if d['status'] == "BLOCK":
data = '{"mode":"async", "messageType":"10ccc49a94008d1bd292", "messages":[{"slotNumber":1, "status":"%s", "startTime":%d, "endTime":%d, "duration":%d}]}' % (
"BLOCK", currentTime, 0, 0)
resp = urequests.post(url, data=data, headers=headers)
print(resp.json())
if resp.status_code == 202:
blinkLed(4)
print("Slot 1 callback : publishing ack")
client.publish("aaaparking/Slotsensor/ack", 'BLOCK_ONE')
if d['status'] == "RELEASE":
data = '{"mode":"async", "messageType":"10ccc49a94008d1bd292", "messages":[{"slotNumber":1, "status":"%s", "startTime":%d, "endTime":%d, "duration":%d}]}' % (
"RELEASE", 0, currentTime, 0)
resp = urequests.post(url, data=data, headers=headers)
print(resp.json())
if resp.status_code == 202:
blinkLed(4)
print("Slot 1 callback : publishing ack")
client.publish("aaaparking/Slotsensor/ack", 'RELEASE_ONE')
print("Slot 1 callback completed")
elif d['Slot'] and d['Slot'] == '2':
currentTime = time.time()
if d['status'] == "BLOCK":
data = '{"mode":"async", "messageType":"10ccc49a94008d1bd292", "messages":[{"slotNumber":2, "status":"%s", "startTime":%d, "endTime":%d, "duration":%d}]}' % (
"BLOCK", currentTime, 0, 0)
resp = urequests.post(url, data=data, headers=headers)
print(resp.json())
if resp.status_code == 202:
blinkLed(4)
print("Slot 2 callback : publishing ack")
client.publish("aaaparking/Slotsensor/ack", 'BLOCK_TWO')
if d['status'] == "RELEASE":
data = '{"mode":"async", "messageType":"10ccc49a94008d1bd292", "messages":[{"slotNumber":2, "status":"%s", "startTime":%d, "endTime":%d, "duration":%d}]}' % (
"RELEASE", 0, currentTime, 0)
resp = urequests.post(url, data=data, headers=headers)
print(resp.json())
if resp.status_code == 202:
blinkLed(4)
print("Slot 2 callback : publishing ack")
client.publish("aaaparking/Slotsensor/ack", 'RELEASE_TWO')
print("Slot 2 callback completed")
#################
elif topic == b'aaaparking/Slotsensor/ack':
if message == b'BLOCK_ONE':
print('MQTT thread : ack received : BLOCK_ONE ')
machine.Pin(13, machine.Pin.OUT).on() # because of RGB used, need to change
elif message == b'RELEASE_ONE':
print('MQTT thread : ack received : RELEASE_ONE ')
machine.Pin(13, machine.Pin.OUT).off()
elif message == b'BLOCK_TWO':
print('MQTT thread : ack received : BLOCK_TWO ')
machine.Pin(12, machine.Pin.OUT).on()
elif message == b'RELEASE_TWO':
print('MQTT thread : ack received : RELEASE_TWO ')
machine.Pin(12, machine.Pin.OUT).off()
#################
sta_if = network.WLAN(network.STA_IF)
if not sta_if.isconnected():
print('No network conencted , connecting to network...')
sta_if.active(True)
sta_if.connect('RailWire1', '8drowssap')
while not sta_if.isconnected():
pass
print("Connecting to client...")
client = MQTTClient("receive", 'iot.eclipse.org')
client.set_callback(callback)
client.connect()
print("Client Connected")
blinkLed(5)
client.subscribe('aaaparking/Slotsensor/ack')
client.subscribe('aaaparking/Slotsensor')
while True:
machine.Pin(5, machine.Pin.OUT).on()
print("MQTT thread running")
client.check_msg()
machine.Pin(5, machine.Pin.OUT).off()
time.sleep(4)
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
User | Count |
---|---|
5 | |
5 | |
5 | |
4 | |
4 | |
4 | |
3 | |
3 | |
3 | |
3 |