---
# System prepended metadata

title: Publish Client
tags: [python, mqtt, boards]

---

# Publish Client

###### tags: `mqtt` `python` `boards`

[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)


## Publish


Import library


```python=
from umqtt.simple import MQTTClient #According your library path 
import time
import ubinascii
import machine
import micropython
import network
import esp
```


### 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/messages'
```

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

#the time between each message setnt
messageInterval =1
```

### Connect to Wi-Fi

```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 successful')

```

### Create the client 

```pyth=
def connectMqtt():  
  
  global clientID, mqttBroker
  
  #Conner to MQTT broker  
  client = MQTTClient(clientID, mqttBroker, port=port, user='test', password='test')
  client.connect()
  print(f'connect to {mqttBroker} MqttBroker')
  
  
  return client
```


## Final code
```python=
#Mqtt main libary 
from umqtt.simple import MQTTClient

import time
import ubinascii
import machine
import micropython
import network
import esp
#from bme680 import *
#from machine import Pin, I2C


networkName = 'zsystem'
networkPassword = 'zang670623'

mqttBroker='122.117.14.208'
port=3390

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

#create topic 

publishMessagesTopic = b'meowhecker/messages'

#Hold the last message before you sent  
lastMessage = 0

#the time between each message setnt
messageInterval =1

#Connet the ESP to your local network

station = network.WLAN(network.STA_IF)

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

while station.isconnected() == False:
  print("Wait to connect")
  time.sleep(2)
print('connect successful')


#connect to MQTT broker
def connectMqtt():  
  
  global clientID, mqttBroker
  
  #Establish client  
  client = MQTTClient(clientID, mqttBroker, port=port, user='test', password='test')
  client.connect()
  print(f'connect to {mqttBroker} MqttBroker')
  
  
  return client
  
#Restart and Reconnect
def reconnect():
  print('Reconnecting...')
  time.sleep(5)
  machine.reset()
  
try:
  client = connectMqtt()
  #print(1)
except OSError as e:
  reconnect()


while True:
  
  client.publish(publishMessagesTopic,b'阿晟好帥')  #publish message
  time.sleep(1)
  
  #print(1)
```

### Result 

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


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


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

receive message : 阿晟好帥


