2 Star 0 Fork 1

yeluo/huawei-iotda-tools

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
iotedge_worker.py 3.07 KB
一键复制 编辑 原始数据 按行查看 历史
jingjuan 提交于 2022-03-23 09:38 . 边缘增加删除设备任务
import logging
import time
from huaweicloudsdkcore.auth.credentials import Credentials
from huaweicloudsdkcore.client import ClientBuilder
from huaweicloudsdkcore.http.http_config import HttpConfig
from huaweicloudsdkiotedge.v2 import IoTEdgeClient, DeleteDeviceRequest
from repository import DeviceRepository
logger = logging.getLogger()
class IoTEdgeWorker:
def __init__(self, endpoint, credential: Credentials, instance_id=None, app_id=None):
logger.info(f"创建到{endpoint}的访问链接...")
builder = ClientBuilder(IoTEdgeClient, credential_type=credential.__class__.__name__)
config = HttpConfig.get_default_config()
config.ignore_ssl_verification = True
self.client: IoTEdgeClient = builder.with_http_config(config) \
.with_credentials(credential).with_endpoint(endpoint) \
.build()
def get_edge_node_id(loaded_device_map, device):
edge_node_id = device["gateway_id"]
while device["gateway_id"] is not None:
edge_node_id = device["gateway_id"]
device = loaded_device_map[edge_node_id]
return edge_node_id
class IoTEdgeDeviceWorker(IoTEdgeWorker):
def __init__(self, endpoint, credential, product_id_map, device_map, instance_id=None, app_id=None):
super().__init__(endpoint, credential, instance_id, app_id)
self.product_id_map = product_id_map
self.device_map = device_map
def create_or_update_device(self, repo: DeviceRepository):
logger.info(f"开始添加边缘设备。")
loaded_device_map = repo.get_device_map()
for device_id, device in loaded_device_map.items():
if device["gateway_id"] is None:
logger.info(f"设备:node_id:{device_id}, node_name:{device['device_name']}为边缘节点")
elif device_id not in self.device_map:
logger.info(f"创建边缘设备:{device_id}-{device['device_name']}")
edge_node_id = get_edge_node_id(loaded_device_map, device)
add_device_request = repo.to_add_edge_device_request(device, edge_node_id, self.product_id_map)
self.client.add_device(add_device_request)
else:
# 更新设备
logger.info(f"已经存在设备:{device['device_id']}-{device['device_name']}")
time.sleep(0.1)
logger.info("同步完成")
def delete_edge_device(self, repo: DeviceRepository):
logger.info("批量删除边缘子设备。")
loaded_device_map = repo.get_device_map()
platform_device_map = self.device_map
for device_id, device in reversed(loaded_device_map.items()):
logger.info(f"删除设备{device_id}-{device['device_name']}")
if device_id not in platform_device_map:
logger.warning(f"平台不能存在指定设备,device_id:{device_id}")
continue
edge_node_id = device["gateway_id"]
self.client.delete_device(DeleteDeviceRequest(edge_node_id=edge_node_id, device_id=device_id))
time.sleep(0.2)
logger.info("删除完成。")
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/qinghanfun/huawei-iotda-tools.git
git@gitee.com:qinghanfun/huawei-iotda-tools.git
qinghanfun
huawei-iotda-tools
huawei-iotda-tools
master

搜索帮助

0d507c66 1850385 C8b1a773 1850385