Estimote: Beacon Manager Ranging Questions - listener

The following is code being used in an app I am working on. The app will try to detect an Estimote beacon and then output in Android notifications the distance of the beacon. The issue I am running into is that the notification is being sent every second, when it should be sent every 1/10th of a second - from setting the foreground scan period. Changing the advertising interval of the beacon didn't seem to have much of an effect either. Is there something I am missing with this?
beaconManager.setBackgroundScanPeriod(100,0);
beaconManager.setForegroundScanPeriod(100,0);
beaconManager.setRangingListener(new BeaconManager.RangingListener() {
int count = 0;
#Override
public void onBeaconsDiscovered(Region region, List<Beacon> beacons) {
if (beacons.size() < 1) {
return;
}
count++;
String distance = "" + getDistance(beacons.get(0).getRssi(), beacons.get(0).getMeasuredPower());
String beaconName = beacons.get(0).getName();
showNotification(count + " Name + Distance", beaconName + ": " + distance);
}
});

Related

Create one time popup with materialize css

Is there any way to evade jquery and make notification be shown only one time per browser ?
For example, goes to website, notification pops up and that is it, next time when user comes to site from same browser notification wont be showen to him.
I would mainly try to evade adding jquery just for that, so if anyone knows a way to do this with materializecss or some plain html i would be thankful.
How do you trigger the notification?
You could do a basic localStorage check for example to "detect" if the notification has been displayed or not:
function foo() {
const hasSeenNotification = window.localStorage.getItem('shown');
if (!hasSeenNotification) {
window.localStorage.setItem('shown', true);
// show notification here
// ...
}
}
You need to add cookies.
And then check is it is exists:
if (GetCookieShowMessageDocument('ShowPoPUP'))
{
...
}
Here is a sample:
function GetCookieShowMessageDocument(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
function SetCookieShowMessageDocument(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + escape(value) + expires + "; path=/";
}

How to make a user on my website ping a specific ip address?

I'm wondering how website like this one : https://ping.eu/ping/ manage to make our ip ping an other ip and get the result.
Someone have an idea ?
Thanks
It Doesn't. A PHP script(on the server) will most likely do it with "PHP Sockets". Have a look at
this: https://www.php.net/manual/en/sockets.examples.php
Else it could use exec() function, but that would be a security flaw.
So to answer your question: The website will ping the IP address not the 'client'
If you want to ping a server, i.e. an actual web address/URL like www.google.com, you can look at this JSFiddle http://jsfiddle.net/GSSCD/203/ or GitHub repository https://github.com/jdfreder/pingjs.
Here's some code from the JSFiddle:
function Pinger_ping(ip, callback) {
if(!this.inUse) {
this.inUse = true;
this.callback = callback
this.ip = ip;
var _that = this;
this.img = new Image();
this.img.onload = function() {_that.good();};
this.img.onerror = function() {_that.good();};
this.start = new Date().getTime();
this.img.src = "http://" + ip;
this.timer = setTimeout(function() { _that.bad();}, 1500);
}
}
Another way to ping a server/web address is to use JavaScript and the XMLHttpRequest() function it supports:
HTML:
<div id="result"></div>
JavaScript:
function http_ping(fqdn) {
var NB_ITERATIONS = 4; // number of loop iterations
var MAX_ITERATIONS = 5; // beware: the number of simultaneous XMLHttpRequest is limited by the browser!
var TIME_PERIOD = 1000; // 1000 ms between each ping
var i = 0;
var over_flag = 0;
var time_cumul = 0;
var REQUEST_TIMEOUT = 9000;
var TIMEOUT_ERROR = 0;
document.getElementById('result').innerHTML = "HTTP ping for " + fqdn + "</br>";
var ping_loop = setInterval(function() {
// let's change non-existent URL each time to avoid possible side effect with web proxy-cache software on the line
url = "http://" + fqdn + "/a30Fkezt_77" + Math.random().toString(36).substring(7);
if (i < MAX_ITERATIONS) {
var ping = new XMLHttpRequest();
i++;
ping.seq = i;
over_flag++;
ping.date1 = Date.now();
ping.timeout = REQUEST_TIMEOUT; // it could happen that the request takes a very long time
ping.onreadystatechange = function() { // the request has returned something, let's log it (starting after the first one)
if (ping.readyState == 4 && TIMEOUT_ERROR == 0) {
over_flag--;
if (ping.seq > 1) {
delta_time = Date.now() - ping.date1;
time_cumul += delta_time;
document.getElementById('result').innerHTML += "</br>http_seq=" + (ping.seq-1) + " time=" + delta_time + " ms</br>";
}
}
}
ping.ontimeout = function() {
TIMEOUT_ERROR = 1;
}
ping.open("GET", url, true);
ping.send();
}
if ((i > NB_ITERATIONS) && (over_flag < 1)) { // all requests are passed and have returned
clearInterval(ping_loop);
var avg_time = Math.round(time_cumul / (i - 1));
document.getElementById('result').innerHTML += "</br> Average ping latency on " + (i-1) + " iterations: " + avg_time + "ms </br>";
}
if (TIMEOUT_ERROR == 1) { // timeout: data cannot be accurate
clearInterval(ping_loop);
document.getElementById('result').innerHTML += "<br/> THERE WAS A TIMEOUT ERROR <br/>";
return;
}
}, TIME_PERIOD);
}
But, of course, these are web addresses, not IP addresses, so I'm not sure if that's what you're aiming for. I'm also not sure if you're looking for the amount of time spent to get the connection and the number of packets and bytes sent and received, or if you just want to validate the connection. The above code does all of those things. For IP addresses, you can try an AJAX request to ping a server, which only sees if there is a connection using YOUR SERVER'S IP address, NOT THE USER'S CLIENT, like this:
client --AJAX-- yourserver --ICMP ping-- targetservers
You could also try:
Using a Java applet with isReachable
Writing a server-side script which pings, and using AJAX to communicate to your server-side script
You might also be able to ping in Flash (using ActionScript)
One last hypothetical and unorthodox way to get an IP address is to inspect and view the source of the website you mentioned and copy some code, mostly JavaScript, and test it on your end and try to implement it.

Source event strange latitude & longitude

My name is Cyrille and i'm working on a map app on codename one. The goal is to make an app that can search around the user for companies (with a search bar) and add companies they want to a list. Then the list appear in the main window and clicking on them show it on the map.
I've got a problem with the event part on codename one. Here's a part of my code :
PointLayer point = new PointLayer(new Coord(lat.doubleValue(), lng.doubleValue()),
companyName, null);
pl.addPoint(point);
pl.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
PointLayer p = (PointLayer) evt.getSource();
System.out.println("pressed " + p);
Dialog.show("Details", "" + p.getName() + "\nLatitude: " + p.getLatitude() + "\nLongitude: " + p.getLongitude(), "Ok", null);
}
});
Yes I took the basic map template ^^'
My problem is : When i ask for the coordonates of point I get :
{'longitude':2.3485853, 'latitude':48.8769309}
but when I ask for the coordonates of evt.getSource i get :
{'longitude':261443.31964417442,'latitude':6254004.882818963}
which is kind of perturbing ...
I looked over the internet since yesterday but i didn't find any thing, maybe i'm not searching at the right place. Any clue of what's happening ?
EDIT :
Thanks to the replyers i found the issue. The coordonates was given in an other system use by codename one : Popular Visualisation CRS Mercator. In order to use it you have to convert it with : com.codename1.maps.Mercator.inverseMercator(latitude, longitude);
Or you can use google marker instead of codename one's [That's what i did]
I think the coordinates you get in the event are in the Popular Visualisation CRS Mercator (EPSG:900913 or EPSG:3785) coordinate system, which is what the map control uses. The points you add in lat/lon are automatically transformed to this system when added to the map. "latitude" and "longitude" are slightly misleading; "x" and "y" are the standard terms for projected coordinates.
I can't find why it returns this value but maybe you can bypass this issue by building a coord object.
Example :
Coord coord = new Coord(lat.doubleValue(), lng.doubleValue());
PointLayer point = new PointLayer(coord, companyName, null);
pl.addPoint(point);
pl.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
PointLayer p = (PointLayer) evt.getSource();
System.out.println("pressed " + p);
Dialog.show("Details", "" + p.getName() + "\nLatitude: " + coord.getLatitude() + "\nLongitude: " + coord.getLongitude(), "Ok", null);
}
});
EDITED
I had the same problem 1 month ago. I resolved it by using the MapContainer and i use the addMarker(); from the map. By this way i can use it like this :
MapContainer map = new MapContainer(); // This used gMaps
for(Coord points : coords){
map.addMarker((EncodedImage) myIcon, coord,"","", new ActionListener(){
Dialog.show("Details", "" + p.getName() + "\nLatitude: " + points.getLatitude() + "\nLongitude: " + points.getLongitude(), "Ok", null);
})
}

Gmail thread object unexpected behavior

I am trying to write a Google Apps Script that will process all emails that have a specific label.
I am using the GmailApp.search function to retrieve all of the relevant emails, but when I try to use the functions document in the GmailThread class, I get an error message that says that it can't find the function.
Here is my code;
var incoming = "To_Bot"
function readBotsEmail()
{
var emails = GmailApp.search("label:" + incoming);
Logger.log("This is the 'emails' object:" + emails)
var emailsLoopIndex = 0
for (var email in emails)
{
emailsLoopIndex += 1;
try
{
Logger.log("iteration " + emailsLoopIndex + " " + email.getMessageCount());
}
catch(e)
{
Logger.log("iteration " + emailsLoopIndex + " " + e);
}
}
}
Here is the logger output.
[14-01-26 03:40:00:909 EST] This is the 'emails' object:GmailThread,GmailThread
[14-01-26 03:40:00:911 EST] iteration 1 TypeError: Cannot find function getMessageCount in object 0.
[14-01-26 03:40:00:914 EST] iteration 2 TypeError: Cannot find function getMessageCount in object 1.
Where am I going wrong?
You should avoid using ambiguous variable names, "email" and "emails" are really bad choice when talking about threads on one side and index integer on the other...
Your issue comes mainly from this confusion between both variables, you used email instead of email*S* and also seem to forget that your value was an array of threads thus needing to be indexed.
Here is your working code, just one letter difference ;-) and a couple of brackets...
function readBotsEmail()
{
var emails = GmailApp.search("label:" + incoming);
Logger.log("This is the 'emails' object:" + emails)
var emailsLoopIndex = 0
for (var email in emails)
{
emailsLoopIndex += 1;
try
{
Logger.log("iteration " + emailsLoopIndex + " " + emails[email].getMessageCount());
}
catch(e)
{
Logger.log("iteration " + emailsLoopIndex + " " + e);
}
}
}
That said, you still have a lot of work on this script to make it return something interesting... for now it informs you on the number of threads and how many message they have... Anyway, that's a good start...
Good luck !

Google distances using C# - Over-Query-Limit

I am trying to fetch google distances in gridview RowDataBound with a force sleep of 1000ms,Nothing helping,Am getting correct distance for the first query,ie the first row of the gridview, all others i get 'Over-Query-Limit' for content variable ,I want to know three things:
Is there any solution for this situation.
Is google limiting queries per day OR
Is google limiting queries per second ?
public int getDistance(string origin, string destination)
{
System.Threading.Thread.Sleep(1000);
int distance = 0;
string url = "http://maps.googleapis.com/maps/api/directions/json?origin=" + origin + "&destination=" + destination + "&sensor=false";
string requesturl = url;
string content = fileGetContents(requesturl);
JObject o = JObject.Parse(content);
try
{
distance = (int)o.SelectToken("routes[0].legs[0].distance.value");
return distance;
}
catch
{
return distance;
}
return distance;
}
Ok,As above 2500 queries per day makes google search a paid service i went for another logic,We can calculate distances without google.com as follows :
public decimal calcDistance(decimal latA, decimal longA, decimal latB, decimal longB)
{
double theDistance = (Math.Sin(DegreesToRadians(latA)) *
Math.Sin(DegreesToRadians(latB)) +
Math.Cos(DegreesToRadians(latA)) *
Math.Cos(DegreesToRadians(latB)) *
Math.Cos(DegreesToRadians(longA - longB)));
return Convert.ToDecimal((RadiansToDegrees(Math.Acos(theDistance)))) * 69.09M * 1.6093M;
}
public double DegreesToRadians(decimal degrees)
{
return Convert.ToDouble((Convert.ToDecimal(Math.PI) / 180.0M) * degrees);
}
public double RadiansToDegrees(double radians)
{
return Convert.ToDouble((180.0M / Convert.ToDecimal(Math.PI)) * Convert.ToDecimal(radians));
}