Skip to content

Instantly share code, notes, and snippets.

@jpwesselink
Created December 6, 2019 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpwesselink/496a20dd441a898224163e0349c88c4e to your computer and use it in GitHub Desktop.
Save jpwesselink/496a20dd441a898224163e0349c88c4e to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const checkWifiCredentials = (context) => {
const { wifi: { ssid, password, encryptionType, hidden } } = context;
return !!ssid && !!password && !!encryptionType && hidden !== undefined;
};
const checkAccessToken = (context) => {
return !!context.accessToken;
};
const checkCredentials = (context, event, { cond }) => {
return ((checkWifiCredentials(context) && checkAccessToken(context)) ===
!cond.negate);
};
const checkWifiConnection = (context, event, { cond }) => {
console.log('----');
const connectionStatus = cond.connectionStatus || 'connected';
return (context.wifiConnection &&
context.wifiConnection.connectionStatus === connectionStatus);
};
const resetConnectionAttempts = (context) => {
return Object.assign(Object.assign({}, context), { attempts: 0 });
};
const increaseConnectionAttempts = (context) => {
return Object.assign(Object.assign({}, context), { attempts: context.attempts + 1 });
};
const credentialsMachine = Machine({
id: 'app',
// the initial context (extended state) of the statechart
context: {
accessToken: '123',
wifi: {
ssid: 'ssid',
password: ' pwd',
encryptionType: 'WEP',
hidden: false
},
wifiConnection: {
connectionStatus: 'disconnected'
},
credentials: true
},
initial: 'init',
states: {
init: {
on: {
'': [
{
target: 'connectToWifi',
cond: 'checkCredentials'
},
{
target: 'QR',
cond: {
type: 'checkCredentials',
negate: true
}
}
]
}
},
connectToWifi: {
id: 'wifi',
initial: 'waitingToRetry',
states: {
connected: {
on: {
WIFI_DISCONNECT: 'waitingToRetry'
},
entry: ['resetConnectionAttempts']
},
disconnected: {},
waitingToRetry: {
after: {
// after 1 second, transition to yellow
1000: 'retrying'
}
},
retrying: {
after: {
// after 1 second, transition to yellow
1000: 'connected'
},
entry: ['increaseConnectionAttempts']
}
}
},
QR: {}
}
}, {
actions: { resetConnectionAttempts, increaseConnectionAttempts },
guards: { checkCredentials, checkWifiCredentials, checkWifiConnection }
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment