Simple read gpio status to html text

4,250 views
Skip to first unread message

Caroline Blue

unread,
Jan 26, 2014, 5:46:18 PM1/26/14
to web...@googlegroups.com
Hey everyone, I am new to the Raspberry Pi/webiopi community, and I have spent countless hours trying to simply read an LED status to display the words "On" or "Off" on the index.html page.

I can't seem to be able to use any macro correctly. I found many examples using sensors and buttons that seem overly complex for this, but I just want the output in text. I am pretty sure I had something wrong with the callback function in index.html.

Here is the basic macro that I have in my Script.py:

@webiopi.macro
def getLedStatus():
    p0 = int(gpio17.digitalRead())
    print (p0)
    return ("%s % (p0))

I tried calling the macro in my index.html, and countless other methods including using a button:
webiopi().callMacro("getLedStatus")


I find it easier to do in other languages and call the function, ie: document.print(getLedStatus()) or print(gpio17.digitalread()). I have a python script that uses a switch to turn the LED and returns whether the LED was On or Off correctly, and I just need help implementing it into webiopi.

Here is my python script:

import sys
import webiopi
import RPi.GPIO as GPIO

Switch = 27
Led_light = 17

GPIO.setmode(GPIO.BCM)
GPIO.setup(Door_pin, GPIO.IN)
GPIO.setup(Led_light, GPIO.OUT)

while True:
    input_value = GPIO.input(Switch)
    if input_value:
      print('On')
      GPIO.output(Led_light, True)
    else:
      print('Off')
      GPIO.output(Led_light, False)
    time.sleep(.01)


I would greatly appreciate any assistance and direction!! I've been wanting to give up on webiopi and go back to just good old apache just from the different API and how I have to implement things. Granted it is a matter of not being familiar with it, but hopefully someone here can steer me in the right direction.




Eric PTAK

unread,
Jan 26, 2014, 5:58:22 PM1/26/14
to web...@googlegroups.com
Did you try the tutorials I wrote on the wiki ?
You will found exactly what you need.

You don't need RPi.GPI, neither while True.
Use webiopi GPIO driver and loop feature instead.

in script.py :
...
GPIO = webiopi.GPIO

def loop():
    input_value = GPIO.digitalRead(Switch)

    if input_value:
      print('On')
      GPIO.digitaWrite(Led_light, True)
    else:
      print('Off')
      GPIO.digitaWrite(Led_light, False)
    time.sleep(.01)

@webiopi.macro
def getLedStatus():
    p0 = int(GPIO.digitalRead(17))
    print (p0)
    return ("%s % (p0))

In Javascript :
webiopi().callMacro("getLedStatus", [], myCallback);
function myCallback(macroName, args, data) {
if (data == "1") {
$("#mybuttonid").text("ON");
}
else {
$("#mybuttonid").text("OFF");
}



--
You received this message because you are subscribed to the Google Groups "WebIOPi" group.
To unsubscribe from this group and stop receiving emails from it, send an email to webiopi+u...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Caroline Blue

unread,
Jan 26, 2014, 9:49:17 PM1/26/14
to web...@googlegroups.com
Thanks for the fast response Trouch!

I did see your tutorial, and looks like where I was failing was the callback function because I didn't want input and was trying to figure how to use text. Your example helped a lot, and makes more sense now, however, I put the code exactly as your example (after correcting some syntax issues and such that I had) and it makes my button disappear.

My Script.py file looks good, looks like my html file is where I am doing something wrong. Do I need to put the macro call function before the webiopi().refreshGPIO(true); or after?

I modified some things, what I have is a switch on a door (gpio27) which I'd like the output to display on the page on whether it is open or closed and an LED on gpio17 to manually turn on a light. Eventually I will add another LED that turns on when the door is open.

Here is what I have, it still doesn't show anything, the page is blank and my button is gone:

Put this all into a new Script.py:

import sys
import webiopi

GPIO = webiopi.GPIO


Switch = 27
Led_light = 17

GPIO.setup(Switch, GPIO.IN)
GPIO.setup(Led_light, GPIO.OUT)



def loop():
    input_value = GPIO.digitalRead(Switch)

    if input_value:
      print('On')
      GPIO.digitalWrite(Led_light, True)
    else:
      print('Off')
      GPIO.digitalWrite(Led_light, False)
    time.sleep(.01)


@webiopi.macro
def getLSwitchStatus():
    p0 = int(GPIO.digitalRead(27))

    print (p0)
    return ("%s" % (p0))


// The javascript part of my index.html:

<script type="text/javascript" src="/webiopi.js"></script>
<script type="text/javascript">

webiopi().ready(function()) {
webiopi().setFunction(17, "out");
webiopi().setFunction(27, "in");

 var content, button;
 content = $("#content");

    //Light Button
    button = webiopi().createGPIOButton(17,"LIGHT");
    content.append(button); // append button to content div


webiopi().callMacro("getSwitchStatus", [], SwitchStatus);
function SwitchStatus(macroName, args, data) {

if (data == "1") {
$("#text_on").text("Open");
}
else {
$("#text_off").text("Closed");
};
   
webiopi().refreshGPIO(true);
});



//My CSS:

#text_on{
    font: 18px/100% Arial, Helvetica, sans-serif;
    color: Red
}

#text_off{
    font: 18px/100% Arial, Helvetica, sans-serif;
    color: Green
Message has been deleted

Caroline Blue

unread,
Jan 27, 2014, 8:54:16 PM1/27/14
to web...@googlegroups.com
I have tried so many things now for days and still cannot get any output to the webpage on the switch status.

I had forgot to import time in my script, so I made some progress. I have the script running in the background correct and an LED correctly turns on when the door is opened. I just can't get the status to report on the webpage. I read some things about using the AJAX GET HTTP call, not sure how to implement that either.

I feel worse than a noob here. Could someone please tell me what i'm doing wrong in my function, please?? I would be so happy to finally get some output to my page.



Here is my script.py (I tried two different macros):


def loop():
    input_value = GPIO.digitalRead(Door)
    if input_value:
      print('Open')
      GPIO.digitalWrite(Led_light, True)
    else:
      print('Closed')
      GPIO.digitalWrite(Led_light, False)
    time.sleep(.01)



@webiopi.macro
def getDoorStatus():
    p0 = int(GPIO.digitalRead(27))
    print (p0)
    return ("%s" % (p0))

@webiopi.macro
def DoorState():
    OC = GPIO.digitalRead(Door)
    if OC:
      print('Open')
      return ("%s" % (OC))
      GPIO.digitalWrite(Led_light, True)
    else:
      print('Closed')
      return ("%s" % (OC))
      GPIO.digitalWrite(Led_light, False)
    time.sleep(.01)

Below are all of the functions I have tried:

doorstate=webiopi().digitalRead(27, gpioReadCallback);

function gpioReadCallback(27, value) {
  print("server returned " + value + " for gpio " + gpio);
}
    
webiopi().refreshGPIO(true);
});



function callMacro_getGarageStatus(){
webiopi().toggleValue(27);
callMacro_getGarageStatus()}

setInterval ("callMacro_getDoorStatus()", 5000);{
}
function callMacro_getDoorStatus(){
var args = [0]
webiopi().callMacro("getGarageStatus", args, macro_getGarageStatus_Callback);}
function macro_getGarageStatus_Callback(macro, args, data){
g0 = data.split(" ")[0];
if (g0==1){
print("ON");
     }
else{
print("OFF");
}

       }




function callMacro() {
                var args = [] // no args
                // call myMacroWithArgs(arg)
                webiopi().callMacro("getDoorStatus", args, macroCallback);
        }
        
        function macroCallback(getDoorStatus, args, data) {
                print(macro + " returned with " + data);
        }



setInterval ("callMacro_getDoorStatus()", 5000);{
}
function callMacro_getDoorStatus(){
var args = [0]
webiopi().callMacro("getDoorStatus", args, macro_getDoorStatus_Callback);}
function macro_getDoorStatus_Callback(macro, args, data){
g0 = data.split(" ")[0];
if (g0==1){
webiopi().setClass("text_on", "Open");
webiopi().setLabel("text_on", "GPIO 27 Open");}
else{
webiopi().setClass("text_off", "Closed");
webiopi().setLabel("text_off", "GPIO 27 Closed");}

}


webiopi().callMacro("getDoorStatus", [], myCallback);
function myCallback(getDoorStatus, args, data) {

Toshi Bass

unread,
Jan 28, 2014, 9:23:45 AM1/28/14
to web...@googlegroups.com
HI Caroline

You look like your almost there, however first pointer you should run webiopi in the background only when everything is running correctly, before that you should run webiopi in debug mode which will help you find any bugs in your python code so ssh into the pi and at the $ prompt type     sudo webiopi -d -c /etc/webiopi/config   also in the script.py file I find putting in some temporary print statements at critical points will help you see whats happening on the debug screen, similarly if you are using chrome as your web browser go to customize and control (icon top right like 3 bars) - Tools - Javascript console that will help you debug your javascript code

Your script.py should looks something like this:

import sys
import webiopi

GPIO = webiopi.GPIO

Switch = 27
Led_light = 17

# Called by WebIOPi at script loading
def setup():
    webiopi.debug("Setup")
    # Setup GPIOs
    GPIO.setFunction(Switch, GPIO.IN)
    GPIO.setFunction(Led_light, GPIO.OUT)


def loop():
    input_value = GPIO.digitalRead(Switch)
    if input_value == 1:
        print('On')
        GPIO.digitalWrite(Led_light, True)
    else:
        print('Off')
        GPIO.digitalWrite(Led_light, False)

    # you could replace above with:
    # value = Not GPIO.digitalRead(Switch)
    #GPIO.digitalWrite(Led_light, value)

    time.sleep(1)

# Called by WebIOPi at script loading
def destroy():
    webiopi.debug("Basic script - Setup")
    # Setup GPIOs
    GPIO.setFunction(Switch, GPIO.IN)
    GPIO.setFunction(Led_light, GPIO.IN)

@webiopi.macro
def get_SwitchStatus():
    p0 = int(GPIO.digitalRead(Switch)  # you could replace (Switch) with (Led_Light) to check state of output instead of input.
    print (p0)
    return ("%s" % (p0))

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">
<meta name="viewport" content = "height = device-height, width = 420, user-scalable = no" /> 
<title>WebIOPi | Demo</title>
<script type="text/javascript" src="/webiopi.js"></script>
<script type="text/javascript">
webiopi().ready(function() {
var content, button;
content = $("#content");
                // create a button which call function to get SwitchStatus from script.py (GPIO 27) 
                button = webiopi().createButton("macro1", "Door", callMacro_get_DoorStatus);
                content.append(button); // append button to content div
webiopi().setClass("macro1", "Closed"); //set color state

webiopi().refreshGPIO(true);
});
       window.onload = function(){
callMacro_get_DoorStatus()
       }

               setInterval ("callMacro_get_DoorStatus()", 5000);{
}

function callMacro_get_DoorStatus(){
var args = [0]
                //Get data form script.py and return it with Callback
webiopi().callMacro("get_SwitchStatus", args, macro_get_SwitchStatus_Callback);}

function macro_get_SwitchStatus_Callback(macro, args, data){
p0 = data.split(" ")[0];
if (p0==1){
webiopi().setClass("macro1", "Open");
webiopi().setLabel("macro1", "Door Open");}
else{
webiopi().setClass("macro1", "Closed");
webiopi().setLabel("macro1", "Door Closed");}
}
</script>
<style type="text/css">
button {
display: block;
margin: 5px 5px 5px 5px;
width: 160px;
height: 45px;
font-size: 24pt;
font-weight: bold;
color: black;
}
input[type="range"] {
display: block;
width: 160px;
height: 45px;
}
.Open {
background-color: Green;
}
.Closed {
background-color: Red;
}
</style>
</head>
<body>
<div id="content" align="center"></div>
</body>
</html>

I didn't test as I am on vacation, but think it should be ok

Hope it helps 

Toshi

Caroline Blue

unread,
Jan 29, 2014, 11:28:24 AM1/29/14
to web...@googlegroups.com
Toshi, I don't know you but want to say you are AWESOME! I have seen many of your posts/contributions to the webiopi community that have been really helpful, and I just want to say Thank You!! I have made a lot of progress.

I used your examples, and I had to import time again, and I changed my Switch variables to Door. I used the webiopi debugger and found that while it was giving me the correct status in the console, it was throwing a TypeError: get_DoorStatus() takes no arguments (1 given). error. I found that I had to change my webiopi macro to get_DoorStatus(self) to correct this. I am no longer getting any errors, and the console displays "open" or "closed" correctly while turning on an LED when Open. Progress :).

However, I also do see the button now on the page that shows "closed" but it it static. The button is always red with "closed" and does not change to report the different status. I ran the deb Web Inspector to debug the javascript, and it found no errors. It seems that it is only reading webiopi().setClass("macro1", "Closed") at all times.

You have been extremely helpful Toshi, please help me understand why the button still doesn't function as it should, even with no errors :(.


Here is my script.py:

import sys
import webiopi
import time

GPIO = webiopi.GPIO

Door = 27 #should be 27 for Door
Led_light = 18

# Called by WebIOPi at script loading
def setup():
    webiopi.debug("Setup")
    # Setup GPIOs
    GPIO.setFunction(Door, GPIO.IN) #tenp change to check LED output
    GPIO.setFunction(Led_light, GPIO.OUT)


def loop():
    value = GPIO.digitalRead(Door)
    if value == 1:
        print('Open')
        GPIO.digitalWrite(Led_light, True)
    else:
        print('Closed')
        GPIO.digitalWrite(Led_light, False)
       
   # you could replace above with:
    # value = Not GPIO.digitalRead(Switch)
    #GPIO.digitalWrite(Led_light, value)

    time.sleep(1)

# Called by WebIOPi at script loading
def destroy():
    webiopi.debug("Basic script - Setup")
    # Setup GPIOs
    GPIO.setFunction(Door, GPIO.IN)
    GPIO.setFunction(Led_light, GPIO.IN)

@webiopi.macro
def get_DoorStatus(self):
    p0 = GPIO.digitalRead(Door)  # you could replace (Switch) with (Led_Light) to check state of output instead of input.
    print (p0)
    return ("%s" % (p0))


Here is my 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">
<meta name="viewport" content = "height = device-height, width = 420, user-scalable = no" /> 
<title>WebIOPi | Demo</title>
<script type="text/javascript" src="/webiopi.js"></script>
<script type="text/javascript">
webiopi().ready(function() {
var content, button;
content = $("#content");
                // create a button which call function to get SwitchStatus from script.py (GPIO 27) 
                button = webiopi().createButton("macro1", "Door", callMacro_get_DoorStatus);
                content.append(button); // append button to content div
webiopi().setClass("macro1", "Closed"); //set color state

webiopi().refreshGPIO(true);
});
      window.onload = function(){
callMacro_get_DoorStatus()
       }

               setInterval ("callMacro_get_DoorStatus()", 5000);{
}

function callMacro_get_DoorStatus(){
var args = [0]
                //Get data form script.py and return it with Callback
webiopi().callMacro("get_DoorStatus", args, macro_get_DoorStatus_Callback);}

function macro_get_DoorStatus_Callback(macro, args, data){

Toshi Bass

unread,
Jan 29, 2014, 12:38:31 PM1/29/14
to web...@googlegroups.com
Hi Caroline,

I took another look, found my mistake as follows:

time.sleep(1)  should be  webiopi.sleep(1)  then no need for importing sleep ( actually (5) would be fine, to use less cpu

def get_DoorStatus(): should be def get_DoorStatus(arg0):  not (self)

replacing those should have you working

Toshi

Caroline Blue

unread,
Jan 29, 2014, 3:59:22 PM1/29/14
to web...@googlegroups.com
Hi Toshi,

Thanks for the fast response. I have made the changes you suggested, and was able to not import time. I made the arg0 change as well in my macro as such:

@webiopi.macro
def get_DoorStatus(arg0):
    p0 = GPIO.digitalRead(Door)  # you could replace (Switch) with (Led_Light) to check state of output instead of input.
    print (p0)
    return ("%s" % (p0))

The html button is still not updating to reflect the change in status. It stays Red showing "Door". I then played wight he CSS and changed the SetLabel to "open" and the other to "Closed" as such:

webiopi().setClass("macro1", "Open");
webiopi().setLabel("macro1", "Open");}
else{
webiopi().setClass("macro1", "Closed");
webiopi().setLabel("macro1", "Closed");}
}

Now the button changed to always show the word "Closed" but still Red. I am wondering if there is some sort of CSS conflict. I even ended up renaming webiopi.css to prevent it interfering, no changes.

I've been debugging the JS in Chrome and Safari, and the JS debug console shows no errors. If I keep hitting refresh real fast in the browser I can see for a split second the button text change to "Door" then back to "Closed".

webiopi console shows good also:

True

2014-01-29 13:52:30 - HTTP - DEBUG - "POST /macros/get_DoorStatus/0 HTTP/1.1" 200 -

2014-01-29 13:52:30 - HTTP - DEBUG - "GET /* HTTP/1.1" 200 -

2014-01-29 13:52:31 - HTTP - DEBUG - "GET /* HTTP/1.1" 200 -

Open

2014-01-29 13:52:31 - HTTP - DEBUG - "GET /* HTTP/1.1" 200 -

True

2014-01-29 13:52:32 - HTTP - DEBUG - "POST /macros/get_DoorStatus/0 HTTP/1.1" 200 -

2014-01-29 13:52:32 - HTTP - DEBUG - "GET /* HTTP/1.1" 200 -

2014-01-29 13:52:33 - HTTP - DEBUG - "GET /* HTTP/1.1" 200 -

2014-01-29 13:52:33 - HTTP - DEBUG - "GET /* HTTP/1.1" 200 -

Open


I am really running out of ideas, not sure what else it can be :/

Eric PTAK

unread,
Jan 29, 2014, 4:49:56 PM1/29/14
to web...@googlegroups.com
your macro returns "True" or "False" whereas you are testing for "1" in Javascript.
Change your macro by this :

@webiopi.macro
def get_DoorStatus(arg0):
    p0 = GPIO.digitalRead(Door)
    print (p0)
    return "%d" % p0 # returns "0" or "1"


--

Caroline Blue

unread,
Jan 29, 2014, 5:30:27 PM1/29/14
to web...@googlegroups.com
I knew it had to be something that simple that I didn't catch. Thank you soooo much trouch!!!

I am so happy it finally worked!!

Thank you both for all your help. I feel so relieved now. You guys are amazing!!

Pancracius

unread,
Jan 29, 2014, 6:15:15 PM1/29/14
to web...@googlegroups.com
I can confirm that it works well, this will be very useful for my project.

I want a thing more sophisticated.

Using this code I have a button to control the state of a door with one switch, but in a garage door I think that is more useful to have two sensors instead one.
I have two switches, one detects door opened and another detects door closed. If switch1 is closed, door is closed, if switch2 is closed, door is opened and if both switches are opened, door is opening/closing.
How can I show the three states (OPEN, CLOSED and OPENING/CLOSING) in the same button with the Caroline code??.

Thanks for your work.

Eric PTAK

unread,
Jan 29, 2014, 6:33:30 PM1/29/14
to web...@googlegroups.com
in the macro :
switch1 = ...
switch2 = ...

if (switch1 and switch 2):
return ...
if (switch1 and not switch2):
return ...
...



--

Pancracius

unread,
Feb 8, 2014, 1:22:30 PM2/8/14
to web...@googlegroups.com
Thanks for your help trouch, as you say works like a charm.

Eric PTAK

unread,
Feb 8, 2014, 2:07:08 PM2/8/14
to web...@googlegroups.com
thumb up !

Павел Вялых

unread,
Feb 9, 2014, 12:03:24 PM2/9/14
to web...@googlegroups.com
a good example of a macro 
thank you


вторник, 28 января 2014 г., 18:23:45 UTC+4 пользователь Toshi Bass написал:
Message has been deleted

Slappy

unread,
Jun 21, 2014, 7:02:31 AM6/21/14
to web...@googlegroups.com
I'm trying to achieve something similar but simpler, it's breaking my brain. I simply wish to look at the state of a gpio (OUT) and show an image in a separate div according to the result. Like this:

gpio2 low -> hide light.png
gpio2 high -> show light.png

Sounds simple but do you think I can achieve it? Please help my aching brain!
Thanks heaps.

Toshi Bass

unread,
Jun 23, 2014, 11:50:55 AM6/23/14
to web...@googlegroups.com
Hi Slappy

Simply replace usual button color style css and point to your image files like:

.LOW {
//background-color: Yellow;
background-image: url(/webiopi/htdocs/Switch_Low.png);
}
.HIGH {
//background-color: Orange;
background-image: url(/webiopi/htdocs/Switch_High.png);
}

Just make sure the path to your image files is correct, as an example paste the attached files into /home/pi/webiopi/htdocs

and then point your browser at http://xxx.xxx.x.xx:8000/webiopi/htdocs

Toshi
index.html
Switch_High.png
Switch_Low.png
Message has been deleted

Slappy

unread,
Jun 23, 2014, 6:03:47 PM6/23/14
to web...@googlegroups.com
Thank you Toshi, I should have elaborated a little. I wanted to 'switch' an image external to that on the button/s. My problem actually lay in the fact that I was updating webiopi.js in the root of htdocs and not the redirected root of my project. It seems that in the absence of a copy of it in the new root it defaults to another copy, somewhere. The solution I am using is the following:

webiopi.js (around line 250)

WebIOPi.prototype.updateValue = function (gpio, value) {
    w().GPIO[gpio].value = value;
    var style = (value == 1) ? "HIGH" : "LOW";
    $("#gpio"+gpio).attr("class", style);
    var deckImg = (value == 1) ? "HIGH" : "LOW";
    $("#deck"+gpio).attr("class", deckImg);

}

Which gives me an external image that corresponds to each gpio state.

in the css

#deckControl {
    width: 300px;
    height: 263px;
    background-image:url('deck.gif');
    margin: auto;
}

#deck2.HIGH {
            background-image:url('perimeter.png');
        }
        #deck3.HIGH {
            background-image:url('floods.png');
        }
        #deck2.LOW, #deck3.LOW {
            background-image: none;
        }


and in the html

<div id="deckControl"><div id="deck2"><div id="deck3"></div></div></div>

Toshi Bass

unread,
Jun 24, 2014, 4:24:29 AM6/24/14
to web...@googlegroups.com
Slappy

I am guessing from your response and code that you have a solution and if its working for you and your happy with it fine, but I would say you are approaching this the wrong way, you can achieve this easily without modifying webiopi.js.

I would strongly recommend to anyone who may follow this NOT to modify webiopi.js  you will be limiting webiopi's built in flexibility as you further develop your code, the changes will not be supported here and of coarse you will lose your changes with any new release of webiopi,    

Toshi

Slappy

unread,
Jun 24, 2014, 10:38:09 PM6/24/14
to web...@googlegroups.com
Thanks again for your advice Toshi, you are of course correct. Can you make a suggestion as to how that might be achieved? I have tried many different approaches including macro's and loops in script.py and javascript in index.html and php but none seem to give me results. I like the idea of javascript/jquery best.

Thanks!

Toshi Bass

unread,
Jun 25, 2014, 6:10:39 AM6/25/14
to web...@googlegroups.com
Hi Slappy

Well presumably you were following the code in this original post and you are calling a macro in your script.py to get the state of the gpio - high or low and amending the button with the callback, if so then you could add the following in RED

setInterval ("callMacro_get_DoorStatus()", 5000);{
}

function callMacro_get_DoorStatus(){
var args = [0]
//Get data form script.py and return it with Callback
webiopi().callMacro("get_DoorStatus", args, macro_get_DoorStatus_Callback);}

function macro_get_DoorStatus_Callback(macro, args, data){

p0 = data.split(" ")[0];
if (p0==1){
webiopi().setClass("macro1", "Open");
webiopi().setLabel("macro1", "Door Open");
document.getElementById("pic0").src = "/webiopi/htdocs/Switch_Low.png"; }
else{
webiopi().setClass("macro1", "Closed");
webiopi().setLabel("macro1", "Door Closed");
document.getElementById("pic0").src = "/webiopi/htdocs/Switch_High.png"; }
}

Then in the head section add

       <div><img name="pic0" id="pic0"></div>

If this is not the case and your not using python then you could check the state of the GPIO - High or Low in the index.html file, see attached, I am sure there are loads of other perhaps better ways to achieve this, but it should give you some ideas to check (obviously you would change the example .png's to your images)

Toshi 
index.html
Switch_High.png
Switch_Low.png

Gianpic69

unread,
May 15, 2016, 2:15:18 PM5/15/16
to WebIOPi
Hi Toshi

First of all, good job

I'm trying to adapt the published files to my needs but I can not figure out where to make mistakes.
the python file runs without error but the html shows only the date and time and the link to another raspberry owned by me.
I ask you, if possible, to check the attached file and propose a solution.
thank you
GP
index.html
ingpiostatus.py

Toshi Bass

unread,
May 15, 2016, 4:13:10 PM5/15/16
to WebIOPi
I cannot download or open files you attached as I am on vacation and only have iPhone / iPad So sorry I cannot help, maybe someone else can offer a solution or if not paste the code into the body of the post and if I get some time I will have a look.

Gianpic69

unread,
May 15, 2016, 6:11:52 PM5/15/16
to WebIOPi
Hi Toshi
thanks for the quick reply and availability

here below is the file ingpiostatus.py


import sys
import webiopi
import time

GPIO = webiopi.GPIO

Sala = 20       #should be 20 for Sala
Camera = 21       #should be 21 for Sala

def setup():
    webiopi.debug("Setup")
    GPIO.setFunction(Sala, GPIO.IN)
    GPIO.setFunction(Camera, GPIO.IN)

def loop():
    value = GPIO.digitalRead(Sala)
    if value == 1:
        print('OK')
    else:
        print('Alarm')

    value = GPIO.digitalRead(Camera)
    if value == 1:
        print('Ok')
    else:
        print('Alarm')

    webiopi.sleep(5)

def destroy():
    webiopi.debug("Basic script - Setup")
    GPIO.setFunction(Sala, GPIO.IN)
    GPIO.setFunction(Camera, GPIO.IN)

@webiopi.macro
def get_SalaStatus(arg0):
    p0 = GPIO.digitalRead(Sala)
    p0 = GPIO.digitalRead(Camera)
    print (p0)
    return ("%d" % (p0))

 
here below is the file 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">
<meta name="viewport" content = "height = device-height, width = 420, user-scalable = no" />
<title>Cucina</title>
<script type="text/javascript" src="/webiopi.js"></script>
<script type="text/javascript">
  webiopi().ready(function () {

  webiopi().setFunction(17, "out"); //
webiopi().setFunction(27, "out"); //
webiopi().setFunction(22, "out"); //
webiopi().setFunction(23, "out"); //
webiopi().setFunction(24, "out"); //
webiopi().setFunction(21, "in"); //
                var content, button;
content = $("#content");

// create a "button" labeled PIR 1 for GPIO 20
button = webiopi().createButton("macro1", "Sala", callMacro_get_SalaStatus);
content.append(button); // append button to content div

// create a "button" labeled PIR 1 for GPIO 21
button = webiopi().createGPIOButton(21, "Allarme PIR 1");
content.append(button);

// you can also create a button which calls a different function for mouse down and up events
    button = webiopi().createButton("","Emergency",  mousedown0, mouseup);
content.append(button);      // append button to content div

// create a "button" labeled Notturna for GPIO 24
    button = webiopi().createGPIOButton(24, "Notturna");
    content.append(button); // append button to content div

// you can also create a button which calls a different function for Pulse Event
    button = webiopi().createButton("", "Tapparelle Sù", pulseRelay27, pulseRelay23);
    content.append(button);

// you can also create a button which calls a different function for mouse down and up events
    button = webiopi().createButton("","Tapparella Sinistra Sù",  mousedown1, mouseup);
    content.append(button);

// you can also create a button which calls a different function for mouse down and up events
    button = webiopi().createButton("", "Tapparella Destra Sù", mousedown2, mouseup);
    content.append(button);

// you can also create a button which calls a different function for Pulse Event
    button = webiopi().createButton("", "Tapparelle Giù", pulseRelay17, pulseRelay22);
    content.append(button);

// you can also create a button which calls a different function for mouse down and up events
    button = webiopi().createButton("", "Tapparella Sinistra Giù", mousedown3, mouseup);
    content.append(button);

// you can also create a button which calls a different function for mouse down and up events
    button = webiopi().createButton("", "Tapparella Destra Giù", mousedown4, mouseup);
    content.append(button);

    webiopi().refreshGPIO(true);

webiopi().setClass("macro1", "Ok");
webiopi().setLabel("macro1", "Ok");}
else{
webiopi().setClass("macro1", "Alarm");
webiopi().setLabel("macro1", "Alarm");}
}

webiopi().refreshGPIO(true);
});

    function mousedown0() {
    webiopi().digitalWrite(17, 0);
    webiopi().digitalWrite(27, 0);
    webiopi().digitalWrite(22, 0);
    webiopi().digitalWrite(23, 0);
    webiopi().digitalWrite(24, 0);

}

function mousedown1() {
    webiopi().digitalWrite(17, 1);
    webiopi().digitalWrite(27, 0);
    webiopi().digitalWrite(22, 0);
    webiopi().digitalWrite(23, 0);

}

function mousedown2() {
    webiopi().digitalWrite(17, 0);
    webiopi().digitalWrite(27, 1);
    webiopi().digitalWrite(22, 0);
    webiopi().digitalWrite(23, 0);

}

function mousedown3() {
    webiopi().digitalWrite(17, 0);
    webiopi().digitalWrite(27, 0);
    webiopi().digitalWrite(22, 1);
    webiopi().digitalWrite(23, 0);

}

function mousedown4() {
    webiopi().digitalWrite(17, 0);
    webiopi().digitalWrite(27, 0);
    webiopi().digitalWrite(22, 0);
    webiopi().digitalWrite(23, 1);

}

function mouseup() {
    webiopi().digitalWrite(17, 0);
    webiopi().digitalWrite(27, 0);
    webiopi().digitalWrite(22, 0);
    webiopi().digitalWrite(23, 0);
}

function pulseRelay17() {
 var pin = 17;                                        // pin your relay is controlled by
 webiopi().digitalWrite(pin, 1);                                     // Turn the relay ON
    setTimeout( function(){ webiopi().digitalWrite(pin, 0); }, 20000);  // Wait 20 seconds, turn the relay OFF
}

function pulseRelay27() {
 var pin = 27;                                                       // pin your relay is controlled by
 webiopi().digitalWrite(pin, 1);                                     // Turn the relay ON
 setTimeout( function(){ webiopi().digitalWrite(pin, 0); }, 20000);  // Wait 20 seconds, turn the relay OFF
}

function pulseRelay22() {
 var pin = 22;                                                      // pin your relay is controlled by
 webiopi().digitalWrite(pin, 1);                                    // Turn the relay ON
 setTimeout( function(){ webiopi().digitalWrite(pin, 0); }, 20000); // Wait 20 seconds, turn the relay OFF
}

function pulseRelay23() {
    var pin = 23;                                                      // pin your relay is controlled by
 webiopi().digitalWrite(pin, 1);                                    // Turn the relay ON
 setTimeout( function(){ webiopi().digitalWrite(pin, 0); }, 20000); // Wait 20 seconds, turn the relay OFF
    }

window.onload = function(){
callMacro_get_SalaStatus()
}

setInterval ("callMacro_get_SalaStatus()", 5000);{
}

function callMacro_get_SalaStatus(){
var args = [0]  //Get data form script.py and return it with Callback
webiopi().callMacro("get_SalaStatus", args, macro_get_SaStatus_Callback);}
function macro_get_SalaStatus_Callback(macro, args, data)
{

</script>
<style type="text/css">
button {
display: block;
margin: 1px 1px 1px 1px;
width: 300px;
height: 58px;
font-size: 20pt;
font-weight: bold;
color: black;
      border-radius: 26px;
}

input[type="range"] {
display: block;
width: 160px;
height: 45px;
}

.LOW {
background-color: #32F45F;
}

.HIGH {
background-color: #FB0505;
}

#gpio24.LOW {
      background-color: #070AEA;
}
#gpio24.HIGH {
background-color: #FB0505;
}
#gpio20.LOW {
background-color: #FDF904;
}
#gpio20.HIGH {
background-color: #FB0505;
}

</style>

</head>
<body>
  <h1>Cucina<h1>
<a href="http://172.26.100.220:8000" style="font-size:30px">Cameretta</a>
  <a href="http://time.is/Milan" id="time_is_link" rel="nofollow" style="font-size:30px"></a>
  <span id="Milan_z723" style="font-size:30px"></span>
  <script src="http://widget.time.is/it.js"></script>
  <script>
  time_is_widget.init({Milan_z723:{template:"TIME<br>DATE", date_format:"dayname daynum/monthnum/year"}});
  </script>
  <div id="content" align="Left"></div>
  <body bgcolor=”#ECF4F3”>
</body>
</html>

Pete Dudash

unread,
May 15, 2016, 9:19:40 PM5/15/16
to WebIOPi

It’s very nice of Toshi to offer helping you while he’s on vacation! Hopefully I can help so he can relax. :-)

GP, it looks like you have some copy/paste errors in your javascript. If you open the javascript console, you would see where the messages are. Press F12 in Chrome browser.

First error is at the end of your webiopi().ready(function () {}); function.

// you can also create a button which calls a different function for mouse down and up events
     button = webiopi().createButton("", "Tapparella Destra Giù", mousedown4, mouseup);
     content.append(button);

     webiopi().refreshGPIO(true
);
     if(0){                                   // looks like you forgot the IF statement here - so I added one to make it happy

     webiopi().setClass("macro1", "Ok");
     webiopi().setLabel("macro1", "Ok");}
     else{
     webiopi().setClass("macro1", "Alarm"
);
     webiopi().setLabel("macro1", "Alarm");}  // remove this closing bracket at the end of this line
     }

     webiopi().refreshGPIO(true);             // remove this - no need to call it twice
});

The second error is at the very end of your </script> section. You started a new function declaration, but didn’t finish it.

function callMacro_get_SalaStatus(){
     var args = [0]  //Get data form script.py and return it with Callback
     webiopi().callMacro("get_SalaStatus", args, macro_get_SaStatus_Callback);}
function macro_get_SalaStatus_Callback(macro, args, data)
{
}                                             // this bracket was missing - so I added one to make it happy
</script>

Gianpic69

unread,
May 16, 2016, 9:53:56 AM5/16/16
to WebIOPi
Hi Pete
Thanks for the answer, if I can, tonight I will try to change the file as you suggested
Regards
GP


Toshi
have a nice holiday :-)

Pete Dudash

unread,
May 16, 2016, 12:39:21 PM5/16/16
to WebIOPi

One more thing, your <div id="content" align="Left"></div> is outside of your <body></body> tags. It might work for certain browsers, but technically isn’t valid HTML. You might as well move it inside like this:

<body bgcolor="#ECF4F3">

     <div id="content" align="Left"></div>
</body>
Reply all
Reply to author
Forward
0 new messages