使用Python开发IOT Edge应用(2)

 

使用Python创建IOT Edge模块(续)

 

4. 打开main.py程序,在目前的Azure IOT Edge demo程序库里面没有用python开发的模拟程序模块,只有一个filter模块,经常用来做测试的tempSensor是用.net来写的,我在这里写了一个python版本的设备模拟程序,源代码可以从我的Github库里下载:

https://github.com/kingliantop/AzureIOTEdgeSample/tree/master/PythonDeviceSolution

代码部分,定义温度和湿度作为基本信息:

# Define the JSON message to send to IoT Hub.

TEMPERATURE = 20.0

HUMIDITY = 60

MSG_TXT = "{"temperature": %.2f,"humidity": %.2f}"

增加证书部分,避免安全认证报错:

def set_certificates(self):

isWindows = sys.platform.lower() in ['windows', 'win32']

if not isWindows:

CERT_FILE = os.environ['EdgeModuleCACertificateFile']

print("Adding TrustedCerts from: {0}".format(CERT_FILE))

 

# this brings in x509 privateKey and certificate

file = open(CERT_FILE)

try:

self.client.set_option("TrustedCerts", file.read())

print ( "set_option TrustedCerts successful" )

except IoTHubClientError as iothub_client_error:

print ( "set_option TrustedCerts failed (%s)" % iothub_client_error )

 

file.close()

在消息发送层面,你可以看到消息其实是发送到了上行队列,而不是直接发送到IOT Hub,然后消息会由Edge runtime负责发送:

# Send the message.

print( "Steven demo sending message: %s" % message.get_string() )

hub_manager.forward_event_to_output("temperatureOutput", message, 0)

5. 使用VSCode插件构建Edge solution,其实最主要做的就是做docker build和docker push,把打包的镜像推送到ACR,方便IOT Edge设备部署,选择deployment.template.json单击右键,选择Build IOT Edge Solution,该插件会完成相应操作,打包镜像并推送到容器注册表:

 

 

以此类推,你可以构建PythonFilter程序,代码可以从如下地址下载,或则会自己生成:

https://github.com/kingliantop/AzureIOTEdgeSample/tree/master/PythonFilterSolution

从容器注册表部署到IOT Edge设备

  1. 创建IOT Hub服务,设置你的边界设备等步骤在我之前的文章中已经有详细介绍,再次不再赘述。目前IOT Edge处于预览阶段,我建议使用我之前博客中的方法安装配置,而不是现在最新的文档。

https://www.cnblogs.com/cloudapps/p/9085656.html

sudo apt-get install python-pip

sudo pip install --upgrade pip

sudo pip install -U azure-iot-edge-runtime-ctl

 

sudo iotedgectl setup --connection-string " HostName=steveniothub.azure-devices.cn;DeviceId=myubuntudevice;SharedAccessKey=Kr5Y7gSGKT7GWQF3tkvdm/3QyhKHrfTmTz81EYzv4bc=" --nopass

sudo iotedgectl start

  1. 为你的边界设备配置容器注册表的访问密码,这一部分非常重要,否则会出现部署错误,因为你不设置容器注册表密码的时候,边界设备不会知道你的容器注册表的访问地址:

    # 首先获取你的容器注册表的用户名密码

    az acr list -o table

az acr credential show –name stevenacrdemo

或者也可以在容器注册表的管理界面,访问秘钥部分,启用管理员用户,获得用户名,密码和登录服务器:

# 登录容器注册表

sudo iotedgectl login --address stevendemoacr.azurecr.cn --username stevendemoacr --password vFjKAE2G2PoDsQWPLfu+M9xwQfnK9l4u

 

  1. 部署IOT Edge模块,name部分是模块名称,Image URI是你的容器注册表中模块的路径,保存,全部next,然后提交即可:

    稍等一段时间,可以看到module部署状态变成了running

     

  2. 在边界设备上使用docker logs监控pythonSensor模块状态,也可以使用VSCodeIOT Hub插件进行监控消息,可以看到一切正常:

     

 

原文地址:https://www.cnblogs.com/cloudapps/p/9356234.html