Example projects

How about some examples ?

In this section we have something good. Several examples whose proposal show the possibilities of using Cloud Guardian. All examples can be found in GitHub.

We will explain how to assemble and use such examples, including not only with examples Arduino, but also examples using other languages and platforms. Our examples are always up to date, so we follow the GitHub or at Facebook.

If desired, the libraries used in the project can be downloaded via the link: libraries

Example with Arduino

Arduino Data Collection Ethernet + DHT11

Temperature sensor / humidity

This example consists of a UNO Arduino, having an Ethernet shield coupled to connect to the Internet and DHT11 sensor to collect temperature information and humidity environment. We can apply this example to monitor changes in temperature and humidity, in an attempt to generate alerts in adverse situations.

#include <dht.h>
#include <SPI.h>
#include <Ethernet.h>

#define DHTPIN 7 //port connected to DHT11
static char apiKey[] = "xxxxxxxx-yyyy-zzzz-wwww-kkkkkkkkkkkk";
static char serial[] = "IOTWBS0001";

dht DHT;
EthernetClient client;

signed long next;
unsigned long frequencyTime = 60000; //Time will be read and sent values (1 min.).
static byte mac[] = { 0xDE, 0xAD, 0x09, 0xEF, 0xFE, 0xED }; // Mac address
static char serverName[] = "guardiao.cl";//DO NOT CHANGE THIS VALUE - URL Cloud Guardian

void setup() {
Serial.begin(9600);
Ethernet.begin(mac); //IP automatic
next = 0;
}

void loop() {
if (((signed long)(millis() - next)) > 0)
{
  Serial.println(F("Coletando...")); 
  next = millis() + frequencyTime;
  char temp[6] PROGMEM;
  char hum[6] PROGMEM;
  int chk = DHT.read11(DHTPIN); //It is possible to use other sensors DHT necessary to switch the call.
  if(chk == DHTLIB_OK){  
    dtostrf(DHT.temperature, 1, 2, temp);
    dtostrf(DHT.humidity, 1, 2, hum);
  }
  else{
    temp[0] = '0';
    hum[0] = '0';
  }
  char queryString[128];
  char outBuf[128];
  char host[64];

  if (client.connect(serverName, 80)) 
  {
    sprintf(queryString,"apiKey=%s&temperature=%s&humidity=%s",apiKey, temp,hum);
    sprintf(outBuf,"GET /collect/%s/?%s HTTP/1.1",serial,queryString);
    client.println(outBuf);
    sprintf(host,"Host: %s",serverName);
    client.println(host);
    client.println("User-Agent: arduino-ethernet");
    client.println("Connection: close");
    client.println();
    client.stop();
  }
  else
  {
    Serial.println(F("Connection failure"));
  } 
}

}

To download this code, please visit: guardiaocl-coleta

The list of materials for this example:

  • Arduino UNO or compatible
  • Shield Ethernet - Chip Wiznet W5100
  • Temperature sensor DHT11 -Wires (Male-Female)

For DHT11 connection with Arduino, and the proposed example, the connection may be made in the following way:

Port Arduino connection
S Digital 7
- GND
+ 5V

Arduino Data Collection with Ethernet + DHT11 + Display LCD 16x2

Arduino DHT11 DISPLAY

The spread of this assembly relative to the previous one, is that we add a 16x2 LCD diplay to display the information for users. It may be a detail that makes all the difference.

#include <dht.h>
#include <SPI.h>
#include <Ethernet.h>
#include <LiquidCrystal_I2C.h>
#include <Wire.h>

#define DHTPIN 7 //port connected to DHT11
static char apiKey[] = "xxxxxxxx-yyyy-zzzz-wwww-kkkkkkkkkkkk"; //@Change all for Key Project API.
static char serial[] = "IOTWBS0001"; //@Change all to Serial Device.

dht DHT;
EthernetClient client;
LiquidCrystal_I2C lcd(0x27,16,2);

signed long next;
unsigned long frequencyTime = 60000; //Time frequency to be read and sent values (1 min.).
static byte mac[] = { 0xDE, 0xAD, 0x09, 0xEF, 0xFE, 0xED }; // MAC address, switch if you have various
static char serverName[] = "guardiao.cl"; //DO NOT CHANGE THIS VALUE
static byte termometru[8] = //icon to temperature
{
  B00100,
  B01010,
  B01010,
  B01110,
  B01110,
  B11111,
  B11111,
  B01110
};

static byte picatura[8] = //icon humidity
{
  B00100,
  B00100,
  B01010,
  B01010,
  B10001,
  B10001,
  B10001,
  B01110,
};

void setup() {
  lcd.init();
  lcd.clear();
  lcd.backlight(); 
  lcd.print(F("System Starting"));
  lcd.setCursor(0, 1);
  lcd.print(F("Guardiao Cloud"));
  lcd.createChar(1,termometru);
  lcd.createChar(2,picatura);

  Ethernet.begin(mac); //IP Automatic
  next = 0;
}

void loop() {
  if (((signed long)(millis() - next)) > 0)
  {
    next = millis() + frequencyTime;
    char temp[6] PROGMEM;
    char hum[6] PROGMEM;
    float temperature = 0;
    float humidity = 0;
    int chk = DHT.read11(DHTPIN); //Sensor reading DHT11
    if(chk == DHTLIB_OK){  
      temperature = DHT.temperature;
      humidity = DHT.humidity;
      dtostrf(temperature, 1, 2, temp);
      dtostrf(humidity, 1, 2, hum);
    }
    else{
      temp[0] = '0';
      hum[0] = '0';
    }
    char queryString[128];
    char outBuf[128];
    char host[64];

    lcd.clear();
    lcd.setCursor(0, 0);  
    lcd.print(F("Serie - "));
    lcd.print(serial);
    lcd.setCursor(1, 1);  
    lcd.write(1);
    lcd.setCursor(3, 1);
    lcd.print((float)temperature,0);
    lcd.setCursor(5, 1);
    lcd.print((char)223); //sinal de graus
    lcd.print(F("C"));

    lcd.setCursor(9, 1);
    lcd.write(2);
    lcd.setCursor(11, 1);
    lcd.print((float)humidity,0);
    lcd.print(F("%"));

    if (client.connect(serverName, 80)) 
    {
      sprintf(queryString,"apiKey=%s&temperatura=%s&humidade=%s",apiKey, temp,hum);
      sprintf(outBuf,"GET /collect/%s/?%s HTTP/1.1",serial,queryString);
      client.println(outBuf);
      sprintf(host,"Host: %s",serverName);
      client.println(host);
      client.println("User-Agent: arduino-ethernet");
      client.println("Connection: close");
      client.println();
      client.stop();
    }
    else
    {
      Serial.println(F("Connection failure"));
    } 
  }

}

To download this code, please visit: guardiaocl-coleta

The list of materials for this example:

  • Arduino UNO or compatible
  • Shield Ethernet - Chip Wiznet W5100
  • Temperature sensor DHT11
  • Wires (Male-Female)
  • Display I2C - LCD 16x2

For DHT11 connection with Arduino, and the proposed example, the connection may be made in the following way:

Port Arduino connection
S Digital 7
- GND
+ 5V

And to connect the display 16x2, the connection can be made according to the scheme below:

Port Arduino connection
SDA Analógico 4
SCL Analógico 5
GND GND
VCC 5V

Data collection with DHT11 and sending through MQTT

Temperature sensor / humidity

This example is composed of an Arduino UNO, having an Ethernet Shield coupled to connect to the Internet, the data is sent through MQTT, with the collection of a DHT11 sensor for temperature information and humidity of the environment. We can apply this example to monitor changes in temperature and humidity, in an attempt to generate alerts in adverse situations.

#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
#include <dht.h>

#define DHT11_PIN 7

byte mac[]    = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
byte server[] = { 54,175,116,131 }; //Concerning the IP guardiao.cl

void callback(char* topic, byte* payload, unsigned int length) {

}

EthernetClient ethClient;
PubSubClient client(server, 1883, callback, ethClient);
dht DHT;

float tempC = 0.0;
float humidity = 0.0;

String clientName = String("IOTWBS0001");
String topicName = String("IOTWBS/collect/IOTWBS0001"); //Project prefix + Collection Canal + Serial Device

void setup()
{
  Ethernet.begin(mac);
  Serial.begin(9600);
}

void loop()
{
  char clientStr[34];
  clientName.toCharArray(clientStr,34);
  char topicStr[26];
  topicName.toCharArray(topicStr,26);
  //Lendo dados do sensor
  DHT.read11(DHT11_PIN);
  humidity = (float)DHT.humidity;
  tempC = (float)DHT.temperature;

  if (!client.connected()) {
    client.connect(clientStr,"suporte@webonesystem.com.br","497aa991-d8e6-4bb6-ad17-f01a13648333");
  }
  if (client.connected() ) {
    String json = buildJson();
    char jsonStr[200];
    json.toCharArray(jsonStr,200);
    boolean pubresult = client.publish(topicStr,jsonStr);
    if (pubresult)
      Serial.println("successfully sent");
    else
      Serial.println("unsuccessfully sent");
  }
  delay(5000);
}

String buildJson() {
  String data = "{";
  data+="\n";
  data+= "\"data\": {";
  data+="\n";
  data+="\"temperature\": ";
  data+=(int)tempC;
  data+= ",";
  data+="\n";
  data+="\"humidity\": ";
  data+=(int)humidity;
  data+="\n";
  data+="}";
  data+="\n";
  data+="}";
  return data;
}

To download this code, please visit: guardiaocl-coleta-mqtt

The list of materials for this example:

  • Arduino UNO or compatible
  • Shield Ethernet - Chip Wiznet W5100
  • DHT11 Temperature Sensor
  • Wires (Male-Female)

For DHT11 connection with Arduino, and the proposed example, the connection may be made in the following way:

Port Arduino connection
S Digital 7
- GND
+ 5V

Exemplo com Python

Data collection with DHT11 + Console Reading (Python)

There is another possible assembly to be made for people who do not have Ethernet Shield and want to read the data from the sensor DHT11 to send to the Cloud Guardian. Connecting the Arduino, and writing the data collection in console, you can use Python to read console and send such information.

To download this code, please visit: python-serialport-guardiao

The list of materials for this example:

  • Arduino UNO or compatible
  • DHT11 Temperature Sensor
  • Wires (Male-Female)

For DHT11 connection with Arduino, and the proposed example, the connection may be made in the following way:

Port Arduino connection
S Digital 7
- GND
+ 5V

In linux to facilitate the process run the installation commands the pip and pyserial.

#Installation codes.
sudo apt-get install python-pip
sudo pip install pyserial

For the Arduino, you only need to put the system to write on the island, in a pattern that Python can convert and send the data.

//Arduino code
#include <dht.h>
dht DHT;
#define DHT11_PIN 7

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

void loop()
{
  int chk = DHT.read11(DHT11_PIN);
  Serial.print(DHT.humidity);
  Serial.print("|");
  Serial.println(DHT.temperature);
  delay(60000);
}

Create a Python script (coleta.py), use the code to the side and then run with python coleta.py:

#Code Python
import serial
import urllib2
__author__ = 'Guardiao Cloud'

apiKey = "xxxxxxxx-yyyy-zzzz-wwww-kkkkkkkkkkkk" #@all Change Number of API Key
serialKey = "IOTWBS0001" #@Change all serial number of the collection device
serialPort = '/dev/ttyS0' #@Change all the way Arduino Serial port

if __name__ == '__main__':
    ser = serial.Serial(serialPort, 9600)
    while True:
        arduinoRead = ser.readline()
        arduinoRead = arduinoRead.replace('\n','').replace('\r','')
        listaVal = arduinoRead.split("|")
        param = "apiKey={0}&humidade={1}&temperatura={2}".format(apiKey,listaVal[0],listaVal[1])
        url = "http://guardiao.cl/collect/{0}/?{1}".format(serialKey,param)
        print urllib2.urlopen(url).read()

Collecting data with SNMP GET

In order to show that the Cloud Guardian, allows you to receive data from any source and format, we will show some examples of how we can use SNMP (Simple Network Management Protocol), to carry out the data collection.

In the example below, we monitor the LA (Load Average) of a Linux box, which will be sent for monitoring. May, for example, such information see the use of a machine and generate warning before the machine will cause locking.

To download this code, please visit: python-snmpget-guardiao

#Installation codes.
sudo apt-get install python-pip
sudo pip install pysnmp pysnmp-mibs
#Código Python
import urllib2,time
from pysnmp.entity.rfc3413.oneliner import cmdgen

__author__ = 'Guardiao Cloud'

apiKey = "xxxxxxxx-yyyy-zzzz-wwww-kkkkkkkkkkkk" #@all Change Number of API Key
serialKey = "IOTWBS0001" #@Change all serial number of the collection device
checkedTime = 60  #Time in seconds collection and transmission of informations

snmpPort = 161 #@Change all SNMP port
snmpIP = '127.0.0.1' #@Change all IP of the machine with SNMP
snmpCommunity = 'public' #@Change all default SNMP community

#containing map the oid=nomeEnvio
mapaGuardiao = {}
mapaGuardiao['.1.3.6.1.4.1.2021.10.1.3.1'] = 'load1min'  #Chave 1
mapaGuardiao['.1.3.6.1.4.1.2021.10.1.3.2'] = 'load5min'  #Chave 2
mapaGuardiao['.1.3.6.1.4.1.2021.10.1.3.3'] = 'load15min'  #Chave 3

if __name__ == '__main__':
    while True:
        cmdGen = cmdgen.CommandGenerator()
        errorIndication, errorStatus, errorIndex, varBinds = cmdGen.getCmd(
            cmdgen.CommunityData(snmpCommunity, mpModel=0),
            cmdgen.UdpTransportTarget((snmpIP, snmpPort)),
            cmdgen.MibVariable('.1.3.6.1.4.1.2021.10.1.3.1'),  #Even value of Key  1
            cmdgen.MibVariable('.1.3.6.1.4.1.2021.10.1.3.2'),  #Even value of Key  2
            cmdgen.MibVariable('.1.3.6.1.4.1.2021.10.1.3.3'),  #Even value of Key  3

        )

        if errorIndication:
            print(errorIndication)
        else:
            if errorStatus:
                print('%s at %s' % (
                    errorStatus.prettyPrint(),
                    errorIndex and varBinds[int(errorIndex)-1] or '?'
                    )
                )
            else:
                valorEnvio = ""
                for name, val in varBinds:
                    chave = mapaGuardiao["."+name.prettyPrint()] #Making a parse-based key generation for URL
                    valor = val.prettyPrint()
                    valorEnvio += "{0}={1}&".format(chave,int(valor))
                url = "http://guardiao.cl/collect/{0}/?{1}apiKey={2}".format(serialKey,valorEnvio,apiKey)
                print urllib2.urlopen(url).read()
        time.sleep(checkedTime)

In linux to facilitate the process run the installation commands the pip and pysnmp pysnmp-mibs.

Create a Python script (coleta.py), use the code to the side and then run with python coleta.py.

Collecting data with SNMP WALK

The example below shows how to use SNMP Walk, for traffic of network interfaces of a particular machine. The system will perform a first collection, and after a time X, hold a second collection to get the amount of traffic.

To download this code, please visit: python-snmpwalk-guardiao

#Installation codes.
sudo apt-get install python-pip
sudo pip install pysnmp pysnmp-mibs
#Code Python
import urllib2,time
from pysnmp.entity.rfc3413.oneliner import cmdgen
from pysnmp.smi import builder, view

__author__ = 'Guardiao Cloud'

mibBuilder = builder.MibBuilder().loadModules('IP-MIB')
mibView = view.MibViewController(mibBuilder)

apiKey = "xxxxxxxx-yyyy-zzzz-wwww-kkkkkkkkkkkk" #@all Change Number of API Key
serialKey = "IOTWBS0001" #@Change all serial number of the collection device
checkedTime = 5

snmpPort = 161 #@Change all SNMP port
snmpIP = '127.0.0.1' #@Change all IP of the machine with SNMP
snmpCommunity = 'public' #@Change all default SNMP community
snmpInterface = 'eth0' #@Change all network interface that want to monitor

lastValueIn = 0
lastValueOut = 0
valorRef = False
tempoIncial = time.time()

if __name__ == '__main__':
    while True:
        cmdGen = cmdgen.CommandGenerator()
        errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.nextCmd(
            cmdgen.CommunityData(snmpCommunity, mpModel=0),
            cmdgen.UdpTransportTarget((snmpIP, snmpPort)),
            cmdgen.MibVariable('IF-MIB', 'ifDescr'),
            cmdgen.MibVariable('IF-MIB', 'ifInOctets'),
            cmdgen.MibVariable('IF-MIB', 'ifOutOctets'),
        )

        if errorIndication:
            print(errorIndication)
        else:
            if errorStatus:
                print('%s at %s' % (
                    errorStatus.prettyPrint(),
                    errorIndex and varBindTable[-1][int(errorIndex)-1] or '?'
                    )
                )
            else:
                for varBindTableRow in varBindTable:
                    controle = False
                    consumoIn = 0
                    consumoOut = 0
                    for oid, val in varBindTableRow:
                        if val.prettyPrint() == snmpInterface and controle == False :
                            controle = True
                        if controle:
                            oid, label, suffix = mibView.getNodeName(oid)
                            oidLabel = label[len(label)-1]
                            if(oidLabel == 'ifInOctets'):
                                actualInVal = float(val.prettyPrint())
                                consumoIn = (((lastValueIn - actualInVal) * 8)/(tempoIncial - time.time()))/1024
                                lastValueIn = float(val.prettyPrint())
                            if(oidLabel == 'ifOutOctets'):
                                actualOutVal = float(val.prettyPrint())
                                consumoOut = (((lastValueOut - actualOutVal) * 8)/(tempoIncial - time.time()))/1024
                                lastValueOut = float(val.prettyPrint())
                if valorRef == True :
                    valorEnvio = "bandwidthEntrada={0}&bandwidthSaida={1}".format(int(round(consumoIn)),int(round(consumoOut)))
                    url = "http://guardiao.cl/collect/{0}/?apiKey={1}&{2}".format(serialKey,apiKey,valorEnvio)
                    print urllib2.urlopen(url).read()
                valorRef = True
        time.sleep(checkedTime)
        tempoIncial = time.time()

In linux to facilitate the process run the installation commands the pip and pysnmp pysnmp-mibs.

Create a Python script (coleta.py), use the code to the side and then run with python coleta.py.