Developing webpage with Webiopi on a raspberry Pi - javascript

I'm a noob and new to web-development and i'm overwhelmed with the multitude of languages. I got the basic understanding on whats going on but I still don't know where I am getting stuck.
I have a DS18B20 connected to my Raspberry Pi and I am able to fetch the temperature in the terminal. I am running the WebIOPi successfully as well and able to see the temperature in its default web page under Devices. So I was hoping to create my own web page that would do the exact same thing with other options for future. I got a hold of some tutorials on WebIOPi and i got 4 files. An HTML file, the JavaScript file, the CSS file and a Python file. In my understanding the HTML file contains the logic and links to other things like clickable buttons and backgrounds etc. The CSS file contains the background and maybe text, the JavaScript file contains animation and buttons? Here I get confused. Last but not least the Python file is what runs the code that contains sensor model and libraries. I configured the Webiopi config file with my sensors serial number as mentioned here: http://webiopi.trouch.com/OneWireTemp.html. I am loosely trying to follow this tutorial where I got most parts of the code: http://webiopi.trouch.com/Tutorial_Devices.html.
Now when I log into the webpage from my browser the background is displayed correctly, but nothing else. There is no box or button showing the temperature. Pictures are attached. I was hoping for a button like attached in the picture.
Any guidance or help would be appreciated!
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>WebIOPi | UNB Temperature</title>
<script type="text/javascript" src="/webiopi.js"></script>
<script type="text/javascript">
<script type="text/javascript" src="/scripts/bacon.js"></script>
<link rel="stylesheet" type="text/css" href="/styles/bacon.css">
<script type="text/javascript">
// declare few global variables
var tmp;
webiopi().ready(init);
// defines function passed to webiopi().ready()
function init() {
// setup helpers to remotely control devices
tmp = new Temperature("tmp");
// automatically refresh UI each seconds
setInterval(updateUI, 1000);
}
// function called through setInterval
function updateUI() {
// call Temperature.getCelsius REST API
// result is asynchronously displayed using the callback
tmp.getCelsius(temperatureCallback);
}
// callback function used to display the temperature
function temperatureCallback(sensorName, data) {
// jQuery functions
$("#bt_heater").text(data + "°C");
}
bacon.js
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
<div align="center">
<button id="bt_mode" onclick="toggleMode()"/><br>
<button id="bt_heater" onclick="toggleHeater()"/>
</div>
</body>
</html>
bacon.css
body {
background-color:#000000;
background-image:url('/img/wall.jpg');
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center;
background-size: cover;
}
script.py
import webiopi
GPIO = webiopi.GPIO
AUTO = True
def loop():
if (AUTO):
tmpwebiopi.deviceInstance("tmp")
celsius = tmp.getCelsius()
print ("Temperature: %f" % celsius)
webiopi.sleep(1)

I do not know about your specific case, but to me it seems quite obvious that there is nothing to see here. You have been mixing up things quite a bit.
To clarify things
The HTML contains the logical structure of your website
the CSS contains the look and feel (design)
the JavaScript and the Python files contain (UI)-Logic
This is quite coarse and might deviate, but it should suffice as a start and should apply here.
The obvious errors in your code
The HTML file is incomplete. It should not stop in the middle of the script-section, there should be markup defining the buttons you want to display. Currently there is none, hence there is nothing to see (but the HTMl-body, which is added automatically - and since the background color is defined for the body it is displayed)
The JavaScript file does not actually contain JavaScript, but HTML, which is most likely not correct
At the moment all your JavaScript is located within the script-section of your HTML file. This is fine as long as your are just trying to work it out, but renders a separate JS-file useless at the moment.
All in all your HTML file should look more like this.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>WebIOPi | UNB Temperature</title>
<script type="text/javascript" src="/webiopi.js"></script>
<script type="text/javascript">
<script type="text/javascript" src="/scripts/bacon.js"></script>
<link rel="stylesheet" type="text/css" href="/styles/bacon.css">
<script type="text/javascript">
// declare few global variables
var tmp;
webiopi().ready(init);
// defines function passed to webiopi().ready()
function init() {
// setup helpers to remotely control devices
tmp = new Temperature("tmp");
// automatically refresh UI each seconds
setInterval(updateUI, 1000);
}
// function called through setInterval
function updateUI() {
// call Temperature.getCelsius REST API
// result is asynchronously displayed using the callback
tmp.getCelsius(temperatureCallback);
}
// callback function used to display the temperature
function temperatureCallback(sensorName, data) {
// jQuery functions
$("#bt_heater").text(data + "°C");
}
</script></head>
<body>
<div align="center">
<button id="bt_mode" onclick="toggleMode()"/><br>
<button id="bt_heater" onclick="toggleHeater()"/>
</div>
</body>
</html>

My Current code that is WORKING but with minor style problems.
.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>WebIOPi | UNB Temperature</title>
<script type="text/javascript" src="/webiopi.js"></script>
<link rel="stylesheet" type="text/css" href="/styles/bacon.css">
<script type="text/javascript">
// declare few global variables
var tmp;
webiopi().ready(init);
// defines function passed to webiopi().ready()
function init() {
// setup helpers to remotely control devices
tmp = new Temperature("tmp");
// automatically refresh UI each seconds
setInterval(updateUI, 1000);
}
// function called through setInterval
function updateUI() {
// call Temperature.getCelsius REST API
// result is asynchronously displayed using the callback
tmp.getCelsius(temperatureCallback);
}
// callback function used to display the temperature
function temperatureCallback(sensorName, data) {
// jQuery functions
$("#temp_disp").text(data + "°C");
}
</script></head>
<body>
<div align="center">
<button id="temp_disp" />
</div>
</body>
</html>
.CSS
body {
background-color:#000000;
background-image:url('/img/wall.jpg');
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center;
background-size: cover;
}
Current view of the webpage!

Related

How to use constants across files? [duplicate]

A bunch of my JavaScript code is in an external file called helpers.js. Inside the HTML that calls this JavaScript code I find myself in need of knowing if a certain function from helpers.js has been called.
I have attempted to create a global variable by defining:
var myFunctionTag = true;
In global scope both in my HTML code and in helpers.js.
Heres what my html code looks like:
<html>
...
<script type='text/javascript' src='js/helpers.js'></script>
...
<script>
var myFunctionTag = false;
...
//I try to use myFunctionTag here but it is always false, even though it has been se t to 'true' in helpers.js
</script>
Is what I am trying to do even feasible?
You need to declare the variable before you include the helpers.js file. Simply create a script tag above the include for helpers.js and define it there.
<script type='text/javascript' >
var myFunctionTag = false;
</script>
<script type='text/javascript' src='js/helpers.js'></script>
...
<script type='text/javascript' >
// rest of your code, which may depend on helpers.js
</script>
The variable can be declared in the .js file and simply referenced in the HTML file.
My version of helpers.js:
var myFunctionWasCalled = false;
function doFoo()
{
if (!myFunctionWasCalled) {
alert("doFoo called for the very first time!");
myFunctionWasCalled = true;
}
else {
alert("doFoo called again");
}
}
And a page to test it:
<html>
<head>
<title>Test Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<script type="text/javascript" src="helpers.js"></script>
</head>
<body>
<p>myFunctionWasCalled is
<script type="text/javascript">document.write(myFunctionWasCalled);</script>
</p>
<script type="text/javascript">doFoo();</script>
<p>Some stuff in between</p>
<script type="text/javascript">doFoo();</script>
<p>myFunctionWasCalled is
<script type="text/javascript">document.write(myFunctionWasCalled);</script>
</p>
</body>
</html>
You'll see the test alert() will display two different things, and the value written to the page will be different the second time.
OK, guys, here's my little test too. I had a similar problem, so I decided to test out 3 situations:
One HTML file, one external JS file... does it work at all - can functions communicate via a global var?
Two HTML files, one external JS file, one browser, two tabs: will they interfere via the global var?
One HTML file, open by 2 browsers, will it work and will they interfere?
All the results were as expected.
It works. Functions f1() and f2() communicate via global var (var is in the external JS file, not in HTML file).
They do not interfere. Apparently distinct copies of JS file have been made for each browser tab, each HTML page.
All works independently, as expected.
Instead of browsing tutorials, I found it easier to try it out, so I did. My conclusion: whenever you include an external JS file in your HTML page, the contents of the external JS gets "copy/pasted" into your HTML page before the page is rendered. Or into your PHP page if you will. Please correct me if I'm wrong here. Thanx.
My example files follow:
EXTERNAL JS:
var global = 0;
function f1()
{
alert('fired: f1');
global = 1;
alert('global changed to 1');
}
function f2()
{
alert('fired f2');
alert('value of global: '+global);
}
HTML 1:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="external.js"></script>
<title>External JS Globals - index.php</title>
</head>
<body>
<button type="button" id="button1" onclick="f1();"> fire f1 </button>
<br />
<button type="button" id="button2" onclick="f2();"> fire f2 </button>
<br />
</body>
</html>
HTML 2
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="external.js"></script>
<title>External JS Globals - index2.php</title>
</head>
<body>
<button type="button" id="button1" onclick="f1();"> fire f1 </button>
<br />
<button type="button" id="button2" onclick="f2();"> fire f2 </button>
<br />
</body>
</html>
Hi to pass values from one js file to another js file we can use Local storage concept
<body>
<script src="two.js"></script>
<script src="three.js"></script>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
</body>
Two.js file
function myFunction() {
var test =localStorage.name;
alert(test);
}
Three.js File
localStorage.name = 1;
//Javascript file 1
localStorage.setItem('Data',10);
//Javascript file 2
var number=localStorage.getItem('Data');
Don't forget to link your JS files in html :)
If you're using node:
Create file to declare value, say it's called values.js:
export let someValues = {
value1: 0
}
Then just import it as needed at the top of each file it's used in (e.g., file.js):
import { someValues } from './values'
console.log(someValues);
I think you should be using "local storage" rather than global variables.
If you are concerned that "local storage" may not be supported in very old browsers, consider using an existing plug-in which checks the availability of "local storage" and uses other methods if it isn't available.
I used http://www.jstorage.info/ and I'm happy with it so far.
You can make a json object like:
globalVariable={example_attribute:"SomeValue"};
in fileA.js
And access it from fileB.js like:
globalVariable.example_attribute
You can set
window['yourVariableName'] = yourVariable;
and it will make that variable global for all the files.

Calling a javascript function in a document created with document.write

I have a web page with a button. The click code is:
var html = ...html string containing visual and script elements...
var view = window.open();
view.document.write(html);
view.init(<parameters>); // see next code block
the html content is:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
html, body {
height: 100%;
margin: 0;
}
</style>
</head>
<body>
<div id="id1"></div>
<script>
function init(<parameters>) {
...work...
}
</script>
</body>
</html>
The problem is with the init function call in chrome: all good if I am in IE, but in chrome I get "init function not defined" exception.
How should I do to get this working in all browsers? Of course I am looking for a solution that doesn't require a server round trip.
IM a noob so idk if this is exaclty true but i have read that ie allows you to do alot more then chrome or firefox. It might be one of those example where ie will let you do something.
using document.write does in fact work when it comes to create the page I want. Problem is when I want to call a function defined in a javascript block inside that page. Different browsers give different results so I guess this is a matter not completely standardized yet. There are posts in the internet about this, but I couldn't find a clear and common answer.
I then solved my impasse with a workaround. The initial markup contains now placeholders for the parameters:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
html, body {
height: 100%;
margin: 0;
}
</style>
</head>
<body>
<div id="id1"></div>
<script>
(init = function () {
var parameter1 = ${{placeholder1}}
var parameter2 = ${{placeholder2}}
...
...work...
})();
</script>
</body>
</html>
The creating code, then, replaces the placeholders with actual values:
var html = ...html string containing placeholders...
html = html.replace("${{placeholder1}}", actual1);
html = html.replace("${{placeholder2}}", actual2);
...
var view = window.open();
view.document.write(html);
Now the init function is called in the same page context, and this works in Chrome as well.
It is not possible to write to a new window if its not on the same domain. What I suggest is that you can open an iframe an work inside that.
How to write to iframe
How to write to page on same domain

JS acees variable another HTML

I'm actually trying to access variable of other HTML file using JS.
I mean, I have a file (file1.htm) that open dialog box and I would like to send information of the file selected to another file (file2.htm) and modify a value in this file. I found solution but only for JS files, and not HTML :/
I had already done it with 2 files but file1a was the parent of the other, so I used
parent.framWin = window; in file2a and
framWin.divX=document.getElementById("one").offsetWidth; for example in file1a to modify the variable divX in file2a (I'm pretty sure this is not the best solution, but it works ;) ). Here, in this case, file1 and file2 are not parent, and they are just located in the same folder.
I tried <script type="text/javascript" src="file1.htm"> to access var but it doesn't seem to work.
Do you have any idea how I can accomplish this?
Thanks a lot!
(Here's my code :
file1.htm :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>SiteMap</title>
<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8" />
<style type="text/css">
</style>
<script type="text/javascript">
<!--
function OK(e){
var name = document.getElementById("dialog").value;
//Here I would like to do something like File2.NameSpace1 = name;
//And File2.modifyMyName(); // But here, it's another question, to use JS script in another file ;)
}
//-->
</script>
</head>
<body >
<form action='' method='POST' enctype='multipart/form-data'>
<input type='file' name='userFile' onchange="OK()" id="dialog">
</form>
</body>
</html>
and file2.htm:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>SiteMap</title>
<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8" />
<script type="text/javascript">
<!--
var NameSpace1;
function modifyMyName(){
document.GetElementById("first").src = NameSpace1;
}
//-->
</script>
</head>
<body>
<div>
<img src ="" id="first" />
</div>
</body>
I know this won't work properly because there are some errors here in the syntax. But the problem is visible ;)
Thanks again :)
You can't simply modify the content of file on the server using client side code.
The examples you've cited just change the data that is loaded into the browser at the time the code runs while leaving the data on the server untouched.
There are two approaches you can take to this:
Store the changes in the browser.
In page one, use localstorage to record information about the change you want to make. (You'd probably want to convert the image into a data: scheme URL to achieve this given your example code).
In page two, have some more JS that reads from localstorage and uses that information to make the change to itself after it loads.
Send the changes to the server.
Submit a form (so you don't need to use client side code at all) or use Ajax to send information about the change to the server.
Have server side code read it and then store it in a session (if you want the change to be on a per-user basis) or somewhere more permanent (in a database if you are sensible but you could modify the file directly) (if you want it to be shared between users).
Page two would then be a server side program that would read that data and use it to generate the page.
You can use localStorage to perform this operation.
function OK(e){
var name = document.getElementById("dialog").value;
window.localStorage.setItem('dialogValue', "Name");
}
And In your file2.html
function modifyMyName(){
var NameSpace1 = window.localStorage.getItem('dialogValue');
document.GetElementById("first").src = NameSpace1;
}

JavaScript object properties are "sometimes" undefined

I am very confused.
I created the following script which is located at http://tapmeister.com/test/dom.html. For some unknown reason, tinymce.editors.ta1 and tinymce.editors[0] show up as undefined, and attempting to use a method under them results in an error. But when I inspect tinymce or tinymce.editors using FireBug, I see them in the DOM.
So, I create a jsfiddle http://jsfiddle.net/JWyWM/ to show the people on stackoverflow. But when I test it out, tinymce.editors.ta1 and tinymce.editors[0] are no longer undefined, and the methods work without error.
What is going on??? Maybe something to do with public/protected/private properties? How do I access methods such as tinymce.editors.ta1.hide()? Thank you!!!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />
<title>Testing</title>
<script src="http://tinymce.cachefly.net/4.0/tinymce.min.js"></script>
<script type="text/javascript">
tinymce.init({selector: "textarea#ta1"});
tinymce.init({selector: "textarea#ta2"});
console.log(tinymce);
console.log(tinymce.editors);
console.log(tinymce.editors.ta1);
console.log(tinymce.editors[0]);
//tinymce.editors.ta1.hide();
//alert('pause');
//tinymce.editors.ta1.show();
</script>
</head>
<body>
<form>
<textarea id="ta1"></textarea>
<textarea id="ta2"></textarea>
</form>
</body>
</html>
TinyMCE doesn't do all of the setup work immediately when you call init. It provides a callback, setup, to tell you when the work is done.
So if you provide a setup callback, you can interact with the editor instance then.
Here's an example (I've also moved your scripts to the end, which is best practice regardless):
Live Example | Live Source
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1" />
<title>Testing</title>
</head>
<body>
<form>
<textarea id="ta1"></textarea>
<textarea id="ta2"></textarea>
</form>
<script src="http://tinymce.cachefly.net/4.0/tinymce.min.js"></script>
<script type="text/javascript">
tinymce.init({
selector: "#ta1, #ta2",
setup: function(e) {
console.log("Editor " + e.id + " is ready");
}
});
</script>
</body>
</html>
Now, if you want to actually access the editor instance, bizarrely TinyMCE doesn't add it to tinymce.editors until after calling the setup function. But if you throw in a brief yield, you're all set. Here's the above with a changed setup function:
Live Copy | Live Source
setup: function(e) {
// Bizarrely, TinyMCE calls `setup` *before* adding
// the relevant editor to `tinymce.editors`,
// so we have to yield briefly
console.log("Editor " + e.id + " is ready");
if (e.id === "ta2") {
console.log("It's ta2, I'll hide it in a moment.");
setTimeout(function() {
tinymce.editors[e.id].hide();
}, 0);
}
}
So why did it work on jsFiddle? Well, jsFiddle has a truly brain dead surprising default setting, which is to put all of your script in a window#load callback function. window#load happens very late in the load process, after all external resources have been loaded. (You can see that in the jsFiddle UI, it's the second drop-down list on the left.) So apparently TinyMCE was completely ready at that point, where it isn't earlier in the cycle.
Side note: 99.9% of the time, there is absolutely no point in supplying a tag name with an id selector, e.g. textarea#ta1. id values are unique, so you don't have to qualify them unless you explicitly want to avoid matching an element that may sometimes have one tag name, or other times have another, which is a pretty unusual use case.
There's a large chance that your script is running before tinyMCE has actually loaded. It might be the case that it loads faster from your test site so that is why it works.
Use as a quick check.

Adding divs to the HTML body using Lift

I have been playing around with Scala/Lift/Comet/Ajax etc. recently. I came across a problem which boils down to this:
Summary
I want to update a specific div (by id) when a certain event occurs. If the div does not exist yet, it must be created and appended to the HTML body.
Currently I cannot get this to work when using the Lift framework.
Source File
LIFT_PROJECT/src/main/webapp/static/mouseViewTest.html:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
// <![CDATA[
$(document).ready(function() {
updateOrCreateMouseDiv('123', 'coords')
});
function updateOrCreateMouseDiv(uniqueId, coords) {
if ($('#mouse_'+uniqueId).length == 0) {
$('body').append('<div id=' + uniqueId + '>' + coords + '</div>');
}
$('#mouse_'+uniqueId).html(coords)
}
// ]]>
</script>
</head>
<body></body>
</html>
The Error
If I open the above file directly in a browser (file:///LIFT_PROJECT/src/main/webapp/static/mouseViewTest.html) it works i.e. a new div is created.
But if I run it through Lift/Jetty (http://localhost:8080/static/mouseViewTest) I get the following JavaScript error:
Chrome:
Uncaught Error: NO_MODIFICATION_ALLOWED_ERR: DOM Exception 7
Firefox (Firebug):
An invalid or illegal string was specified" code: "12
Comparing the Sources in Browser
When comparing the page sources in the browser, I can see only one difference, namely: Lift adds the following JavaScript just before the closing </body> tag:
<script type="text/javascript" src="/ajax_request/liftAjax.js"></script>
<script type="text/javascript">
// <![CDATA[
var lift_page = "F320717045475W3A";
// ]]>
</script>
Questions
Does anyone have an idea why this happens?
If I would want to move the JavaScript code into the Scala file (using Lift's JavaScript and jQuery support), what would the code look like?
Please note: When I used Jq("body") ~> JqAppend() to create new divs, it worked. I just didn't know how to check whether the div id already existed. Thats why I moved the code into the template, planning on using Lift's Call function to execute the JS function. And thats when these problems started...
Thanks!
I recently ran into a similar problem and, from what I've gathered, the problem is because the page when served by lift is served as XHTML and there are some issues when writing to the DOM if the page is XHTML vs. HTML. I don't know whether this is a bug with jQuery or Safari or if it's just something that's not possible in XHTML, but a quick way to fix it is to modify your Boot.scala to tell Lift to not use XHTML as the mime type with this line:
LiftRules.useXhtmlMimeType = false

Categories

Resources