-
应用侧接收MQTT数据流传的信息,有没有例程,我根据教程,时好时坏
-
数据转发,应用侧接收老失败,有时候可以ClientConf.py:from typing import Optionalclass ClientConf:def __init__(self):# mqtt订阅地址self.__host: Optional[str] = "95e74068ba.st1.iotda-app.cn-north-4.myhuaweicloud.com"# mqtt订阅端口号self.__port: Optional[int] = 8883# mqtt接入凭据access_keyself.__access_key: Optional[str] = "glWckaFu"# mqtt接入凭据access_codeself.__access_code: Optional[str] = "x83VLjH7MAPikrIR36916sAStLoPXEK7"# mqtt订阅topicself.__topic: Optional[str] = "topic456"# 实例Id,同一Region购买多个标准版实例时需要填写该参数self.__instance_id: Optional[str] = "5b6a80f0-75d5-4091-b28a-7809838c524c"# mqtt qosself.__qos = 1# tcp 服务器 IPself.__tcp_ip: Optional[str] = "10.16.64.116"# tcp 服务器端口self.__tcp_port: Optional[int] = 11111@propertydef host(self):return self.__host@host.setterdef host(self, host):self.__host = host@propertydef port(self):return self.__port@port.setterdef port(self, port):self.__port = port@propertydef access_key(self):return self.__access_key@access_key.setterdef access_key(self, access_key):self.__access_key = access_key@propertydef access_code(self):return self.__access_code@access_code.setterdef access_code(self, access_code):self.__access_code = access_code@propertydef topic(self):return self.__topic@topic.setterdef topic(self, topic):self.__topic = topic@propertydef instance_id(self):return self.__instance_id@instance_id.setterdef instance_id(self, instance_id):self.__instance_id = instance_id@propertydef qos(self):return self.__qos@qos.setterdef qos(self, qos):self.__qos = qos@propertydef tcp_ip(self):return self.__tcp_ip@tcp_ip.setterdef tcp_ip(self, tcp_ip):self.__tcp_ip = tcp_ip@propertydef tcp_port(self):return self.__tcp_port@tcp_port.setterdef tcp_port(self, tcp_port):self.__tcp_port = tcp_portMqttClient.py:import osimport sslimport threadingimport timeimport tracebackimport secretsimport socketfrom typing import Optionalfrom ClientConf import ClientConfimport paho.mqtt.client as mqttimport jsonclass MqttClient:def __init__(self, client_conf: ClientConf):print("__init__ 66666")self.__host = client_conf.hostself.__port = client_conf.portself.__access_key = client_conf.access_keyself.__access_code = client_conf.access_codeself.__topic = client_conf.topicself.__instance_id = client_conf.instance_idself.__qos = client_conf.qosself.__tcp_ip = client_conf.tcp_ipself.__tcp_port = client_conf.tcp_portself.__paho_client: Optional[mqtt.Client] = Noneself.__connect_result_code = -1self.__default_backoff = 1000self.__retry_times = 0self.__min_backoff = 1 * 1000 # 1sself.__max_backoff = 30 * 1000 # 30sdef connect(self):print("connect 66666")self.__valid_params()rc = self.__connect()while rc != 0:# 退避重连low_bound = int(self.__default_backoff * 0.8)high_bound = int(self.__default_backoff * 1.0)random_backoff = secrets.randbelow(high_bound - low_bound)backoff_with_jitter = int(pow(2, self.__retry_times)) * (random_backoff + low_bound)wait_time_ms = self.__max_backoff if (self.__min_backoff + backoff_with_jitter) > self.__max_backoff else (self.__min_backoff + backoff_with_jitter)wait_time_s = round(wait_time_ms / 1000, 2)print("client will try to reconnect after " + str(wait_time_s) + " s")time.sleep(wait_time_s)self.__retry_times += 1self.close() # 释放之前的connectionrc = self.__connect()# rc为0表示建链成功,其它表示连接不成功if rc != 0:print("connect with result code: " + str(rc))if rc == 134:print("connect failed with bad username or password, ""reconnection will not be performed")passreturn rcdef __connect(self):try:print("__connect 66666")timestamp = self.current_time_millis()user_name = "accessKey=" + self.__access_key + "|timestamp=" + timestampif self.__instance_id:user_name = user_name + "|instanceId=" + self.__instance_idpass_word = self.__access_codeself.__paho_client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, "mqttClient")# 关闭自动重试, 采用手动重试的方式刷新时间戳self.__paho_client._reconnect_on_failure = False# 设置回调函数self._set_callback()# topic放在userdata中,回调函数直接拿topic订阅self.__paho_client.user_data_set(self.__topic)self.__paho_client.username_pw_set(user_name, pass_word)# 当前mqtt broker仅支持TLS1.2context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)# 不校验服务端证书context.verify_mode = ssl.CERT_NONEcontext.check_hostname = Falseself.__paho_client.tls_set_context(context)rc = self.__paho_client.connect(self.__host, self.__port)self.__connect_result_code = rcif rc == 0:threading.Thread(target=self.__paho_client.loop_forever, args=(1, False), name="MqttThread").start()# 等待建链time.sleep(1)except Exception as e:self.__connect_result_code = -1print("Mqtt connection error. traceback: " + traceback.format_exc())if self.__paho_client.is_connected():return 0else:return self.__connect_result_codedef __valid_params(self):print("__valid_params 66666")assert self.__access_key is not Noneassert self.__access_code is not Noneassert self.__topic is not None@staticmethoddef current_time_millis():return str(int(round(time.time() * 1000)))def _set_callback(self):print("_set_callback 6666 ")# 当平台响应连接请求时,执行self._on_connect()self.__paho_client.on_connect = self._on_connectprint("_on_disconnect ")# 当与平台断开连接时,执行self._on_disconnect()self.__paho_client.on_disconnect = self._on_disconnectprint("_on_subscribe ")# 当订阅topic时,执行self._on_subscribeself.__paho_client.on_subscribe = self._on_subscribe# 当接收到一个原始消息时,执行self._on_message()print("_on_message ")self.__paho_client.on_message = self._on_messagedef _on_connect(self, client, userdata, flags, rc: mqtt.ReasonCode, properties):print("_on_connect 66666 ")if rc == 0:print("Connected to Mqtt Broker! topic " + self.__topic)client.subscribe(userdata, 1)else:# 只有当用户名或密码错误,才不进行自动重连。# 如果这里不使用disconnect()方法,那么loop_forever会一直进行重连。if rc == 134:self.__paho_client.disconnect()print("Failed to connect. return code :" + str(rc.value) + ", reason" + rc.getName())def _on_subscribe(self, client, userdata, mid, granted_qos, properties):print("_on_subscribe 66666 ")print("Subscribed: " + str(mid) + " " + str(granted_qos) + " topic: " + self.__topic)def _on_message(self, client, userdata, message: mqtt.MQTTMessage):print("_on_message 66666666666")print("topic " + self.__topic + " Received message: " + message.payload.decode())# 通过TCP发送消息try:with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:s.connect((self.__tcp_ip, self.__tcp_port))s.sendall(message.payload)print("Message sent over TCP")except Exception as e:print("TCP send error. traceback: " + traceback.format_exc())# def _on_message(self, client, userdata, message: mqtt.MQTTMessage):# print("_on_message 66666666666")# print("topic " + self.__topic + " Received message: " + message.payload.decode())## try:# # 解析收到的 JSON 消息# received_msg = json.loads(message.payload.decode())## # 提取需要的部分# extracted_data = received_msg["notify_data"]["body"]## # 添加上报类型和类型# extracted_data["report_type"] = "Send"# extracted_data["type"] = "货物"## # 将提取和修改后的数据转换回 JSON# extracted_data_str = json.dumps(extracted_data)## # 打印发送的信息# print("Message to be sent over TCP: " + extracted_data_str)## # 通过 TCP 发送消息# with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:# s.connect((self.__tcp_ip, self.__tcp_port))# s.sendall(extracted_data_str.encode())# print("Message sent over TCP")# except Exception as e:# print("TCP send error. traceback: " + traceback.format_exc())def _on_disconnect(self, client, userdata, flags, rc, properties):print("Disconnect to Mqtt Broker. topic: " + self.__topic)# 断链后将客户端主动关闭,手动重连刷新时间戳try:self.__paho_client.disconnect()except Exception as e:print("Mqtt connection error. traceback: " + traceback.format_exc())self.connect()def close(self):print("close 66666 ")if self.__paho_client is not None and self.__paho_client.is_connected():try:self.__paho_client.disconnect()print("Mqtt connection close")except Exception as e:print("paho client disconnect failed. exception: " + str(e))else:passMqttDemo.py:import osfrom ClientConf import ClientConffrom MqttClient import MqttClientimport osfrom typing import Optionalfrom huaweicloudsdkcore.auth.credentials import BasicCredentials, DerivedCredentialsfrom huaweicloudsdkcore.region.region import Region as coreRegionfrom huaweicloudsdkcore.exceptions import exceptionsfrom huaweicloudsdkiotda.v5 import *def main():client_conf = ClientConf()client_conf.host = "95e74068ba.st1.iotda-app.cn-north-4.myhuaweicloud.com"client_conf.port = 8883client_conf.topic = "topic456"# mqtt接入凭据access_key可使用环境变量的方式注入client_conf.access_key = "glWckaFu"# mqtt接入凭据a ccess_code可使用环境变量的方式注入client_conf.access_code = "x83VLjH7MAPikrIR36916sAStLoPXEK7"client_conf.instance_id = "5b6a80f0-75d5-4091-b28a-7809838c524c"mqtt_client = MqttClient(client_conf)if mqtt_client.connect() != 0:print("init failed")return# 调用华为IoTDA服务接口if __name__ == "__main__":main()
-
使用pythonSDK示例失败# coding: utf-8import osfrom huaweicloudsdkcore.auth.credentials import BasicCredentialsfrom huaweicloudsdkcore.auth.credentials import DerivedCredentialsfrom huaweicloudsdkcore.region.region import Region as coreRegionfrom huaweicloudsdkcore.exceptions import exceptionsfrom huaweicloudsdkiotda.v5 import *if __name__ == "__main__":# The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.# In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environmentak = "jfdjkjCjk8C84"sk = "ljkjQjkfdjhvgdfffjWVzJDUB"endpoint = "85e44068ba.st1.iotda-app.cn-north-4.myhuaweicloud.com"credentials = BasicCredentials(ak, sk).with_derived_predicate(DerivedCredentials.get_default_derived_predicate())client = IoTDAClient.new_builder() \.with_credentials(credentials) \.with_region(coreRegion(id="cn-north-4", endpoint=endpoint)) \.build()try:request = UpdatePropertiesRequest()request.body = DevicePropertiesRequest(services="[{\"service_id\":\"Temperature\",\"properties\":{\"value\":57}}, {\"service_id\":\"Battery\",\"properties\":{\"level\":80}}]")response = client.update_properties(request)print(response)except exceptions.ClientRequestException as e:print(e.status_code)print(e.request_id)print(e.error_code)print(e.error_msg)
-
在访问过程中,已经能够返回201值,说明连接完成,后使用python继续访问,获得成功,想问下各位是如何解决该问题的。
-
添加转发目标转发目标第三方应用服务(HTTP推送)平台支持根据规则配置将指定的设备数据推送到第三方应用服务器。您可以设置将不同类型的设备数据推送到对应地址进行数据处理。推送URL注:推送请求方法为POST鉴权这个url怎么写
-
怎么用nodered httprequest请求华为云上设备属性
-
B站视频只有芯片教程,请问有没有讲解系统的视频,下面思维导图的视频在哪能找到小熊派IoT开发板系列教程正式发布——免费学习-云社区-华为云 (huaweicloud.com)
-
请问使用NB-IOT SIM7020X为什么一直连不上华为云,这个AT指令有什么格式
-
烧录说makefile文件有错误,无法打开,我也没有修改过,不知道怎么弄了困扰了好久,求大神解惑
-
刚开始学习,我看示例的编译目录不是源码目录,请问应该在哪里编译呢
-
属性设置的是可写,使用Coap上报,产品文档里只看到使用MQTT的
-
MQTT协议的核心设计理念是什么?
-
请问各位大神,这个target包从哪里来的,跟着教程走,前面那个iot_link都找到了,这个target包没有找到!
-
请问下,在构建物联网解决方案时,如何平衡设备成本、能耗和性能?
-
请问下,如何利用CoAP协议在资源受限的设备上实现物联网通信?
上滑加载中
推荐直播
-
华为云码道Agent集成与鸿蒙实战2026/08/11 周二 19:00-21:00
王一男-华为云码道产品规划专家;李炎-华为云码道产品专家;彭江敏-华为云鸿蒙端云一体化开发专家
本次直播带你解读华为云码道7月份产品新特性、新功能。更有专家演示码道Agent Space × 钉钉机器集成实战,从0到1打通消息通道;码道鸿蒙端云一体化实战,快速搭建员工签到系统。
回顾中 -
华为云开发者AI素养直播课·第五期2026/09/04 周五 16:00-18:00
林华鼎-华为云AI开发者运营负责人;蒋春阳-华为云AI开发者案例开发专家
本期直播内容: AI工具体验营 · 第5-8课连讲。Agent-Team 多智能体协作完成毕业设计实践
回顾中 -
华为云开发者AI素养ClassRoom·第六期2026/09/08 周二 19:00-20:00
樊渊-2026华为软件挑战赛冠军
高手来了:看软挑高手解析二维排样问题—从工业难题到算法突破
回顾中
热门标签