1console.log('iot: testing iot...'); 2var iot = require('iot'); 3 4if (!(iot && iot.device)) { 5 throw new Error("iot: [failed] require(\'iot\')"); 6} 7 8console.log('iot: [success] require(\'iot\')'); 9 10var productKey = 'a10h6IdruJf'; 11var deviceName = 'nodemcu_02'; 12var deviceSecret = 'StFYN4UigwDiRbhRwVFkFIKsEqpuaHKu'; 13 14var device = iot.device({ 15 productKey: productKey, 16 deviceName: deviceName, 17 deviceSecret: deviceSecret, 18 region: 'cn-shanghai', 19 success: function () { 20 console.log('iot: [success] connect'); 21 onConnect(); 22 }, 23 fail: function () { 24 console.log('iot: [failed] connect'); 25 } 26}); 27 28var postCnt = 10; 29 30var lightSwitch = 0; 31function onConnect() { 32 var intervalHandle = setInterval(function () { 33 postCnt--; 34 if(postCnt <= 0) { 35 clearInterval(intervalHandle); 36 } 37 /** post properties */ 38 lightSwitch = 1 - lightSwitch; 39 device.postProps({ 40 payload: { 41 LightSwitch: lightSwitch 42 }, 43 success: function () { 44 console.log('iot: [success] iot.postProps cnt: ' + postCnt); 45 }, 46 fail: function () { 47 console.log('iot: [failed] iot.postProps cnt: ' + postCnt); 48 } 49 }); 50 /** post events */ 51 device.postEvent({ 52 id: 'Error', 53 params: { 54 ErrorCode: 0 55 }, 56 success: function () { 57 console.log('iot: [success] iot.postEvent cnt: ' + postCnt); 58 59 }, 60 fail: function () { 61 console.log('iot: [failed] iot.postEvent cnt: ' + postCnt); 62 } 63 }); 64 }, 1000); 65} 66 67device.on('connect', function () { 68 console.log('iot: [success] iot.on(\'connect\')'); 69}); 70 71/* 网络断开事件 */ 72device.on('disconnect', function () { 73 console.log('iot: [success] iot.on(\'disconnect\')'); 74}); 75 76/* 关闭连接事件 */ 77device.on('close', function () { 78 console.log('iot: [success] iot.on(\'close\')'); 79}); 80 81/* 发生错误事件 */ 82device.on('error', function (err) { 83 throw new Error('iot: [failed] iot.on(\'error\') ' + err); 84}); 85 86/* 云端设置属性事件 */ 87device.on('props', function (payload) { 88 console.log('iot: [success] iot.on(\'props\'), payload: ' + JSON.stringify(payload)); 89}); 90 91/* 云端下发服务事件 */ 92device.on('service', function (id, payload) { 93 console.log('iot: [success] iot.on(\'service\'), id: ' + id + ', payload: ' + JSON.stringify(payload)); 94});