1var appota = require('appota');
2var iot = require('iot');
3
4/* device info */
5var productKey = '';      /* your productKey */
6var deviceName = '';      /* your deviceName */
7var deviceSecret = '';  /* your deviceSecret */
8var module_name = 'default';
9var default_ver = '1.0.0';
10
11var ota;
12var status;
13/* download info */
14var info = {
15	url: '',
16	store_path: '/data/jsamp/pack.bin',
17	install_path: '/data/jsamp/',
18	length: 0,
19	hashType: '',
20	hash: ''
21}
22
23var device = iot.device({
24	productKey: productKey,
25	deviceName: deviceName,
26	deviceSecret: deviceSecret
27});
28
29device.on('connect', function(iot_res) {
30	console.log('device connected');
31	var iotDeviceHandle = device.getDeviceHandle();
32	ota = appota.open(iotDeviceHandle);
33	console.log('report default module ver');
34	ota.report({
35		device_handle: iotDeviceHandle,
36		product_key: productKey,
37		device_name: deviceName,
38		module_name: module_name,
39		version: default_ver
40	});
41	ota.on('new', function(res) {
42		console.log('length is ' + res.length);
43		console.log('module_name is ' + res.module_name);
44		console.log('version is ' + res.version);
45		console.log('url is ' + res.url);
46		console.log('hash is ' + res.hash);
47		console.log('hash_type is ' + res.hash_type);
48
49		info.url = res.url;
50		info.length = res.length;
51		info.module_name = res.module_name;
52		info.version = res.version;
53		info.hash = res.hash;
54		info.hashType = res.hash_type;
55
56		ota.download({
57			url: info.url,
58			store_path: info.store_path
59		}, function(res) {
60			if (res >= 0) {
61				console.log('download success');
62				console.log('verify start');
63				console.log(info.hashType);
64				ota.verify({
65					length: info.length,
66					hash_type: info.hashType,
67					hash: info.hash,
68					store_path: info.store_path
69				}, function(res) {
70					if (res >= 0) {
71						console.log('verify success');
72						console.log('upgrade start');
73						ota.upgrade({
74							length: info.length,
75							store_path: info.store_path,
76							install_path: info.install_path
77						}, function(res) {
78							if (res >= 0) {
79								console.log('upgrade success')
80							} else {
81								console.log('upgrade failed')
82							}
83						})
84					} else {
85						console.log('verify failed');
86					}
87				})
88			} else {
89				console.log('download failed');
90			}
91		});
92	});
93})
94
95