使用JS根据ArduinoYún上另一个网站的内容更改CSS样式

时间:2014-04-29 22:48:17

标签: javascript css arduino

我有一个问题,最终(希望?)归结为JS,但由于我正在研究ArduinoYún,我认为最好显示问题的一面,以免遗漏任何东西。那些愿意阅读我对那些与手头问题没有多大关系的完全无趣解释的人,可以随意这样做。其他人,跟我来! +跳到 JS问题 +

Yún方

这是交易:我想基于将PIN2和PIN3连接到GND的一些开关来更改Yún上托管的网页的css属性。

我使用Bridge示例作为我在Arduino方面的代码的基础,我相信它的设置应该是:

#include <Bridge.h>
#include <YunServer.h>
#include <YunClient.h>
//variable constante que guarda la cantidad de puertas

#define CANT_PUERTAS 2

//variable tipo array que guarda los estados de las diferentes puertas
int estado[CANT_PUERTAS];

YunServer server;

void setup() {
  Serial.begin(9600);

  // Bridge startup
  Bridge.begin();

  //Pines que van a monitorear las puertas
  pinMode(2, INPUT_PULLUP);
  pinMode(3, INPUT_PULLUP);

  server.listenOnLocalhost();
  server.begin();
}

void loop() {
  //hacer poll de estado de puertas
  pollPuertas(estado, CANT_PUERTAS);

  YunClient client = server.accept();

  if (client) {
    process(client);
    client.stop();
  }

  delay(50); 
}

...与

void pollPuertas(int estado[], int arraySize) {
  for (int i = 0; i < arraySize; i++) {
        estado[i] = digitalRead(2 + i);
  }
}

...和

void process(YunClient client) {
  String command = client.readStringUntil('/');
  if (command == "estado") {
    int puerta = client.parseInt();
    client.print(estado[puerta]);
  }
}

因此,代码背后的基本思想如下: CANT_PUERTAS是我要监视的PIN数量,而estado []是一个数组,我将保存这些引脚的值。

函数pollPuertas是一个简单的for loop,可以读取PIN的状态(在我的情况下,我将保留PIN0和PIN1以备将来通信,所以我从PIN2开始)并保存这些状态到estado []。

函数process处理REST调用。我的呼叫组织得像这个命令/号码,虽然我现在只想使用一个命令。因此,如果我的命令是“estado”,我只需使用NUMBER作为我的数组的索引,并将该PIN的值打印到客户端。

此代码没有问题。如果我访问arduinoyun.local / arduino / estado / NUMBER,我会得到预期的结果:

  • a 1表示打开开关,或
  • a 0表示关闭的开关。

JS问题

还在我身边吗?哇。谢谢:D。

对于那些没有阅读上一部分的人,这是一个非常简单的评论:

  • 我正在监控两个交换机(如灯开关,而不是网络交换机)。
  • 我已经设置了两个“网页”(每个交换机一个),其内容根据交换机是否关闭而变化。它们托管在本地网络上。
  • “网页”的内容是1或0. ASCII。没有HTML标题或任何内容,这就是我称之为“网页”的原因。

现在出现了实际问题。我是HTML,JS和JQuery的新手,所以请耐心等待。

我想在ArduinoYún上托管一个简单的网站,其CSS属性根据交换机的状态而变化。我的想法是编写一个脚本,使用if条件来评估如何更改这些属性。将定期调用此脚本,以便网站以“实时”方式反映交换机状态的变化。

这是我对此的尝试:

<!DOCTYPE html>
<html>

  <head>
    <title>Poll de Puertas</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js">    </script>
<!--    <script type="text/javascript"     src="https://code.angularjs.org/1.2.9/angular.js"></script>-->

    <script type="text/javascript">        
        function cambiarColor(){
        //  if($http.get("arduinoyun.local/arduino/estado/1") === 0){
            if(1==0){
                $('p:nth-child(1)').css('color','green');
            } else{
                $('p:nth-child(1)').css('color','red');
            }

            $('p:nth-child(2)').css('color','blue');
        }
    </script>

  </head>
    <body onload ="setInterval(cambiarColor,3000);">
    <p id="puerta1">Puerta 1</p>
    <p id="puerta2">Puerta 2</p>
  </body>

</html>

在身体中我有2个<p>元素,每个开关一个元素。函数cambiarColor是我的脚本,负责使用<p>条件和一些简单的JQuery来更改if的颜色。

在此尝试中,我设法至少使逻辑正常工作:第一个<p>始终更改为红色,因为if始终评估为FALSE。此外,还定期调用该函数。第二个<p>我刚离开聚会,因为他称我为胖子;(

现在,我不知道的,以及这篇长篇文章背后的真正问题是,在我的脚本中放入if(),以便从“网页”中提取值“我已经设置了(无论是1还是0),以便脚本响应交换机的状态。

提前感谢所有帮助。

2 个答案:

答案 0 :(得分:0)

编辑2

好吧,自从你上次发表评论以来,我认为你可以尝试一下,看看会发生什么:

    var response ;
    var file_path = 'path/to/your/file.txt';

     $.ajax({
                url: file_path,
                method: 'GET',
                dataType: 'text',
                async: false,
                success: function (data) {
                    response = data;
                }
            });
    //this should, in theory get you the inner contents of your file, and assign it to the variable 
    "response".

    //now you can validate

    if(parseInt(response) == 0){
                        //i still think using $('#puerta1') as the DOM selector is better.
                        $('p:nth-child(1)').css('color','green');
                    } else{
                        $('p:nth-child(1)').css('color','red');
                    }

                    $('p:nth-child(2)').css('color','blue');
        });

//if nothin' happens, try and uncomment the next line to try and find what jquery is reading from your file:
//alert(response);

我认为这应该是它,或者至少我正在接近你的问题并找到可能的解决方案。

修改

再次阅读你的问题,我想我终于不喜欢你在这里想做的事了,所以,我认为你的问题的答案如下:

//The url to the webpage where arduino is outputing the values
$.get( "URLTOMYWEBPAGE.HTML").done(function( data ) {
if( parseInt(data ) == 0){
                //i still think using $('#puerta1') as the DOM selector is better.
                $('p:nth-child(1)').css('color','green');
            } else{
                $('p:nth-child(1)').css('color','red');
            }

            $('p:nth-child(2)').css('color','blue');
});

希望这实际上是解决问题的方法。

OLD

我不确定你在这一行"if(1==0)"上做什么,这总是会是假的,我也不知道你是如何得到你想要阅读和评估你的网页的价值观但是,让我们说,价值(我所理解的1和0)将在P元素内部,也就是说,你的html会看到广告如下:

<!-- assuming this values where returned from arduino -->
<p id="puerta1">1</p>
<p id="puerta2">0</p>

假设以上所有情况都属实,您的脚本将如下所示:

var puertaUNO = document.getElementById("puerta1").innerHTML;
var puertaDOS = document.getElementById("puerta2").innerHTML;

if( parseInt(puertaUNO) == 0){
                $('p:nth-child(1)').css('color','green');
            } else{
                $('p:nth-child(1)').css('color','red');
            }

            $('p:nth-child(2)').css('color','blue');

或者使用Jquery

var puertaUNO = $('#puerta1').text();
 var puertaDOS = $('#puerta2').text();

if( parseInt(puertaUNO) == 0){
                    $('#puerta1').css('color','green');
                } else{
                    $('#puerta1').css('color','red');
                }

                $('#puerta2').css('color','blue');

还不完全清楚你想做什么,但我认为就是这样。

答案 1 :(得分:0)

首先,非常感谢Q_ro的帮助。

以下是我设法解决问题的方法: 按照与上次相同的顺序,首先是 Arduino代码

#include <Bridge.h>
#include <YunServer.h>
#include <YunClient.h>

//variable constante que guarda la cantidad de puertas
#define CANT_PUERTAS 2

//variable tipo array que guarda los estados de las diferentes puertas
int estado[CANT_PUERTAS];

// Listen on default port 5555, the webserver on the Yun
// will forward there all the HTTP requests for us.
YunServer server;

void setup() {
  Serial.begin(9600);
  // Bridge startup
  Bridge.begin();
  //Pines que van a monitorear las puertas a partir de D2
  for (int i = 0; i < CANT_PUERTAS; i++) {
    pinMode(2 + i, INPUT_PULLUP);
  }
  // Listen for incoming connection only from localhost
  // (no one from the external network could connect)
  server.listenOnLocalhost();
  server.begin();
}

void loop() {
  //hacer poll de estado de puertas
  pollPuertas(estado);

  // Get clients coming from server
  YunClient client = server.accept();

  // There is a new client?
  if (client) {
    // Process request
    process(client);

    // Close connection and free resources.
    client.stop();
  }

  delay(50); // Poll every 50ms
}

我在这里的唯一更改是void setup(){},而不是手动声明要监控的引脚,我创建了一个for loop来根据要监控的引脚数自动设置它们;在pollPuertas中,我改变了传递给它的参数。

void pollPuertas(int estado[]) {
  for (int i = 0; i < CANT_PUERTAS; i++) {
    estado[i] = digitalRead(2 + i);
  }
}

就像我之前说过的,我将参数更改为此函数。决定只使用我之前定义的常量。

void process(YunClient client) {
  // read the command
  String command = client.readStringUntil('/');
  command.trim();
  //confirmar que el comando recibido es el correcto
  if (command == "estado") {
    client.println("Status: 200");
    client.println("Content-type: application/json");
    client.println();
    //Inicio del array JSON
    client.print("[");
    //Valores del array
    for (int i = 0; i < CANT_PUERTAS; i++) {
      client.print(estado[i]);
      //Si no es el ultimo valor del array, intercalar una coma
      if (i < (CANT_PUERTAS - 1)) client.print(",");
    }
    //Cerrar array JSON
    client.print("]");
  }
}

最后但并非最不重要的是,process(YunClient client)。这里发生了最大的变化(至少是Arduino方面)。

将Q_ro建议作为指南,将我的REST调用从我原来的结构(arduinoyun.local/arduino/estado/PIN)更改为我有个人&#34;网页&#34;每个PIN,到一个新的结构(arduinoyun.local/arduino/estado),我将所有当前监控的PIN放在一个&#34;网页&#34;作为JSON对象(在本例中为数组)。

我想在这里做一个特别的评论:在我的测试中,我开始意识到(艰难的)修剪空白的重要性。不知道为什么不这么问我,但直到我 command.trim(); 我的代码才起作用。也许浏览器在查询页面时会插入一些空格,我不知道。我所知道的是,当我注意到Grallator的代码中的arduinoyun.local/arduino/estado时,我已经撞到墙上试图找出为什么trim()不会带出任何东西。

无论如何,在正确验证命令之后,我打印一个标题,告诉浏览器这是一个JSON对象。

之后,我只打印出一个包含此表单的数组:[value, value, value]。您可以在来源中获取所有详细信息。

关于这一方面的问题。

HTML和JavaScript

<!DOCTYPE html>
<html>

  <head>
    <title>Cambio de CSS con JSON</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.1.js"></script>
    <script type="text/javascript">
    var Timer =setInterval(function(){cambiarColor()},500);
        function cambiarColor(){
        var i=0;
        $.getJSON("/arduino/estado/",function(json){
            var LENGTH = json.length;
            for(i; i < LENGTH; i++){
                if(json[i]==0){
                    $("#puerta"+i).css("color","green");
                } else{
                    $("#puerta"+i).css("color","red");
                }//cierra if
            }//cierra for
        }); //cierra $.getJSON
    } //cierra cambiarColor();
    </script>

  </head>
    <body>
    <p id="puerta0">Puerta 1</p>
    <p id="puerta1">Puerta 2</p>
  </body>

</html>

var Timer =setInterval(function(){cambiarColor()},500);只是设置一个计时器,以便定期调用函数cambiarColor()

根据cambiarColor()本身,它发生了很大的变化。您可以在来源中详细了解函数$.getJSON的工作原理,但这里是要点:

  • 假设JSON对象在服务器端格式正确,$ -getJSON()返回JS对象或JS数组(在我的情况下是一个数组)
  • 将数组传递给变量json
  • 创建一个变量来保存json数组
  • 的长度
  • 执行for loop以查看json
  • 中的值
  • 根据从Arduino yaaaayyy 获取的JSON对象的值,使用jQuery更改CSS值

@Q_ro我发现了如何将i连接到jQuery选择器,以便我可以通过ID工作!的Wooo!

所以你去吧。再一次,感谢Q_ro帮助我。希望这对未来的其他人有用。

要记住的一个提示(我知道我忘了这件事的时间比我承认的要长):代码的$ .getJSON部分用});关闭,而不仅仅是}

<强>来源

在最后一页的末尾有一堆有用的工具。尤其是jsoneditoronline(dot)org对我来说非常有用;帮助我更好地可视化JSON对象结构。