-
之前创建好设备后模拟MQTT客户端登陆能够正确登陆上,显示在线状态,现在不行了,查了异常运行日志显示这个问题已经尝试过换成域名解析IP还是失败
-
应用侧接收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)
-
想问一下,这个调用修改设备属性dAPI超时的问题该怎么解决
-
在访问过程中,已经能够返回201值,说明连接完成,后使用python继续访问,获得成功,想问下各位是如何解决该问题的。
-
使用微信小程序开发工具,调用设备影子接口查看信息,报错如下,使用的是iam账号访问申请得到的token,同时资源空间内也能访问到主账号的资源
-
添加转发目标转发目标第三方应用服务(HTTP推送)平台支持根据规则配置将指定的设备数据推送到第三方应用服务器。您可以设置将不同类型的设备数据推送到对应地址进行数据处理。推送URL注:推送请求方法为POST鉴权这个url怎么写
-
怎么用nodered httprequest请求华为云上设备属性
-
为什么一次上报两个属性会失败,请问是数据格式问题,还是超出上报限制?
-
topic定义为:$oc/devices/{device_id}/sys/messages/down错误原因也搜不到
-
真机调试未激活,串口工具报错
-
B站视频只有芯片教程,请问有没有讲解系统的视频,下面思维导图的视频在哪能找到小熊派IoT开发板系列教程正式发布——免费学习-云社区-华为云 (huaweicloud.com)
-
"access_key": "JDHGRb9S", "access_code": "czKqacaRXrDS44yMtwLM9DYkEf5tHWDG",都是才生成的,还有要注意什么吗
-
get的格式分别是https://6f06f62e8e.iotda-device.cn-south-4.myhuaweicloud.com/v5/iot/{project_id}/devices和https://6f06f62e8e.iotda-device.cn-south-4.myhuaweicloud.com/v5/iot/{project_id}/devices/shadow感觉是无法访问6f06f62e8e.iotda-device.cn-south-4.myhuaweicloud.com求解决办法
上滑加载中
推荐直播
-
DTT年度收官盛典:华为开发者空间大咖汇,共探云端开发创新
2025/01/08 周三 16:30-18:00
Yawei 华为云开发工具和效率首席专家 Edwin 华为开发者空间产品总监
数字化转型进程持续加速,驱动着技术革新发展,华为开发者空间如何巧妙整合鸿蒙、昇腾、鲲鹏等核心资源,打破平台间的壁垒,实现跨平台协同?在科技迅猛发展的今天,开发者们如何迅速把握机遇,实现高效、创新的技术突破?DTT 年度收官盛典,将与大家共同探索华为开发者空间的创新奥秘。
回顾中 -
GaussDB应用实战:手把手带你写SQL
2025/01/09 周四 16:00-18:00
Steven 华为云学堂技术讲师
本期直播将围绕数据库中常用的数据类型、数据库对象、系统函数及操作符等内容展开介绍,帮助初学者掌握SQL入门级的基础语法。同时在线手把手教你写好SQL。
去报名 -
算子工具性能优化新特性演示——MatMulLeakyRelu性能调优实操
2025/01/10 周五 15:30-17:30
MindStudio布道师
算子工具性能优化新特性演示——MatMulLeakyRelu性能调优实操
即将直播
热门标签