在上一篇博文中我们完成了led的控制,我们也可以通过webiopi框架的Marco来实现。Marco可以自定义python函数使其绑定到REST API,这允许进行复杂的计算,实现功能等等

step1 python脚本中添加

将Marco注册到本机服务上只需要在python函数前添加装饰器,参照上一篇博客https://blog.hdussta.cn/raspberry/webiopi%E6%A1%86%E6%9E%B6%E5%9F%BA%E7%A1%80.html的程序,更改python代码

使用@webiopi.marco装饰器将getLighterHours/ setLightHours 函数声明给webiopi,第一个函数返回字符串,第二个函数设置字符串并向html提供反馈。

import webiopi
...
HOUR_ON = 8
HOUR_OFF = 18
...
def setup():
...
def loop():
...
def destroy():
...

@webiopi.macro
def getLightHours():
    return "%d;%d" % (HOUR_ON, HOUR_OFF)

@webiopi.macro
def setLightHours(on, off):
    global HOUR_ON, HOUR_OFF
    HOUR_ON = int(on)
    HOUR_OFF = int(off)
    return getLightHours()

 

step2 JavaScript调用Marco

编辑html文件

1、在body中添加输入框体和标签

<html>
...
<body>
<div align="center">
Turn On at :<input type="text" id="inputOn" /><br/>
Turn Off at: <input type="text" id="inputOff" /><br/>
<div id="controls"></div>
</div>
</body>
</html>

 

2、继续添加

webiopi().ready(function() {
        // Following function will process data received from set/getLightHours macro.
        var updateLightHours = function(macro, args, response) {
                    var hours = response.split(";");
                    // Following lines use jQuery functions
                    $("#inputOn").val(hours[0]);
                    $("#inputOff").val(hours[1]);
        }

        // Immediately call getLightHours macro to update the UI with current values
        // "getLightHours" refers to macro name
                // [] is an empty array, because getLightHours macro does not take any argument
                // updateLightHours is the callback function, defined above
                webiopi().callMacro("getLightHours", [], updateLightHours);

        // Create a button to call setLightHours macro
        var sendButton = webiopi().createButton("sendButton", "Send", function() {
           // Arguments sent to the macro
                    var hours = [$("#inputOn").val(), $("#inputOff").val()];
            // Call the macro
                    webiopi().callMacro("setLightHours", hours, updateLightHours);
                });

        // Append the button to the controls box using a jQuery function
                $("#controls").append(sendButton);

        // Create a "Light" labeled button for GPIO 17
        var button = webiopi().createGPIOButton(17, "Light");

        // Append the button to the controls box
        $("#controls").append(button);

        // Refresh GPIO buttons
        // pass true to refresh repeatedly of false to refresh once
        webiopi().refreshGPIO(true);

        });

 

Test

如前一篇博文操作即可

发表评论