1var fanSwitch = 0;
2var waterSwitch = 0;
3var beepSwitch = 0;
4var gpio = require('gpio');
5var beep = gpio.open({
6	id: 'D4'
7});
8var relay1 = gpio.open({
9	id: 'D3'
10});
11var relay2 = gpio.open({
12	id: 'D2'
13});
14// GPIO will ouput high in default
15// Turn off beep and relay immediately
16beep.writeValue(beepSwitch);
17relay1.writeValue(waterSwitch);
18relay2.writeValue(fanSwitch);
19console.log('turn off beep and relay');
20sleepMs(100);
21
22var iot = require('iot');
23var network = require('network');
24
25var net = network.openNetWorkClient();
26
27var productKey = 'yourproductkey';      /* your productKey */
28var deviceName = 'yourdevicename';      /* your deviceName */
29var deviceSecret = 'yourdevicesecret';  /* your deviceSecret */
30var device;
31var mqtt_connected = false;
32
33var modbus = require('./modbus.js');
34
35var deviceAddr = 1;
36var timeout = 300;
37var modbus_device = modbus(
38  { id: 'UART2' },
39  { id: 'D13', polarity: 1 },
40  deviceAddr
41);
42
43var temperature = 25.0;
44var pressure = 0.0;
45var bmp280 = require('./bmp280.js');
46bmp280.bmp280_init();
47
48var adc = require('adc');
49var pir = adc.open({
50  id: 'ADC0',
51  success: function() {
52    console.log('adc: open adc1 success')
53  },
54  fail: function() {
55    console.log('adc: open adc1 failed')
56  }
57});
58var pirStatus = 0;
59var pirTempStatus = 0;
60var pirCount = 0;
61
62//----------------------- GPS Start--------------------------------
63var GPS = require("./gps.js");
64var gps = new GPS();
65
66var uart1 = require('uart');
67// gnss uart
68var gnss = uart1.open({
69    id: 'UART1'
70});
71
72var geoLocation_data = {'lat':0, 'lon':0, 'alt':0}
73gps.on("data", function (parsed) {
74    //console.log(parsed);
75    geoLocation_data['lat'] = gps.state["lat"];
76    geoLocation_data['lon'] = gps.state["lon"];
77    geoLocation_data['alt'] = gps.state["alt"];
78    console.log("geo data " + JSON.stringify(geoLocation_data, null, 4))
79});
80
81
82function ArrayToString(fileData) {
83    var dataString = "";
84    for (var i = 0; i < fileData.length; i++) {
85        dataString += String.fromCharCode(fileData[i]);
86    }
87    return dataString;
88}
89
90var GGA;
91gnss.on('data', function(data) {
92    var aaa = ArrayToString(data);
93    var bbb = aaa.split("$");
94    GGA = "$" + bbb[1];
95});
96
97// GPS data post
98setInterval(function(){
99    var gga_default = "$GNGGA,033122.000,3111.28510,N,12136.26122,E,1,13,1.0,1.3,M,11.7,M,,*4B"
100
101    /* gga_default is temporary data for agriculture demo, we should use real 'GGA' data */
102    gps.update(gga_default);
103    //gps.update(GGA);
104    if(mqtt_connected) {
105        device.postProps(JSON.stringify({
106            GeoLocation: {
107                Longitude: geoLocation_data['lon'],
108                Latitude:  geoLocation_data['lat'],
109                Altitude:  geoLocation_data['alt'],
110                CoordinateSystem: 1
111                }
112            }));
113    }
114}, 5000);
115//----------------------- GPS End--------------------------------
116
117setInterval(function(){
118    temperature = bmp280.bmp280TemperatureRead();
119    pressure = bmp280.bmp280PressureRead();
120    pressure = pressure / 100; // iot needs hPa
121    console.log('Temperature is ' + temperature + ' Pressure is ' + pressure);
122    if(mqtt_connected) {
123        device.postProps(JSON.stringify({
124            CurrentTemperature: temperature
125        }));
126        device.postProps(JSON.stringify({
127            Atmosphere: pressure
128        }));
129    }
130}, 10000);
131
132setInterval(function(){
133    var pinStatus = (pir.readValue() > 512) ? 1 : 0;
134    if(pirTempStatus == pinStatus) {
135        pirCount++;
136        if(pirCount > 4) {
137            pirCount = 0;
138            if(pirTempStatus != pirStatus) {
139                pirStatus = pirTempStatus;
140                if(mqtt_connected) {
141                    device.postProps(JSON.stringify({
142                        AlarmState: pirStatus
143                    }));
144                }
145                console.log('Pir status is ' + pirStatus);
146            }
147        }
148    } else {
149        pirTempStatus = pinStatus;
150        pirCount = 0;
151    }
152}, 50);
153
154function createDevice() {
155    device = iot.device({
156        productKey: productKey,
157        deviceName: deviceName,
158        deviceSecret: deviceSecret
159    });
160    var humidity = 50;
161
162    device.on('connect', function () {
163        console.log('(re)connected');
164        mqtt_connected = true;
165        /* post props */
166        device.postProps(JSON.stringify({
167            Coil: fanSwitch, CurrentTemperature: temperature, WaterOutletSwitch: waterSwitch, Buzzer: beepSwitch,
168            CurrentHumidity:humidity, AlarmState: pirStatus, Atmosphere: pressure, SoilTemperature: 25.5,
169            SoilMoisture: 50.5
170        }));
171
172        /* 云端设置属性事件 */
173        device.onProps(function (res) {
174            console.log('cloud req msg_id is ' + res.msg_id);
175            console.log('cloud req params_len is ' + res.params_len);
176            console.log('cloud req params is ' + res.params);
177            var payload = JSON.parse(res.params);
178            if(payload.Coil !== undefined)
179            {
180                fanSwitch = parseInt(payload.Coil);
181                relay2.writeValue(fanSwitch);
182                device.postProps(JSON.stringify({
183                    Coil: fanSwitch
184                }));
185            }
186            if(payload.WaterOutletSwitch !== undefined)
187            {
188                waterSwitch = parseInt(payload.WaterOutletSwitch);
189                relay1.writeValue(waterSwitch);
190                device.postProps(JSON.stringify({
191                    WaterOutletSwitch: waterSwitch
192                }));
193            }
194            if(payload.Buzzer !== undefined)
195            {
196                beepSwitch = parseInt(payload.Buzzer);
197                beep.writeValue(beepSwitch);
198                device.postProps(JSON.stringify({
199                    Buzzer: beepSwitch
200                }));
201            }
202        });
203
204        /* 云端下发服务事件 */
205        device.onService(function (res) {
206            console.log('received cloud msg_id is ' + res.msg_id);
207            console.log('received cloud service_id is ' + res.service_id);
208            console.log('received cloud params_len is ' + res.params_len);
209            console.log('received cloud params is ' + res.params);
210        });
211    });
212
213    /* 网络断开事件 */
214    device.on('disconnect', function () {
215        console.log('disconnect ');
216        mqtt_connected = false;
217    });
218
219    /* 关闭连接事件 */
220    device.on('end', function () {
221        console.log('iot client just closed');
222        mqtt_connected = false;
223    });
224
225    /* 发生错误事件 */
226    device.on('error', function (err) {
227        console.log('error ' + err);
228    });
229}
230
231var status = net.getStatus();
232console.log('net status is: ' + status);
233
234
235if (status == 'connect') {
236    createDevice();
237} else {
238    net.on('connect', function () {
239        createDevice();
240    });
241}
242