update: aliyun Iot funtions

This commit is contained in:
JackSun-qc 2022-03-21 11:21:01 +08:00
parent 0ee3223e86
commit 80dc661c68
9 changed files with 185 additions and 73 deletions

View File

@ -1,3 +1,4 @@
import ujson
import utime import utime
import _thread import _thread
import osTimer import osTimer
@ -6,6 +7,7 @@ from aLiYun import aLiYun
from usr.logging import getLogger from usr.logging import getLogger
from usr.settings import settings from usr.settings import settings
from usr.settings import default_values_sys
from usr.common import numiter from usr.common import numiter
from usr.common import power_restart from usr.common import power_restart
@ -52,39 +54,70 @@ object_model = {
'gps_mode', 'gps_mode',
'user_ota_action', 'user_ota_action',
'ota_status', 'ota_status',
'GeoLocation',
], ],
} }
class AliYunIotError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class AliYunIot(object): class AliYunIot(object):
def __init__(self, pk, ps, dk, ds): def __init__(self, pk, ps, dk, ds, downlink_queue):
self.ali = aLiYun(pk, ps, dk, ds)
clientID = dk
self.ali.setMqtt(clientID, clean_session=False, keeyAlive=60, reconn=True)
self.ali.setCallback(self.ali_sub_cb)
self.ica_topic_property_post = 'sys/%s/%s/thing/event/property/post' % (pk, dk)
self.ica_topic_property_post_reply = 'sys/%s/%s/thing/event/property/post_reply' % (pk, dk)
self.ica_topic_property_set = 'sys/%s/%s/thing/service/property/set' % (pk, dk)
self.ica_topic_event_post = 'sys/%s/%s/thing/event/{}/post' % (pk, dk)
self.ica_topic_event_post_reply = 'sys/%s/%s/thing/event/{}/post_reply' % (pk, dk)
self.ali_subcribe_topic()
self.post_res = {} self.post_res = {}
self.ali_timer = osTimer() self.ali_timer = osTimer()
self.downlink_queue = downlink_queue
self.id_iter = numiter() self.id_iter = numiter()
self.id_lock = _thread.allocate_lock() self.id_lock = _thread.allocate_lock()
self.ica_topic_property_post = '/sys/%s/%s/thing/event/property/post' % (pk, dk)
self.ica_topic_property_post_reply = '/sys/%s/%s/thing/event/property/post_reply' % (pk, dk)
self.ica_topic_property_set = '/sys/%s/%s/thing/service/property/set' % (pk, dk)
self.ica_topic_property_get = '/sys/%s/%s/thing/service/property/get' % (pk, dk)
self.ica_topic_property_query = '/sys/%s/%s/thing/service/property/query' % (pk, dk)
self.ica_topic_event_post = '/sys/%s/%s/thing/event/{}/post' % (pk, dk)
self.ica_topic_event_post_reply = '/sys/%s/%s/thing/event/{}/post_reply' % (pk, dk)
current_settings = settings.get()
if current_settings['sys']['ali_burning_method'] == default_values_sys._ali_burning_method.one_type_one_density:
dk = None
elif current_settings['sys']['ali_burning_method'] == default_values_sys._ali_burning_method.one_machine_one_density:
ps = None
self.ali = aLiYun(pk, ps, dk, ds)
self.clientID = dk
setMqttres = self.ali.setMqtt(self.clientID, clean_session=False, keepAlive=60, reconn=True)
if setMqttres == -1:
raise AliYunIotError('setMqtt Falied!')
self.ali.setCallback(self.ali_sub_cb)
self.ali_subcribe_topic()
self.ali.start() self.ali.start()
def ali_subcribe_topic(self): def ali_subcribe_topic(self):
self.ali.subcribute(self.ica_topic_property_post, qos=0) if self.ali.subscribe(self.ica_topic_property_post, qos=0) == -1:
self.ali.subcribute(self.ica_topic_property_post_reply, qos=0) log.error('Topic [%s] Subscribe Falied.' % self.ica_topic_property_post)
self.ali.subcribute(self.ica_topic_property_set, qos=0) if self.ali.subscribe(self.ica_topic_property_post_reply, qos=0) == -1:
log.error('Topic [%s] Subscribe Falied.' % self.ica_topic_property_post_reply)
if self.ali.subscribe(self.ica_topic_property_set, qos=0) == -1:
log.error('Topic [%s] Subscribe Falied.' % self.ica_topic_property_set)
if self.ali.subscribe(self.ica_topic_property_get, qos=0) == -1:
log.error('Topic [%s] Subscribe Falied.' % self.ica_topic_property_get)
if self.ali.subscribe(self.ica_topic_property_query, qos=0) == -1:
log.error('Topic [%s] Subscribe Falied.' % self.ica_topic_property_query)
for tsl_event_identifier in object_model['event']: for tsl_event_identifier in object_model['event']:
self.ali.subcribute(self.ica_topic_event_post.format(tsl_event_identifier), qos=0) post_topic = self.ica_topic_event_post.format(tsl_event_identifier)
self.ali.subcribute(self.ica_topic_event_post_reply.format(tsl_event_identifier), qos=0) if self.ali.subscribe(post_topic, qos=0) == -1:
log.error('Topic [%s] Subscribe Falied.' % post_topic)
post_reply_topic = self.ica_topic_event_post_reply.format(tsl_event_identifier)
if self.ali.subscribe(post_reply_topic, qos=0) == -1:
log.error('Topic [%s] Subscribe Falied.' % post_reply_topic)
def get_id(self): def get_id(self):
with self.id_lock: with self.id_lock:
@ -140,11 +173,8 @@ class AliYunIot(object):
'params': property_params, 'params': property_params,
'method': 'thing.event.property.post' 'method': 'thing.event.property.post'
} }
pub_res = self.ali.publish(self.ica_topic_property_post, publish_data, qos=0) self.ali.publish(self.ica_topic_property_post, ujson.dumps(publish_data), qos=0)
if pub_res == 0:
msg_ids.append(msg_id) msg_ids.append(msg_id)
else:
return False
# Publish Event Data. # Publish Event Data.
if event_params: if event_params:
for event in event_params.keys(): for event in event_params.keys():
@ -159,11 +189,8 @@ class AliYunIot(object):
'params': event_params[event], 'params': event_params[event],
'method': 'thing.event.%s.post' % event 'method': 'thing.event.%s.post' % event
} }
pub_res = self.ali.publish(topic, publish_data, qos=0) self.ali.publish(topic, ujson.dumps(publish_data), qos=0)
if pub_res == 0:
msg_ids.append(msg_id) msg_ids.append(msg_id)
else:
return False
pub_res = [self.get_post_res(msg_id) for msg_id in msg_ids] pub_res = [self.get_post_res(msg_id) for msg_id in msg_ids]
return True if False not in pub_res else False return True if False not in pub_res else False
@ -173,8 +200,16 @@ class AliYunIot(object):
return False return False
def ali_sub_cb(self, topic, data): def ali_sub_cb(self, topic, data):
log.info('topic: %s, data: %s' % (topic, data)) # log.info('topic: %s, data: %s' % (topic.decode(), data.decode()))
topic = topic.decode()
data = ujson.loads(data)
if topic.endswith('/post_reply'): if topic.endswith('/post_reply'):
log.info('topic: %s, data: %s' % (topic, data))
self.put_post_res(data['id'], True if data['code'] == 200 else False) self.put_post_res(data['id'], True if data['code'] == 200 else False)
elif topic.endswith('/property/set'):
log.info('topic: %s, data: %s' % (topic, data))
if data['method'] == 'thing.service.property.set':
dl_data = list(zip(data.get("params", {}).keys(), data.get("params", {}).values()))
self.downlink_queue.put(('object_model', dl_data))
else: else:
pass pass

View File

@ -132,6 +132,38 @@ class GPS(Singleton):
return "" return ""
def read_quecIot(self):
data = []
r = self.read_location_GxRMC()
if r:
data.append(r)
r = self.read_location_GxGGA()
if r:
data.append(r)
r = self.read_location_GxVTG()
if r:
data.append(r)
return data
def read_aliyun(self):
gga_data = self.read_location_GxGGA()
gps_data = {'CoordinateSystem': 1}
if gga_data:
Latitude_re = ure.search(r",[0-9]+\.[0-9]+,[NS],", gga_data)
if Latitude_re:
gps_data['Latitude'] = round(float(Latitude_re.group(0)[1:-3]), 2)
Longtitude_re = ure.search(r",[0-9]+\.[0-9]+,[EW],", gga_data)
if Longtitude_re:
gps_data['Longtitude'] = round(float(Longtitude_re.group(0)[1:-3]), 2)
Altitude_re = ure.search(r"-*[0-9]+\.[0-9]+,M,", gga_data)
if Altitude_re:
gps_data['Altitude'] = round(float(Altitude_re.group(0)[:-3]), 2)
gps_info = {'GeoLocation': gps_data}
return gps_info
class CellLocator(object): class CellLocator(object):
def __init__(self, cellLocator_cfg): def __init__(self, cellLocator_cfg):
@ -149,6 +181,11 @@ class CellLocator(object):
def read_quecIot(self): def read_quecIot(self):
return ['LBS'] return ['LBS']
def read_aliyun(self):
gps_data = self.read()
gps_info = {'GeoLocation': {'Longtitude': round(gps_data[0], 2), 'Latitude': round(gps_data[1], 2), 'Altitude': 0.0, 'CoordinateSystem': 1}}
return gps_info
class WiFiLocator(object): class WiFiLocator(object):
def __init__(self, wifiLocator_cfg): def __init__(self, wifiLocator_cfg):
@ -160,6 +197,11 @@ class WiFiLocator(object):
def read_quecIot(self): def read_quecIot(self):
return [] return []
def read_aliyun(self):
gps_data = self.read()
gps_info = {'GeoLocation': {'Longtitude': round(gps_data[0], 2), 'Latitude': round(gps_data[1], 2), 'Altitude': 0.0, 'CoordinateSystem': 1}}
return gps_info
class Location(Singleton): class Location(Singleton):
gps = None gps = None
@ -205,19 +247,12 @@ class Location(Singleton):
current_settings = settings.settings.get() current_settings = settings.settings.get()
if self.gps: if self.gps:
data = []
if current_settings['sys']['cloud'] == settings.default_values_sys._cloud.quecIot: if current_settings['sys']['cloud'] == settings.default_values_sys._cloud.quecIot:
r = self.gps.read_location_GxRMC() data = self.gps.read_quecIot()
if r: elif current_settings['sys']['cloud'] == settings.default_values_sys._cloud.AliYun:
data.append(r) data = self.gps.read_aliyun()
else:
r = self.gps.read_location_GxGGA() data = self.gps.read()
if r:
data.append(r)
r = self.gps.read_location_GxVTG()
if r:
data.append(r)
if len(data): if len(data):
return (settings.default_values_app._loc_method.gps, data) return (settings.default_values_app._loc_method.gps, data)
@ -225,6 +260,8 @@ class Location(Singleton):
if self.cellLoc: if self.cellLoc:
if current_settings['sys']['cloud'] == settings.default_values_sys._cloud.quecIot: if current_settings['sys']['cloud'] == settings.default_values_sys._cloud.quecIot:
data = self.cellLoc.read_quecIot() data = self.cellLoc.read_quecIot()
elif current_settings['sys']['cloud'] == settings.default_values_sys._cloud.AliYun:
data = self.cellLoc.read_aliyun()
else: else:
data = self.cellLoc.read() data = self.cellLoc.read()
@ -234,6 +271,8 @@ class Location(Singleton):
if self.wifiLoc: if self.wifiLoc:
if current_settings['sys']['cloud'] == settings.default_values_sys._cloud.quecIot: if current_settings['sys']['cloud'] == settings.default_values_sys._cloud.quecIot:
data = self.wifiLoc.read_quecIot() data = self.wifiLoc.read_quecIot()
elif current_settings['sys']['cloud'] == settings.default_values_sys._cloud.AliYun:
data = self.wifiLoc.read_aliyun()
else: else:
data = self.wifiLoc.read() data = self.wifiLoc.read()

View File

@ -5,12 +5,11 @@ from queue import Queue
from usr.logging import getLogger from usr.logging import getLogger
from usr.settings import settings from usr.settings import settings
from usr.settings import DATA_NON_LOCA
from usr.settings import DATA_LOCA_GPS
from usr.settings import DATA_LOCA_NON_GPS
from usr.common import power_restart from usr.common import power_restart
DATA_NON_LOCA = 0x0
DATA_LOCA_NON_GPS = 0x1
DATA_LOCA_GPS = 0x2
log = getLogger(__name__) log = getLogger(__name__)
object_model = [ object_model = [

View File

@ -12,10 +12,14 @@ import usr.settings as settings
from usr.battery import Battery from usr.battery import Battery
from usr.common import Singleton from usr.common import Singleton
from usr.logging import getLogger from usr.logging import getLogger
from usr.settings import DATA_NON_LOCA
from usr.settings import DATA_LOCA_NON_GPS
from usr.settings import DATA_LOCA_GPS
if settings.settings.get()['sys']['cloud'] == settings.default_values_sys._cloud.quecIot: if settings.settings.get()['sys']['cloud'] == settings.default_values_sys._cloud.quecIot:
from usr.quecthing import QuecThing from usr.quecthing import QuecThing
from usr.quecthing import DATA_NON_LOCA, DATA_LOCA_NON_GPS, DATA_LOCA_GPS if settings.settings.get()['sys']['cloud'] == settings.default_values_sys._cloud.AliYun:
from usr.aliyunIot import AliYunIot
log = getLogger(__name__) log = getLogger(__name__)
@ -200,6 +204,8 @@ def uplink_process(argv):
key = 'loca_gps' key = 'loca_gps'
else: else:
continue continue
if hist.get(key) is None:
hist[key] = []
hist[key].append(msg[1]) hist[key].append(msg[1])
need_refresh = True need_refresh = True
else: else:
@ -243,13 +249,17 @@ class Remote(Singleton):
self.remote_read_cb = remote_read_cb self.remote_read_cb = remote_read_cb
self.downlink_queue = Queue(maxsize=64) self.downlink_queue = Queue(maxsize=64)
self.uplink_queue = Queue(maxsize=64) self.uplink_queue = Queue(maxsize=64)
self.DATA_NON_LOCA = DATA_NON_LOCA
self.DATA_LOCA_NON_GPS = DATA_LOCA_NON_GPS
self.DATA_LOCA_GPS = DATA_LOCA_GPS
current_settings = settings.settings.get() current_settings = settings.settings.get()
cloud_init_params = current_settings['sys']['cloud_init_params'] cloud_init_params = current_settings['sys']['cloud_init_params']
if current_settings['sys']['cloud'] == settings.default_values_sys._cloud.quecIot: if current_settings['sys']['cloud'] == settings.default_values_sys._cloud.quecIot:
self.cloud = QuecThing(cloud_init_params['PK'], cloud_init_params['PS'], cloud_init_params['DK'], cloud_init_params['DS'], self.downlink_queue) self.cloud = QuecThing(cloud_init_params['PK'], cloud_init_params['PS'], cloud_init_params['DK'], cloud_init_params['DS'], self.downlink_queue)
self.DATA_NON_LOCA = DATA_NON_LOCA elif current_settings['sys']['cloud'] == settings.default_values_sys._cloud.AliYun:
self.DATA_LOCA_NON_GPS = DATA_LOCA_NON_GPS self.cloud = AliYunIot(cloud_init_params['PK'], cloud_init_params['PS'], cloud_init_params['DK'], cloud_init_params['DS'], self.downlink_queue)
self.DATA_LOCA_GPS = DATA_LOCA_GPS
else: else:
raise settings.SettingsError('Current cloud (0x%X) not supported!' % current_settings['sys']['cloud']) raise settings.SettingsError('Current cloud (0x%X) not supported!' % current_settings['sys']['cloud'])

View File

@ -12,6 +12,10 @@ PROJECT_NAME = 'QuecPython_Tracker'
PROJECT_VERSION = '2.0.0' PROJECT_VERSION = '2.0.0'
DATA_NON_LOCA = 0x0
DATA_LOCA_NON_GPS = 0x1
DATA_LOCA_GPS = 0x2
ALERTCODE = { ALERTCODE = {
20000: 'fault_alert', 20000: 'fault_alert',
30002: 'low_power_alert', 30002: 'low_power_alert',
@ -105,7 +109,7 @@ class default_values_app(object):
loc_mode = _loc_mode.cycle loc_mode = _loc_mode.cycle
loc_cycle_period = 1 loc_cycle_period = 30
low_power_alert_threshold = 20 low_power_alert_threshold = 20
@ -158,6 +162,10 @@ class default_values_sys(object):
update_successed = 3 update_successed = 3
update_failed = 4 update_failed = 4
class _ali_burning_method(object):
one_type_one_density = 0
one_machine_one_density = 1
''' '''
variables of system default settings below MUST NOT start with '_' variables of system default settings below MUST NOT start with '_'
''' '''
@ -171,12 +179,14 @@ class default_values_sys(object):
ota_status = _ota_status.none ota_status = _ota_status.none
cloud = _cloud.quecIot cloud = _cloud.AliYun
cloud_init_params = {} cloud_init_params = {}
cloud_timeout = 180 cloud_timeout = 180
ali_burning_method = _ali_burning_method.one_machine_one_density
_quecIot = { _quecIot = {
'PK': 'p11275', 'PK': 'p11275',
'PS': 'Q0ZQQndaN3pCUFd6', 'PS': 'Q0ZQQndaN3pCUFd6',

View File

@ -2,15 +2,17 @@ import ure
import utime import utime
import _thread import _thread
import usr.settings as settings from queue import Queue
from machine import UART from machine import UART
from queue import Queue import usr.settings as settings
from usr.logging import getLogger from usr.logging import getLogger
from usr.quecthing import QuecThing from usr.quecthing import QuecThing
from usr.remote import Remote from usr.remote import Remote
from usr.location import Location, GPS from usr.location import Location, GPS
from usr.tracker import Tracker from usr.tracker import Tracker
from usr.aliyunIot import AliYunIot
log = getLogger(__name__) log = getLogger(__name__)
@ -99,16 +101,23 @@ def test_tracker():
log.info('[.] sleep 3') log.info('[.] sleep 3')
utime.sleep(3) utime.sleep(3)
# log.info('[.] test tracker.locator.read()')
# loc_read_res = tracker.locator.read()
# log.info('[.] loc_read_res:', loc_read_res)
# log.info('[.] sleep 3')
# utime.sleep(3)
log.info('[.] test tracker.loc_report()') log.info('[.] test tracker.loc_report()')
loc_report_res = tracker.loc_report() loc_report_res = tracker.loc_report()
log.info('[.] loc_report_res:', loc_report_res) log.info('[.] loc_report_res:', loc_report_res)
log.info('[.] sleep 3') # log.info('[.] sleep 3')
utime.sleep(3) # utime.sleep(3)
log.info('[.] test tracker.machine_check()') # log.info('[.] test tracker.machine_check()')
machine_check_res = tracker.machine_check() # machine_check_res = tracker.machine_check()
log.info('[.] machine_check_res:', machine_check_res) # log.info('[.] machine_check_res:', machine_check_res)
log.info('[x] end test_tracker') log.info('[x] end test_tracker')
@ -151,6 +160,18 @@ def test_gps():
log.debug('[x] end test_gps') log.debug('[x] end test_gps')
def test_aliyuniot():
log.debug('[x] start test_aliyuniot')
current_settings = settings.settings.get()
cloud_init_params = current_settings['sys']['cloud_init_params']
downlink_queue = Queue(maxsize=64)
cloud = AliYunIot(cloud_init_params['PK'], cloud_init_params['PS'], cloud_init_params['DK'], cloud_init_params['DS'], downlink_queue)
log.debug("cloud.ali.getAliyunSta(): ", cloud.ali.getAliyunSta())
log.debug('[x] end test_aliyuniot')
def main(): def main():
# test_quecthing() # test_quecthing()
# test_settings() # test_settings()
@ -158,6 +179,7 @@ def main():
# test_remote() # test_remote()
# test_location() # test_location()
# test_gps() # test_gps()
# test_aliyuniot()
test_tracker() test_tracker()
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -57,7 +57,7 @@ class TrackerTimer(Singleton):
self.quecthing_ota_timer() self.quecthing_ota_timer()
def loc_timer(self): def loc_timer(self):
self.tracker.loc_report() self.tracker.machine_info_report()
def battery_timer(self): def battery_timer(self):
current_settings = settings.settings.get() current_settings = settings.settings.get()

View File

@ -80,7 +80,7 @@ class Tracker(Singleton):
return False return False
def machine_info_report(self, power_switch=True): def machine_info_report(self, power_switch=True):
if self.loc_report(): self.loc_report()
# TODO: Other Machine Info. # TODO: Other Machine Info.
current_settings = settings.settings.get() current_settings = settings.settings.get()
machine_info = { machine_info = {
@ -91,9 +91,6 @@ class Tracker(Singleton):
} }
machine_info.update(current_settings['app']) machine_info.update(current_settings['app'])
self.remote.post_data(self.remote.DATA_NON_LOCA, machine_info) self.remote.post_data(self.remote.DATA_NON_LOCA, machine_info)
return True
return False
def machine_check(self): def machine_check(self):
net_check_res = self.check.net_check() net_check_res = self.check.net_check()

View File

@ -237,7 +237,7 @@ res = tracker.machine_info_report()
- 返回值: - 返回值:
返回`bool`类型数据, `True`成功, `False`失败。
### machine_check 机器自检功能 ### machine_check 机器自检功能