var rp = require('request-promise');
const crypto = require('crypto');
const deviceConfig = {
productKey: "替换productKey",
deviceName: "替换deviceName",
deviceSecret: "替换deviceSecret"
}
const topic = `/sys/${deviceConfig.productKey}/${deviceConfig.deviceName}/thing/event/property/post`;
//1.获取身份token
rp(getAuthOptions(deviceConfig))
.then(function(parsedBody) {
console.log('Auth Info :'+JSON.stringify(parsedBody))
//2.发布物模型数据
pubData(topic, parsedBody.info.token, getPostData())
})
.catch(function(err) {
console.log('Auth err :'+JSON.stringify(err))
});
//生成Auth认证的参数
function getAuthOptions(deviceConfig) {
const params = {
productKey: deviceConfig.productKey,
deviceName: deviceConfig.deviceName,
timestamp: Date.now(),
clientId: Math.random().toString(36).substr(2),
}
//1.生成clientId,username,password
var password = signHmacSha1(params, deviceConfig.deviceSecret);
var options = {
method: 'POST',
uri: 'https://iot-as-http.cn-shanghai.aliyuncs.com/auth',
body: {
"version": "default",
"clientId": params.clientId,
"signmethod": "hmacsha1",
"sign": password,
"productKey": deviceConfig.productKey,
"deviceName": deviceConfig.deviceName,
"timestamp": params.timestamp
},
json: true
};
return options;
}
//publish Data to IoT
function pubData(topic, token, data) {
const options = {
method: 'POST',
uri: 'https://iot-as-http.cn-shanghai.aliyuncs.com/topic' + topic,
body: data,
headers: {
password: token,
'Content-Type': 'application/octet-stream'
}
}
rp(options)
.then(function(parsedBody) {
console.log('publish success :' + parsedBody)
})
.catch(function(err) {
console.log('publish err ' + JSON.stringify(err))
});
}
//模拟物模型数据
function getPostData() {
var payloadJson = {
id: Date.now(),
params: {
humidity: Math.floor((Math.random() * 20) + 60),
temperature: Math.floor((Math.random() * 20) + 10)
},
method: "thing.event.property.post"
}
console.log("===postData\n topic=" + topic)
console.log(payloadJson)
return JSON.stringify(payloadJson);
}
//HmacSha1 sign
function signHmacSha1(params, deviceSecret) {
let keys = Object.keys(params).sort();
// 按字典序排序
keys = keys.sort();
const list = [];
keys.map((key) => {
list.push(`${key}${params[key]}`);
});
const contentStr = list.join('');
return crypto.createHmac('sha1', deviceSecret).update(contentStr).digest('hex');
}