import JsonRpc from 'node-jsonrpc-client' import esMain from 'es-main' const DEFAULT_OPTS = { url: process.env.RUT950_UBUS_URL || 'http://192.168.1.1/ubus', username: process.env.RUT950_USERNAME || 'admin', password: process.env.RUT950_PASSWORD || 'admin01' } const EMPTY_SESSID = '00000000000000000000000000000000' export class Rut950 { constructor (opts = {}) { opts = { ...DEFAULT_OPTS, ...opts } this.client = new JsonRpc(opts.url) this.opts = opts } async init () { const res = await this.client.call('call', [ EMPTY_SESSID, 'session', 'login', { username: this.opts.username, password: this.opts.password } ]) if (!res.result || !res.result.length === 2) { throw new Error('received invalid response') } const [code, data] = res.result this.sessid = data.ubus_rpc_session } async call (...params) { if (!this.sessid) await this.init() const res = await this.client.call('call', [ this.sessid, ...params ]) console.log(res) if (res.error) { const err = new Error('RUT950 error: ' + res.error.message) err.code = res.error.code throw err } const result = res.result if (!result || !result.length === 2 || result[0] !== 0) { throw new Error('received invalid response') } return res.result[1] } } if (esMain(import.meta)) { const rut = new Rut950() let iwinfo = await rut.call('iwinfo', 'info', { device: 'wlan0' }) console.log('IWINFO', iwinfo) //let uci = await rut.call('uci', 'show') let uci = await rut.call('file', 'exec', { command: 'uci', params: ['show'] }) const res = uci.stdout const data = {} const lines = res.split('\n') for (const line of lines) { const [key, value] = line.split('=') data[key] = value //const keyParts = key.split('.') //let part = data //let last = keyParts.pop() //console.log(keyParts, last, value) //for (const keyPart of keyParts) { // if (!part[keyPart]) part[keyPart] = {} // part = part[keyPart] //} } console.log('UCI', data) //console.log('UCI', JSON.stringify(uci)) }