import { Loading, scaleUtils } from '@widergy/mobile-ui'; import React, { Fragment, useCallback, useEffect, useState } from 'react'; import { View } from 'react-native'; import { useBluetoothContext } from '../../../../bluetooth/useBluetoothContext'; import { BluetoothState } from '../../../../bluetooth/constants'; import Colors from '../../../Colors'; import GeneralStep from '../../../GeneralStep'; import ProbeReadingToRead from '../../../assets/probeReading/probeReadingToRead.png'; import MeterFamilyTypeBadge from '../MeterFamilyTypeBadge'; import { readMeter } from '../../../../bluetooth/readMeter'; import { COMMUNICATION_INTERVAL_PER_PROBE_IN_MS } from '../../../../bluetooth/constants'; import styles from './styles'; const TakingReading = ({ translations, closeProbeReading, meterFamilyType, setReadingResult, onError, mockCode, readStrategy, loadingCurrentDevice, readingDisabled = false, children, timeoutRef, readingTimeouts, meterTypeCode, showFamilyBadgeLibrary, }) => { const SIZE_LOADING = scaleUtils.moderateHorizontalScale(164); const [beginReading, setBeginReading] = useState(false); const bluetoothContext = useBluetoothContext(); const onBeginReading = useCallback(() => { if (readingTimeouts?.probeReadingTimeoutInMilliseconds) { clearTimeout(timeoutRef.current); timeoutRef.current = setTimeout(() => { onError({ message: translations.timeoutError }); }, readingTimeouts?.probeReadingTimeoutInMilliseconds); } setBeginReading(true); }, [onError, readingTimeouts?.probeReadingTimeoutInMilliseconds, timeoutRef, translations.timeoutError]); const onSuccess = useCallback( arrayResult => { setReadingResult(arrayResult); }, [setReadingResult], ); const disabledStep = !bluetoothContext.isConnected() || bluetoothContext.batteryPercentage == null || readingDisabled; useEffect(() => { let subscription: { unsubscribe: any }; if (!disabledStep) { setTimeout(() => { subscription = readMeter({ mockCode, readStrategy, bluetoothContext, onBeginReading, onSuccess, onError, meterTypeCode, }); }, COMMUNICATION_INTERVAL_PER_PROBE_IN_MS); } return () => { subscription?.unsubscribe?.(); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [disabledStep]); useEffect(() => { if ( bluetoothContext.connectionError || (bluetoothContext.bluetoothState === BluetoothState.IDLE && !loadingCurrentDevice && !bluetoothContext.targetDevice) ) onError(); }, [ bluetoothContext.bluetoothState, bluetoothContext.connectionError, onError, loadingCurrentDevice, bluetoothContext.targetDevice, ]); return ( {!beginReading ? ( { closeProbeReading(); }, key: 'exit', secondary: true, disabled: disabledStep, }, ]} withOpacity={disabledStep} > {children && children} {showFamilyBadgeLibrary && ( )} ) : ( { closeProbeReading(); }, key: 'exit', secondary: true, }, ]} > {children && children} {showFamilyBadgeLibrary && ( )} )} ); }; export default TakingReading;