การประยุกต์ใช้งาน thingspeak ในแบบต่างๆ นอกเหนือจากแค่เก็บข้อมูลจาก iot


  Thingspeak เป็น cloud ที่ถูกออกแบบสำหรับเก็บข้อมูลของอุปกรณ์ IOT(internet of things) เป็นบริการฟรีที่มีข้อจำกัด  เช่น การเก็บข้อมูลของ arduino , raspberry pi เป็นต้น ไม่เป็นแค่เก็บข้อมูลเท่านั้น ยังสามารถแสดผลข้อมูลที่เก็บเป็นกราฟ หรือ export ข้อมูลเพื่อทำไปใช้ต่อได้ จริงๆ มันไม่เพียงเก็บข้อมูลเฉพาะพวก iot แต่ยังเก็บข้อมูลของ server ได้อีก บทความนี้เราจะแสดงตัวอย่างว่าเราสามารถนำ thingspeak ไปประยุกต์ใช้ได้อย่างไรบ้าง

1.การส่งข้อมูลจาก arduino หรือ nodemcu ขึ้นไปเก็บ

2.การส่งข้อมูลจาก raspberry pi ขึ้นไปเก็บ

3.การส่งข้อมูลจาก server linux ขึ้นไปเก็บ

4.การส่งข้อมูลจาก server windows ขึ้นไปเก็บ

5.การนำกรา่ฟจาก thinspeak มาแสดงทีหน้าเว็บของตัวเอง

6.การนำข้อมูลจาก thingspeak มาแสดงผลบน google chart แบบ gauge

7.การนำข้อมูลจาก thingspeak มาแสดงผลด้วย PHP 


/////////////////////////////////////////////////////////////////////////////

1.การส่งข้อมูลจาก arduino หรือ nodemcu ขึ้นไปเก็บ ด้วยภาษา C++

ตัวอย่างใช้ nodemcu รับค่าจาก sensor อุณหภูมิ  DS18B20

/////////////////////////
#include "ThingSpeak.h"
#include <ESP8266WiFi.h>
#include <OneWire.h>
#include <DallasTemperature.h>

const char* ssid     = "ssid"; //Set Wifi SSID
const char* password = "password";//Set Wifi password
WiFiClient client;

// Variable Setup
unsigned long myChannelNumber = 22xxxx;
const char * myWriteAPIKey = "xxxxxxxxx";

#define ONE_WIRE_BUS D5
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

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

  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  sensors.begin();
  ThingSpeak.begin(client);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}


void loop() {
  Serial.print(" Requesting temperatures...");
  sensors.requestTemperatures(); // Send the command to get temperatures
  Serial.println("DONE");

  float temp = sensors.getTempCByIndex(0);

  Serial.print("Temperature for Device 1 is: ");
  Serial.print(temp);
  Serial.println(" *C");

  ThingSpeak.writeField(myChannelNumber, 1, temp, myWriteAPIKey);
  delay(30000);
}


/////////////////////

2.การส่งข้อมูลจาก raspberry pi ขึ้นไปเก็บ ด้วยภาษา python

ตัวอย่างคือ raspberry pi รับค่าอุณหภูมิความชื้นจาก DHT11
////////
import RPi.GPIO as GPIO
import os
from time import sleep
import Adafruit_DHT
import urllib2



DEBUG = 1
# Setup the pins we are connect to
RCpin = 24
DHTpin = 23

#Setup our API and delay
myAPI = "thingspeak_api_key"
myDelay = 15 #how many seconds between posting data

GPIO.setmode(GPIO.BCM)
GPIO.setup(RCpin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)



def getSensorData():
    RHW, TW = Adafruit_DHT.read_retry(Adafruit_DHT.DHT11, DHTpin)
 
    #Convert from Celius to Farenheit
    TWF = 9/5*TW+32
 
    # return dict
    return (str(RHW), str(TW),str(TWF))

def RCtime(RCpin):
    LT = 0
 
    if (GPIO.input(RCpin) == True):
        LT += 1
    return (str(LT))
 
# main() function
def main():
 
    print 'starting...'

    baseURL = 'https://api.thingspeak.com/update?api_key=%s' % myAPI
    print baseURL
 
    while True:
        try:
            RHW, TW, TWF = getSensorData()
            LT = RCtime(RCpin)
            f = urllib2.urlopen(baseURL +
                                "&field1=%s&field2=%s&field3=%s" % (TW, TWF, RHW)+
                                "&field4=%s" % (LT))
            print f.read()
            print TW + " " + TWF+ " " + RHW + " " + LT
            f.close()
         

            sleep(int(myDelay))
        except:
            print 'exiting.'
            break


////////////

3.การส่งข้อมูลจาก server linux ขึ้นไปเก็บ  ด้วยภาษา python
   คล้ายๆ กับข้อ 4 แต่ตั้งเวลาการทำงานโดยใช้ crontab แทน

4.การส่งข้อมูลจาก server windows ขึ้นไปเก็บ ด้วยภาษา python
   ตัวอย่างนี้เป็นการส่งค่า cpu , mem ,disk ของ server เป็นเก็บไว้บน thingspeak  โดยการติดตั้ง python ลงบน server windows แล้วตั้งค่า scheduled task ให้ทำงานอ่านโปรแกรม python ที่เราเขียน ตามเวลาที่กำหนด

/////////// python /////////////
 #!/usr/bin/env python
import psutil
import httplib, urllib
import time
import os,sys
import netifaces as ni
import requests
from subprocess import call
import socket
import urllib
import urllib2

used = psutil.disk_usage("C:/").percent
sleep = 60 # how many seconds to sleep between posts to the channel
key = 'thing_speak_api_key'  # Thingspeak channel to update
ip = socket.gethostbyname(socket.gethostname())


def thermometer():
    while True:
       temp
cpu = psutil.cpu_percent()
        mem = psutil.virtual_memory().used/1000000
        temp = 50
        mem_percent = (psutil.virtual_memory().used*100/psutil.virtual_memory().total)
#d=$(df -h | awk '$NF=="/"{printf "%d/%d\n", $2,$3,$5}')
        params = urllib.urlencode({'field1':cpu ,'field2':mem,'field3':used,'field4':mem_percent,'key':key})
        headers = {"Content-typZZe": "application/x-www-form-urlencoded","Accept": "text/plain"}
        conn = httplib.HTTPConnection("api.thingspeak.com:80")
        try:
            conn.request("POST", "/update", params, headers)
            response = conn.getresponse()
   print cpu
            print used
    print response.status, response.reason
            data = response.read()
            conn.close()
        except:
            print "connection failed",sys.exc_info()
        break
#sleep for desired amount of time
if __name__ == "__main__":
        #while True:
        thermometer()
        # time.sleep(sleep)


///////////////////////////


5.การนำกรา่ฟจาก thinspeak มาแสดงทีหน้าเว็บของตัวเอง 
  ให้เลือกที่กราฟ จะมีเหมือนไอค่อนรูปคำพูด ให้คลิ๊กเข้าไป แล้ว copy iframe ทั้งหมดมาแปะที่หน้า html ของเรา ตัวอย่าง

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Monitor Server Room 2017</TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
</HEAD>
<style type="text/css">
  body { background-color: #ffffff; }
</style>


<BODY>
<h1 align="center">Monitor temp & humidity </h1>
<table align="center">
<tr algin="center">
 <td align="center"><iframe width="450" height="300" style="border: 1px solid #cccccc;" src="https://thingspeak.com/channels/25xxx/charts/1?bgcolor=%23ffffff&color=%23d62020&dynamic=true&results=60&title=temp_sapa&type=line"></iframe></td>
  <td align="center"><iframe width="450" height="300" style="border: 1px solid #cccccc;" src="https://thingspeak.com/channels/244xxxx/charts/2?bgcolor=%23ffffff&color=%23d62020&dynamic=true&results=60&title=Humidity_kasarb&type=line"></iframe></td>
  </tr>
 </table>

</BODY>
</HTML>


6.การนำข้อมูลจาก thingspeak มาแสดงผลบน google chart แบบ gauge

    ใช้ code นี้ได้เลยครับ เพียงแค่เปลี่ยนเลข channel เป็นของเรา และเลือก filed ที่เราต้องการจะแสดง

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<head>

  <title>Google Gauge - ThingSpeak</title>
<style type="text/css">
  body { background-color: #ffffff; }
</style>

<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js'></script>
<script type='text/javascript' src='https://www.google.com/jsapi'></script>
<script type='text/javascript'>

var chart;
var charts;
var data;

      google.load('visualization', '1', {packages:['gauge']});
      google.setOnLoadCallback(initChart);

function displayData(point) {

data.setValue(0, 0, 'Temp');
data.setValue(0, 1, point);
chart.draw(data, options);

}

function loadData() {

// variable for the data point
var p;
       //เปลี่ยนแค่เลข channel
$.getJSON('https://api.thingspeak.com/channels/24xxxx/feed/last.json?callback=?', function(data) {

// get the data point
p = data.field1;   // เลือก filed ที่ต้องการ

if (p)
{
//p = Math.round((p / 1023) * 100);
displayData(p);
}

});

}

function initChart() {

data = new google.visualization.DataTable();
data.addColumn('string', 'Label');
data.addColumn('number', 'Value');
data.addRows(1);
     
       chart = new google.visualization.Gauge(document.getElementById('chart_div'));
       options = {width: 320, height: 320, redFrom: 40, redTo: 100,
           yellowFrom:25, yellowTo: 40, minorTicks: 5};

loadData();

setInterval('loadData()', 1500);
     
}

</script>
  <body>
    <div id='chart_div' align="center"></div>
  </body>
</html>
</HTML>



7.การนำข้อมูลจาก thingspeak มาแสดงผลด้วย PHP
   ตัวอย่าง   เราเก็บข้อมูล อุณหภูมิและความชื้นไว้ที่ thingspeak โดยสร้างเป็น 2 filed เราสามารถดึงข้อมูลล่าสุดมาแสดงผลได้ด้วย code ข้างล่างนี้ครับ

<?php

 $temp = file_get_contents('https://api.thingspeak.com/channels/24xxxx/fields/1/last.txt');
$humidity = file_get_contents('https://api.thingspeak.com/channels/24xxx/fields/2/last.txt');

 echo "temp is = ".$temp."<br>";
 echo "humidity is = ".$humidity;

?>




ความคิดเห็น

โพสต์ยอดนิยมจากบล็อกนี้

แจ้งเตือนเข้าไลน์กลุ่ม ผ่าน Line notify เมื่อมีคน login เข้า server ของเราผ่าน SSH (linux) หรือ remote desktop เข้ามา (windows server)

การทำ cloud iot ด้วย thingsboard ไว้ใช้เองครับ

การประยุกต์ใช้ line notify ในการแจ้งปัญหาการใช้งาน สำหรับ php