def __setupMqttClient(self): self.__mqttClient = MqttClient(self.__mqttUrl, self.__productKey, self.__deviceKey, self.__deviceSecret) self.__mqttClient.get_profile().set_auto_reconnect(True) if (os.path.isfile(self.__caFile) and os.path.isfile(self.__keyFile) and os.path.isfile(self.__cerFile)): self.__mqttClient.get_profile().set_ssl_context( self.__caFile, self.__cerFile, self.__keyFile, self.__keyFilePassword) self.__mqttClient.onOnline = self.__onOnline self.__mqttClient.onOffline = self.__onOffline self.__mqttClient.onConnectFailed = self.__onConnectFailed self.__mqttClient.on_disconnect = self.__onDisconnect self.__mqttClient.connect()
# TODO: download firmware from firmware.fileUrl # mock reporting progress ota_report_progress('35', 'downloading firmware finished') ota_report_progress('70', 'decompressing firmware finished') ota_report_progress('90', 'running firmware finished') ota_report_progress('100', 'upgrading firmware finished') # firmware upgrade success, report new version ota_version_report(firmware.version) if __name__ == "__main__": client = MqttClient(SampleHelper.TCP_SERVER_URL, SampleHelper.GW_PRODUCT_KEY, SampleHelper.GW_DEVICE_KEY, SampleHelper.GW_DEVICE_SECRET) client.get_profile().set_auto_reconnect(True) client.connect() # connect in sync # register a handle_msg to implement the Ota function, e.g: upgrade firmware client.register_arrived_message_handler(OtaUpgradeCommand().get_class(), upgrade_firmware_handler) ota_version_report(1.0) ota_get_version_report() while True: time.sleep(5)
topo_del_response = client.publish(topo_del_request) if topo_del_response: print('topo delete response: %s' % topo_del_response.get_code()) def login_sub_device(): login_request = SubDeviceLoginRequest.builder().set_sub_device_info( sub_product_key, sub_device_key, sub_device_secret).build() login_response = client.publish(login_request) if login_response: print('sub device login response: code: %s' % login_response.get_code()) if __name__ == "__main__": client = MqttClient(enos_mqtt_url_ssl, gateway_product_key, gateway_device_key, gateway_device_secret) # if connection interrupted, the client can automatically reconnect client.get_profile().set_auto_reconnect(True) # set the certificate files for bi-directional certification client.get_profile().set_ssl_context(ca_file, cer_file, key_file, key_file_password) # set basic logger level client.setup_basic_logger(logging.INFO) # register connection callback client.on_connect = on_connect client.on_disconnect = on_disconnect client.on_connected_failed = on_connect_failed
class DecadaPythonClient: """Wrapper class which makes it easier to communicate with DECADA :param baseDirectory: provides the path to the directory of the config file :type baseDirectory: str :param configPath: config file name :type configPath: str :param onConnectSuccessCallback: method hook that is called upon connection success :type onConnectSuccessCallback: def, optional :param onConnectFailedCallback: method hook that is called upon connection failure :type onConnectFailedCallback: def, optional """ def __init__(self, baseDirectoryPath, yamlFilePath, onConnectSuccessCallback=None, onConnectFailedCallback=None): self.__baseDirectoryPath = baseDirectoryPath self.__orgId = None self.__appAccessKey = None self.__appSecretKey = None self.__apiUrlV1 = None self.__apiUrlV2 = None self.__mqttUrl = None self.__productKey = None self.__deviceKey = None self.__deviceSecret = None self.__caFile = None self.__keyFile = None self.__cerFile = None self.__keyFilePassword = None self.__mqttClient = None self.__postClient = None self.__serviceInvocationHandlers = {} self.__restartHandler = None self.__assetId = None self.__filePathPattern = re.compile(r"((?:[\w]\:)?\/{1,2}.*?\.[\w]+)") self.__externalConnectSuccessCallback = onConnectSuccessCallback self.__externalConnectFailedCallback = onConnectFailedCallback try: configFile = open(baseDirectoryPath + "/" + yamlFilePath, "rb") except IOError: print('Unable to open configuration file: ' + baseDirectoryPath + "/" + yamlFilePath) sys.exit() with configFile: documents = yaml.full_load(configFile) decadaConfig = documents.get("decada") if (decadaConfig is not None): self.__orgId = decadaConfig.get("orgId") self.__appAccessKey = decadaConfig.get("appAccessKey") self.__appSecretKey = decadaConfig.get("appSecretKey") self.__apiUrlV1 = decadaConfig.get("apiUrlV1") self.__apiUrlV2 = decadaConfig.get("apiUrlV2") self.__mqttUrl = decadaConfig.get("mqttUrl") self.__productKey = decadaConfig.get("productKey") self.__deviceKey = decadaConfig.get("deviceKey") self.__deviceSecret = decadaConfig.get("deviceSecret") self.__caFile = baseDirectoryPath + \ "/" + decadaConfig.get("caFile") self.__keyFile = baseDirectoryPath + \ "/" + decadaConfig.get("keyFile") self.__cerFile = baseDirectoryPath + \ "/" + decadaConfig.get("cerFile") self.__keyFilePassword = decadaConfig.get("keyFilePassword") if (self.__mqttUrl is not None and self.__productKey is not None and self.__deviceKey is not None and self.__deviceSecret is not None and self.__caFile is not None and self.__keyFile is not None and self.__cerFile is not None and self.__keyFilePassword is not None and self.__orgId is not None and self.__appAccessKey is not None and self.__appSecretKey is not None and self.__apiUrlV1 is not None and self.__apiUrlV2 is not None): print(self.__orgId) print(self.__appAccessKey) print(self.__appSecretKey) print(self.__apiUrlV1) print(self.__apiUrlV2) print(self.__mqttUrl) print(self.__productKey) print(self.__deviceKey) print(self.__deviceSecret) print(self.__caFile) print(self.__keyFile) print(self.__cerFile) print(self.__keyFilePassword) # Internal method for setting up a MqttClient # @param self The object pointer def __setupMqttClient(self): self.__mqttClient = MqttClient(self.__mqttUrl, self.__productKey, self.__deviceKey, self.__deviceSecret) self.__mqttClient.get_profile().set_auto_reconnect(True) if (os.path.isfile(self.__caFile) and os.path.isfile(self.__keyFile) and os.path.isfile(self.__cerFile)): self.__mqttClient.get_profile().set_ssl_context( self.__caFile, self.__cerFile, self.__keyFile, self.__keyFilePassword) self.__mqttClient.onOnline = self.__onOnline self.__mqttClient.onOffline = self.__onOffline self.__mqttClient.onConnectFailed = self.__onConnectFailed self.__mqttClient.on_disconnect = self.__onDisconnect self.__mqttClient.connect() # Internal callback method when client connects to decada # @param self The Object pointer def __onOnline(self): print("Connected with Decada") request = GetDeviceByDeviceKeyRequest(org_id=self.__orgId, product_key=self.__productKey, device_key=self.__deviceKey) response = self.__postClient.execute(request) if response.status == 0 and "assetId" in response.data: self.__assetId = response.data["assetId"] print(self.__assetId) if self.__externalConnectSuccessCallback is not None: self.__externalConnectSuccessCallback() # Internal callback method on client disconnects from decada # @param self The Object pointer def __onOffline(self): print("Disconnected with Decada") # Internal callback method when client connection with decada failed def __onConnectFailed(self): print("Connection with Decada failed") if self.__externalConnectFailedCallback is not None: self.__externalConnectFailedCallback() def __onDisconnect(self): print("On Disconnect from Decada") # Internal method which generates the neccesary hash to make an api call to decada # @param url def __generateUrl(self, url, sign): params = {"path": url} timeStamp = str(int(time.time() * 1000)) params["requestTimestamp"] = timeStamp params["orgId"] = self.__orgId signStr = self.__appAccessKey keys = sorted(params.keys()) for key in keys: signStr += key + str(params[key]) signStr += self.__appSecretKey psw = sha256() psw.update(signStr.encode('utf8')) sign = psw.hexdigest().upper() apiUrl = "{}/sys/productkey={}/integration/measurepoint/post"\ .format(self.__apiUrlV2,url,self.__productKey) #apiUrl = "{}/commonFileService/files?path={}&accessKey={}&requestTimestamp={}&sign={}&orgId={}" \ #.format(self.__apiUrlV1, url, self.__appAccessKey, timeStamp, sign, self.__orgId) return apiUrl # Public method which starts the connecting process to decada # @param self def connect(self): """Starts the connection process to DECADA """ self.__postClient = EnOSDefaultClient(self.__apiUrlV1, self.__appAccessKey, self.__appSecretKey) self.__setupMqttClient() def postMeasurePoints(self, measurePointsDict): """Posts measure points to DECADA :param measurePointsDict: Python dict containing measurepoints in key-value pair format :type measurePointsDict: dict """ print("posting measurepoints") filesToUpload = {} index = 0 for key, value in measurePointsDict.items(): if isinstance(value, dict): for subKey, subValue in value.items(): match = self.__filePathPattern.match(str(subValue)) if match is not None: filePath = match.group(1) name = "file" + str(index) index = index + 1 value[subKey] = "local://" + name filesToUpload[name] = open(filePath, "rb") else: match = self.__filePathPattern.match(str(value)) if match is not None: filePath = match.group(1) name = "file" + str(index) index = index + 1 measurePointsDict[key] = "local://" + name filesToUpload[name] = open(filePath, "rb") if index == 0: # no binary file as values measurePointRequestBuilder = MeasurepointPostRequest.builder() \ .set_product_key(self.__productKey) \ .set_device_key(self.__deviceKey) measurePointRequestBuilder = measurePointRequestBuilder.add_measurepoints( measurePointsDict) measurePointRequest = measurePointRequestBuilder.set_timestamp( int(time.time() * 1000)).build() measurePointResponse = self.__mqttClient.publish( measurePointRequest) if measurePointRequest: print('MeasurePointPostResponse: {}'.format( measurePointResponse.get_code())) else: data = [{ "measurepoints": measurePointsDict, "assetId": self.__assetId, "time": time.time() * 1000 }] params = {"data": json.dumps(data)} request = PostMeasurepointsEnOSRequest( org_id=self.__orgId, product_key=self.__productKey, params=params, upload_file=filesToUpload) response = self.__postClient.execute(request) print("PostMeasurepointsEnOSRequest: {}, {}, {}".format( response.status, response.msg, response.data)) def queryAttributes(self, keys): """Query attributes of asset from DECADA :param keys: Python dict containing measurepoints in key-value pair format :type keys: list :return: dictionary containing the value to each queried field :rtype: dict """ attributeQueryRequestBuilder = AttributeQueryRequest.builder() if (len(keys) > 0): for i in keys: attributeQueryRequestBuilder = attributeQueryRequestBuilder \ .add_attribute(i) else: attributeQueryRequestBuilder = attributeQueryRequestBuilder.query_all( ) attributeQueryRequest = attributeQueryRequestBuilder.build() attributeQueryResponse = self.__mqttClient.publish( attributeQueryRequest) if attributeQueryResponse.get_code() == 200: return json.loads(attributeQueryResponse.get_data()) return None # Public method which allow callers to update attributes # @param self # @param attributesDict Dictionary containing key-value pairs of attributes to be updated def updateAttributes(self, attributesDict): """Update attributes of asset :param attributesDict: Python dict containing attributes in key-value pair format :type attributesDict: dict """ attributeUpdateRequestBuilder = AttributeUpdateRequest.builder() \ .set_product_key(self.__productKey) \ .set_device_key(self.__deviceKey) for key, value in attributesDict.items(): attributeUpdateRequestBuilder = attributeUpdateRequestBuilder.add_attribute( key, value) attributeUpdateRequest = attributeUpdateRequestBuilder.build() attributeUpdateResponse = self.__mqttClient.publish( attributeUpdateRequest) if attributeUpdateResponse: print("AttributeUpdateResponse: {}".format( attributeUpdateResponse.get_code()))
if attribute_query_response: print('attribute_query_response: %s' % attribute_query_response.get_code()) def attribute_update(): """this sample is to update attribute value""" attribute_update_request = AttributeUpdateRequest.builder() \ .add_attribute("wywpoint3", 6) \ .add_attributes(SampleHelper.ATTR) \ .build() attribute_update_response = client.publish(attribute_update_request) if attribute_update_response: print('attribute_update_response: %s' % attribute_update_response.get_code()) if __name__ == "__main__": client = MqttClient(SampleHelper.TCP_SERVER_URL, SampleHelper.GW1_PRODUCT_KEY, SampleHelper.GW1_DEVICE_KEY, SampleHelper.GW1_DEVICE_SECRET) client.get_profile().set_auto_reconnect( True ) # if connection interrupted, the client can automaticlly reconnect client.setup_basic_logger('INFO') client.connect() # connect in sync attribute_delete() attribute_query() attribute_update()
service_name = arg_list[2] params = arrived_message.get_params() print('service params: {}'.format(params)) if service_name == 'multiply': left = params.get('left') right = params.get('right') return ServiceInvocationReply.builder()\ .add_output_data('result', left*right)\ .set_code(200)\ .build() else: return ServiceInvocationReply.builder().set_message( 'unknown service:').set_code(220).build() if __name__ == '__main__': client = MqttClient(SampleHelper.TCP_SERVER_URL, SampleHelper.GW_PRODUCT_KEY, SampleHelper.GW_DEVICE_KEY, SampleHelper.GW_DEVICE_SECRET) client.register_arrived_message_handler( ServiceInvocationCommand.get_class(), service_command_handler) client.connect() # connect in sync while True: time.sleep(5)
def secure_login(): static_ssl_profile = Profile.create_instance( SampleHelper.get_device_static_ssl_login()) client = MqttClient(profile=static_ssl_profile) client.get_profile().set_auto_reconnect(True) # set the certificate files for bi-directional certification client.get_profile().set_ssl_context(ca_file, cer_file, key_file, key_file_password) client.setup_basic_logger(logging.INFO) # register connection callback client.on_connect = on_connect client.on_disconnect = on_disconnect client.on_connected_failed = on_connect_failed client.connect() # connect in sync client.close()
import time from enos.core.MqttClient import MqttClient from enos.core.internal.Profile import Profile from enos.message.upstream.integration.IntModelUpRawRequest import IntModelUpRawRequest from enos.sample.SampleHelper import SampleHelper def int_model_up_raw_post(): int_model_up_raw_request = IntModelUpRawRequest.builder() \ .set_payload(SampleHelper.RAW_PAYLOAD).build() int_model_up_raw_response = up_raw_client.publish(int_model_up_raw_request) print(int_model_up_raw_response.get_payload()) if __name__ == '__main__': integration_up_raw_profile = Profile.create_instance( SampleHelper.get_message_integration_up_raw_login()) up_raw_client = MqttClient(profile=integration_up_raw_profile) up_raw_client.connect() while True: int_model_up_raw_post() time.sleep(5)
def static_device_login(): static_profile = Profile.create_instance( SampleHelper.get_device_static_login()) client = MqttClient(profile=static_profile) client.get_profile().set_auto_reconnect(True) # register connection callback client.on_connect = on_connect client.on_disconnect = on_disconnect client.on_connected_failed = on_connect_failed client.connect() # connect in sync client.close()
def dynamic_device_login(): dynamic_activation_profile = Profile.create_instance( SampleHelper.get_device_dynamic_login()) client = MqttClient(profile=dynamic_activation_profile) client.get_profile().set_auto_reconnect(True) # register dynamic activation callback to acquire device_secret client.on_device_dynamic_active = on_device_dynamic_activation # register connection callback client.on_connect = on_connect client.on_disconnect = on_disconnect client.on_connected_failed = on_connect_failed client.connect() # connect in sync client.close()
def get_measurepoint_command_handler(arrived_message, arg_list): print('receive measurepoint get command, params: {}'.format( arrived_message.get_params())) print('product key = {}, device key= {}'.format(arg_list[0], arg_list[1])) return MeasurepointGetReply().builder()\ .set_code(200) \ .add_measurepoint('wwww0001', 2) \ .set_message('measurepoints get success')\ .build() if __name__ == "__main__": client = MqttClient(SampleHelper.TCP_SERVER_URL, SampleHelper.GW_PRODUCT_KEY, SampleHelper.GW_DEVICE_KEY, SampleHelper.GW_DEVICE_SECRET) client.get_profile().set_auto_reconnect( True ) # if connection interrupted, the client can automaticlly reconnect client.setup_basic_logger('INFO') client.connect() # connect in sync # register a msg handler to handle the downstream measurepoint set command client.register_arrived_message_handler(MeasurepointSetCommand.get_class(), set_measurepoint_command_handler) client.register_arrived_message_handler(MeasurepointGetCommand.get_class(), get_measurepoint_command_handler) while True: sleep(5)
from enos.message.downstream.tsl.ModelDownRawCommand import ModelDownRawCommand from enos.message.downstream.tsl.ModelDownRawReply import ModelDownRawReply from enos.sample.SampleHelper import SampleHelper def down_raw_handler(arrived_message, arg_list): payload = arrived_message.get_payload() print('receive model down raw message, payload: {}'.format(payload)) reply = ModelDownRawReply() reply.set_payload(SampleHelper.RAW_PAYLOAD_REPLY) reply.set_code(200) return reply if __name__ == '__main__': client = MqttClient(SampleHelper.TCP_SERVER_URL, SampleHelper.SUB_PRODUCT_KEY_DOWN_RAW, SampleHelper.SUB_DEVICE_KEY_DOWN_RAW, SampleHelper.SUB_DEVICE_SECRET_DOWN_RAW) client.setup_basic_logger('INFO') client.register_arrived_message_handler(ModelDownRawCommand.get_class(), down_raw_handler) client.connect() # connect in sync while True: time.sleep(5)
from enos.core.MqttClient import MqttClient from enos.message.upstream.register.DeviceRegisterRequest import DeviceRegisterRequest from enos.sample.SampleHelper import SampleHelper def device_register(): """this sample is to register a sub_device in cloud""" device_register_request = DeviceRegisterRequest.builder() \ .add_register_information(SampleHelper.SUB1_PRODUCT_KEY, 'device_key_test_1', SampleHelper.SUB_DEVICE_NAME, "dev desc", '+08:00') \ .add_register_information(SampleHelper.SUB1_PRODUCT_KEY, 'device_key_test_attr', SampleHelper.SUB_DEVICE_NAME, "dev desc", '+08:00', SampleHelper.ATTRIBUTES)\ .build() device_register_response = client.publish(device_register_request) if device_register_response: print('device_register_response: %s' % device_register_response.get_code()) print('device_register_response: %s' % device_register_response.get_message()) if __name__ == "__main__": client = MqttClient(SampleHelper.TCP_SERVER_URL, SampleHelper.GW1_PRODUCT_KEY, SampleHelper.GW1_DEVICE_KEY, SampleHelper.GW1_DEVICE_SECRET) client.connect() device_register()
def on_connect(): """ Called when the connection to the server is completed.""" print('connect success') client.register_arrived_message_handler( ServiceInvocationCommand.get_class(), service_command_handler) print('waiting commands from cloud') def on_disconnect(): """ Called when the client connection lost.""" print('connect lost') def on_connect_failed(): """ Called when the client connect failed""" print('connect failed...') if __name__ == '__main__': client = MqttClient(TCP_SERVER_URL, PRODUCT_KEY, DEVICE_KEY, DEVICE_SECRET) client.get_profile().set_auto_reconnect(True) # register connection callback client.on_connect = on_connect client.on_disconnect = on_disconnect client.on_connected_failed = on_connect_failed client.connect() # connect in sync monitor()
from enos.core.MqttClient import MqttClient from enos.message.upstream.tsl.ModelUpRawRequest import ModelUpRawRequest from enos.sample.SampleHelper import SampleHelper def post_model_up_raw(): """ Device can report raw data (such as binary data stream) """ post_model_up_raw_request = ModelUpRawRequest.builder() \ .set_payload(SampleHelper.RAW_PAYLOAD) \ .build() post_model_up_raw_response = client.publish(post_model_up_raw_request) print(post_model_up_raw_response.get_payload()) if __name__ == "__main__": client = MqttClient(SampleHelper.TCP_SERVER_URL, SampleHelper.GW_PRODUCT_KEY_RAW, SampleHelper.GW_DEVICE_KEY_RAW, SampleHelper.GW_DEVICE_SECRET_RAW) client.get_profile().set_auto_reconnect(True) client.setup_basic_logger('INFO') client.connect() # connect in sync post_model_up_raw()
import random import time from enos.core.MqttClient import MqttClient from enos.core.internal.Profile import Profile from enos.core.message.IResponseCallback import IResponseCallback from enos.message.upstream.integration.IntAttributePostRequest import IntAttributePostRequest from enos.message.upstream.integration.IntEventPostRequest import IntEventPostRequest from enos.message.upstream.integration.IntMeaturepointPostRequest import IntMeaturepointPostRequest from enos.sample.SampleHelper import SampleHelper class ResponseCallback(IResponseCallback): def on_response(self, response): print('[async] receive {} successfully, code: {}'.format( response.get_class(), str(response.get_code()))) if not response.is_success(): print('[async] error message: {}'.format(response.get_message())) def on_failure(self, exception): print('[async] publish failed, exception: {}'.format(exception)) def int_measure_point_post(): int_measure_points_request = IntMeaturepointPostRequest.builder() \ .add_meaturepoint(SampleHelper.GW_DEVICE_KEY, int(time.time() * 1000), {'wwww0001': random.randint(100, 200)}) \ .build() int_measure_points_response = client.publish(int_measure_points_request) if int_measure_points_response.is_success(): print('[sync] receive {} successfully, code: {}'.format( int_measure_points_response.get_class(), str(int_measure_points_response.get_code()))) client.publish(int_measure_points_request, ResponseCallback())
class SampleHelper: TCP_SERVER_URL = "tcp://xxx:11883" # for beta tcp connection SSL_SERVER_URL = "ssl://xxx:18883" # for beta ssl connection GW_PRODUCT_KEY = "gw_product_key" GW_PRODUCT_SECRET = "gw_product_secret" GW_DEVICE_KEY = "gw_device_key" GW_DEVICE_SECRET = "gw_device_secret" # measurepoint_resume/device_register/report_measurepoint GW1_PRODUCT_KEY = "gw1_product_key" GW1_PRODUCT_SECRET = "gw1_product_secret" GW1_DEVICE_KEY = "gw1_device_key" GW1_DEVICE_SECRET = "gw1_device_secret" # get_tsl_template/attribute_query GW2_PRODUCT_KEY = "gw2_product_key" GW2_PRODUCT_SECRET = "gw2_product_secret" GW2_DEVICE_KEY = "gw2_device_key" GW2_DEVICE_SECRET = "gw2_device_secret" # login_device/ota/topo GW3_PRODUCT_KEY = "gw3_product_key" GW3_PRODUCT_SECRET = "gw3_product_secret" GW3_DEVICE_KEY = "gw3_device_key" GW3_DEVICE_SECRET = "gw3_device_secret" GW_PRODUCT_KEY_RAW = "gw_product_key_raw" GW_PRODUCT_SECRET_RAW = "gw_product_secret_raw" GW_DEVICE_KEY_RAW = "gw_device_key_raw" GW_DEVICE_SECRET_RAW = "gw_device_secret_raw" # sud_device SUB_PRODUCT_KEY = "sub_product_key" SUB_PRODUCT_SECRET = "sub_product_secret" SUB_DEVICE_KEY = "sub_device_key" SUB_DEVICE_SECRET = "sub_device_secret" # up raw device SUB_PRODUCT_KEY_RAW = "sub_product_key_raw" SUB_PRODUCT_SECRET_RAW = "sub_product_secret_raw" SUB_DEVICE_KEY_RAW = "sub_device_key_raw" SUB_DEVICE_SECRET_RAW = "sub_device_secret_raw" # down raw device SUB_PRODUCT_KEY_DOWN_RAW = "sub_product_key_down_raw" SUB_PRODUCT_SECRET_DOWN_RAW = "sub_product_secret_down_raw" SUB_DEVICE_KEY_DOWN_RAW = "sub_device_key_down_raw" SUB_DEVICE_SECRET_DOWN_RAW = "sub_device_secret_down_raw" # get_sub_tsl_template SUB_PRODUCT_KEY_TSL_TEMPLATE = "sub_product_key_tsl_template" SUB_PRODUCT_SECRET_TSL_TEMPLATE = "sub_product_secret_tsl_template" SUB_DEVICE_KEY_TSL_TEMPLATE = "sub_device_key_tsl_template" SUB_DEVICE_SECRET_TSL_TEMPLATE = "sub_device_secret_tsl_template" # topo request SUB_PRODUCT_KEY_TOPO = "sub_product_key_topo" SUB_PRODUCT_SECRET_TOPO = "sub_product_secret_topo" SUB_DEVICE_KEY_TOPO = "sub_device_key_topo" SUB_DEVICE_SECRET_TOPO = "sub_device_secret_topo" # device_register/MEASUREPOINT_BATCH_RESUME/report_measurepoint SUB1_PRODUCT_KEY = "sub1_product_key" SUB1_PRODUCT_SECRET = "sub1_product_secret" SUB1_DEVICE_KEY = "sub1_device_key" SUB1_DEVICE_SECRET = "sub1_device_secret" # loginbatch/Ota SUB2_PRODUCT_KEY = "sub2_product_key" SUB2_PRODUCT_SECRET = "sub2_product_secret" SUB2_DEVICE_KEY = "sub2_device_key" SUB2_DEVICE_SECRET = "sub2_device_secret" SUB3_PRODUCT_KEY = "sub3_product_key" SUB3_PRODUCT_SECRET = "sub3_product_secret" SUB3_DEVICE_KEY = "sub3_device_key" SUB3_DEVICE_SECRET = "sub3_device_secret" EVENT_DICT = {'temp': 120.0, 'desc': 'temp too high'} # for model_up_raw RAW_PAYLOAD = bytes([ 0x01, 0x00, 0x00, 0x00, 0x14, 0x01, 0x00, 0x04, 0x00, 0x00, 0x26, 0xf5 ]) RAW_PAYLOAD_REPLY = bytes([0x02, 0x00, 0x00, 0x00, 0x14, 0x00, 0xc8]) DYNAMIC_ACTIVATE_PRODUCT_KEY = "dynamic_activate_product_key" DYNAMIC_ACTIVATE_PRODUCT_SECRET = "dynamic_activate_product_secret" DYNAMIC_ACTIVATE_DEVICE_KEY = "dynamic_activate_device_key" SUB_DEVICE_NAME = (StringI18n("auto_test OldDeviceEnosApiTest device1111")) SUB_DEVICE_NAME.set_localized_value( locale.setlocale(locale.LC_ALL, 'zh_CN'), '中文设备01') SUB_DEVICE_NAME.set_localized_value( locale.setlocale(locale.LC_ALL, 'en_US'), 'eng_dev_01') CLIENT = MqttClient(TCP_SERVER_URL, GW2_PRODUCT_KEY, GW2_DEVICE_KEY, GW2_DEVICE_SECRET) SUB_DEVICE = DeviceCredential(SUB_PRODUCT_KEY, None, SUB_DEVICE_KEY, SUB_DEVICE_SECRET) # for report measure_points MEASURE_POINTS = {'measurepoint1': 99, 'measurepoint2': 00} # for attributes query ATTR = {'attribute1': 4, 'attribute2': 5} ATTRIBUTES_KEY = {'attribute1', 'attribute2'} EVENTS_VALUE = {'time': 2, 'weather': 6.0} # for add sub_devices topo test SUB_DERVICES_FOR_ADD_TOPO = list() SUB_DERVICES_FOR_TOPO1 = SubDeviceInfo(SUB2_PRODUCT_KEY, SUB2_DEVICE_KEY, SUB2_DEVICE_SECRET) SUB_DERVICES_FOR_TOPO2 = SubDeviceInfo(SUB_PRODUCT_KEY_RAW, SUB_DEVICE_KEY_RAW, SUB_DEVICE_SECRET_RAW) SUB_DERVICES_FOR_ADD_TOPO.append(SUB_DERVICES_FOR_TOPO1) SUB_DERVICES_FOR_ADD_TOPO.append(SUB_DERVICES_FOR_TOPO2) # for delete sub_devices topo test SUB_DERVICES_FOR_DELETE_TOPO = list() SUB_DERVICES_FOR_TOPO1 = (SUB2_PRODUCT_KEY, SUB2_DEVICE_KEY) SUB_DERVICES_FOR_TOPO2 = (SUB_PRODUCT_KEY_RAW, SUB_DEVICE_KEY_RAW) SUB_DERVICES_FOR_DELETE_TOPO.append(SUB_DERVICES_FOR_TOPO1) SUB_DERVICES_FOR_DELETE_TOPO.append(SUB_DERVICES_FOR_TOPO2) SUB_DEVICES = list() SUB_DEVICES.append( DeviceCredential(SUB1_PRODUCT_KEY, "", SUB1_DEVICE_KEY, SUB1_DEVICE_SECRET)) SUB_DEVICES.append( DeviceCredential(SUB3_PRODUCT_KEY, "", SUB3_DEVICE_KEY, SUB3_DEVICE_SECRET)) TAGS = {'tag1': 30, 'tag2': 40} ATTRIBUTES = {'attribute': 1, 'attribute2': 3} @classmethod def get_device_static_login(cls): return NormalDeviceLogin(cls.TCP_SERVER_URL, cls.GW_PRODUCT_KEY, cls.GW_DEVICE_KEY, cls.GW_DEVICE_SECRET) @classmethod def get_device_static_ssl_login(cls): return NormalDeviceLogin(cls.SSL_SERVER_URL, cls.GW_PRODUCT_KEY, cls.GW_DEVICE_KEY, cls.GW_DEVICE_SECRET) @classmethod def get_device_dynamic_login(cls): return DynamicActivationLogin(cls.TCP_SERVER_URL, cls.DYNAMIC_ACTIVATE_PRODUCT_KEY, cls.DYNAMIC_ACTIVATE_PRODUCT_SECRET, cls.DYNAMIC_ACTIVATE_DEVICE_KEY) @classmethod def get_message_integration_login(cls): return MessageIntegrationLogin(cls.TCP_SERVER_URL, cls.GW_PRODUCT_KEY, cls.GW_PRODUCT_SECRET) @classmethod def get_message_integration_up_raw_login(cls): return MessageIntegrationLogin(cls.TCP_SERVER_URL, cls.SUB_PRODUCT_KEY_RAW, cls.SUB_PRODUCT_SECRET_RAW)