1'use strict'; 2 3const EventEmitter = require('events'); 4 5class netMgr extends EventEmitter{ 6 constructor(options) { 7 super(); 8 9 if(!options || !options.name){ 10 throw new Error('device info error'); 11 } 12 13 this.options = { 14 name: options.name 15 }; 16 17 this.name = options.name 18 this._init(); 19 this.dev_handler = this._getDev(); 20 } 21 22 _init() { 23 if(__native.NETMGR.serviceInit() !== 0){ 24 this.emit('error', 'netmgr init error'); 25 } 26 } 27 28 _getDev() { 29 console.log('netMgr._getDev: ' + this.name) 30 var dev_handler = __native.NETMGR.getDev(this.name); 31 if (!dev_handler){ 32 this.emit('error', 'netmgr get dev error ' + this.name); 33 return; 34 } 35 36 return dev_handler; 37 } 38 39 setMsgCb(cb) { 40 __native.NETMGR.setMsgCb(this.dev_handler, cb); 41 } 42 43 delMsgCb(cb) { 44 __native.NETMGR.delMsgCb(this.dev_handler, cb); 45 } 46 47 setAutoReconnect(flag) { 48 var ret = __native.NETMGR.setAutoReconnect(this.dev_handler, flag); 49 if (ret !== 0) { 50 this.emit('error', 'netmgr set auto reconnect error'); 51 } 52 } 53 54 connect(options) { 55 56 options = { 57 ssid: options.ssid, 58 password: options.password, 59 bssid: options.bssid || '', 60 timeout_ms: options.timeout_ms || 18000 61 } 62 63 __native.NETMGR.connect(this.dev_handler, options, function(status) { 64 if (status == 'DISCONNECT'){ 65 this.emit('disconnect', options.ssid); 66 return; 67 } 68 this.emit('connect', options.ssid); 69 }.bind(this)); 70 } 71 72 disconnect() { 73 var ret = __native.NETMGR.disconnect(this.dev_handler); 74 if (ret !== 0) { 75 this.emit('error', 'netmgr disconnect error'); 76 return; 77 } 78 this.emit('disconnect', ssid); 79 } 80 81 getState() { 82 var ret = __native.NETMGR.getState(this.dev_handler); 83 switch (ret) { 84 case 0: 85 return 'disconnecting'; 86 case 1: 87 return 'disconnected'; 88 case 2: 89 return 'connecting'; 90 case 3: 91 return 'connected'; 92 case 4: 93 return 'obtaining ip'; 94 case 5: 95 return 'network connected'; 96 case 6: 97 return 'failed'; 98 } 99 } 100 101 saveConfig() { 102 var ret = __native.NETMGR.saveConfig(this.dev_handler); 103 if (ret !== 0) { 104 this.emit('error', 'netmgr save config error'); 105 } 106 } 107 108 setIfConfig(options) { 109 110 options = { 111 dhcp_en: options.dhcp_en || true, 112 ip_addr: options.ip_addr || '', 113 mask: options.mask || '', 114 gw: options.gw || '', 115 dns_server: options.dns_server || '', 116 mac: options.mac || '' 117 } 118 119 var ret = __native.NETMGR.setIfConfig(this.dev_handler, options); 120 if (ret !== 0) { 121 this.emit('error', 'netmgr save config error'); 122 } 123 } 124 125 getIfConfig() { 126 var config = __native.NETMGR.getIfConfig(this.dev_handler); 127 if (!config) { 128 this.emit('error', 'get if config error'); 129 } 130 } 131} 132 133function openNetMgrClient(options) { 134 return new netMgr(options); 135} 136 137module.exports = { 138 openNetMgrClient, 139}