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

 

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

 

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

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

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

# Define the JSON message to send to IoT Hub. github

TEMPERATURE = 20.0 docker

HUMIDITY = 60 json

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

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

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处于预览阶段,我建议使用我以前博客中的方法安装配置,而不是如今最新的文档。

http://www.javashuo.com/article/p-rzuwzoxr-hb.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插件进行监控消息,能够看到一切正常:

     

相关文章
相关标签/搜索