---
# System prepended metadata

title: Subscribe
tags: [esp32, python, mqtt]

---

# Subscribe

###### tags: `python` `esp32` `mqtt`

[Reference Document](https://randomnerdtutorials.com/micropython-mqtt-publish-bme680-esp32-esp8266/)

##MQTT Broker 
[Link](https://chrome.google.com/webstore/detail/mqttlens/hemojaaeigabkbcookmlgmdigohjobjm?hl=zh-TW)

## Upload MQTT library 


 Upload library with uPyCraft IDE 




[Reference Document](https://randomnerdtutorials.com/flash-upload-micropython-firmware-esp32-esp8266/)

[ESp32 library download](https://micropython.org/download/esp32/)

![](https://i.imgur.com/iW55G1v.png)

## Subscribe 

## Boot

Config initial information

### Import libraries 

```pytho=
from umqtt.simple import MQTTClient
import time
import ubinascii
import machine
import micropython
import network
import esp
```

### Set debug to None

```pytho=
esp.osdebug(None) #debug = None

import gc    #garbage collector 
gc.collect()
```

### Set network variables 

```python=
networkName = 'networkName'
networkPassword = 'networkPassword'


#mqttServer
mqttBroker='mqttserver '
port=3390  #optional 

```

### Unique ID 
Unique id, it's used to MQTT Broker to distinguish devices 

```python=
client_id = ubinascii.hexlify(machine.unique_id())
```


### Topic 

set topic path 
```pytho=
publishMessagesTopic  = b'meowhecker/public/messages'
subscribeMessageTopic = b'meowhecker/subscribe/messages'
```



### Config messages
```pyt=
#Hold the last message before you sent  
lastMessage = 0

#the time between each message setnt
messageInterval =3

conunt=0    #counter to be added to the message
```


### Connect to the internet 

```python=
station = network.WLAN(network.STA_IF)

station.active(True)
station.connect(networkName, networkPassword)

while station.isconnected() == False:
  print("Disconnect")
  time.sleep(1)
print('connect successfully')
print(station.ifconfig()) #show network information 
```

### main

Creating a callback function that will run whenever a message is published on a topic the ESP is subscribed to


#### callback
```python=
def subscribeCallback(subTopic ,messages):
  print((subToptic, messages))
  print(1)
  if subTopic != "" and messages !="":
    print("esp received messages")
    
```


check_msg


The check_msg() method checks whether a pending message from the server is available.


### 
Connecte broker as well as to subscribe to a topic



```python=
def brokerConnectSubscribe():
  global clientID, mqttBroker, subscribeMessageTopic
  
  client = MQTTClient(clientID, mqttBroker, port=port, user='test', password='test')
  client.set_callback(subscribeCallback)
  
  #client connect to broker 
  client.connect()
  
  #subscribe to topic
  client.subscribe(subscribeMessageTopic)
  
  print(f'connect to Broker {mqttBroker} , Subscribe to {subscribeMessageTopic}')
  return client 
```







old Code
```python=

#Mqtt main libary 
from umqtt.simple import MQTTClient

import time
import ubinascii
import machine
import micropython
import network

import esp
esp.osdebug(None)

import gc
gc.collect()


#Network account password 
ssid = 'zsystem'
password = 'zang670623'


#mqtt server 
mqtt_server = '122.117.14.208'
port = 3390

client_id = ubinascii.hexlify(machine.unique_id())
topic_sub = b'meowhecker/message'


#mqtt:account/password 
user = 'test'
mqttpassword = 'test'


last_message = 0
message_interval = 5 #time between each message sent
counter = 0


#Connect the ESP to the network
station = network.WLAN(network.STA_IF)
station.active(True)
station.connect(ssid, password)

while station.isconnected() == False:
  pass

print('Connection successful')


print(station.ifconfig())



# print Chinese
def printChinese(msg):
  print(str(msg.decode('utf-8')))

def sub_cb(topic, msg):
  print((topic, msg))
  printChinese(msg)

def connect_and_subscribe():
  global client_id, mqtt_server, topic_sub
  client = MQTTClient(client_id, mqtt_server,port=port,user=user,password=mqttpassword)
  client.set_callback(sub_cb)
  client.connect()
  client.subscribe(topic_sub)
  print('Connected to %s MQTT broker, subscribed to %s topic' % (mqtt_server, topic_sub))
  return client



def restart_and_reconnect():
  print('Failed to connect to MQTT broker. Reconnecting...')
  time.sleep(10)
  machine.reset()


try:
  client = connect_and_subscribe()
  print(1)
except OSError as e:
  restart_and_reconnect()


while True:
    
  try:
    client.check_msg()
    if (time.time() - last_message) > message_interval:
      msg = b'Hello #%d' % counter
#       client.publish(topic_pub, "zzzz")
      last_message = time.time()
      counter += 1
  except OSError as e:
    restart_and_reconnect()

```
new code 

```py=

import time
from umqtt.simple import MQTTClient
import ubinascii
import machine
import micropython
import network

import esp
esp.osdebug(None)
import gc
gc.collect()

networkName = 'zsystem'
networkPassword = 'zang670623'


mqttBroker='122.117.14.208'
port=3390


clientID = ubinascii.hexlify(machine.unique_id())

publishMessagesTopic  = b'meowhecker/public/messages'
subscribeMessageTopic = b'meowhecker/subscribe/messages'

lastMessage = 0
messageInterval = 5
counter = 0

station = network.WLAN(network.STA_IF)

station.active(True)
station.connect(networkName, networkPassword)

while station.isconnected() == False:
  print("Disconnect")
  time.sleep(1)
print('connect successfully')
print(station.ifconfig()) #show network information 





#main()
#CallbackFunction
def subscribeCallback(topic, msg):
  print((topic, msg))

    
    
#Connecte broker as well as to subscribe to a topic
def brokerConnectSubscribe():
  global clientID, mqttBroker, subscribeMessageTopic
  
  client = MQTTClient(clientID, mqttBroker, port=port, user='test', password='test')
  client.set_callback(subscribeCallback)
  
  #client connect to broker 
  client.connect()
  
  #subscribe to topic
  client.subscribe(subscribeMessageTopic)
  
  print(f'connect to Broker {mqttBroker} , Subscribe to {subscribeMessageTopic}')
  return client 
 
#Restart and Reconnect

def restartAndReconnect():
  print('Reconnecting...')
  time.sleep(5)
  machine.reset()

#Handler


try:
  client = brokerConnectSubscribe()
  #print(1)
except OSError as e:
  print("false")
  #restartAndReconnect()




while True:
  a=1
  #print(1)
#send messages to subscribes 

#while True:
#  try:
#    client.check_msg()
#    if(time.time() - lastMessage) > messageInterval:
#      messages=f'sendMessage, messageConter {counter}'
#      client.publich(publishMessagesTopic, messages)
#      lastMessage = time.time()
#      counter ++
#  except OSError as e:
#    restartAndReconnect()
#

```


Result

![](https://i.imgur.com/NGbKvFo.png)

![](https://i.imgur.com/0IAb744.png)









