Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

I have to create a mini IoT Weather Station. I have 3 types of code that will be run in Visual Studio Code. First code:

I have to create a mini IoT Weather Station. I have 3 types of code that will be run in Visual Studio Code.
First code: main.py
#MQTT subscribe and toggle LED
from machine import Pin,reset,unique_id
from time import sleep
from ubinascii import hexlify
from umqttsimple import MQTTClient
from json import loads #change json data to python
client_id = hexlify(unique_id())
CLIENT_NAME = 'MAA-subscriber'
BROKER_ADDR = 'test.mosquitto.org'
apikey='syira'
topic=f'gpioms/{apikey}'
# mqttc = MQTTClient(CLIENT_NAME, BROKER_ADDR, keepalive=60)
mqttc = MQTTClient(client_id, BROKER_ADDR, keepalive=60)
mqttc.connect()
def ambil_gpio_data(topic, msg):
try:
json_data=msg.decode()
python_data=loads(json_data)
print(msg)
for data in python_data:
state=data['state']
gpiono=data['gpiono']
led=Pin(int(gpiono),Pin.OUT)
if state=="1":
led.on()
print(f"gpio no {gpiono} is on")
elif state=="0":
led.off()
print(f"gpio no {gpiono} is off")
except:
print("err.. there is some error")
# mqtt subscription
mqttc.set_callback(ambil_gpio_data)
mqttc.subscribe(topic.encode())
while True:
try:
mqttc.check_msg()
print('.')
except:
# print('Network problem ke?')
reset()
print()
sleep(10)
Second code: umqttsimple.py
try:
import usocket as socket
except:
import socket
import ustruct as struct
from ubinascii import hexlify
class MQTTException(Exception):
pass
class MQTTClient:
def __init__(self, client_id, server, port=0, user=None, password=None, keepalive=0,
ssl=False, ssl_params={}):
if port ==0:
port =8883 if ssl else 1883
self.client_id = client_id
self.sock = None
self.server = server
self.port = port
self.ssl = ssl
self.ssl_params = ssl_params
self.pid =0
self.cb = None
self.user = user
self.pswd = password
self.keepalive = keepalive
self.lw_topic = None
self.lw_msg = None
self.lw_qos =0
self.lw_retain = False
def _send_str(self, s):
self.sock.write(struct.pack("!H", len(s)))
self.sock.write(s)
def _recv_len(self):
n =0
sh =0
while 1:
b = self.sock.read(1)[0]
n |=(b & 0x7f)<< sh
if not b & 0x80:
return n
sh +=7
def set_callback(self, f):
self.cb = f
def set_last_will(self, topic, msg, retain=False, qos=0):
assert 0<= qos <=2
assert topic
self.lw_topic = topic
self.lw_msg = msg
self.lw_qos = qos
self.lw_retain = retain
def connect(self, clean_session=True):
self.sock = socket.socket()
addr = socket.getaddrinfo(self.server, self.port)[0][-1]
self.sock.connect(addr)
if self.ssl:
import ussl
self.sock = ussl.wrap_socket(self.sock, **self.ssl_params)
premsg = bytearray(b"\x10\0\0\0\0\0")
msg = bytearray(b"\x04MQTT\x04\x02\0\0")
sz =10+2+ len(self.client_id)
msg[6]= clean_session <<1
if self.user is not None:
sz +=2+ len(self.user)+2+ len(self.pswd)
msg[6]|=0xC0
if self.keepalive:
assert self.keepalive <65536
msg[7]|= self.keepalive >>8
msg[8]|= self.keepalive & 0x00FF
if self.lw_topic:
sz +=2+ len(self.lw_topic)+2+ len(self.lw_msg)
msg[6]|=0x4|(self.lw_qos & 0x1)<<3|(self.lw_qos & 0x2)<<3
msg[6]|= self.lw_retain <<5
i =1
while sz >0x7f:
premsg[i]=(sz & 0x7f)|0x80
sz >>=7
i +=1
premsg[i]= sz
self.sock.write(premsg, i +2)
self.sock.write(msg)
#print(hex(len(msg)), hexlify(msg,":"))
self._send_str(self.client_id)
if self.lw_topic:
self._send_str(self.lw_topic)
self._send_str(self.lw_msg)
if self.user is not None:
self._send_str(self.user)
self._send_str(self.pswd)
resp = self.sock.read(4)
assert resp[0]==0x20 and resp[1]==0x02
if resp[3]!=0:
raise MQTTException(resp[3])
return resp[2] & 1
def disconnect(self):
self.sock.write(b"\xe0\0")
self.sock.close()
def ping(self):
self.sock.write(b"\xc0\0")
def publish(self, topic, msg, retain=False, qos=0):
pkt = bytearray(b"\x30\0\0\0")
pkt[0]|= qos <<1| retain
sz =2+ len(topic)+ l

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

More Books

Students also viewed these Databases questions

Question

Define money and indicate the basic functions of money.

Answered: 1 week ago

Question

Do you think we should be comparing women and men? Why or why not?

Answered: 1 week ago

Question

How to reverse a Armstrong number by using double linked list ?

Answered: 1 week ago

Question

7. Define cultural space.

Answered: 1 week ago

Question

8. Describe how cultural spaces are formed.

Answered: 1 week ago