yun bridge with sql problem

Hi
i am having troubles with bridge library.

i am trying to read one value from MYSQL data base and use it on arduino sketch,

so i have one python script that conect to data base and then pass the read value to bridge (i only read just one value))

here is the script

!/usr/bin/python
import socket
import _mysql
import sys
sys.path.insert(0, '/usr/lib/python2.7/bridge/')
from bridgeclient import BridgeClient as bridgeclient
con = _mysql.connect('***.***.*.**', '******', '******', 'tempc')
con.query("SELECT * FROM alarma1")
data=con.use_result()
alarma=data.fetch_row()[0]
con.close()
bc = bridgeclient()
bc.put('alarm',alarma)

and here is the arduino sketch who launch the proccess and wait for bridge value

#include <Process.h>
String ala = "/mnt/sda1/sql2bridge.py";//mira el valor de la alarma
float value=7.3;
char thold[10];
float th_f;
float r;
int t= 1;  //// tiempo de espera entre grabacion de datos
void setup() {
  Bridge.begin();	// Initialize the Bridge
  Console.begin();
  pinMode(A0,INPUT);
  while(!Console);
  Console.println("READY");
}

void loop() {
  value = analogRead(A0);
  Process e;
  e.begin("python");
  e.addParameter("/mnt/sda1/sql2bridge.py");
  e.run(); // blocking call to run python; ATMega execution halts until complete 
  // do nothing until the process finishes, so you get the whole output:
  while (e.running());
  Bridge.get("alarm",thold,10);
  th_f=atof(thold);
  r=value-th_f;
  if(r<=0){
    digitalWrite(13,HIGH);
    Console.println(r);
    Console.print("high");
    }
  else{digitalWrite(13,LOW);
        Console.println(r);
        Console.print("low");   
     }  
}

i have try to launct he script manually from putty, and normally appear this error:

Traceback (most recent call last):
File "sql2bridge.py", line 13, in
bc.put('alarm',alarma)
File "/usr/lib/python2.7/bridge/bridgeclient.py", line 92, in put
json = self.socket_open()
File "/usr/lib/python2.7/bridge/bridgeclient.py", line 59, in socket_open
self.json = TCPJSONClient('127.0.0.1', 5700)
File "/usr/lib/python2.7/bridge/tcp.py", line 65, in init
TCPClient.init(self, address, port)
File "/usr/lib/python2.7/bridge/tcp.py", line 38, in init
client.connect((address, port))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 146] Connection refused

i am sure that the script obtain data from sql becouse i can print it, and i have try to use console on the arduino side but it crash when arrive to the line: Bridge.get("alarm",thold,10);

if some one can point me how to debug or have an idea how to change somethin would be nice becouse i have use the las two days and i am a bit block today :smiley:

thanks!!

First off, you're missing a '#' as the first character of your Python code, but I'm guessing that's just a copy/paste error when you inserted your code on the post.

If I comment out the SQL code in your Python code, and just set alarma to a constant, it works, and the value gets put in the Bridge datastore as expected. So either your SQL code is causing a conflict, or there is something broken in your system setup.

But, this is such a trivial case, why are you using Bridge.put()? You are already running a Process object, and anything that is printed by the Python code can be read by the bridge. If you take out everything Bridge related from the Python code, you can simply end the script with [color=blue]print alarma[/color]. That will make it very easy to test from the command line.

Then, when you call the script from the sketch using the Process class, anything output from the script (like the alarma value) can be read using e.available() and e.read(). The Bridge datastore and get/put does not need to be involved.

Install software:

opkg update
opkg install python-mysql

Table structure:

mysql> select * from sensor_data;
+----+-------------+---------------------+
| id | temperature | insert_date         |
+----+-------------+---------------------+
|  1 |          20 | 2015-06-15 16:58:40 |
+----+-------------+---------------------+
1 row in set (0.00 sec)

Python code:

nano /mnt/sda1/sensor.py
!/usr/bin/python
# -*- coding: utf-8 -*-
import _mysql
try:
        con = _mysql.connect('192.168.0.240', 'username', 'password', 'sensors')
        con.query("select temperature from sensor_data")
        data=con.use_result()
        temperature=data.fetch_row()[0][0]
        print    temperature
except _mysql.Error, e:
        print "Error %d: %s" % (e.args[0], e.args[1])
        sys.exit(1)
finally:
        if con:
                con.close()
chmod 755 /mnt/sda1/sensor.py

Testing:

/mnt/sda1/sensor.py
20

ATmega32u4 code:

#include <Process.h>
void setup()
{
  Bridge.begin();
  while (!Serial);     // do nothing until the serial monitor is opened
  Serial.println("Start");
}
void loop()
{ 
  String c = "";
  Process p;
  p.begin("/mnt/sda1/sensor.py");
  p.run();
  while(p.running()) {};
  while (p.available()>0) {
     c += p.readString();
  };
  Serial.println(c);
  delay(10000);
}

You can use sqlite3 and python, which is lighter, dedicated to embedded systems.

Hi!!

Thanks to everyone for your help!!!

i thought that you can only comunicate between linux and arduino with bridge./put-get.

i have tryed your code Sonnyyu and the python script get the data and print it on console when i run it manually, then on the arduino part i have a problem with Serial conectivity on my computer never appear the new device. and on arduino IDE on Tools>Port only appear Network ports and 192.168.1.62(arduino yun).
i have try conecting the USB cable to mini USB on Arduino (i supouse this is the correct conection) but i have try the big USB too, always making resets on 32u4 reset button...and some plug and unplug from power supply too....and i have close the IDE go to control pannel on windows and search changes and nothing...only wifi conection appear so Serial monitor is conected via wifi, and i supouse that is wrong for Serial.print so how can i use Serial port???

again thanks a lot for your help, the problem is the code is not working as espected by this reason i want to debug .
here is the new code that use the Python script from sonnyyu:

#include <Process.h> 
String tabla = "/mnt/sda1/bridge2sql.py";//inserta datos leidos de sensores en tabla
String printalarm = "/mnt/sda1/printalarm.py";//mira el valor de la alarma
String mail = "/mnt/sda1/automail.py";//envia un mail de alarma
float value=7.3;
String thold="";
float th_f;
float r;
int t= 1;  //// tiempo de espera entre grabacion de datos
void setup() {
  Bridge.begin();	// Initialize the Bridge
  pinMode(A0,INPUT);
  while(!Serial);
  Serial.println("READY");
}

void loop() {
  value = analogRead(A0);
  Process e;
  e.begin("python");
  e.addParameter(printalarm);
  e.run(); // blocking call to run python; ATMega execution halts until complete 
  // do nothing until the process finishes, so you get the whole output:
  while (e.running()){};
  while (e.available()>0) {
     thold += e.readString();
  };
  Serial.println("thold:  ");
  Serial.print(thold);
  delay(3000);
  th_f= thold.toFloat();
  r=value-th_f;
  if(r<=0){
      digitalWrite(13,HIGH);
      Serial.println("r:  ");
      Serial.print(r);
    }
  else{
      digitalWrite(13,LOW);
      Serial.println("r:  ");
      Serial.print(r);
     }  
}

The Bridge library provides several useful classes for Linux/sketch communications besides get/put, including the Process class and Mailbox. The Process class is derived from the Stream class, just like the Serial class and Console class. That means that besides starting a Linux task, Process allows bi-directional communications with that task using any of the functions normally used with Serial and Console.

In addition, you can skip the Bridge classes altogether, and use direct serial communications between the sketch (using Serial1) and Linux (using /dev/ttyATH0.) Going that way, you would have to implement the communications code yourself for both sides.

and on arduino IDE on Tools>Port only appear Network ports and 192.168.1.62(arduino yun).

That's curious. Most people have no problems with the USB port, and lots of problems getting the network port to appear in the IDE. You have exactly the opposite situation.

i have try conecting the USB cable to mini USB on Arduino (i supouse this is the correct conection)

Yes, the micro-USB port is connected to the 32U4 Arduino processor. While it can be used for a variety of purposes (the 32U4 can appear as a keyboard or mouse, for example) the main use for it is a serial port to the IDE or a terminal emulator. When used with a terminal emulator or the IDE's serial monitor, it allows communication through the Serial class.

If it doesn't show up, you may have a bad USB driver installation on your computer, a bad USB socket, or you are using a USB cable that is designed only for charging and does not have the data lines. The first thing to try is a different cable, and plug it into a different USB port on your computer.

but i have try the big USB too

While the micro-USB port is a device port to the 32U4 (intended to be connected to a host port on a computer) the larger USB port is exactly the opposite. This port is connected to the Linux processor, and is a host port intended to be connected to various devices (serial adapters, keyboards, etc.)

only wifi conection appear so Serial monitor is conected via wifi, and i supouse that is wrong for Serial.print so how can i use Serial port???

Correct: if connected over the network, the Serial Monitor talks with the Console class, not the Serial class. If you want to use the Serial class for communications, you need to be connected through the micro-USB connector. See my comments above for some things to try.

Maybe your usb cable just powers the device and doesnt support usb communication. This issue happens a lot with usb micro cable.

again Thanks so much!!!

you are on right, the cable was the problem.
Now i can conect via serial port and serial monitor works as espected but wwifi conectivity disapear and its a problem for query to sql.

i have reboot yun and nothing and when i rebut wlan reset appear again but disapear from serial so for me its NOT posible to have serial and wifi working together, here a screen view where you can see that have yun on port com7 but in tools only appear ip addres and when you try to open serial monitor say that com7 connectivity was lost........

well thanks for your help again!!

Well, again thanks to everyone for helping me!!!
for solve the problem with serial an wifi conectivity at the same time i have find one solution,it is not very clean but works....
Two PCs, one Pc is conected to the sql database and arduino yun via wifi and another Pc is conected to the arduino yun via USB micro cable and the Serial monitor and it works as espected :DDD
i just post this coment for share this solution. :DDD