Giter Site home page Giter Site logo

rpi-wifi-connection's Introduction

meg768

rpi-wifi-connection's People

Contributors

azaky avatar meg768 avatar slegouffe avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

rpi-wifi-connection's Issues

removeAllNetworks() in .connect()

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 !

Add network when already connected to a ssid = save connection even if password is wrong

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 !

Connect method leading to success with wrong password

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

Changing console.log to debug print?

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 || ''));

console.log('Connection status:', status);

Modify 2 methods for best results

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'
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.