User speed in expo has low Accuracy - react-native

So im trying to find out my user speed and when he stopped so i can take the coordinates.My problem is that the accuracy of 'expo-location' is sooo low.The user stops and the location speed still gives me like 18 m / per hour .
Here is my code :
const [location, setLocation] = useState(null)
const [latitude, setLatitude] = useState(null)
const [longitude, setLongitude] = useState(null)
const [speed, setSpeed] = useState(null)
useEffect(() =>
async () => {
let location = await Location.getCurrentPositionAsync({})
setTimeout(()=>{
console.log("Latitude : ", location.coords.latitude)
console.log("Longitude : ", location.coords.longitude)
console.log("Speed : ", location.coords.speed)
if(location.coords.speed <= 4 && location.coords.speed != 0 && location.coords.speed != null){
setLocation(location)
setLatitude(location.coords.latitude)
setLongitude(location.coords.longitude)
setSpeed(location.coords.speed)
return ;
}
},3000)
});
console.log("Final location : ",location)
console.log("Final speed : ",speed)
console.log("Final latitude : ",latitude)
console.log("Final lonitude : ",longitude)

Related

Async function react native

We have to create a Bingo game in React Native with Firebase Realtime Database on Android simulator. The app game is for 2 players. When the first player enter in the app, he create the game and wait for the second player to join.
we want to create a screen with the writing: "Waiting for another player" that appears to the first player until the second player connects then when the second player connects the card is shown.
We wrote this code but it return 'undefined' .
function Game(){
const authCtx = useContext(AuthContext);
const gameCtx = useContext(GameContext);
const [loadPlayer, setLoadPlayer] = useState(false);
useEffect(() => {
async function gamePlay(){
gameCtx.player1 = authCtx.token;
const play = await setGame(authCtx.token, gameCtx);
console.log(play); //return undefined
if(play == 'CREATE'){
setLoadPlayer(true);
}else if(play == 'UPDATE'){
setLoadPlayer(false);
}
if(loadPlayer){
return <LoadingOverlay message="Waiting for another player... " />;
}
}
gamePlay();
}, []);
return <Card />;
}
export default Game;
export function create(game){
const db = getDatabase();
const newGameKey = push(child(ref(db), 'GAME')).key;
set(ref(db, '/GAME/' + newGameKey), game)
.then(() => {console.log('Game Create!');})
.catch((error) => {console.log(error);});
}
export function setGame(email, game){
const dbRef = ref(getDatabase());
var player = false;
get(child(dbRef, 'GAME/')).then((snapshot) => {
if (snapshot.exists()) {
snapshot.forEach(function(childSnapshot) {
const key = childSnapshot.key;
const key1 = snapshot.child(key + '/player1').val();
const key2 = snapshot.child(key + '/player2').val();
if( key2 == "" && email != key1){
console.log('P2');
updateGame(email, key);
player = true;
return true;
}
});
if(player == false){
console.log('P1');
player = true;
create(game);
}
} else {
//create the first game!
create(game);
}
}).catch((error) => {
console.error(error);
});
}
export function updateGame(email, key){
console.log('Update: ' + key);
const db = getDatabase();
const updates = {};
updates['/GAME/' + key + '/player2'] = email;
return update(ref(db), updates);
}
We think this is due to "async" and "await" because not working correctly.
Do you have any suggestions?
How can we redirect the first player to a waiting screen?
is ref(getDatabase()) is promise?. if it is then use await before it.
and use async function before setGame if you are using await while calling.
export async function setGame(email, game){
const dbRef = await ref(getDatabase());
var player = false;
get(child(dbRef, 'GAME/')).then((snapshot) => {
if (snapshot.exists()) {
snapshot.forEach(function(childSnapshot) {
const key = childSnapshot.key;
const key1 = snapshot.child(key + '/player1').val();
const key2 = snapshot.child(key + '/player2').val();
if( key2 == "" && email != key1){
console.log('P2');
updateGame(email, key);
player = true;
return true;
}
});
if(player == false){
console.log('P1');
player = true;
create(game);
}
} else {
//create the first game!
create(game);
}
}).catch((error) => {
console.error(error);
});
}

Please Report: Excessing number of pending callbacks - React Native Socket.io client

const [markets,setMarkets]=useState(false)
useEffect(() => {
if (socketConnection != null) {
socketConnection.on("url", (data) => {
getData();
markets.length > 0 &&
markets.map((market) => {
if (data.pair == market.pair) {
let newPrice = data.price.toFixed(data.decimalValue);
let oldData = markets.filter(
(market) => market.pair == data.pair
)[0];
let oldIndex = markets.findIndex(
(market) => market.pair == data.pair
);
let oldPrice = oldData.price.toFixed(oldData.decimalValue);
if (newPrice != oldPrice) {
markets[oldIndex].price = data.price;
markets[oldIndex].lastPrice = data.lastPrice;
markets[oldIndex].change = data.change;
markets[oldIndex].oldPrice = oldData.price;
}
}
});
});
setMarkets(markets);
}
}, [socketConnection]);
I am updating my state like this using socket.io-client but getting this error as Please Report : Excessive number of pending requests and app is hanged.Anyone plse help for the issue

Message event broken ( quick.db )

So i wanna get started with quick.db for my discord.js bot. I asked someone to help me solve this issue but they seem to be unable to. So if theres anyone here that can help could you tell me whats wrong with my code
module.exports = (client) => client.on('messageCreate', async (message) => {
const prefix = [].concat(client.config.prefix);
const ms = require('ms');
if (
message.author.bot ||
!message.guild ||
!prefix.some((x) => message.content.toLowerCase().startsWith(x))
)
return;
const [cmd, ...args] = message.content
.slice(prefix
.filter((x) => message.content.toLowerCase().startsWith(x))
.sort((a, b) => b.length - a.length)[0].length
)
.trim()
.split(/ +/g);
const command =
client.commands.get(cmd.toLowerCase()) ||
client.commands.find((c) =>
[].concat(c.aliases).includes(cmd.toLowerCase())
);
if (!command) return;
const cd = client.cd.get(`${message.author.id}_${command.name}`);
const left = cd - Date.now();
if (left > 0) {
const msg = await message.channel.send(
`You are on cooldown, please wait **${ms(left)}** to use this command again`
);
return setTimeout(() => msg.delete(), left);
}
if (command.cooldown)
client.cd.set(
`${message.author.id}_${command.name}`,
Date.now() + ms(command.cooldown)
);
try {
await command.run(client, message, args);
} catch (error) {
message.channel.send(error.toString());
}
}); 
the above code is the working one but whenever i use this
module.exports = (client) => client.on('messageCreate', async (message) => {
const ms = require('ms');
const { QuickDB } = require('quick.db');
const db = new QuickDB();
const prefix = db.get(`newprefix_${message.guild.id}`) || config.prefix
if (!prefix) return; 
if (!message.content.startsWith(prefix) || message.author.bot) return;
const [cmd, ...args] = message.content
.slice(prefix
.filter((x) => message.content.toLowerCase().startsWith(x))
.sort((a, b) => b.length - a.length)[0].length
)
.trim()
.split(/ +/g);
const command =
client.commands.get(cmd.toLowerCase()) ||
client.commands.find((c) =>
[].concat(c.aliases).includes(cmd.toLowerCase())
);
if (!command) return;
const cd = client.cd.get(`${message.author.id}_${command.name}`);
const left = cd - Date.now();
if (left > 0) {
const msg = await message.channel.send(
`You are on cooldown, please wait **${ms(left)}** to use this command again`
);
return setTimeout(() => msg.delete(), left);
}
if (command.cooldown)
client.cd.set(
`${message.author.id}_${command.name}`,
Date.now() + ms(command.cooldown)
);
try {
await command.run(client, message, args);
} catch (error) {
message.channel.send(error.toString());
}
});  
it doesn't work, meaning my bot doesn't reply

How can I "zoom" into one US state from a topojson of US counties?

I have a D3 topoJSON implementation in React Native that displays US counties' paths and state paths to form a map. I want to essentially "zoom" in or scale up to show only one state with the counties. The bordering paths of the states should be around the focused state. How can I do this?
const COUNTIES = feature(
counties,
counties.objects.counties
).features;
const [countyList, setCountyList] = useState([]);
const mapExtent = useMemo(() => {
return dimensions.width > dimensions.height / 2
? dimensions.height / 2 - 90
: dimensions.width - 90;
}, [dimensions]);
const statePaths = useMemo(() => {
const projection = d3.geoMercator().fitSize([mapExtent, mapExtent], {
type: "FeatureCollection",
features: COUNTIES,
});
const geoPath = d3.geoPath().projection(projection);
const svgPaths = COUNTIES.map(geoPath);
return svgPaths;
}, [dimensions]);
useEffect(() => {
setCountyList(
statePaths.map((path, i) => {
const curCounty = COUNTIES[i].properties.NAME;
const isCountyNameInData = data.some(
(county) => county.name === curCounty + " County"
);
const curCountyData = isCountyNameInData
? data.find((county) => county.name === curCounty + " County")["data"]
: null;
return (
<Path
key={COUNTIES[i].properties.NAME}
d={path}
stroke={"#535252"}
strokeOpacity={0.3}
strokeWidth={0.6}
fill={colorScale(curCountyData)}
/>
);
})
);
}, [data]);

Couldn't read accelerometer and gyro from sensortag using react-native

I have been working on react-native-ble-plx with sensortag cc2650stk and having issues fetching accelerometer and gyro data.
Error: Characteristic "f000aa82-0451-4000-b000-000000000000" write failed for device xxxxxx and service "f000aa80-0451-4000-b000-000000000000"
Things work fine for all the other sensors of the ticc2650 sensortag. like humidity,temperature,barometer etc.
constructor() {
super();
this.manager = new BleManager()
this.state = {info: "", values: {}}
this.prefixUUID = "f000aa"
this.suffixUUID = "-0451-4000-b000-000000000000"
this.sensors = {
0: "Temperature",
8: "Accelerometer",
2: "Humidity",
7: "Magnetometer",
4: "Barometer",
// 5: "Gyroscope"
}
}
serviceUUID(num) {
return this.prefixUUID + num + "0" + this.suffixUUID
}
notifyUUID(num) {
return this.prefixUUID + num + "1" + this.suffixUUID
}
writeUUID(num) {
return this.prefixUUID + num + "2" + this.suffixUUID
}
My sensortag Movemnet UUIDS are:
MOVEMENT_SERVICE = 'f000aa80-0451-4000-b000-000000000000';
MOVEMENT_DATA = 'f000aa81-0451-4000-b000-000000000000';
MOVEMENT_CONFIG = 'f000aa82-0451-4000-b000-000000000000';
MOVEMENT_PERIOD = 'f000aa83-0451-4000-b000-000000000000';
MOVEMENT_NOTIFICATION = '00002902-0000-1000-8000-00805f9b34fb';
if (device.name === 'CC2650 SensorTag' || device.name === 'SensorTag') {
this.info("Connecting to TI Sensor")
this.manager.stopDeviceScan();
device.connect()
.then((device) => {
this.info("Discovering services and characteristics")
return device.discoverAllServicesAndCharacteristics()
})
.then((device) => {
this.info("Setting notifications")
console.log(device);
return this.setupNotifications(device)
})
.then(() => {
this.info("Listening...")
}, (error) => {
this.error(error.message)
})
}
async setupNotifications(device) {
for (const id in this.sensors) {
//id = 8;
const service = this.serviceUUID(id);
const characteristicW = this.writeUUID(id);
const characteristicN = this.notifyUUID(id);
const characteristic = await device.writeCharacteristicWithResponseForService(
service, characteristicW, "AQ==" /* 0x01 in hex */
)
device.monitorCharacteristicForService(service, characteristicN, (error, characteristic) => {
if (error) {
this.error(error.message)
return
}
console.log(characteristic.uuid+":::"+characteristic.value);
this.updateValue(characteristic.uuid, characteristic.value)
})
}
}
work fine for other sensors but not gyro and accelerometer.
Things work fine for other sensors when we write "AQ==" / 0x01 in hex / But for movement sensor we need to add "MDE=" for 0x01 in function for notifications
const characteristic = await device.writeCharacteristicWithResponseForService(
service, characteristicW, "AQ==" /* 0x01 in hex */
)
I dont know why have they done so but this solved the issue for me.