Skip to content

Instantly share code, notes, and snippets.

@ElectricImpSampleCode
Created July 2, 2019 00:14
Show Gist options
  • Save ElectricImpSampleCode/05afdc44845ebb4a02d5f6e3b7a4ba82 to your computer and use it in GitHub Desktop.
Save ElectricImpSampleCode/05afdc44845ebb4a02d5f6e3b7a4ba82 to your computer and use it in GitHub Desktop.
Squirrel bindenv() function example
function stateChangeCallback(state) {
// Define a callback function, which we will bind to the interface record
// in 'getAvailableInterfaces()' so that we know which interface's change
// of state actually triggered the callback
// Is the interface available for use? It is if it's connected
this.isAvailable = (state == imp.net.CONNECTED);
// When we reach a terminal state consider the interface reported
if (state == imp.net.CONNECTED ||
(state >= imp.net.WIFI_STOPPED && state <= imp.net.WIFI_STOPPED_UNHAPPY) ||
(state >= imp.net.ETHERNET_STOPPED && state <= imp.net.ETHERNET_STOPPED_NO_LINK) ||
(state >= imp.net.CELLULAR_REGISTRATION_DENIED && state <= imp.net.CELLULAR_STOPPED_UNHAPPY)) {
// Indirectly close the interface, by nulling the variable referring to it
this.interface = null;
}
}
function getAvailableInterfaces() {
// Run through the known interfaces to see which may be used: these are
// recorded by impOS in the 'interface' table from imp.net.info()'s results
local netInfo = imp.net.info();
foreach (interface in netInfo.interface) {
// Prepare a new app-level record for the interface
local interfaceRecord = {};
// Set the availability state to false; this will be updated when
// the state-change callback is executed
interfaceRecord.isAvailable <- false;
// Now open the interface for local network to test its availability
// When the callback triggers, it sets the availablility-by-type flags, etc.
// NOTE Use bindenv() to set the callback's context object to the current
// interface in the enumeration
interfaceRecord.interface <- imp.net.open({"interface": interface.name},
stateChangeCallback.bindenv(interfaceRecord));
}
}
// Probe the imp's interfaces
getAvailableInterfaces();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment