1import * as iot from 'iot' 2 3var productKey = 'a1MOapE3PH8'; /* your productKey */ 4var deviceName = 'FjWNmTsPWfPSykfkBv1l'; /* your deviceName */ 5var deviceSecret = '2a6afba08a135efda3c49e4cc7684254'; /* your deviceSecret */ 6var device ; 7 8var topic = '/sys/' + productKey + '/' + deviceName + '/user/haas/info'; 9 10function createDevice() { 11 device = iot.device({ 12 productKey: productKey, 13 deviceName: deviceName, 14 deviceSecret: deviceSecret, 15 region: 'cn-shanghai', 16 }); 17 18 device.on('connect', function () { 19 console.log('(re)connected'); 20 21 device.subscribe({ 22 topic: topic, 23 qos: 0 24 }); 25 26 device.unsubscribe({ 27 topic: topic 28 }); 29 30 device.publish({ 31 topic: topic, 32 payload: 'haas haas haas', 33 qos: 1 34 }); 35 36 var lightswitch = 0; 37 var eventid = 'alarmEvent'; 38 39 setInterval(function () { 40 if (lightswitch) { 41 lightswitch = 0; 42 } else { 43 lightswitch = 1; 44 } 45 46 /* post props */ 47 var propertyPayload = JSON.stringify({ 48 LightSwitch: lightswitch 49 }); 50 device.postProps({ 51 payload: propertyPayload 52 }); 53 54 /* post event */ 55 var eventPayload = JSON.stringify({ 56 alarmType: 0 57 }); 58 device.postEvent({ 59 id: eventid, 60 params: eventPayload 61 }); 62 }, 3000); 63 64 /* 云端设置属性事件 */ 65 device.onProps(function (res) { 66 console.log('cloud req msg_id is ' + res.msg_id); 67 console.log('cloud req params_len is ' + res.params_len); 68 console.log('cloud req params is ' + res.params); 69 }); 70 71 /* 云端下发服务事件 */ 72 device.onService(function (res) { 73 console.log('received cloud msg_id is ' + res.msg_id); 74 console.log('received cloud service_id is ' + res.service_id); 75 console.log('received cloud params_len is ' + res.params_len); 76 console.log('received cloud params is ' + res.params); 77 }); 78 }); 79} 80console.log('====== create aiot device ======'); 81createDevice(); 82 83 84