react-native-bluetooth-obd-manager
Version:
A React Native hook library to manage Bluetooth Low Energy connections and communication with ELM327 OBD-II adapters.
2 lines • 8.78 kB
JavaScript
var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.useInternalCommandControl=exports.BluetoothProvider=void 0;var _toConsumableArray2=_interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));var _slicedToArray2=_interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));var _react=_interopRequireWildcard(require("react"));var _reactNative=require("react-native");var _reactNativeBleManager=_interopRequireDefault(require("react-native-ble-manager"));var _BluetoothContext=require("./BluetoothContext");var _BluetoothReducer=require("./BluetoothReducer");var _constants=require("../constants");var _jsxRuntime=require("react/jsx-runtime");var _this=this,_jsxFileName="/Users/rakshitbharat/iOSProject/android/source/lib/react-native-bluetooth-obd-manager/src/context/BluetoothProvider.tsx";function _getRequireWildcardCache(e){if("function"!=typeof WeakMap)return null;var r=new WeakMap(),t=new WeakMap();return(_getRequireWildcardCache=function _getRequireWildcardCache(e){return e?t:r;})(e);}function _interopRequireWildcard(e,r){if(!r&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var t=_getRequireWildcardCache(r);if(t&&t.has(e))return t.get(e);var n={__proto__:null},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var u in e)if("default"!==u&&{}.hasOwnProperty.call(e,u)){var i=a?Object.getOwnPropertyDescriptor(e,u):null;i&&(i.get||i.set)?Object.defineProperty(n,u,i):n[u]=e[u];}return n.default=e,t&&t.set(e,n),n;}var BleManagerModule=_reactNative.NativeModules.BleManager;var bleManagerEmitter=new _reactNative.NativeEventEmitter(BleManagerModule);var InternalCommandControlContext=(0,_react.createContext)(undefined);InternalCommandControlContext.displayName='InternalCommandControlContext';var BluetoothProvider=exports.BluetoothProvider=function BluetoothProvider(_ref){var _state$connectedDevic2;var children=_ref.children;if(!_react.default){throw new Error('React is not available in the runtime environment. This usually indicates a dependency resolution issue.');}var _useReducer=(0,_react.useReducer)(_BluetoothReducer.bluetoothReducer,_BluetoothReducer.initialState),_useReducer2=(0,_slicedToArray2.default)(_useReducer,2),state=_useReducer2[0],dispatch=_useReducer2[1];var currentCommandRef=(0,_react.useRef)(null);var handleIncomingData=(0,_react.useCallback)(function(dataValue){if(state.isAwaitingResponse&¤tCommandRef.current){try{var _commandState$respons;var commandState=currentCommandRef.current;commandState.responseChunks.push((0,_toConsumableArray2.default)(dataValue));(_commandState$respons=commandState.responseBuffer).push.apply(_commandState$respons,(0,_toConsumableArray2.default)(dataValue));var promptIndex=commandState.responseBuffer.indexOf(_constants.ELM327_PROMPT_BYTE);if(promptIndex!==-1){var responseBytes=commandState.responseBuffer.slice(0,promptIndex);var processedChunks=processResponseChunks(commandState.responseChunks,commandState.responseBuffer,promptIndex);commandState.responseBuffer=[];commandState.responseChunks=[];if(commandState.timeoutId){clearTimeout(commandState.timeoutId);}var response;switch(commandState.expectedReturnType){case _constants.CommandReturnType.STRING:response=decodeResponse(responseBytes);break;case _constants.CommandReturnType.BYTES:response=Uint8Array.from(responseBytes);break;case _constants.CommandReturnType.CHUNKED:response={data:Uint8Array.from(responseBytes),chunks:processedChunks.map(function(chunk){return Uint8Array.from(chunk);})};break;default:response=decodeResponse(responseBytes);}commandState.promise.resolve(response);currentCommandRef.current=null;dispatch({type:'COMMAND_SUCCESS'});}}catch(error){var _currentCommandRef$cu;console.error('[BluetoothProvider] Error processing incoming data:',error);if((_currentCommandRef$cu=currentCommandRef.current)!=null&&_currentCommandRef$cu.promise){currentCommandRef.current.promise.reject(handleError(error));currentCommandRef.current=null;}dispatch({type:'COMMAND_FAILURE',payload:handleError(error)});}}},[state.isAwaitingResponse]);var processResponseChunks=function processResponseChunks(chunks,flatBuffer,promptIndex){var processedChunks=(0,_toConsumableArray2.default)(chunks);var runningLength=0;for(var i=0;i<processedChunks.length;i++){var chunkLength=processedChunks[i].length;if(runningLength+chunkLength>promptIndex){var promptPositionInChunk=promptIndex-runningLength;processedChunks[i]=processedChunks[i].slice(0,promptPositionInChunk);processedChunks.splice(i+1);break;}runningLength+=chunkLength;}return processedChunks;};var decodeResponse=function decodeResponse(bytes){try{return new TextDecoder().decode(Uint8Array.from(bytes)).trim();}catch(e){console.warn('[BluetoothProvider] TextDecoder failed, falling back to fromCharCode:',e);return String.fromCharCode.apply(String,(0,_toConsumableArray2.default)(bytes)).trim();}};var handleError=function handleError(error){if(error instanceof Error){return error;}return new Error(String(error));};var listenersRef=(0,_react.useRef)([]);(0,_react.useEffect)(function(){console.info('[BluetoothProvider] Initializing BleManager...');_reactNativeBleManager.default.start({showAlert:false}).then(function(){console.info('[BluetoothProvider] BleManager started successfully.');dispatch({type:'SET_INITIALIZING',payload:false});_reactNativeBleManager.default.checkState();}).catch(function(error){console.error('[BluetoothProvider] BleManager failed to start:',error);dispatch({type:'SET_INITIALIZING',payload:false});dispatch({type:'SET_ERROR',payload:new Error(`BleManager failed to start: ${error}`)});});},[]);(0,_react.useEffect)(function(){var listeners=[];console.info('[BluetoothProvider] Setting up BLE listeners...');listeners.push(bleManagerEmitter.addListener('BleManagerDidUpdateState',function(args){console.info(`[BluetoothProvider] BleManagerDidUpdateState: ${args.state}`);var isBtOn=args.state==='on';dispatch({type:'SET_BLUETOOTH_STATE',payload:isBtOn});if(!isBtOn){console.warn('[BluetoothProvider] Bluetooth is OFF.');}}));listeners.push(bleManagerEmitter.addListener('BleManagerDiscoverPeripheral',function(peripheral){var _peripheral$name;var name=((_peripheral$name=peripheral.name)==null?void 0:_peripheral$name.toUpperCase())||'';var likelyOBDKeywords=['OBD','ELM','VLINK','SCAN','ICAR','KONNWEI'];var isLikelyOBD=likelyOBDKeywords.some(function(keyword){return name.includes(keyword);});var peripheralWithPrediction=Object.assign({},peripheral,{isLikelyOBD:isLikelyOBD});dispatch({type:'DEVICE_FOUND',payload:peripheralWithPrediction});}));listeners.push(bleManagerEmitter.addListener('BleManagerStopScan',function(){console.info('[BluetoothProvider] BleManagerStopScan received.');dispatch({type:'SCAN_STOP'});}));listeners.push(bleManagerEmitter.addListener('BleManagerDisconnectPeripheral',function(data){var _state$connectedDevic;console.warn(`[BluetoothProvider] BleManagerDisconnectPeripheral: ${data.peripheral}`);if(((_state$connectedDevic=state.connectedDevice)==null?void 0:_state$connectedDevic.id)===data.peripheral){if(currentCommandRef.current){console.error('[BluetoothProvider] Rejecting command due to disconnect.');currentCommandRef.current.promise.reject(new Error('Device disconnected during command.'));if(currentCommandRef.current.timeoutId){clearTimeout(currentCommandRef.current.timeoutId);}currentCommandRef.current.responseBuffer=[];currentCommandRef.current=null;}dispatch({type:'DEVICE_DISCONNECTED'});}}));listeners.push(bleManagerEmitter.addListener('BleManagerDidUpdateValueForCharacteristic',function(data){handleIncomingData(data.value);}));listenersRef.current=listeners;return function(){console.info('[BluetoothProvider] Removing BLE listeners...');listenersRef.current.forEach(function(listener){return listener.remove();});listenersRef.current=[];};},[(_state$connectedDevic2=state.connectedDevice)==null?void 0:_state$connectedDevic2.id,handleIncomingData]);var commandControlValue=(0,_react.useMemo)(function(){return{currentCommandRef:currentCommandRef};},[]);return(0,_jsxRuntime.jsx)(_BluetoothContext.BluetoothStateContext.Provider,{value:state,children:(0,_jsxRuntime.jsx)(_BluetoothContext.BluetoothDispatchContext.Provider,{value:dispatch,children:(0,_jsxRuntime.jsx)(InternalCommandControlContext.Provider,{value:commandControlValue,children:children})})});};var useInternalCommandControl=exports.useInternalCommandControl=function useInternalCommandControl(){var context=_react.default.useContext(InternalCommandControlContext);if(context===undefined){throw new Error('useInternalCommandControl must be used within a BluetoothProvider');}return context;};
//# sourceMappingURL=BluetoothProvider.js.map