Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
tutorials_devicehub [2016/12/16 04:16]
admin created
tutorials_devicehub [2017/04/01 06:50] (current)
admin [Sending Commands to the Nodes]
Line 3: Line 3:
 Data collected from the Wireless Sensor Nodes can be aggregated by the gateway and sent for processing and analysis to a Cloud platform. There is a large array of options for Cloud platforms, such as DeviceHub, ThingSpeak, SmartLiving,​ NimBits, Xively, etc. Data collected from the Wireless Sensor Nodes can be aggregated by the gateway and sent for processing and analysis to a Cloud platform. There is a large array of options for Cloud platforms, such as DeviceHub, ThingSpeak, SmartLiving,​ NimBits, Xively, etc.
  
-In this tutorial we will use DeviceHub to aggregate data from multiple Sparrow nodes and use their API to also send commands back to the nodes.+In this tutorial we will use [[https://​devicehub.net/​|DeviceHub]] to aggregate data from multiple Sparrow nodes and use their API to also send commands back to the nodes.
  
-===== DeviceHub =====+====== DeviceHub ​======
  
 +To gain access, you will need to first create an account on the platform. After registering and logging in, select Project > New Project, and give your project a name. Initially, your project will be assigned a Project ID and an API Key, which will serve to identify it on the platform.
  
-Pentru ​avea acces la resursetrebuie să vă creați mai întâi un cont pe platformăDupă înregistrare și crearea contuluiselectați Project > New Project și dați un nume proiectului vostruInițialproiectului i se vor atribui un Project ID și un API Keycare vor îl identifica unic pe platformă.+Next, you need to add new device to your projectby selecting Add DeviceName the deviceselect "​Other"​ from "​Device Type", "​Python"​ from "​Programming Language"​ and "​Ethernet"​ or "​WiFi"​ from Connection TypeAfter creationthe device will gain a Device UUID. Each device can have multiple sensors and actuatorswhich can be added through the web interface.
  
-Trebuie să adăugați un nou dispozitiv proiectului vostruselectând ​Add DeviceDați-i un numela Device Type selectați Other, la Programming Language Python și la Connection Type, Ethernet sau WiFi, după cazLa creare, dispozitivului i se va aloca un Device UUID, care este de asemenea unic. Fiecare dispozitiv poate avea mai mulți senzori și mai multe actuatoare, ce pot fi adăugate din interfața web.+For startersattach a new sensor to your device using the Add Sensor buttonName it "​Temperature"​sensor type should be "​Analogic"​ and fill in "degC" in the "​Measuring Unit" field.
  
-Pentru începutatașați un senzor nou dispozitivului vostru cu Add SensorDenumiți-l Temperaturetipul senzorului ar trebui să fie analogic, iar la measurement unit adăugați deg. C.+DeviceHub uses an API through which multiple IoT platforms can connect directly to its cloud services. As the Sparrow nodes do not have WiFi or Ethernet connectivitywe will first use PC as a DeviceHub clientThe Sparrow node will send data through the serial port to the PCand the PC will run a small Python script to parse incoming data and send them to DeviceHub.
  
-DeviceHub pune la dispoziție un API prin care diverse platforme IoT se pot conecta direct la server-ul din cloud. Din cauză că nodurile Sparrow nu au posibilitatea de a se conecta la WiFi sau Ethernet, vom folosi un PC pe post de client DeviceHub. Nodul Sparrow va trimite datele prin interfața serială către PC, iar acesta va rula un mic program scris în Python pentru a parsa datele primite și a le trimite DeviceHub. +You will need to install ​Python 2.7.x on your machine and also the devicehub ​library ​which can be easily done from the command line using pip:
- +
-Pentru aceasta, trebuie să vă instalați ​Python 2.7.x pe mașina voastră și biblioteca ​devicehub, ​care se poate face rapid din linia de comandă folosind utilitarul ​pip:+
  
  <​code>​ > pip install devicehub </​code>​  <​code>​ > pip install devicehub </​code>​
 +
 +===== Data Transmission =====
 +
 +Next, we will write a small Python program to send data into our DeviceHub account. Use as a reference the code below and fill in the PROJECT_ID, DEVICE_UUID and API_KEY fields with your own values:
 +
 +<code python>
 +from devicehub import Sensor, Device, Project
 +from time import sleep
 +from random import randint
 + 
 +PROJECT_ID ​     = 'your project ID'
 +DEVICE_UUID ​    = 'your Device UUID'
 +API_KEY ​        = 'your API KEY'
 +AN_SENSOR_NAME ​ = '​Temperature'​ #make sure your sensor has the same name on DeviceHub!
 + 
 + 
 +def analog_input(dev,​ sensor):
 +    value = randint(0, 1023)
 +    sensor.addValue(float(value.strip()))
 +    dev.send()
 +    print value
 +    return
 + 
 +project = Project(PROJECT_ID,​ ssl_verify=False)
 +device = Device(project,​ DEVICE_UUID,​ API_KEY)
 + 
 +AN1 = Sensor(Sensor.ANALOG,​ AN_SENSOR_NAME)
 + 
 +device.addSensor(AN1)
 + 
 +while True:
 +    analog_input(device,​ AN1)
 +    sleep(5.0)
 +    ​
 +</​code>​
 +
 +The code will send random data to your DeviceHub account, which you will be able to view in real-time. ​
 +
 +Now, let's send some real sensor data! We will program the sensor nodes to send temperature values through the serial interface, which will be further parsed by the Python code and sent to DeviceHub.
 +
 +First, let's test we are receiving data through the serial interface in our Python code. Program one Sparrow node to send temperature readings once every second through the serial port. Use the code below. If don't have all libraries installed, go back to this [[tutorials_temperature|this tutorial]].
 +
 +<code C>
 +**
 + * Temperature and humidity
 + *
 + * This example demonstrates the use of the Si7021 temperature and
 + * humidity sensor. It measures the temperature and the humidity,
 + * and prints them on the serial console every second.
 + * Before use, the sensor must be powered using pin 7. The sensor
 + * measurements are then read using the Sodaq_SHT2x library.
 + */
 +#include <​Sodaq_SHT2x.h> ​       // provides sensor protocol
 +#include <​Wire.h> ​              // provides communication channel
 +
 +#define powerPin 7              // sensor power controlled by pin 7
 +
 +// runs once, when the sketch starts
 +void setup()
 +{
 +  // power sensors, control is inverted, on when low
 +  pinMode(powerPin,​ OUTPUT);
 +  digitalWrite(powerPin,​ LOW);
 +
 +  Wire.begin(); ​                // init sensor communication channel
 +
 +  Serial.begin(9600); ​          // init serial console for display
 +}
 +
 +// runs over and over again
 +void loop()
 +{
 +  // get and print temperature in degrees Celsius
 +  float temp = SHT2x.GetTemperature();​
 +  Serial.println(temp);​
 +  ​
 +  delay(1000); ​                 // wait for 1 second
 +}
 +</​code>​
 +
 +Now, the node is sending temperature values every second on the serial port. Let's write a small Python code to read this data:
 +
 +<code python>
 +from time import sleep
 +import serial
 + 
 +# Make sure you have the correct port and baud rate selected
 +# For Windows, use COMx instead of ttyUSB
 +ser=serial.Serial('/​dev/​ttyUSB0',​ 9600) 
 + 
 +while True:
 +        line = ser.readline()
 +        print line
 +        sleep(1.0)
 +</​code>​
 +
 +If everything goes well, you will have temperature sensor data coming in every second and printed on the screen.
 +<code bash>
 +pi@raspberrypi:​~ $ python myserial.py ​
 +23.22
 +23.19
 +23.56
 +23.89
 +</​code>​
 +
 +Now, it's only a matter of combining the two python programs above in order to send everything to DeviceHub:
 +
 +<code python>
 +from devicehub import Sensor, Device, Project
 +from time import sleep
 +from random import randint
 +import serial
 + 
 +PROJECT_ID ​     = 'your project ID'
 +DEVICE_UUID ​    = 'your Device UUID'
 +API_KEY ​        = 'your API KEY'
 +AN_SENSOR_NAME ​ = '​Temperature'​ #make sure your sensor has the same name on DeviceHub!
 + 
 + 
 +def analog_input(dev,​ sensor, ser):
 +    value = ser.readline()
 +    sensor.addValue(value)
 +    dev.send()
 +    print value
 +    return
 + 
 +project = Project(PROJECT_ID,​ ssl_verify=False)
 +device = Device(project,​ DEVICE_UUID,​ API_KEY)
 + 
 +AN1 = Sensor(Sensor.ANALOG,​ AN_SENSOR_NAME)
 + 
 +device.addSensor(AN1)
 +
 +# Make sure you have the correct port and baud rate selected
 +# For Windows, use COMx instead of ttyUSB
 +ser=serial.Serial('/​dev/​ttyUSB0',​ 9600) 
 +  ​
 +while True:
 +    analog_input(device,​ AN1, ser)
 +    sleep(1.0)
 +    ​
 +</​code>​
 +
 +If everything goes well, you should now be able to see live temperature data in your DeviceHub account.
 +
 +{{ ::​temperature.png?​800 |}}
 +
 +===== Sending Commands to the Nodes =====
 +
 +We can also send commands back to the nodes through the DeviceHub API. We just need to add an Actuator to our device. Name the actuator LED and choose Digital in the Type field. We will use the RGB LED on the sensor node for easy feedback. ​
 +
 +Run the following Python code to read the state of the actuator from DeviceHub:
 +
 +<code python>
 +from devicehub import Sensor, Actuator, Device, Project
 +from time import sleep
 + 
 +PROJECT_ID ​     = 'your project ID'
 +DEVICE_UUID ​    = 'your Device UUID'
 +API_KEY ​        = 'your API KEY'
 +ACTUATOR_NAME1 ​ = '​LED'​ #make sure your actuator has the same name on DeviceHub!
 + 
 + 
 +def act1_callback(payload):​
 +    """​
 +    :param payload: mqtt payload message
 +    """​
 +    print ACT1.state
 + 
 +project = Project(PROJECT_ID)
 +device = Device(project,​ DEVICE_UUID,​ API_KEY)
 + 
 +ACT1 = Actuator(Actuator.DIGITAL,​ ACTUATOR_NAME1)
 + 
 +device.addActuator(ACT1,​ act1_callback)
 + 
 +try:
 +    while True:
 +        pass
 +except KeyboardInterrupt: ​          
 +    print '​Goodbye!'​
 +</​code>​
 +
 +{{ ::​actuators.png?​600 |}}
 +
 +Similarly, you can add an actuator with an Analog input to the DeviceHub interface. Let's add three of them and control the RGB LED on the Sparrow Node. Name them Red, Green and Blue and use the following code for testing: ​
 +
 +<code python>
 +from devicehub import Sensor, Actuator, Device, Project
 +from time import sleep
 +import serial
 + 
 +PROJECT_ID ​     = 'your project ID'
 +DEVICE_UUID ​    = 'your Device UUID'
 +API_KEY ​        = 'your API KEY'
 +AN1_SENSOR_NAME ​ = '​Red'​ #make sure your actuator has the same name on DeviceHub!
 +AN2_SENSOR_NAME ​ = '​Green'​ #make sure your actuator has the same name on DeviceHub!
 +AN3_SENSOR_NAME ​ = '​Blue'​ #make sure your actuator has the same name on DeviceHub! ​
 +
 +red = "​0"​
 +green = "​0"​
 +blue = "​0" ​
 +
 +def act1_callback(payload):​
 +    global red
 +    print ACT1.state
 +    red = str(ACT1.state)
 +
 +def act2_callback(payload):​
 +    global green
 +    print ACT2.state
 +    green = str(ACT2.state)
 +    ​
 +def act3_callback(payload):​
 +    global blue
 +    print ACT3.state
 +    blue = str(ACT3.state)
 +     
 +project = Project(PROJECT_ID)
 +device = Device(project,​ DEVICE_UUID,​ API_KEY)
 + 
 +ACT1 = Actuator(Actuator.ANALOG,​ AN1_SENSOR_NAME)
 +ACT2 = Actuator(Actuator.ANALOG,​ AN2_SENSOR_NAME)
 +ACT3 = Actuator(Actuator.ANALOG,​ AN3_SENSOR_NAME)
 +
 +device.addActuator(ACT1,​ act1_callback)
 +device.addActuator(ACT2,​ act2_callback)
 +device.addActuator(ACT3,​ act3_callback) ​
 +
 +# Make sure you have the correct port and baud rate selected
 +# For Windows, use COMx instead of ttyUSB
 +ser=serial.Serial('/​dev/​ttyUSB0',​ 9600) 
 +
 +try:
 +    while True:
 +        ser.write(red + ','​ + green + ','​ + blue + '​\n'​) #send RGB values as CSV
 +        sleep(1.0)
 +except KeyboardInterrupt: ​          
 +    print '​Goodbye!'​
 +    ​
 +</​code>​
 +
 +Now we need to write an Arduino sketch for the Sparrow node to read the CSV data from the serial port and refresh the color on the LED:
 +
 +<code C>
 +
 +// pins for the LEDs:
 +const int redPin = 8;
 +const int greenPin = 11;
 +const int bluePin = 10;
 +
 +void setup() {
 +  // initialize serial:
 +  Serial.begin(9600);​
 +  // make the pins outputs:
 +  pinMode(redPin,​ OUTPUT);
 +  pinMode(greenPin,​ OUTPUT);
 +  pinMode(bluePin,​ OUTPUT);
 +
 +}
 +
 +void loop() {
 +  // if there'​s any serial available, read it:
 +  while (Serial.available() > 0) {
 +
 +    // look for the next valid integer in the incoming serial stream:
 +    int red = Serial.parseInt();​
 +    // do it again:
 +    int green = Serial.parseInt();​
 +    // do it again:
 +    int blue = Serial.parseInt();​
 +
 +    // look for the newline. That's the end of your
 +    // sentence:
 +    if (Serial.read() == '​\n'​) {
 +      // constrain the values to 0 - 255 and invert
 +      // if you're using a common-cathode LED, just use "​constrain(color,​ 0, 255);"
 +      red = 255 - constrain(red,​ 0, 255);
 +      green = 255 - constrain(green,​ 0, 255);
 +      blue = 255 - constrain(blue,​ 0, 255);
 +
 +      // fade the red, green, and blue legs of the LED:
 +      analogWrite(redPin,​ red);
 +      analogWrite(greenPin,​ green);
 +      analogWrite(bluePin,​ blue);
 +
 +      // print the three numbers in one string as hexadecimal:​
 +      Serial.print(red,​ HEX);
 +      Serial.print(green,​ HEX);
 +      Serial.println(blue,​ HEX);
 +    }
 +  }
 +}
 +</​code>​