Android - How to connect to the strongest Access Point if all have the same SSID? - android-wifi

I know how to connect to an access point, but I don't know how to connect to the strongest one,
if all have the same SSID.
I configured something like this
WifiConfiguration conf = new WifiConfiguration();
conf.SSID = convertToQuotedString("XYZ");
conf.status = WifiConfiguration.Status.ENABLED;
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
int netId = wifi.addNetwork(conf);
and then I say something like this
List<WifiConfiguration> _configs = wifi.getConfiguredNetworks();
for (WifiConfiguration config : _configs) {
if ( config.SSID.equalsIgnoreCase(convertToQuotedString("XYZ"))){
boolean erg = wifi.enableNetwork(config.networkId, true);
Log.d(TAG, "enabling configured Network: " + Boolean.toString(erg) +
" SSID=[" + config.SSID + "] and ID=[" + config.networkId );
}
}
The question now is ?
How can I connect to another access point with the same SSID but a better signal ?
In the WifiConfiguration there is no possibility to tell him something this, is it ?
I find a better access point with the same SSID using the method
WifiManager.compareSignalLevel(bestSignal.level, connectedAcc.level) <0
How can I connect to the better one, if in the WifiConfiguration there is no difference between them, because they both have the same SSID ?
I hope you can help me please,
thanks a lot

Once you know the best one, you can change the priority in the corresponding WifiConfiguration.

Well if you still haven't found an answer to your issue then you can do as follows -
1) Check whether the BSSID of best signal and the device you have connected to is the same.
a) If its same then it means you are connected to the SSID with the best signal and all is well.
b) If not move to step two.
2) Use wifi.disconnect();
This will ensure that at the moment you are not connected to any access point.
3) Now use the SSID as previously used to connect to the access point and it will connect to the one with the strongest signal.

Related

Error: Cannot enqueue Query after fatal error in mysql node

I am using felixge/node-mysql. Also I am using express-myconnection which prevents mysql timeout and in turn prevents killing of node server. What I am doing is logging the activities in mysql. The scenario is I have a file upload functionality once the file is uploaded I am performing different operations on the file. During every stage of processing I am logging those activities in database. This works fine if the file is small. If the file is large say 100 MB it takes some time to load so in the mean time the mysql server reconnects and creates a new connection but the logging code still uses the old reference. Error: Cannot enqueue Query after fatal error. So, my question is is there a way that i can use the new connection reference instead of the old one. There is a single function in which all the different phases of activities regarding file takes place. Any help is greatly appreciated. thanks
Hi #paul, if you have seen the gist link you can see that I have the upload.on('begin', function (fileInfo, reqs, resp) { } where I have logged the activity that file upload process has begin. Once the file is uploaded upload.on('end', function (fileInfo,request,response) { } is triggered. I am also logging some activity here. As I said in my question, if the file is big the upload takes time. In the mean time a new MySql connection is created but the insert query in 'end' event still refers to the old myconnection. So, I wanted to know how can I use the new mysql connection reference in this scenario? I hope this has explained the scenario better.
Actually, I decided to google your error for you, and after reading this thread: https://github.com/felixge/node-mysql/issues/832 I realized that you're not releasing the connection after the first query completes, and so the pool never tries to issue you a new one. You were correct that the stale connection might be the problem. here's how you fix that if it is:
upload.on('begin', function (fileInfo, reqs, resp) {
var fileType = resp.req.fields.file_type;
var originalFileName = fileInfo.name;
var renamedFilename = file.fileRename(fileInfo,fileType);
/*renaming the file */
fileInfo.name = renamedFilename;
/*start: log the details in database;*/
var utcMoment = conf.moment.utc();
var UtcSCPDateTime = new Date( utcMoment.format() );
var activityData = {
activity_type : conf.LIST_UPLOAD_BEGIN,
username : test ,
message : 'test has started the upload process for the file',
activity_datetime : UtcSCPDateTime
};
reqs.params.activityData = activityData;
req.getConnection(function(err,connection) {
var dbData = req.params.activityData;
var activity_type = dbData.activity_type;
console.dir("[ Connection ID:- ] "+connection.threadId+' ] [ Activity type:- ] '+activity_type);
var insertQuery = connection.query("INSERT INTO tblListmanagerActivityLog SET ? ",dbData, function(err, result) {
if (err) {
console.log("Error inserting while performing insert for activity "+activity_type+" : %s ",err );
} else {
console.log('Insert successfull');
}
/// Here is the change:
connection.release();
});
});
/*end: log the details in database;*/
});
I fixed mine. I always suspect that when errors occur along with my queries it has something to do with the MySQL80 Service being stopped in the background. In case other solutions failed. Try going to the task manager, head to the services, find MySQL80 and check if it is stopped, when it is, click start or set it as automatic so that it will start at the moment desktop is running.
For pool connection to work we need to comment out https://github.com/pwalczyszyn/express-myconnection/blob/master/lib/express-myconnection.js#L84 this line. Hope it helps anyone facing the same issue.
Also we can use single connection option.
I had the same issue. Came across one solution -
Re-Install MySQl and while doing so, in the configuration step, select "legacy encryption" option instead and finish the installation.
Hope this helps!

How do I use MySQL for dynamic doc root with Nginx?

I've been trying to find out a way to first capture environment variable HOSTNAME and then use a MySQL query to fetch and return back to the Nginx conf the document root for our vhosts. We use them for dynamic doc roots currently in Apache but are migrating to Nginx.
example nginx.conf (might look something like this):
server {
listen 80;
# grab Environment variable HOSTNAME
$hostname= ENV(HOSTNAME);
# execute mysql query
$doc_root = mysql(select docroot from table where host = '$hostname' );
# set document root
root /var/www/$doc_root;
.....
I was exploring using Lua and https://github.com/openresty/lua-resty-mysql but have been unable to figure out how this could be done to capture HOSTNAME and mysql query as a variable and return the results back.
Thanks for your help. It didn't work for me, but after a lot of work, I finally got something working. This is for someone else if they ever need it
it turns out $http_host is already defined globally in nginx - so that was fixed.
set $httphost $http_host; # create and initialize var
set $docroot "";
# begin LUA scripting
rewrite_by_lua '
-- make sure http host is defined
if not ngx.var.httphost then
ngx.log(ngx.ERR,"ERROR - no httphost defined")
return
end
-- begin mysql
local mysql = require "resty.mysql"
local db, err = mysql:new()
db:set_timeout(1000) -- 1 sec
local ok, err, errno, sqlstate = db:connect
{
host = "127.0.0.1",
port = 3306,
database = "db",
user = "user",
password = "password",
max_packet_size = 1024 * 1024
}
if not ok then
ngx.log(ngx.ERR,"MySQL failed to connect: ", err, ": ", errno, " ", sqlstate)
return
end
-- prevent injection attack
local hname = ngx.unescape_uri(client)
local quoted_name = ngx.quote_sql_str(hname)
local sql = "select docroot from users where customer =" .. quoted_name
result,err,errno,sqlstate = db:query(sql,1)
if not result then
ngx.log(ngx.ERR,"MySQL bad result: ", err, ": ", errno, ": ", sqlstate, ".")
return
end
if not result[1].docroot then
ngx.log(ngx.ERR,"MySQL ERROR - no docroot was returned")
return
end
ngx.var.docroot = result[1].docroot
';
# now we can set the docroot for this host
root /var/www/$docroot;
First of all, using a database for doing basic routing does not sound like a very good idea - I would recommend having the results cached in memory and maybe refreshing them periodically from the database.
Second, the basic Nginx config file will get you only so far - in order to get more advanced functionality you will need to use a scripting language (like Lua) on top of it. One of the things this allows you is reading environment variables. I wrote about how to do it here:
https://docs.apitools.com/blog/2014/07/02/using-environment-variables-in-nginx-conf.html
The usual way to get Lua working on Nginx is using Openresty, a version of Nginx which comes with several modules pre-installed, including the Lua one. You can add lua-resty-mysql to the mix, and then do everything you want directly from Lua. I have never used lua-resty-mysql so I can't code that for you. If you are set on using Mysql, you will have to study its docs. Give a look at Redis while you are at it, it might be a better fit than Mysql.

Ascmd.exe process stuck on OLAP creation

I'm pulling my hair out here for that I can't understand what is going on
I have the following:
Windows Server 2008 R2 64-bit
SQL Server 2008 R2 64-bit
When I run ascmd.exe it giving xml file in order to build OLAP database, most of the time the process just gets stuck and the console window is open even after ten minutes with no further messages.
However if I check in the SQL Server Managment, I can see that the OLAP database is created. Then in other times (Same machine, Same scenario, Same snapshot) it succeeds.
What can cause this odd behaviour?
I've tried to search everywhere but did not find any similar issue
I've tried to replace the ascmd.exe tool with its latest(Version 10.0.87.5)
I don't know whats causing this, please help!
Thanks!!!
Update:
Please someone? it is very important
Update:
I think I have a progress on it but can't explain the behaviour.
I've looked into the code of the Ascmd and I've found that for some reason the trace file(log file) did not start, therefore the code got into a loop forever section and did not get out(I've added prints to the code to check out if it is get stuck here and i've noticed that it gets stuck on while (!TraceStarted) { Thread.Sleep(1); } :
private static void WaitForTraceToFinish()
{
int delay = Int32.Parse(TraceTimeout, CultureInfo.CurrentCulture);
TraceTimeoutCount = TraceTimeoutCountReset = delay * PollingInterval; // TraceTimeoutCount is in 1/4 seconds
Console.WriteLine("TraceTimeoutCount is : " + TraceTimeoutCount);
Console.WriteLine("Did Trace Start Already ? : " + TraceStarted);
// Wait for trace to start to flow
while (!TraceStarted) { Thread.Sleep(1); } // loop every 20ms waiting for trace to start
// Wait BeginEndBlockCount becomes 0 or TraceTimeoutCount expires
while (TraceTimeoutCount > 0)
{ // loop forever until TraceFinished
Console.WriteLine("TraceTimeoutCount is : " + TraceTimeoutCount);
Console.WriteLine("PollingInterval is : " + PollingInterval);
Console.WriteLine("1000 / PollingInterval = " + 1000 / PollingInterval);
if (BeginEndBlockCount == 0) return;
Thread.Sleep(1000 / PollingInterval); // wait a polling interval
Console.WriteLine("TraceTimeoutCount is : " + TraceTimeoutCount);
TraceTimeoutCount--;
Console.WriteLine("TraceTimeoutCount is : " + TraceTimeoutCount);
}
Console.WriteLine("Got out from trace");
// TraceTimeoutCount expired -- just exit
}
Does anyone know why the trace file is not started?
Does it related to Windows Server 2008 hard security rules?
I cannot remove the trace file since its a requirement for us
Any suggestions? thanks!
Its so frustrating to know that administrative privileges in Windows Server 2008 + SQL Server 2008 could make those errors
Running as administrator solved my problem and the OLAP creation process did not stuck

MySQL credentials/hosts variables best practices

I want to know what is the best practice or what is recommended to do when a variables are created for MySQL credentials/host.
define('HOST', 'localhost');
// etc..
mysql_connect(HOST, // etc...
vs
$host = 'localhost';
// etc..
mysql_connect($host, // etc...
For both you can easily check what are the declared variables or constants and maybe can find what are the value easily. I have code that multiple users can share and use.
What is the best way to protect these variables?
Here's few solutions
1) You give each user a user and password and each user has their permissions in the database (only select, or insert ect..). So in your code you simply include a db.config.php so all the variables are set. It does not really matter if the user echo the variables since they use their own.
2) you can give a common username/pass for the database and then encode the file (either using custom encoding, zend optimizer or ioncube and unset the variables. Here's a sample code:
// file mysql_connect.php
$link = mysql_connect("localhost", "mysql_user", "mysql_password")
or die("cannot connect to database : " . mysql_error());
// then this file is encoded so nobody can view it.
3) At some point, someone, somehow will be able to find this information. I would simply recommend to trust your user (assuming these are developers)
At some point in your code you will have to hardcode this kind of information, the important thing is to keep it in only one place to promote maintanability.
However, as you are worried about security I suggest you to check this: Convert PHP file to binary

MySQL / SQLite3

I stumbled upon the following:
def save_formset(self, request, form, formset, change):
instances = formset.save(commit=False)
bargain_id = 0
total_price = Decimal(0)
for instance in instances:
if isinstance(instance, BargainProduct):
total_price += instance.quantity * instance.product.price
bargain_id = instance.id
instance.save()
updateTotal = Bargain.objects.get(id=bargain_id)
updateTotal.total_price = total_price - updateTotal.discount_price
updateTotal.save()
This code is working for me on my local MySQL setup, however, on my live test enviroment running on SQLite3* I get the "Bargain matching query does not exist." error..
I am figuring this is due to a different hierarchy of saving the instances on SQLite.. however it seems they run(and should) act the same..?
*I cannot recompile MySQL with python support on my liveserver atm so thats a no go
Looking at the code, if you have no instances coming out of the formset.save(), bargain_id will be 0 when it gets down to the Bargain.objects.get(id=bargain_id) line, since it will skip over the for loop. If it is 0, I'm guessing it will fail with the error you are seeing.
You might want to check to see if the values are getting stored correctly in the database during your formset.save() and it is returning something back to instances.
This line is giving the error:
updateTotal = Bargain.objects.get(id=bargain_id)
which most probably is because of this line:
instances = formset.save(commit=False)
Did you define a save() method for the formset? Because it doesn't seen to have one built-in. You save it by accessing what formset.cleaned_data returns as the django docs say.
edit: I correct myself, it actually has a save() method based on this page.
I've been looking at this same issue. It is saving the data to the database, and the formset is filled. The problem is that the save on instances = formset.save(commit=False) doesn't return a value. When I look at the built-in save method, it should give back the saved data.
Another weird thing about this, is that it seems to work on my friends MySQL backend, but not on his SQLITE3 backend. Next to that it doesn't work on my MySQL backend.
Local loop returns these print outs (on MySQL).. on sqlite3 it fails with a does not excist on the query
('Formset: ', <django.forms.formsets.BargainProductFormFormSet object at 0x101fe3790>)
('Instances: ', [<BargainProduct: BargainProduct object>])
[18/Apr/2011 14:46:20] "POST /admin/shop/deal/add/ HTTP/1.1" 302 0