1// import * as iot from 'iot'
2import * as iot from 'gateway'
3
4var productKey = 'a17rAb1ltpS';
5var deviceName = '123454';
6var deviceSecret = 'abf0028f3d7ccf2b9c555826f32381d8';
7
8var lightSwitch = 0;
9var gateway;
10
11var subdev = [
12    {
13        productKey: 'a1zK6eTWoZO',
14        deviceName: 'test101',
15        deviceSecret: 'caf25b3839a24a772be3d386f6c5bd74'
16    },
17    {
18        productKey: 'a1zK6eTWoZO',
19        deviceName: 'test100',
20        deviceSecret: '253ab8d388094c0087c4c9a2c58b7373'
21    }
22];
23
24/* post property */
25function postProperty(id, devInfo, content) {
26    var topic = '/sys/' + devInfo.productKey + '/' + devInfo.deviceName + '/thing/event/property/post';
27    var payload = JSON.stringify({
28        id: id,
29        version: '1.0',
30        params: content,
31        method: 'thing.event.property.post'
32    });
33
34    gateway.publish({
35        topic: topic,
36        payload: payload,
37        qos: 1
38    });
39}
40
41/* post event */
42function postEvent(id, devInfo, eventId, content) {
43    var topic = '/sys/' + devInfo.productKey + '/' + devInfo.deviceName + '/thing/event/' + eventId + '/post';
44    var payload = JSON.stringify({
45        id: id,
46        version: '1.0',
47        params: content,
48        method: 'thing.event.' + eventId + '.post'
49    });
50
51    gateway.publish({
52        topic: topic,
53        payload: payload,
54        qos: 1
55    });
56}
57
58function createGateway() {
59    gateway = iot.gateway({
60        productKey: productKey,
61        deviceName: deviceName,
62        deviceSecret: deviceSecret
63    });
64
65    gateway.on('connect', function () {
66        console.log('(re)connected');
67
68        // gateway.addTopo(subdev);
69
70        gateway.login(subdev);
71
72        setTimeout(function () {
73            postProperty(1, subdev[0], { 'PowerSwitch_1': lightSwitch });
74            postEvent(1, subdev[0], 'Error', { 'ErrorCode': 0 });
75        }, 2000);
76    });
77
78    /* 网络断开事件 */
79    gateway.on('disconnect', function () {
80        console.log('disconnect ');
81    });
82
83    /* mqtt消息 */
84    gateway.on('message', function (res) {
85        /* 通过 topic中的pk和dn信息,判断是对哪个子设备的调用 */
86        var pk = res.topic.split('/')[2];
87        var dn = res.topic.split('/')[3];
88        console.log('mqtt message')
89        console.log('mqtt topic is ' + res.topic);
90        console.log('PK: ' + pk)
91        console.log('DN: ' + dn)
92        console.log('mqtt payload is ' + res.payload);
93    })
94
95    /* 关闭连接事件 */
96    gateway.on('end', function () {
97        console.log('iot client just closed');
98    });
99
100    /* 发生错误事件 */
101    gateway.on('error', function (err) {
102        console.log('error ' + err);
103    });
104}
105
106
107console.log('====== create aiot gateway ======');
108createGateway();
109
110
111