iotstack-application-sdk-py.../examples/demo/index.py

65 lines
2.0 KiB
Python
Raw Permalink Normal View History

2020-12-07 10:42:06 +08:00
import json
import logging
import time
2021-03-17 11:53:00 +08:00
from iotedgeapplicationlinksdk import getLogger
from iotedgeapplicationlinksdk.client import get_application_config, get_application_name, get_gateway_product_sn, get_gateway_device_sn, publish, register_callback
2020-12-07 10:42:06 +08:00
# 配置log
log = getLogger()
log.setLevel(logging.DEBUG)
# 主函数
if __name__ == "__main__":
try:
2021-03-17 15:24:10 +08:00
# 获取应用配置信息
2021-03-17 11:53:00 +08:00
appConfig = get_application_config()
log.info('app config:{}'.format(appConfig))
2020-12-07 10:42:06 +08:00
2021-03-17 15:24:10 +08:00
# 从应用配置获取设备数据上报周期
2020-12-07 10:42:06 +08:00
uploadPeriod = 5
2021-03-17 11:53:00 +08:00
if "period" in appConfig.keys() and isinstance(appConfig['period'], int):
uploadPeriod = int(appConfig['period'])
2020-12-07 10:42:06 +08:00
2021-03-17 11:53:00 +08:00
appName = get_application_name()
productSN = get_gateway_product_sn()
deviceSN = get_gateway_device_sn()
log.info('app info:{}, {}, {}'.format(appName, productSN, deviceSN))
2020-12-07 10:42:06 +08:00
2021-03-17 15:24:10 +08:00
# 设置应用上报topic
2021-03-17 11:53:00 +08:00
topic = '/{}/{}/upload'.format(productSN, deviceSN)
2020-12-07 10:42:06 +08:00
2021-03-17 15:24:10 +08:00
# 设置应用消息回调
2021-03-17 11:53:00 +08:00
def callback(topic: str, payload: bytes):
2020-12-07 10:42:06 +08:00
log.info("recv message from {} : {}".format(topic, str(payload)))
2021-03-17 15:24:10 +08:00
# 设置应用RRPC消息回调
2021-03-17 11:53:00 +08:00
def rrpc_callback(topic: str, payload: bytes):
log.info("recv rrpc message from {} : {}".format(
topic, str(payload)))
2020-12-07 10:42:06 +08:00
2021-03-17 11:53:00 +08:00
register_callback(callback, rrpc_callback)
2020-12-07 10:42:06 +08:00
i = 0
2021-03-17 15:24:10 +08:00
# 周期上报消息
2020-12-07 10:42:06 +08:00
while True:
relayStatus = ("on", "off")[i % 2 == 0]
payload = {
"timestamp": time.time(),
2021-03-17 11:53:00 +08:00
'RelayStatus': relayStatus
2020-12-07 10:42:06 +08:00
}
2021-03-17 11:53:00 +08:00
2020-12-07 10:42:06 +08:00
byts = json.dumps(payload).encode('utf-8')
2021-03-17 11:53:00 +08:00
publish(topic, byts)
2020-12-07 10:42:06 +08:00
log.info("upload {} : {}".format(topic, str(byts)))
time.sleep(uploadPeriod)
i = i+1
2021-03-17 15:24:10 +08:00
if (i > 1000):
i = 1
2020-12-07 10:42:06 +08:00
except Exception as e:
2021-03-17 11:53:00 +08:00
log.error('load app config error: {}'.format(str(e)))
exit(1)