import actionCreatorFactory from 'typescript-fsa' ; import { asyncFactory } from 'typescript-fsa-redux-thunk' ; import { SensorService , PacketType , HistoryPacket } from '../service' ; import * as Commands from '../service/commands' ; const create = actionCreatorFactory ( 'SENSOR' ) ; const createAsync = asyncFactory ( create ) ; export const setConnected = create < boolean > ( 'SET_CONNECTED' ) ; export const updatePacket = create < PacketType > ( 'UPDATE_PACKET' ) ; export const requestDevice = createAsync ( 'REQUEST_DEVICE' , async ( ) => { return SensorService . requestDevice ( ) ; } ) ; export const connect = createAsync ( 'CONNECT' , async ( params , dispatch , getState ) => { const { sensor } = getState ( ) ; if ( sensor === null ) { return ; } await sensor . connect ( ) ; dispatch ( setConnected ( true ) ) ; sensor . on ( 'disconnected' , ( ) => dispatch ( setConnected ( false ) ) ) ; sensor . on ( 'packet' , async ( packet ) => { if ( packet instanceof HistoryPacket ) { await sensor . sendCommand ( Commands . nextHistory ( ) ) ; } return dispatch ( updatePacket ( packet ) ) ; } ) ; sensor . on ( 'failed' , ( packet ) => { console . log ( 'Block' , packet . toString ( 'hex' ) . toUpperCase ( ) ) ; } ) ; await sensor . sendCommand ( Commands . setRTC ( ) ) ; } ) ; export const disconnect = createAsync ( 'DISCONNECT' , async ( params , dispatch , getState ) => { const { sensor } = getState ( ) ; return sensor ?. disconnect ( ) ; } ) ; const sendMessage = createAsync ( 'SEND_MESSAGE' , async ( payload , dispatch , getState ) => { const { sensor } = getState ( ) ; return sensor ?. sendCommand ( payload ) ; } ) ; export const setMeasurementEnable = ( enabled ) => sendMessage ( Commands . setMeasurementEnable ( enabled ) ) ; export const setMeasurementInterval = ( value ) => sendMessage ( Commands . setMeasurementInterval ( value ) ) ; export const shutdown = ( ) => sendMessage ( Commands . shutdown ( ) ) ; export const readHistory = ( ) => sendMessage ( Commands . readHistory ( ) ) ;