<jupyter_start><jupyter_text>W05-1 : MQTT- 控制設備----  push message to control<jupyter_code># push mqtt msg

import paho.mqtt.client as mqtt
import time, json, datetime, sys, os
import random

def on_connect(client, userdata, flags, rc):
    m="Connected flags"+str(flags)+", result code "+str(rc)+", client_id  "+str(client)
    print(m)

# some online free broker:
#   iot.eclipse.org
#   test.mosquitto.org
#   broker.hivemq.com
broker_address = "broker.hivemq.com"
broker_port = 1883

client1 = mqtt.Client()    #create new instance
client1.on_connect = on_connect        #attach function to callback

time.sleep(0.5)
client1.connect(host=broker_address, port=broker_port, keepalive=60)      #connect to broker
topic_str = '/malo/home/light'
        
client1.loop_start()    #start the loop
time.sleep(0.5)
print("loop start")

#-- start to push data
for k in range(1, 7):
    value = k%2
    print('--> push', topic_str, value)
    client1.publish(topic_str, value, qos=1)
    time.sleep(5)

time.sleep(0.1)

client1.disconnect()<jupyter_output>Connected flags{'session present': 0}, result code 0, client_id  <paho.mqtt.client.Client object at 0x000001CA1B4AE0F0>
loop start
--> push /malo/home/light 1
--> push /malo/home/light 0
--> push /malo/home/light 1
--> push /malo/home/light 0
--> push /malo/home/light 1
--> push /malo/home/light 0
{'fraction_non_alphanumeric': 0.13967310549777118, 'fraction_numerical': 0.033432392273402674, 'mean_word_length': 3.8107142857142855, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 12, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '285064', 'license': 'MIT', 'n_tokens_mistral': 529, 'n_tokens_neox': 510, 'n_words': 125, 'path': 'W05/iot/W05-iot-2.ipynb', 'repo_name': 'maloyang/KH20210925_Python_Data_Science', 'size': '1346'}