I'm programming an website to control my Raspberry Pi robot. I'm driving two stepper motor using .py script I call it:
sudo ./GPS.py forward 100 30
Fist argument is way to go, second is how many steps to do, and the last is delay between steps.
The script open location.txt file (it looks like "100/50/18") and take coordinations x=100, y=50 and Alpha=18 degress. Then make a move, calculate new coordination and write it into this file.
Read part at the top of script:
fo = open("location.txt", "r")
data = fo.read()
fo.close()
coordinates= data.split("/")
temp1 = coordinates[0]
temp2 = coordinates[1]
temp3 = coordinates[2]
Alpha= float(temp3)
X = float(temp1)
Y = float(temp2)
Then it make all requested moves and calculations, and then at the end save new X,Y,Alpha back to file:
fo =open("location.txt", "w")
fo.write(str(X)+"/"+str(Y)+"/"+str(Alpha))
fo.close
Allright, this works perfect in Putty, but now I wanted to drive my robot through website, so I've made website to control it.
But now I have a problem. Now I have site like this:
HTTP --> Javascript --> PHP --> .PY script to move robot.
This works, but I have no idea how refresh X,Y,Alpha coordinates from location.txt on my website. I have an idea:
Javascript run .PY and wait it finishes, then JS open .txt and get data and finally set new coordinates to my webpage. But I don't know how to do it. This waiting to .PY finishes is killing me.
Thanks for your help!
Yacked2
PS.
I have apache installed on my Raspberry Pi, and I can donwload my .py script though webpage and I can open .txt file.
The classic web way of doing this would be to poll from the client until you are told of a change.
E.g.
Tweak your file so that it contains a date+time updated.
Implement a PHP script to open the file and serve the contents as a JSON object (with the date updated, X, Y and Alpha as properties)
On load of the page, load the location and store all 4 components.
When you send a move instruction to the server, start to poll for a change - periodically reload the JSON object until you have one with a changed date updated. You can then stop polling.
This updated location should then be stored and used to update your page.
Set a maximum number of times to poll and abort with error if you reach the maximum.
Let's say your main page contains
<div id="locationInfo" />
And you have implemented the PHP script getLocationInfo.php that returns a JSON object like this:
{ date_updated: "13-11-2013 15:45:98",
x_position: 105,
y_position: 120,
alpha: 123 }
In the main page you can have a script using jQuery that will (for example, something along the lines of - but more complex than)
$.get( "getLocationInfo.php", function( data ) {
var html = 'Location: ' + data.x_position + ', ' + data.y_position + ' #' + data.alpha
$( "#locationInfo" ).html( html );
});
All that's really missing from the above is the bit that repeatedly polls and aborts when date_updated has changed.
There is a simple example of polling described here by #johnny-craig: jQuery, simple polling example
In those examples you just need an exit condition for once you have the data you need (recognised by a change in date_updated)
It'll probably work, be pretty simple to implement, but suffers from the amount of duff requests being made from the web page. Though bear in mind the web has worked for a LONG time doing this kind of thing.
Alternatively, you can get all HTML5 about it and read up on websockets. Using websockets you can instigate the update from the server side, rather than the client side. There's less polling required and the response time on the client should be better.
Here's something that'll give you the basics:
http://www.html5rocks.com/en/tutorials/websockets/basics/
Related
Currently I am getting data from a hardware device(charge/load controller) over WiFi, it has an ESP8266 configured as an AccessPoint.
The WiFi is setup to ignore all request from computer, just send its data once per second.
The data is a single string representing about 20 JavaScript Variables...
var xx1="text1";
var xx2="text2"; etc...
I get the data by refreshing the HTML5 page, process with JavaScript & logging to localStorage.
It all works well except I can only refresh about 3 second interval minimum for reliable consistent data-logging. The browser (FireFox) takes a while to complete refresh.
Q. Is there a way I can get every 'data send' using JavaScript without page refresh, this way I can log just the periodic strings I choose from 1 second to xxx second.
I suspect I might need to install some library component to access with my JavaScript ?, i would need to embed this into my HTML file if possible or have it reside in the same folder.
I have been learning JS for about 2 weeks now, getting most from examples & my mistakes.
I'm running an API to retrieve information. I have to call this API via php 5 times, but each time I have to wait 60 seconds.
So the PHP File is running for like 6 minutes and gets timed-out. I tried extending the time limit but that doesn't work so I thought of another solution.
Since I have to run this PHP anyway on CRON job, here is the setup:
-- A.php is run every 10 minutes scheduled in Cron manager. This now runs the header("B.PHP?round=1") command and loads B.PHP
---- B.PHP runs, does what it needs to, now uses javascript setInterval waits 60 seconds and loads (window.location.href ="B.PHP?round=2" again with new parameter (to run 2nd or 3rd etc api token).
THE problem is, it never does load the B.PHP again for second round. I tried doing ajax query xmlhttp all type of JS script to load a page.....NOTHING! It seems to either ignore the javascript completely, or just ignores applying the JS code that loads b.php with new parameter
I really don't want to use the sleep(60) method (well it times out anyway). and I have to use Cron job and I know javascript is the only way to make the script just chill during a wait without causing timedout.
Any solutions at all? Please guys..be gentle I'm a biiit new at this stuff and know nothing about linux/ubunto :(
ps: The B.php I have the entire URL still doesn't work. I HAVE To call a PHP file from the cron manager.
I KNOW javascript is only on client side, but, the JS code is...loading a file on the server .. ? Ugh...I don't know what to do :/
As you said correctly, JavaScript is only client side.
Also, cron jobs usually only request a given URL but do not do anything with that result. And they obviously do not execute javascript.
You need to place the whole logic into your PHP code and use cronjobs to "trigger" your script(s).
Cronjob 1: Running every 10 minutes: start.php
Cronjob 2: Running every 60 Seconds (maybe make it a little more, if your API has a limit of exactly 60 seconds): process.php
Since you are using only PHP, you need to store your variable somewhere on your server. This could either be a database or a file on your filesystem. You can find a more detailed explanation on how to persist a variable here:
PHP store a single variable on the server?. (In my example I use a file as storage)
prosess.php:
// number of times the script should be executed
$maxRounds = 5;
// load $round from your storage
$round = file_get_contents('store.txt');
if ($round < $maxRounds) {
// increase round number for the next call
// you may want to add some checks to determine if the current round was successful before increasing the value
// depending on how log your round takes, it might be wise to add another variable (eg "working") to the store, so that multiple calls to the process file do not overlap
file_put_contents('store.txt', $round + 1);
// execute your code using the $round argument
doRound($round);
}
else {
// already done all rounds
}
start.php
// reset the $round variable
file_put_contents('store.txt', 0);
Keep in mind that this code is not production ready, but it should point you in the right direction :)
I'm currently creating an image hosting script and so far so good. I've used several plugins to create the local uploading process with drag & drog + AJAX which works totally fine. Now I've moved to the part where I need to create the remote uploading process with jQuery AJAX and a PHP script to handle the whole thing.
How it's gonna work
My thought are like this: There is a big box in the middle of the page that accepts the URLs to be remote uploaded. Once valid URL(s) are passed into the text area, they will be immediately sent to the server side script via jQuery AJAX. It's bound with a keyup event.
This is how it looks like: http://i.imgur.com/NhkLKii.png.
The "HERE COME THE URLS" part is already a text area - So that part's already done.
Where I need help
The issue with this whole situation is: Once there are valid URLs pasted into the text area, those must be immediately be converted to some sort of box which also includes an uploading progress. Something that looks like this (copied from the local uploading part): http://i.imgur.com/q7RyDmb.png
It was easy implement the progress indicator for the local uploading, since it was a feature offered by the plugin I've used, but I don't know how to indicate the progress of remote uploading, which is totally being made from scratch.
So this is how I've imagined the logic to flow:
User pastes some URLs into the text area
There is a client-side check to validate the pasted URLs
Validated URLs are send to upload.php on keyup (?)
URLs are being processed
While the upload goes on, we show the users the progress in the knob (?)
PHP script finishes the process and returns back the uploaded URLs
I update the page in the AJAX success callback to display the uploaded files
So, the two process flows marked with (?) are unclear to me - I don't know how to achieve those...
What I have tried
Well, I didn't just come here and ask you to do everything for me, but I've come across a dead end and I don't know how to continue. What I've done so far is collect the URLs from the text area, and if there are multiple URLs separated by a line break (\n), I simply use split to get an array of pasted text and then use another function inside the loop to validate if they are URLs. If there is no line break detected inside the text area value, then I simply check the one line that was provided. On each case, I send the whole text area to the PHP script, because I don't know how to get rid of the invalid URLs in jQuery. I've created a function called debug() in PHP which stores anything into a debug.log file and this is what I'm getting (in one try) when I paste something into the text area:
https://www.google.com/https://www.google.com/
I paste https://www.google.com/ once in the text area, but it gets logged twice in the PHP side and I can't determine why.
This is how my jQuery looks like:
// Remote upload
var char_start = 10;
var index = 0;
var urls = $('.remote-area');
var val_ary = [];
urls.keyup(function(){
if (urls.val().length >= char_start)
{
var has_lbrs = /\r|\n/i.test(urls.val());
val_ary = urls.val().split('\n');
if (has_lbrs)
{
for (var i = 0; i < val_ary.length; i++)
{
if (!validate_url(val_ary[i]))
{
val_ary.splice(i, 1);
continue;
}
}
$.ajax({
type: 'POST',
url: 'upload.php',
data: {
upload_type: 'remote', // Used to determine the upload type in PHP
urls: val_ary, // Sending the whole array here
},
});
}
else
{
if (!validate_url(urls.val()))
{
// Display an error here
return;
}
$.ajax({
type: 'POST',
url: 'upload.php',
data: {
upload_type: 'remote', // Used to determine the upload type in PHP
urls: urls.val(), // Sending what's in the text area
},
});
}
}
});
The questions
So the final questions are:
How do I send my information correctly to the PHP script, only valid URLs and have them kind of "process-able" in my PHP script.
How do I indicate the progress of the upload?
If I was somewhere unclear during my question, please let me know, I'll try to reexplain.
Thank you.
Updates
09/12/2013
I think I have managed to solve the double-sending issue where my AJAX would send the same information twice to the PHP script. What I did was code in a delay anonymous function that sends the text area content to the PHP script after an user stops typing for 2 seconds. Once the user stops typing again, the timer resets and a new AJAX request will be made. So, I'm assuming that this issue has been solved. I'll come back to it if anything strange occurs.
Now I'm still left with the progress indicators part. I'd appreciate your thoughts on that one.
My new code: http://pastebin.com/SaFSLeE9
What you're looking for in terms of communicating progress back and forth is "pushing". That refers to the technique of server sending data to the client, rather than the other way around, which is the standard HTTP way of doing things.
You've got plenty of options available, as described in the explanatory Wikipedia article, though perhaps more relevant to this topic would be Comet. What happens is you trigger and $.ajax call just like the one you have now, but you set a very long timeout. That essentially gives the server a "channel" to send data back to the page whenever it's available.
So what you need is a .php on the server that is capable of handling long polling and will send data back to the page as the upload progress changes (probably in array form for multiple uploads). This article should get you started with some jQuery code. Just remember that this request doesn't go to upload.php. This request goes to a different script that deals solely with upload percentages and only returns data when that is available, it doesn't return immediately as all others scripts - the Ajax will happily wait for the data.
Also, don't separate your code like that with has_lbrs. One line or many are not distinct cases, one line is just an edge case of many lines. You're duplicating the code unnecessarily. What does the else case do that would break in the general case? Further, the "error handling" in the else case is misleading. The only error reporting you do is if there is only one line and it's wrong. What if you have two lines and they're both wrong? Your code will happily send an empty array to upload.php.
This is why I think you shouldn't separate your code like that, because then you'll split logic and not even notice it.
In my opinoin, the best way is to call your cURL script with ajax and use it to upload your files on remote server. You need ajax.js, curl.php, index.php (whatever name you want) on your app server. And image.php, class.image.php (whatever name you want) on your remote server.
Steps that I did for my app
1) I am going to upload an image from my index.php file. It will call curl.php file using ajax.js and the cURL file will check file's extension and all (for your app's security, make sure what you want to allow users to upload).
2) Now the curl file will upload the file to your pre defined temporary folder with the default file name.
3) Now if move_uploaded_file function (which I used in my script) run successfully, you can call your cURL function to send your data as post on your remote server, where image file will receive posts and will process further. You can keep your class in image.php or you can create two PHP files on your remote server, as you want.
4) Now in your class file, you should check file once again that it is image file (and whatever you want to allow) or not for better security. If file is good, process to rename it and add file into folder if you want to.
5) Add file's new name and folder name into your database by using remote database connection. So, cURL will show you result on the same page.
Now, why cURL? I prefer cURL because, you can add secret key or API for your communication to make it more secure, with if else conditions. Your remote server file which is going to receive all posts, will check if API == 'yourKey' then will process other wise it wont process and nobody will be able to send images on your server with bots and all.
I don't know that my answer is going to help you or not, probably my method is lengthy or not good for your app, but try to Google about cURL and you will understand what I am trying to say. Hope you like it and understood it. If any doubt, you can ask me any time.
I have some images in a folder save automatically from a web camera naming by current date_time. Now i just want to load each image after some seconds(let say 4 sec) which matches to my server current date_time.
Using java script..
I can get server time using PHP
**
I more simple words, Is there any
jquery plugin that load images from
folder with respect to image name
where the name is based on current
date_time?
**
Thanks
You can't know the exact server time from from javascript(unless your server and your computer are the same one). Getting time from server using any of the server languages to synchronize time between client and server will not work because of the response time of server. How about another idea. Write a page on server that will return list of last images(or last image), query it with javascript and show the last image(s).
I need to do as much as possible on the client side. In more details, I would like to use JavaScript to code an interface (which displays information to the user and which accepts and processes response from the user). I would like to use the web serve just to take a date file from there and then to send a modified data file back. In this respect I would like to know if the following is possible in JavaScript:
Can JavaScript read content of a external web page? In other words, on my local machine I run JavaScript which reads content of a given web page.
Can JavaScript process values filled in a HTML form? In other words, I use HTML and JavaScript to generate an HTML form. User is supposed to fill in the form and press a "Submit" button. Then data should be sent to the original HTML file (not to a web server). Then this data should be processed by JavaScript.
In the very end JavaScript will generate a local data-file and I want to send this file to a PHP web server. Can I do it with JavaScript?
Can I initiate an execution of a local program from JavaScript. To be more specific, the local program is written in Python.
I will appreciate any comments and answers.
It could technically, but can't in reality due to the same origin policy. This applies to both reading and writing external content. The best you can do is load an iframe with a different domain's page in it - but you can't access it programmatically. You can work around this in IE, see Andy E's answer.
Yes for the first part, mmmm not really for the second part - you can submit a form to a HTML page and read GET arguments using Javascript, but it's very limited (recommended maximum size of data around 1024 bytes). You should probably have all the intelligence on one page.
You can generate a file locally for the user to download using Downloadify. Generating a file and uploading it to a server won't be possible without user interaction. Generating data and sending it to a server as POST data should be possible, though.
This is very, very difficult. Due to security restrictions, in most browsers, it's mostly not possible without installing an extension or similar. Your best bet might be Internet Explorer's proprietary scripting languages (WScript, VBScript) in conjuction with the "security zones" model but I doubt whether the execution of local files is possible even there nowadays.
Using Internet Explorer with a local file, you can do some of what you're trying to do:
It's true that pages are limited by the same origin policy (see Pekka's link). But this can be worked around in IE using the WinHttpRequest COM interface.
As Pekka mentioned, the best you can manage is GET requests (using window.location.search). POST request variables are completely unobtainable.
You can use the COM interface for FileSystemObject to read & write local text files.
You can use the WScript.Shell interface's Exec method to execute a local program.
So just about everything you asked is attainable, if you're willing to use Internet Explorer. The COM interfaces will require explicit permission to run (a la the yellow alert bar that appears). You could also look at creating a Windows Desktop Gadget (Vista or Win 7) or a HTML Application (HTA) to achieve your goal.
Failing all that, turn your computer into a real server using XAMPP and write your pages in PHP.
see i got what you want to do
best things is do following
choose a javascript library (eg:jquery,dojo,yui etc), i use jquery.this will decrease some of your load
inspite of saving forms data in in a local file, store them in local variables process them and send them to server (for further processing like adding/updating database etc) using XMLHttp request, and when webservice returns data process that data and update dom.
i am showing you a sample
--this is dom
Name:<input type='text' id='name' />
<a href='javascript:void(0)' onClick='submit()'>Submit Form</a>
<br>
<div id='target'></div>
--this is js
function submit()
{
var _name=$('#name').val();// collect text box's data
//now validate it or do any thing you want
callWebservice(_name,_suc,_err);
//above call service fn has to be created by you where you send this data
//this function automatically do xmlHttprequest etc for you
//you have to create it ur self
}
//call this fn when data is sucessfully returned from server
function _suc(data)
{
//webservice has returned data sucessefully
//data= data from server, may be in this case= "Hello user Name"; (name = filled in input box);
//update this data in target div(manipulate dom with new data);
$('#target').html(data);
}
function _err()
{
//call this fn when error occurs on server
}
// in reality most of the work is done using json. i have shown u the basic idea of how to use js to manipulate dom and call servcies and do rest things. this way we avoid page-reloads and new data is visible to viewer
I would answer saying there's a lot you can do, but then in the comment to the OP, you say "I would like to program a group game."
And so, my answer becomes only do on the client side what you are able and willing to double check on the server side. Never Trust the Client!
And I do not want to do my job twice.
If you are going to do things on the client side, you will have to do it twice, or else be subject to rampant cheating.
We had the same question when we started our project.In the end we moved everything we could on the JS side. Here's our stack:
The backend receives and send JSON data exclusively.We use Erlang, but Python would be the same. It handles the authentication/security and the storage.
The frontend, is in HTML+CSS for visual elements and JS for the logic.A JS template engine converts the JSON into HTML. We've built PURE, but there are plenty of others available. MVC can be an overkill on the browser side, but IMO using a template engine is the least separation you can do.
The response time is amazing. Once the page and the JS/CSS are loaded(fresh or from the cache), only the data cross the network for each request.