meg768 / rpi-wifi-connection Goto Github PK
View Code? Open in Web Editor NEWModule to connect a Raspberry Pi to Wi-Fi
Module to connect a Raspberry Pi to Wi-Fi
Unable to connect to open network, setting psk to null or removing does not work
Hi !
I'm really surprise that the connect method call "removeAllNetwork". After testing, it really does : all my configured Wifi Network are deleted in my wpa_supplicant.conf.
Any chance to remove "removeAllNetworks()" and just call "addNetwork()" ?
Thanks !
Hi !
Here is the situation : My RPi is connected to my "home" wifi, now I want to associate it to my "iphone". If I run .connect() everything is ok, expect that the "waiting for network connection" return immediatly true as I'm previously connected. In this case If I set a wrong password, the new network is saved and the old is set to "disabled=1"...
Suggestion :
Create to new methods "reconnect" and "disconnect" and in "connect" method call disconnect at the very beginning and at the very end of "connect" method, if everything is ok add a call to "reconnect" method.
Here what could be the new suggesting methods :
disconnect() { console.log('Disconnecting...'); return new Promise((resolve, reject) => { this.wpa_cli('disconnect').then((result) => { setTimeout(resolve, 500); //--wait to be sure that wlan is really disconnected }) .catch((error) => { reject(error); }) }); }
reconnect() { console.log('Reconnecting...'); return new Promise((resolve, reject) => { this.wpa_cli('reconnect').then(() => { resolve(); }) .catch((error) => { reject(error); }) }); }
Let me know if you are ok with that...
Bye !
Hello,
When I enter same number of letters as my password (but it's not actually my password, I enter it wrong), I get to connected part of code, and I'm not in catch.
Is there any way to fix this?
Kind Regards,
TribalKing
Thanks for a very useful library 👍
I notice a lot of console logs when calling the connect function and I was wondering if that is by design or if it could be moved to a debug log like the rest of the logging?
This would be a suggested solution:
debug(sprintf('Connection status ssid=%s ip_address=%s ...', status.ssid || '', status.ip_address || ''));
rpi-wifi-connection/src/wifi-connection.js
Line 211 in 9af7fcf
I have modified the getStatus() method to be able to get more data that can be useful like the frequency.
I added an alternative method of scan() named scanGroups() in which it returns a JSON grouped by technology 2.5, 5, 6 or another, in each group the connections will be ordered by the strength of the signal, the ssids are not repeated to have a list of unique ssids and showing the beginning of the group that corresponds to the current connection.
This is translated by google translate from spanish
const Wifi = require('rpi-wifi-connection')
// Crear clase extendida de Wifi
class WifiExt extends Wifi {
// Se sobre escribe el método para agregar datos al resultado
getStatus() {
return new Promise((resolve, reject) => {
this.wpa_cli('status').then((output) => {
var match;
// Que sin importar el resultado se tenga la misma estructura básica de salida
var status = { ssid: "", ip_address: "", frequency: "", uuid: "", wifi_generation: "" }
// SSID
if ((match = output.match(/[^b]ssid=([^\n]+)/))) {
status.ssid = match[1];
}
// Dirección IP
if ((match = output.match(/ip_address=([^\n]+)/))) {
status.ip_address = match[1];
}
// Frecuencia de la conexión
if ((match = output.match(/freq=([^\n]+)/))) {
status.frequency = parseFloat(match[1]);
}
// UUID
if ((match = output.match(/uuid=([^\n]+)/))) {
status.uuid = match[1];
}
// WIFI GENERATION
if ((match = output.match(/wifi_generation=([^\n]+)/))) {
status.wifi_generation = match[1];
}
resolve(status);
})
.catch((error) => {
reject(error);
})
});
}
// Se crea un método alterno de scan() para entregar un JSON agrupado por tecnología 2.4, 5, 6 u otro
// En los resultados de cada grupo los SSID serán únicos y ordenados por la potencia de señal (primero estará la conexión actual)
scanGroups() {
var self = this;
function scan() {
return self.wpa_cli('scan');
}
function scan_results() {
return self.wpa_cli('scan_results');
}
return new Promise((resolve, reject) => {
scan().then((ssid) => {
return scan_results();
})
.then(async (output) => {
output = output.split('\n');
output.splice(0, 1);
var ssids = [];
output.forEach((line) => {
var params = line.split('\t');
ssids.push({
bssid: params[0],
frequency: parseInt(params[1]),
signalLevel: parseInt(params[2]),
ssid: params[4]
});
});
// Ordenar por potencia de señal
ssids.sort((a, b) => b.signalLevel - a.signalLevel)
// Catálogo de rangos de frecuencia por tecnología
const ranges = {
wifi_24: { min: 2400, max: 2500 },
wifi_5: { min: 5150, max: 5850 },
wifi_6: { min: 5925, max: 7125 },
}
// Obtener la conexión actual
const currentWifi = await self.getStatus()
// Esquema básico para formar la respuesta
const availables = { wifi_24: [], wifi_5: [], wifi_6: [], wifi_other: [] }
// Agregar las conexiones a la tecnología que corresponden por la frecuencia
// Se detecta si la conexión listada es la actual, si es el caso quedará primero en la lista de su grupo
ssids.map(result => {
if (result.frequency >= ranges.wifi_24.min && result.frequency <= ranges.wifi_24.max) {
result.current = result.ssid == currentWifi.ssid && result.frequency == currentWifi.frequency
result.current ? availables.wifi_24.unshift(result) : availables.wifi_24.push(result)
} else if (result.frequency >= ranges.wifi_5.min && result.frequency <= ranges.wifi_5.max) {
result.current = result.ssid == currentWifi.ssid && result.frequency == currentWifi.frequency
result.current ? availables.wifi_5.unshift(result) : availables.wifi_5.push(result)
} else if (result.frequency >= ranges.wifi_6.min && result.frequency <= ranges.wifi_6.max) {
result.current = result.ssid == currentWifi.ssid && result.frequency == currentWifi.frequency
result.current ? availables.wifi_6.unshift(result) : availables.wifi_6.push(result)
} else {
result.current = result.bssid == currentWifi.ssid && result.frequency == currentWifi.frequency
result.current ? availables.wifi_other.unshift(result) : availables.wifi_other.push(result)
}
})
// Eliminar los grupos vacíos
if (availables.wifi_24.length == 0) delete availables.wifi_24
if (availables.wifi_5.length == 0) delete availables.wifi_5
if (availables.wifi_6.length == 0) delete availables.wifi_6
if (availables.wifi_other.length == 0) delete availables.wifi_other
// Dejar sólo SSID únicos para mejorar el listado
Object.keys(availables).forEach(key => {
const ssidSet = new Set()
availables[key] = availables[key].filter((wifi) => {
if (wifi.ssid.trim().length < 1) return false
if (!ssidSet.has(wifi.ssid)) {
ssidSet.add(wifi.ssid);
return true;
}
return false;
});
})
resolve(availables);
})
.catch((error) => {
reject(error);
})
});
}
}
module.exports = WifiExt
Example:
WifiExt = require('./modules/WifiExt.module')
const wifi = new WifiExt()
async function init() {
console.log("\n\nscanGroups")
const scann = await wifi.scanGroups()
console.log(scann)
console.log("\n\ngetStatus")
const status = await wifi.getStatus()
console.log(status)
}
init()
This return some like:
scanGroups
{
wifi_24: [
{
bssid: '4e:22:13:9f:3c:c6',
frequency: 2417,
signalLevel: -25,
ssid: 'mangos77_inv',
current: false
},
{
bssid: '48:22:34:4f:4a:c6',
frequency: 2417,
signalLevel: -28,
ssid: 'mangos77',
current: false
},
{
bssid: '10:2a:7e:91:51:2a',
frequency: 2462,
signalLevel: -61,
ssid: 'INFINITUM1326_2.4',
current: false
},
{
bssid: 'b4:0f:21:6a:a4:48',
frequency: 2437,
signalLevel: -61,
ssid: 'Camus2',
current: false
},
{
bssid: 'f4:23:9c:8a:5d:b4',
frequency: 2462,
signalLevel: -63,
ssid: 'm77_router',
current: false
}
],
wifi_5: [
{
bssid: '48:2b:54:9d:3a:ce',
frequency: 5240,
signalLevel: -83,
ssid: 'mangos77',
current: true
},
{
bssid: '4f:23:2c:9d:2f:c7',
frequency: 5240,
signalLevel: -41,
ssid: 'mangos77_inv',
current: false
},
{
bssid: 'e4:a3:3c:7f:4e:ca',
frequency: 5500,
signalLevel: -66,
ssid: 'm77_router',
current: false
}
]
}
getStatus
{
ssid: 'mangos77',
ip_address: '192.168.68.87',
frequency: 5240,
uuid: 'abfc61cf-a73f-58b0-9281-eeacbc5e495a',
wifi_generation: '5'
}
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.