Avant de connecter un appareil à IoT Platform, celui-ci doit passer la vérification d'identité. Cette rubrique explique comment initialiser Link SDK pour Android afin de connecter un appareil à IoT Platform.
Prérequis
Un produit et un appareil ont été créés. Pour plus d'informations, consultez la section Créer un produit et un appareil.
Le package de démonstration de Link SDK pour Android a été téléchargé.
Les informations du certificat de l'appareil et l'endpoint auquel vous souhaitez connecter l'appareil ont été obtenus. Pour plus de détails, reportez-vous aux configurations des paramètres dans la rubrique Link SDK pour Android.
Informations générales
Link SDK pour Android vous permet d'utiliser un DeviceSecret ou un IoT Device ID (ID²) pour vérifier l'identité d'un appareil.
-
Utilisation d'un DeviceSecret pour vérifier un appareil :
Méthode de vérification
Méthode d'enregistrement
Description
N/A
Un certificat d'appareil incluant un ProductKey, un DeviceName et un DeviceSecret est gravé sur chaque appareil.
Préenregistrement
Un certificat de produit incluant un ProductKey et un ProductSecret est gravé sur tous les appareils d'un produit.
Vous devez activer la fonctionnalité dynamic registration pour le produit.
L'enregistrement dynamique permet à un appareil d'obtenir un DeviceSecret.
Sans préenregistrement
Un certificat de produit incluant un ProductKey et un ProductSecret est gravé sur tous les appareils d'un produit.
Vous devez activer la fonctionnalité dynamic registration pour le produit.
L'enregistrement dynamique permet aux appareils d'obtenir une combinaison du ClientID et du DeviceToken.
RemarquePour connaître les différences entre la vérification par certificat unique par produit avec préenregistrement et celle sans préenregistrement, consultez la section Différences entre les méthodes de vérification.
Utiliser un ID² pour vérifier un appareil : un ID² est un identificateur fiable pour un appareil IoT Platform. L'ID² est résistant à la falsification et infalsifiable.
Pour savoir comment utiliser un ID² afin de vérifier un appareil, consultez l'exemple de code dans le fichier InitManager.java.
Vérification par certificat unique par appareil
Exemple de code pour la méthode de vérification par certificat unique par appareil :
AppLog.setLevel(ALog.LEVEL_DEBUG);
final LinkKitInitParams params = new LinkKitInitParams();
String productKey = "${YourProductKey}";
String deviceName = "${YourDeviceName}";
String deviceSecret = "${YourDeviceSecret}";
String productSecret = "";
// Step 1: Specify the information about a device certificate.
DeviceInfo deviceInfo = new DeviceInfo();
deviceInfo.productKey = productKey; // The ProductKey of the product.
deviceInfo.deviceName = deviceName; // The DeviceName of the device.
deviceInfo.deviceSecret = deviceSecret; // The DeviceSecret of the device.
deviceInfo.productSecret = productSecret; // The ProductSecret of the product.
params.deviceInfo = deviceInfo;
// Step 2: Specify the global default domain name.
IoTApiClientConfig userData = new IoTApiClientConfig();
params.connectConfig = userData;
// Step 3: Cache the Thing Specification Language (TSL) model.
Map<String, ValueWrapper> propertyValues = new HashMap<>();
/**
* The TSL data is cached in the preceding parameter. You cannot delete or leave this parameter empty. Otherwise, TSL-related features may fail.
* After you call an API operation to submit TSL data, the TSL data is cached.
*/
params.propertyValues = propertyValues;
// Step 4: Configure MQTT parameters.
/**
* The MQTT parameters, such as the endpoint. For more information, see the deviceinfo file.
* The domain name, ProductSecret, and security verification method.
*/
IoTMqttClientConfig clientConfig = new IoTMqttClientConfig();
clientConfig.receiveOfflineMsg = false;//cleanSession=1 Offline messages cannot be received.
// The information about the Message Queuing Telemetry Transport (MQTT) endpoint.
clientConfig.channelHost = "${YourMqttHostUrl}:8883";
params.mqttClientConfig = clientConfig;
MqttConfigure.pingSenderType = "android"; // Set the heartbeat detection type to android and set the timer type for heartbeat detection to AlarmTImer. This ensures that the heartbeat detection is performed as scheduled when the display is automatically shut down.
// Step 5: Configure advanced features. By default, all advanced features are disabled except for the TSL model feature.
IoTDMConfig ioTDMConfig = new IoTDMConfig();
// By default, the TSL model feature is enabled. After you initialize the TSL model that is requested from IoT Platform, onInitDone is returned.
ioTDMConfig.enableThingModel = true;
// By default, the gateway feature is disabled. After you enable the gateway feature, the gateway module is initialized to obtain the sub-device list of the gateway module from IoT Platform.
ioTDMConfig.enableGateway = false;
// By default, the log push feature is disabled. You can enable this feature.
ioTDMConfig.enableLogPush = false;
params.ioTDMConfig = ioTDMConfig;
// Step 6: Configure a callback function to process downstream messages.
LinkKit.getInstance().registerOnPushListener(new IConnectNotifyListener() {
@Override
public void onNotify(String s, String s1, AMessage aMessage) {
// You can configure the callback function for downstream message processing based on the documentation.
}
@Override
public boolean shouldHandle(String s, String s1) {
return true; // Configure the parameters based on your business requirements and the documentation.
}
@Override
public void onConnectStateChange(String s, ConnectState connectState) {
// The callback for the connection status change of the corresponding connection type. For information about the connection status, see ConnectState in the SDK.
// If the SDK disconnects the device from IoT Platform due to poor network conditions, the SDK automatically attempts to reconnect the device to IoT Platform at intervals of 2 to the power of n (unit: seconds). n is an integer ranging from 0 to 7. The maximum interval is 128s.
}
});
// If you want to verify a device by using the preregistration-free unique-certificate-per-product verification method, the DeviceToken and ClientID are required when you connect the device to IoT Platform.
// Step7: Configure the parameters for the preregistration-free unique-certificate-per-product verification. This feature is disabled by default.
// MqttConfigure.deviceToken = DemoApplication.deviceToken;
// MqttConfigure.clientId = DemoApplication.clientId;
// Step8: Configure parameters that are required to upload files over HTTP/2.
/**
* If you want to upload files to IoT Platform over HTTP/2, you must specify a domain name.
*/
// IoTH2Config ioTH2Config = new IoTH2Config();
// ioTH2Config.clientId = "client-id";
// ioTH2Config.endPoint = "https://" + productKey + ioTH2Config.endPoint;// The endpoint that is used to upload files over HTTP/2 to IoT Platform.
// params.iotH2InitParams = ioTH2Config;
/**
* Initialize the SDK to connect a device to IoT Platform.
* onError The initialization failed. If the initialization fails due to network issues, you must re-initialize the SDK.
* onInitDone The initialization is successful.
*/
LinkKit.getInstance().init(getAppContext(), params, new ILinkKitConnectListener() {
@Override
public void onError(AError error) {
ALog.d(TAG, "onError() called with: error = [" + (error) + "]");
}
@Override
public void onInitDone(Object data) {
ALog.d(TAG, "onInitDone() called with: data = [" + data + "]");
// Device verification is complete and the device is connected. You can run your business as required.
}
});
Vérification par certificat unique par produit
La vérification par certificat unique par produit est également appelée enregistrement dynamique. Cette fonctionnalité permet de demander des DeviceSecrets à IoT Platform. Les méthodes de vérification par certificat unique par produit se divisent en deux types : sans préenregistrement et avec préenregistrement. Avant d'utiliser cette fonctionnalité, assurez-vous que les conditions suivantes sont remplies :
L'option Dynamic Registration est activée pour un produit que vous avez créé dans la console IoT Platform.
Dans le fichier
deviceinfodu package de démonstration, le paramètre deviceSecret est laissé vide et le paramètre productSecret n'est pas vide.Les étapes 1 à 3 de l'exemple de code sont effectuées.
Après la réussite ou l'échec d'un enregistrement dynamique, fermez la connexion persistante utilisée pour l'enregistrement dynamique. Pour savoir comment fermer la connexion, reportez-vous à l'étape 4.
Pour garantir la sécurité de l'appareil, gravez un DeviceSecret sur l'appareil après avoir obtenu ce dernier via la méthode de vérification par certificat unique par produit.
Le tableau suivant décrit les différences entre les méthodes de vérification par certificat unique par produit sans préenregistrement et avec préenregistrement.
Élément | Avec préenregistrement | Sans préenregistrement |
Protocoles | MQTT et HTTPS | MQTT |
Régions |
| Chine (Shanghai) et Chine (Pékin) |
DeviceSecrets renvoyés | Pour savoir comment utiliser un DeviceSecret, consultez l'étape 1 de l'exemple de code pour la vérification par certificat unique par appareil. | Gravez le ClientID et le DeviceToken d'un appareil sur l'appareil. Ainsi, ces informations pourront être utilisées lors de l'utilisation de certaines fonctionnalités, telles que la connexion de l'appareil à IoT Platform. Pour plus d'informations, consultez l'étape 7 de l'exemple de code pour la vérification par certificat unique par appareil. |
Enregistrement de l'appareil | Vous devez préenregistrer le DeviceName d'un appareil dans la console IoT Platform. | Vous n'avez pas besoin de préenregistrer le DeviceName d'un appareil dans la console IoT Platform. |
Nombre d'utilisations |
| Chaque ProductKey, ProductSecret et DeviceName peut servir à activer jusqu'à cinq appareils physiques. Vous pouvez activer les appareils simultanément dans la console IoT Platform. IoT Platform génère un ClientID et un DeviceToken uniques pour chaque appareil. |
Pour plus d'informations sur le code, consultez le fichier DemoApplication.java dans le package de démonstration.
Exemple de code pour l'enregistrement dynamique :
String productKey = "${YourProductKey}";
String deviceName = "${YourDeviceName}";
String deviceSecret = "${YourDeviceSecret}";
String productSecret = "";
MqttInitParams initParams = new MqttInitParams(productKey, productSecret, deviceName, deviceSecret, MqttConfigure.MQTT_SECURE_MODE_TLS);
// Step 1: Check whether the unique-certificate-per-product verification method is preregistration-free or pre-registration.
// Case 1: If you set the registerType parameter to regnwl, the preregistration-free unique-certificate-per-product verification method is used and you do not need to create a device.
// Case 2: If you leave the registerType parameter empty or set the registerType parameter to register, the pre-registration unique-certificate-per-product verification method is used and you must create a device.
initParams.registerType = "";
// Step 2: Specify an endpoint for dynamic registration.
MqttConfigure.mqttHost = "${YourMqttHostUrl}:8883";;
// (Optional) Step 3: You must specify this parameter for Enterprise Edition instances, or public instances of the IoT Platform service that is activated on July 30, 2021 and later.
// For public instances of the IoT Platform service that was activated before July 30, 2021, the value of this parameter is an empty string "".
MqttConfigure.registerInstanceId = "${YourInstanceId}";
final Object lock = new Object();
LinkKit.getInstance().deviceDynamicRegister(this, initParams, new IOnCallListener() {
@Override
public void onSuccess(com.aliyun.alink.linksdk.channel.core.base.ARequest request, com.aliyun.alink.linksdk.channel.core.base.AResponse response) {
ALog.i(TAG, "onSuccess() called with: request = [" + request + "], response = [" + response + "]");
// response.data is byte array
try {
String responseData = new String((byte[]) response.data);
JSONObject jsonObject = JSONObject.parseObject(responseData);
String pk = jsonObject.getString("productKey");
String dn = jsonObject.getString("deviceName");
// The result returned if the pre-registration unique-certificate-per-product verification method is used.
String deviceSecret = jsonObject.getString("deviceSecret");
// The result returned if the preregistration-free unique-certificate-per-product verification method is used.
String clientId = jsonObject.getString("clientId");
String deviceToken = jsonObject.getString("deviceToken");
// Save the returned credentials and proceed to Step 4. After you complete Step 4, you can use the onSuccess method to connect the device to IoT Platform.
// Call the API operation that waits for the thread.
synchronized (lock){
lock.notify();
}
} catch (Exception e) {
}
}
@Override
public void onFailed(com.aliyun.alink.linksdk.channel.core.base.ARequest request, com.aliyun.alink.linksdk.channel.core.base.AError error) {
ALog.e(TAG, "onFailed() called with: request = [" + request + "], error = [" + error + "]");
// Call the API operation that waits for the thread.
synchronized (lock){
lock.notify();
}
}
@Override
public boolean needUISafety() {
return false;
}
});
try{
// Wait for a downstream message. In most cases, the downstream message is returned within 1 second.
synchronized (lock){
lock.wait(3000);
}
// Step 4: Exit dynamic registration
// Do not run the following function in the LinkKit.getInstance().deviceDynamicRegister callback function. Otherwise, an error may occur.
LinkKit.getInstance().stopDeviceDynamicRegister(10 * 1000, null, new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken iMqttToken) {
ALog.d(TAG, "onSuccess() called with: iMqttToken = [" + iMqttToken + "]");
// Connect the device to IoT Platform and initialize the connection based on the unique-certificate-per-device verification method.
}
@Override
public void onFailure(IMqttToken iMqttToken, Throwable throwable) {
ALog.w(TAG, "onFailure() called with: iMqttToken = [" + iMqttToken + "], throwable = [" + throwable + "]");
}
});
}catch (Exception e){
};
Vérification de l'appareil basée sur ID²
. /**
* Create a device that uses the iTLS-based verification in the IoT Platform console and perform the iTLS-based verification to initialize the device.
* Grant the ID² permissions to the product to which the device belongs.
*/
IoTMqttClientConfig clientConfig = new IoTMqttClientConfig(productKey, deviceName, deviceSecret);
clientConfig.channelHost = productKey + ".itls.cn-shanghai.aliyuncs.com:1883";
clientConfig.productSecret = productSecret;
clientConfig.secureMode = 8;
linkKitInitParams.mqttClientConfig = clientConfig;
// If you use an Enterprise Edition instance or a public instance of the IoT Platform service that was activated on July 30, 2021 or later, you can specify the instance ID by replacing the ${Instance ID} variable in the following command with the actual instance ID in the iot-******* format.
MqttConfigure.extraMqttClientIdItems=",instanceId=" + "${Instance ID}";
Le paramètre clientConfig.channelHost dans l'exemple de code spécifie l'endpoint que l'appareil peut utiliser pour se connecter à IoT Platform.
Paramètres supplémentaires
Vous pouvez configurer les paramètres suivants pour définir des paramètres supplémentaires liés à la connexion de l'appareil.
-
Connexion MQTT
Élément
Description
Exemple de code
Intervalle de maintien de connexion
Définissez un intervalle de maintien de connexion pour un appareil. Ce paramètre spécifie la durée pendant laquelle une connexion persistante peut être conservée entre l'appareil et IoT Platform.
RemarqueLa période de maintien de connexion par défaut définie dans le SDK est de 65 secondes.
Vous pouvez spécifier un intervalle de maintien de connexion compris entre 30 et 1 200 secondes.
// The keepalive interval. Unit: seconds. MqttConfigure.setKeepAliveInterval(int interval);Niveau QoS
Spécifiez un niveau de Quality of Service (QoS). Un niveau QoS est un accord qui définit la qualité de la livraison des messages entre un appareil et IoT Platform. Valeurs possibles :
0: chaque message est livré au plus une fois.1: chaque message est livré au moins une fois.
MqttPublishRequest request = new MqttPublishRequest(); // Valid values: 0 and 1. Default value: 0. request.qos = 0; request.isRPC = false; request.topic = topic.replace("request", "response"); String resId = topic.substring(topic.indexOf("rrpc/request/")+13); request.msgId = resId; // Configure the parameters based on your business requirements. request.payloadObj = "{\"id\":\"" + resId + "\", \"code\":\"200\"" + ",\"data\":{} }";Messages hors ligne
Le paramètre cleanSession indique s'il faut recevoir les messages hors ligne.
IoTMqttClientConfig clientConfig = new IoTMqttClientConfig(); // Correspond to the following code: receiveOfflineMsg = !cleanSession. By default, offline messages cannot be received. clientConfig.receiveOfflineMsg = true;Le ClientID.
Le paramètre clientId spécifie un ClientID. Pour plus d'informations, consultez la description du paramètre clientId.
MqttConfigure.clientId = "abcdef******";Mécanisme de reconnexion
Le paramètre automaticReconnect indique s'il faut reconnecter un appareil à IoT Platform. Valeurs possibles :
true: le système reconnecte l'appareil à IoT Platform.false: le système ne reconnecte pas l'appareil à IoT Platform.
Exemple de code :
MqttConfigure.automaticReconnect = true; -
Désinitialisation du SDK
Pour effectuer la désinitialisation, appelez la fonction suivante. La fonction fonctionne de manière synchrone.
RemarqueSi vous souhaitez initialiser le SDK, assurez-vous que la désinitialisation précédente du SDK est terminée. Sinon, l'initialisation du SDK pourrait échouer.
// Unregister the notifyListener object. The object must be the same as the notifyListener object that is registered. LinkKit.getInstance().unRegisterOnPushListener(notifyListener); LinkKit.getInstance().deinit(); -
État de la connexion et écouteurs de messages descendants
Vous pouvez configurer l'écouteur suivant pour surveiller les messages de connexion et de déconnexion d'un appareil, ainsi que les données envoyées depuis IoT Platform :
IConnectNotifyListener notifyListener = new IConnectNotifyListener() { @Override public void onNotify(String connectId, String topic, AMessage aMessage) { // The callback for downstream data from IoT Platform. // The connectId parameter specifies a connection type, the topic parameter specifies a downstream topic from IoT Platform, and the aMessage parameter specifies downstream data from IoT Platform. // Define a function named pushData to parse data. //String pushData = new String((byte[]) aMessage.data); // pushData example: {"method":"thing.service.test_service","id":"123374967","params":{"vv":60},"version":"1.0.0"} // The method parameter specifies a service type, and the params parameter specifies the content of data that you want to push. } @Override public boolean shouldHandle(String connectId, String topic) { // Specify whether to process the downstream data of a topic from IoT Platform. // If a topic is not processed, the onNotify listener cannot receive the downstream data of the topic from IoT Platform. return true; // Specify a value based on your business scenario. } @Override public void onConnectStateChange(String connectId, ConnectState connectState) { // The callback for the connection status change of the corresponding connection type. For information about the connection status, see the description of ConnectState in the SDK. // If the SDK disconnects the device from IoT Platform due to poor network conditions, the SDK automatically attempts to reconnect the device to IoT Platform at intervals of 2 to the power of n (unit: seconds). n is an integer ranging from 0 to 7. The maximum interval is 128s. After the interval reaches 128s, the SDK attempts to reconnect the device to IoT Platform at the interval of 128s until the device is connected. } } // Register a listener to listen to downstream data, including the status of a persistent connection and downstream data from IoT Platform. LinkKit.getInstance().registerOnPushListener(notifyListener); // Unregister the listener that listens to downstream data. Make sure that the listener to be unregistered is the same as the listener that you registered. // LinkKit.getInstance().unRegisterOnPushListener(notifyListener);RemarquePar défaut, la fonction de rappel
onNotifyest appelée pour transmettre les données descendantes dans le thread d'interface utilisateur. Danslp-iot-linkkitV1.7.3 et versions ultérieures, vous pouvez définir le paramètrePersistentConnect.mNotifyReceivedMsgOnMainThreadsur false pour transmettre les données descendantes dans des threads autres que le thread d'interface utilisateur. Nous vous recommandons de définir le paramètre PersistentConnect.mNotifyReceivedMsgOnMainThread surfalselorsque les messages descendants sont fréquemment transmis ou que le thread d'interface utilisateur est surchargé. -
Commutateur de journalisation
Activez le commutateur de sortie des journaux internes du SDK pour Android :
PersistentNet.getInstance().openLog(true); ALog.setLevel(ALog.LEVEL_DEBUG); -
Obtenez le numéro de version du SDK pour Android :
ALog.i(TAG, "sdk version = " + LinkKit.getInstance().getSDKVersion());
Reconnecter rapidement un appareil Android
Si le SDK pour Android déconnecte un appareil d'IoT Platform, l'appareil est automatiquement reconnecté à IoT Platform après 65 secondes. Si vous souhaitez reconnecter l'appareil après un intervalle personnalisé suite à la déconnexion, suivez les étapes ci-dessous :
Importez
import com.aliyun.alink.linksdk.channel.core.persistent.PersistentNet;et appelez la fonctionPersistentNet.getInstance().reconnect();.Si vous souhaitez spécifier un intervalle de reconnexion personnalisé, démarrez un minuteur. À la fin du minuteur, appelez la fonction
PersistentNet.getInstance().reconnect();pour rétablir en temps réel une connexion MQTT fermée.
Remarques relatives au package de démonstration
Si l'initialisation d'un appareil échoue, vous devez réinitialiser le SDK. Si un appareil est déconnecté d'IoT Platform pour des raisons spécifiques, telles que des pannes réseau, le SDK reconnecte automatiquement l'appareil à IoT Platform.
Modifiez les paramètres requis du fichier
./app/src/main/res/raw/deviceinfodans le package de démonstration de Link SDK pour Android pour connecter un appareil à IoT Platform. Configurez les paramètres marqués comme Obligatoire et utilisez les valeurs par défaut pour les paramètres marqués comme Facultatif. Le tableau suivant décrit les paramètres.Si vous connectez un appareil à une instance publique de la nouvelle version ou à une instance Enterprise Edition, accédez à la page Instance Details dans la console IoT Platform et copiez le numéro de port affiché sur la page. Format :
{instanceid}.mqtt.iothub.aliyuncs.com:8883Si vous connectez un appareil à une instance publique de la version précédente, aucun numéro de port n'est affiché sur la page Instance Details dans la console IoT Platform. Vous devez spécifier un numéro de port pour l'endpoint que vous avez copié depuis la page. Format :
{YourProductKey}.iot-as-mqtt.{region}.aliyuncs.com:8883. Pour plus d'informations, consultez la section Afficher l'endpoint d'une instance.
Paramètre | Description | Vérification par certificat unique par appareil | Vérification par certificat unique par produit avec préenregistrement | Vérification par certificat unique par produit sans préenregistrement |
productKey | L'identifiant unique émis par IoT Platform pour le produit. | Obligatoire | Obligatoire | Obligatoire |
deviceName | L'identifiant unique de l'appareil au sein du produit. | Obligatoire | Obligatoire | Obligatoire |
productSecret | Le ProductSecret du produit. | Facultatif | Obligatoire | Obligatoire |
deviceSecret | Le DeviceSecret de l'appareil. | Obligatoire | Facultatif | Facultatif |
registerType | La vérification par certificat unique par produit sans préenregistrement ou avec préenregistrement. | Facultatif | Facultatif | Obligatoire. Définissez la valeur sur regnwl. |
instanceId | L'ID de l'instance. Les instances Enterprise Edition et les instances publiques de la nouvelle version possèdent des IDs d'instance. Pour plus d'informations, consultez la section Présentation des instances IoT Platform. | Facultatif | Obligatoire | Obligatoire |
mqttHost | L'endpoint utilisé par un appareil pour se connecter à l'instance IoT Platform via MQTT. | Obligatoire, sauf pour les instances de la région Chine (Shanghai). Vous devez spécifier le nom de domaine et le numéro de port dans l'endpoint en fonction de votre région réelle. | ||