uci-wifi/src/connect.js

60 lines
2.0 KiB
JavaScript

import cmd from './cmd'
import del from './delete'
import tc from '@uci/try-catch'
async function connect(ap) {
let ret = null
let cmdStr = ''
// check to see if already connected
cmdStr = `nmcli --terse --fields UUID c show --active | grep ${ap.uuid}`
ret = await tc(cmd)(cmdStr)
if (!ret.err && ret.res !== '')
return { connect: 'already connected', ap: ap }
// check for existing connection, if some connect if not it's new
cmdStr = `nmcli --terse --fields device,name,UUID c show | grep ${ap.uuid}`
ret = await tc(cmd)(cmdStr)
console.log('check-exisiting', ap.uuid, ap.ssid)
if (!ret.err && ret.res !== '') {
console.log('existing nm connection', ap.ssid)
if (ap.update) {
cmdStr = `nmcli con modify ${ap.uuid} 802-11-wireless-security.psk ${
ap.password
}`
ret = await tc(cmd)(cmdStr)
if (ret.err) return { error: 'unable to update password', ap: ap }
}
cmdStr = `nmcli con up uuid ${ap.uuid}`
ret = await tc(cmd)(cmdStr)
if (ret.err) {
if (ap.update) {
return { error: 'updated password failed', ap: ap }
}
return { error: ret.err.message }
}
return { connect: 'reconnected', ap: ap }
}
console.log('NEW CONNECTION')
// connect with new connection
// first clean out any connections with same or similar name to SSID
ret = await tc(del)({ name: ap.ssid })
cmdStr = `nmcli -w 10 device wifi connect '${ap.ssid}' password '${
ap.password
}' ifname ${ap.iface}`
ret = await tc(cmd)(cmdStr)
if (ret.err) {
return { error: `new connection failed -- ${ret.err.cmd}` }
}
// TODO set interface method if other than auto which is default
// `nmcli con modify ${ap.ssid} ipv4.method shared
cmdStr = `nmcli --terse --fields connection.uuid c show id '${ap.ssid}'`
ret = await tc(cmd)(cmdStr)
console.log(ret.res)
ap.uuid = ret.res.split(/[\n:]+/)[1]
console.log(ap.uuid)
return { connect: 'new', ap: ap }
} // end connect
export default connect