File name
Commit message
Commit date
File name
Commit message
Commit date
File name
Commit message
Commit date
import React, {
useRef,
useCallback,
useContext,
useEffect,
useState,
} from 'react';
import Button from '../component/Button';
import {View, Text, StyleSheet, Alert, Linking} from 'react-native';
import Map from '../component/Map';
import {MapContext} from './../context/MapContext';
import {useCameraDevices, Camera} from 'react-native-vision-camera';
import RNFS from 'react-native-fs';
import {url} from '../url';
import {PRIMERY, RED, WHITE} from '../color';
import ModalComponent from '../component/ModalComponent';
export default function Main({navigation}) {
const {onQuery, searchQuery, location, nodes} = useContext(MapContext);
const [isDrivingStarted, setIsDrivingStarted] = useState(false);
const [shouldLog, setShouldLog] = useState(false);
const [infoMessage, setInfoMessage] = useState('');
const [sendTime, setSendTime] = useState(null);
const [devicesLoaded, setDevicesLoaded] = useState(false);
const devices = useCameraDevices();
const device = devices.back;
const camera = useRef(null);
let timerId;
const [isModalVisible, setModalVisible] = useState(false);
const toggleModal = () => {
setModalVisible(!isModalVisible);
};
const requestCameraPermission = useCallback(async () => {
const permission = await Camera.requestCameraPermission();
if (permission === 'denied') await Linking.openSettings();
}, []);
useEffect(() => {
requestCameraPermission();
if (
devices &&
devices.back &&
devices.back.devices.includes('telephoto-camera') &&
!devicesLoaded
) {
const telephotoCamera = devices.back.devices.find(
device => device === 'telephoto-camera',
);
if (telephotoCamera) {
camera.current = telephotoCamera;
setDevicesLoaded(true);
}
}
}, [devices, devicesLoaded]);
useEffect(() => {
if (devicesLoaded && shouldLog) {
const intervalId = setInterval(() => {
setInfoMessage('정보가 송신되었습니다.');
setSendTime(new Date());
takePicture();
}, 5000);
return () => {
clearInterval(intervalId);
setInfoMessage('');
setSendTime(null);
};
}
}, [devicesLoaded, shouldLog]);
const handleStartDriving = () => {
setIsDrivingStarted(prevState => !prevState);
if (isDrivingStarted) {
setShouldLog(false);
clearInterval(timerId);
} else {
setShouldLog(true);
}
};
const takePicture = async () => {
if (!devicesLoaded || !camera.current) {
console.log('Devices are not loaded or camera is not available.');
return;
}
const photoResult = await camera.current.takePhoto({
flash: 'off',
qualityPrioritization: 'speed',
});
if (photoResult && photoResult.path) {
const {path} = photoResult;
let pathSplit = path.split('/');
let fileName = pathSplit[pathSplit.length - 1];
let splitFileName = fileName.split('.');
let sFileName = splitFileName[0];
let files = [
{
name: 'file',
filename: fileName,
filepath: path,
filetype: 'image/jpg',
},
];
let upload = response => {
let jobId = response.jobId;
console.log('UPLOAD HAS BEGUN! JobId: ' + jobId);
};
let uploadProgress = response => {
let percentage = Math.floor(
(response.totalBytesSent / response.totalBytesExpectedToSend) * 100,
);
console.log('UPLOAD IS ' + percentage + '% DONE!');
};
await RNFS.uploadFiles({
toUrl: `${url}//action/image_summit`,
files: files,
method: 'POST',
headers: {},
begin: upload,
progress: uploadProgress,
})
.promise.then(response => {
if (response.statusCode !== 200) {
throw new Error('SERVER ERROR: ' + response.statusCode);
}
return fetch(`${url}/action/image_anal`, {
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=UTF-8',
},
body: JSON.stringify({
filename: sFileName,
file_type: '.jpg',
gps_x: location.latitude,
gps_y: location.longitude,
}),
});
})
.then(response => response.json())
.then(data => {
const {node, rain} = data;
if (node === null || rain !== 'rain') {
throw new Error('No data or not fog');
}
toggleModal();
})
.catch(error => {
console.error('Error during file upload or image analysis:', error);
});
} else {
console.log('Failed to take a photo.');
}
};
return (
<View style={{flex: 1}}>
<Map
lat={location.latitude}
long={location.longitude}
latDelta={0.005}
longDelta={0.005}
showsUserLocation={true}
/>
<View style={styles.container}>
<Button
title={isDrivingStarted ? '운행 종료' : '운행 시작'}
// onPress={handleStartDriving}
onPress={toggleModal}
color={WHITE}
width={'100%'}
textAlign={'center'}
padding={10}
backgroundColor={isDrivingStarted ? RED : PRIMERY}
/>
{devicesLoaded && shouldLog && (
<Camera ref={camera} device={device} isActive={true} photo={true} />
)}
{infoMessage && sendTime && (
<View style={styles.infoContainer}>
<Text>{infoMessage}</Text>
<Text style={styles.normalText}>
Sent at: {sendTime.toLocaleTimeString()}
</Text>
<Text style={styles.normalText}>
{infoMessage === '정보가 송신되었습니다.'
? '사진을 촬영합니다.'
: ''}
</Text>
</View>
)}
</View>
<ModalComponent
isVisible={isModalVisible}
toggleModal={toggleModal}
alertTitle="폭우 발생 알림"
alertMessage="폭우가 발생하였습니다."
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
width: '45%',
// marginLeft: 5,
// justifyContent: 'center',
// alignItems: 'center',
position: 'absolute',
bottom: 7,
right: 15,
},
infoContainer: {
marginTop: 16,
justifyContent: 'center',
alignItems: 'center',
},
normalText: {
color: 'black',
},
});