树莓派连接阿里云

树莓派连接阿里云

代码

# -*- coding: utf-8 -*-
import paho.mqtt.client as mqtt
import time
import hashlib
import hmac
import random
import json
#这个就是我们在阿里云注册产品和设备时的三元组啦
#把我们自己对应的三元组填进去即可
options = {
    'productKey':'gn1y3ZtF5Ii',
    'deviceName':'ESP8266_test',
    'deviceSecret':'3b7a4b32af967cdfd8ac741cdfd5b66a',
    'regionId':'cn-shanghai'
}

HOST = options['productKey'] + '.iot-as-mqtt.'+options['regionId']+'.aliyuncs.com'
PORT = 1883 
PUB_TOPIC = "/sys/" + options['productKey'] + "/" + options['deviceName'] + "/thing/event/property/post";


# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    # client.subscribe("the/topic")

# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))

def hmacsha1(key, msg):
    return hmac.new(key.encode(), msg.encode(), hashlib.sha1).hexdigest()

def getAliyunIoTClient():
    timestamp = str(int(time.time()))
    CLIENT_ID = "paho.py|securemode=3,signmethod=hmacsha1,timestamp="+timestamp+"|"
    CONTENT_STR_FORMAT = "clientIdpaho.pydeviceName"+options['deviceName']+"productKey"+options['productKey']+"timestamp"+timestamp
    # set username/password.
    USER_NAME = options['deviceName']+"&"+options['productKey']
    PWD = hmacsha1(options['deviceSecret'],CONTENT_STR_FORMAT)
    client = mqtt.Client(client_id=CLIENT_ID, clean_session=False)
    client.username_pw_set(USER_NAME, PWD)
    return client


if __name__ == '__main__':

    client = getAliyunIoTClient()
    client.on_connect = on_connect
    client.on_message = on_message
    
    client.connect(HOST, 1883, 300)
    #while True:
    payload_json = {
        'id': int(time.time()),
        'params': {
            'temperature': random.randint(20, 30),#随机温度
            'humidity': random.randint(40, 50)#随机相对湿度
        },
        'method': "thing.event.property.post"
    }
    print('send data to iot server: ' + str(payload_json))

    client.publish(PUB_TOPIC,payload=str(payload_json),qos=1)
    client.loop_forever()

双线程代码

# -*- coding: utf-8 -*-
import paho.mqtt.client as mqtt
import time
import hashlib
import hmac
import random
import json
import threading  # 导入线程模块
#这个就是我们在阿里云注册产品和设备时的三元组啦
#把我们自己对应的三元组填进去即可
options = {
    'productKey':'gn1y3ZtF5Ii',
    'deviceName':'ESP8266_test',
    'deviceSecret':'3b7a4b32af967cdfd8ac741cdfd5b66a',
    'regionId':'cn-shanghai'
}

HOST = options['productKey'] + '.iot-as-mqtt.'+options['regionId']+'.aliyuncs.com'
PORT = 1883 
PUB_TOPIC = "/sys/" + options['productKey'] + "/" + options['deviceName'] + "/thing/event/property/post";


# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    # client.subscribe("the/topic")

# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))

def hmacsha1(key, msg):
    return hmac.new(key.encode(), msg.encode(), hashlib.sha1).hexdigest()

def getAliyunIoTClient():
    timestamp = str(int(time.time()))
    CLIENT_ID = "paho.py|securemode=3,signmethod=hmacsha1,timestamp="+timestamp+"|"
    CONTENT_STR_FORMAT = "clientIdpaho.pydeviceName"+options['deviceName']+"productKey"+options['productKey']+"timestamp"+timestamp
    # set username/password.
    USER_NAME = options['deviceName']+"&"+options['productKey']
    PWD = hmacsha1(options['deviceSecret'],CONTENT_STR_FORMAT)
    client = mqtt.Client(client_id=CLIENT_ID, clean_session=False)
    client.username_pw_set(USER_NAME, PWD)
    return client
    
# 定义发布消息的函数
def publish_data(client):
    while True:  # 创建一个循环来持续发送数据
        payload_json = {
            'id': int(time.time()),
            'params': {
                'temperature': random.randint(20, 30),  # 随机温度
                'humidity': random.randint(40, 50)      # 随机相对湿度
            },
            'method': "thing.event.property.post"
        }
        print('Sending data to IoT server: ' + str(payload_json))
        client.publish(PUB_TOPIC, payload=json.dumps(payload_json), qos=1)
        time.sleep(5)  # 每隔5秒发送一次数据

if __name__ == '__main__':
    client = getAliyunIoTClient()
    client.on_connect = on_connect
    client.on_message = on_message

    # 连接 MQTT 服务器
    client.connect(HOST, PORT, 300)

    # 使用线程来发布消息,不干扰主线程的接收消息循环
    publish_thread = threading.Thread(target=publish_data, args=(client,))
    publish_thread.start()  # 启动线程

    # 开始 MQTT 客户端的循环,处理接收到的消息和重新连接等
    client.loop_forever()
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值