EdgeX(5)使用Python 进行服务的注册,参考github 上面的项目,通过API 服务进行注册。

目录

  • 前言
  • 1,关于EdgeX Python
  • 2,项目说明
  • 3,总结

前言


相关EdgeX Foundry 全部分类:
https://blog.csdn.net/freewebsys/category_9437788.html

本文的原文连接是:
https://blog.csdn.net/freewebsys/article/details/107606848

未经博主允许不得转载。
博主地址是:http://blog.csdn.net/freewebsys

1,关于EdgeX Python


EdgeX 有 golang 的和 c的 SDK,但是目前没有 python 的服务。
需要自己折腾。还好万能 的GITHUB 上面有人已经研究了。

https://github.com/jonas-werner/EdgeX_Foundry-Device_Creation

2,项目说明


特别简单,一个python 脚本。
egfCreateEndpoint-07.py

运行的时候直接

python egfCreateEndpoint-07.py -ip  xx.xx.xx.xx -version edinburgh

脚本就支持两个 版本 一个 edinburgh ,一个 delhi

使用python 的requests 和 requests_toolbelt 库直接进行接口访问:

#!/usr/bin/python

##############################################################################################################
#     ______    __          _  __        __          _                                   __            
#    / ____/___/ /___ ____ | |/ /   ____/ /__ _   __(_)_______     _____________  ____ _/ /_____  _____
#   / __/ / __  / __ `/ _ \|   /   / __  / _ \ | / / / ___/ _ \   / ___/ ___/ _ \/ __ `/ __/ __ \/ ___/
#  / /___/ /_/ / /_/ /  __/   |   / /_/ /  __/ |/ / / /__/  __/  / /__/ /  /  __/ /_/ / /_/ /_/ / /    
# /_____/\__,_/\__, /\___/_/|_|   \__,_/\___/|___/_/\___/\___/   \___/_/   \___/\__,_/\__/\____/_/     
#             /____/                                                                                   
##############################################################################################################
# Name;     egfCreateEndpoint-07.py
# Version:  0.7
# Author:   Jonas Werner
##############################################################################################################


import requests, json, sys, re, time, os, warnings, argparse
from requests_toolbelt.multipart.encoder import MultipartEncoder
from datetime import datetime

warnings.filterwarnings("ignore")

# Gather information from arguments
parser=argparse.ArgumentParser(description="Python script for creating a new device from scratch in EdgeX Foundry")
parser.add_argument('-ip',help='EdgeX Foundry IP address', required=True)
parser.add_argument('-version',help='EdgeX Foundry version (delhi or edinburgh)', required=True)

args=vars(parser.parse_args())

edgex_ip=args["ip"]
edgexVer=args["version"]


# Make two calls to Core Metadata, to create the Addressable for the Device Service:
def createAddressables():
    # Create the addressable for the Device Service:
    url = 'http://%s:48081/api/v1/addressable' % edgex_ip
    payload =   {
                    "name":         "humidity and temp address 1",
                    "protocol":     "HTTP",
                    "address":      "172.17.0.1",
                    "port":         49999,
                    "path":         "/hum_and_temp_cluster-01",
                    "publisher":    "none",
                    "user":         "none",
                    "password":     "none",
                    "topic":        "none"
                }
    headers = {'content-type': 'application/json'}
    response = requests.post(url, data=json.dumps(payload), headers=headers, verify=False)

    print("Result of create addressables: %s with message %s" % (response, response.text))
    

def createValueDescriptors():
    url = 'http://%s:48080/api/v1/valuedescriptor' % edgex_ip
    payload =   {
                    "name":         "Humidity",
                    "description":  "Ambient humidity in percent",
                    "max":          "100",
                    "min":          "0",
                    "type":         "I",
                    "uomLabel":     "count",
                    "defaultValue": "0",
                    "formatting":   "%s",
                    "labels":       [
                                    "humidity",
                                    "percent"
                                    ]
                }
    headers = {'content-type': 'application/json'}
    response = requests.post(url, data=json.dumps(payload), headers=headers, verify=False)

    print("Result of creating value descriptor for humidity: %s with message %s" % (response, response.text))
    

    payload =   {
                    "name":         "Temperature in C",
                    "description":  "Ambient temperature in Celcius",
                    "min":          "-10",
                    "max":          "100",
                    "type":         "I",
                    "uomLabel":     "count",
                    "defaultValue": "0",
                    "formatting":   "%s",
                    "labels":       [
                                    "temp",
                                    "celcius"
                                    ]
                }
    headers = {'content-type': 'application/json'}
    response = requests.post(url, data=json.dumps(payload), headers=headers, verify=False)

    print("Result creating value descriptor for temperature: %s with message %s" % (response, response.text))
    


def uploadDeviceProfile():
    multipart_data = MultipartEncoder(
        fields={
                # a file upload field
                'file': ('file.py', open('EdgeX_TempHumidity_MonitorProfile.yml', 'rb'), 'text/plain')
               }
        )

    url = 'http://%s:48081/api/v1/deviceprofile/uploadfile' % edgex_ip
    response = requests.post(url, data=multipart_data,
                      headers={'Content-Type': multipart_data.content_type})

    print("Result of uploading device profile: %s with message %s" % (response, response.text))


def createDeviceService():
    url = 'http://%s:48081/api/v1/deviceservice' % edgex_ip
    payload =   {
                    "name":             "sensor cluster control device service",
                    "description":      "Manage sensor clusters delivering humidity and temperature readings",
                    "labels":           [
                                        "Raspberry Pi",
                                        "Sensor cluster"
                                        ],
                    "adminState":       "unlocked",
                    "operatingState":   "enabled",
                    "addressable":  {
                        "name": "humidity and temp address 1"
                    }
                }
    headers = {'content-type': 'application/json'}
    response = requests.post(url, data=json.dumps(payload), headers=headers, verify=False)

    print("Result of create device service: %s with message %s" % (response, response.text))
    


def addNewDevice(edgexVer):
    url = 'http://%s:48081/api/v1/device' % edgex_ip

    if edgexVer == "delhi":
        payload =   {
                        "name":             "Temp_and_Humidity_sensor_cluster_01",
                        "description":      "Raspberry Pi sensor cluster",
                        "adminState":       "unlocked",
                        "operatingState":   "enabled",
                        "addressable": {
                            "name": "humidity and temp address 1"
                        },
                        "labels": [
                            "Raspberry Pi",
                            "Sensor cluster"
                        ],
                        "location": "",
                        "service": {
                            "name": "sensor cluster control device service"
                        },
                        "profile": {
                            "name": "Temp and Humidity sensor cluster monitor profile - 01"
                        }
                    }

    elif edgexVer == "edinburgh": 
        payload =   {
                        "name":             "Temp_and_Humidity_sensor_cluster_01",
                        "description":      "Raspberry Pi sensor cluster",
                        "adminState":       "unlocked",
                        "operatingState":   "enabled",
                        "protocols": {
                            "example": {
                            "host": "localhost",
                            "port": "1234",
                            "unitID": "1"
                            }
                        },
                        "addressable": {
                            "name": "humidity and temp address 1"
                        },
                        "labels": [
                            "Raspberry Pi",
                            "Sensor cluster"
                        ],
                        "location": "",
                        "service": {
                            "name": "sensor cluster control device service"
                        },
                        "profile": {
                            "name": "Temp and Humidity sensor cluster monitor profile - 01"
                        }
                    }

    headers = {'content-type': 'application/json'}
    response = requests.post(url, data=json.dumps(payload), headers=headers, verify=False)
    
    print("Result of creating the device: %s with message %s" % (response, response.text))



if __name__ == "__main__":
    # Sanity check
    if not edgexVer == "delhi" and not edgexVer == "edinburgh":
        print("Supported versions are either delhi or edinburgh")
        sys.exit()
    else:
        print("EdgeX Foundry version is: %s" % edgexVer)

    createAddressables()
    createValueDescriptors()
    uploadDeviceProfile()
    createDeviceService()
    addNewDevice(edgexVer)

同时本地还要有个配置文件:

EdgeX_TempHumidity_MonitorProfile.yml

# Copyright 2017 Dell Inc. All rights reserved.
name: "Temp and Humidity sensor cluster monitor profile - 01"
manufacturer: "Dell EMC"
model: "Dell_EMC sensor cluster model ABC12345"
labels:
    - "sensorcluster"
description: "Temp and Humidity sensor cluster monitor profile - 01"
commands:
  -
    name: Humidity
    get:
        path: "/api/v1/devices/{deviceId}/temperature"
        responses:
          -
            code: "200"
            description: "Humidity near sensorcluster"
            expectedValues: ["humidity"]
          -
            code: "503"
            description: "service unavailable"
            expectedValues: ["sensorclustererror"]
  -
    name: Temperature
    get:
        path: "/api/v1/devices/{deviceId}/humidity"
        responses:
          -
            code: "200"
            description: "Temperature near sensorcluster"
            expectedValues: ["temperature"]
          -
            code: "503"
            description: "service unavailable"
            expectedValues: ["sensorclustererror"]
  -
  -
    name: hum_temp_values
    get:
        path: "/api/v1/devices/{deviceId}/values"
        responses:
          -
            code: "200"
            description: "Get the humidity and temperature values"
            expectedValues: ["value","value"]
          -
            code: "503"
            description: "service unavailable"
            expectedValues: []

启动之后就可以注册 python 的服务了。

3,总结


开源边缘计算框架 EdgeX Foundry ,服务启动之后,python的程序也可以进行注册。
注册之后就可以提供服务了。

本文的原文连接是:
https://blog.csdn.net/freewebsys/article/details/107606848

相关EdgeX Foundry 全部分类:
https://blog.csdn.net/freewebsys/category_9437788.html

博主地址是:https://blog.csdn.net/freewebsys

你可能感兴趣的:(edgex,Python,边缘计算,edgex,python)