Example Using InfluxDB: Difference between revisions

From lechacal
Jump to navigation Jump to search
No edit summary
Line 48: Line 48:
  import time
  import time
  import datetime
  import datetime
 
 
  serial_port = "/dev/ttyAMA0"
  serial_port = "/dev/ttyAMA0"
  baud = 38400
  baud = 38400
 
  host = 'lenovo'
  host = 'lenovo'
  port = 8086
  port = 8086

Revision as of 13:36, 22 March 2017


UNDER CONSTRUCTION...


This is a basic example to forward data to an InfluxDB database. Note this will only cover a skeleton to start building your own application.

Prerequisites

The RPICT series board must output as CSV for this work.

Installation

Server side hosting InfluxDB

Install InfluxDB and Chronograf as recommended. This link provides compiled executables.

Github link is here.

We will call this server hostname myserver for our example below.

Raspberrypi side

Install the python biding to influxdb. Available from github here.

Do not be tempted by using apt-get install! Thsi will install an old version that does not work. Use pip or download the package from github and install using

sudo setup.py install

Check version using

python
import influxdb
print influxdb.__version__

Testing

Use some of the example from influxdb documentation to test the correct communication between the server and raspberrypi.

Also make sure you can access Chronograf by going to

http://myserver:8888

Python Script

The python script below should be a good starting point to forward any RPICT series data to influxdb.

Copy the content into a file on the raspberrypi and make it executable:

chmod 755 InfluxDB_forward.py

Make sure you modify the head parameters first.

#!/usr/bin/python
import time
import datetime


serial_port = "/dev/ttyAMA0"
baud = 38400

host = 'lenovo'
port = 8086
DBNAME = 'mydb'
USER = 'root'
PASSWORD = 'root'

import serial
ser = serial.Serial(serial_port, baud, timeout=1)

from influxdb import InfluxDBClient
client = InfluxDBClient(host, port, USER, PASSWORD, DBNAME)

try:
       while 1:
                response = ser.readline()
                Z = response.split(",")
                if len(Z)>=2:
                        now = datetime.datetime.today()
                        i = 0
                        points = []
                        for z in Z:
                                i += 1
                                point = {
                                        "measurement":'ch%02d'%i,
                                        "time": 1000000000*int(now.strftime('%s')),
                                        "fields": {
                                                "value":float(Z[0])
                                        }
                                }
                                points.append(point)

                        client.write_points(points)

except KeyboardInterrupt:
       ser.close()