IoThook IoT Device Dashboard

What is IOT?

The Internet of things (IoT) describes physical objects (or groups of such objects) with sensors, processing ability, software and other technologies that connect and exchange data with other devices and systems over the Internet or other communications networks. Internet of things has been considered a misnomer because devices do not need to be connected to the public internet, they only need to be connected to a network and be individually addressable. <https://en.wikipedia.org/wiki/Internet_of_things>

internet-of-things.png

What is IOTHOOK?

IoThook is a web service network project that transfers data between internet-connected objects (IoT, IIoT). IoThook connects Arduino, Raspberry Pi, Android, iOS, Windows Phone, Website, Banana Pi, Orange Pi, Beaglebone, ARM, Pic, Windows, Mac OS X, and Linux based systems. It supports HTTP and MQTT protocols. With IoThook, you can send and receive data via HTTP and MQTT, and record data. IoThook is open source. <https://iothook.com/>

iothook.png

Why IoThook?

  • IoThook is free,

  • IoThook is Open Source,

  • IoThook is fast (HTTP and MQTT),

  • You can create Unlimited Devices,

  • You can add Unlimited Sensors,

  • You can easily send data with all your devices. (HTTP Post, HTTP Get, MQTT Publish),

  • You can easily get data from all iot devices (HTTP Post, HTTP Get, MQTT Subscribe),

  • You can monitor your data in real time,

  • You can create real-time graphs for your data,

IoThook is an internet-connected object that seamlessly transfers data between all your devices. It supports communication protocols that it can easily reach.

It integrates with ChartJS to monitor data in real time.

IoThook allows you to write your own Python scripts with fx function support. (Beta)

iothook-dashboard-img.png

Add New Device

IoThook; created to enable data transmission between internet-connected objects is a web service. The device and other iot systems can share data and operate by triggering each other.

You must be a member to use IoThook web services.

After the membership step, the ‘Add Device’ screen is entered via the administration panel. Add Device screens are divided into HTTP and MQTT. Continue by choosing the appropriate one according to the working protocol of your IoT device.

Add HTTP Device

The steps to add HTTP Device are as follows:

  • Log in to your DEMO account with the free login button, if you already have an account, log in.

  • Add HTTP Device button is click.

  • Name: Enter device name. To remember, the Home Guest Room can be named like Temperature.

  • 1.Field Type: Select Field Type (First field is required)

  • 1.Field Name: Enter a field name (First field is required)

  • 2-8.Field Type: Select Field Type (Optional)

  • 2-8.Field Name: Enter a field name (Optional)

  • Label(s): Label(s) write please (Optional)

  • Website address: Please Website address.

  • Git Website address: Git Website address, for source code.

  • Show Location: The incoming data source is shown on the map.

  • Video address: Video URL address, If there is a promotional video, the address is written.

  • Description: Detailed description of the project can be written.

  • Enable: Active/Passive setting of the device is provided here.

  • Response: Response detail Enable/Disable (Return record ID is response False, else return all field value and timestamp)

  • Is Public: Share Device and data.

HTTP Device Add Sensor

For IoT systems, you must create the data fields you want to exist. Start importing data into these fields is added for. At least 1 field must be added. Sensors can be named as Humidity, Heat, Oxygen, Wind.

  • 1.Field Type: Select Field Type (First field is required)

  • 1.Field Name: Enter a field name (First field is required)

  • 2-8.Field Type: Select Field Type (Optional)

  • 2-8.Field Name: Enter a field name (Optional)

Add MQTT Device

The steps to add MQTT Device are as follows:

  • Log in to your DEMO account with the free login button, if you already have an account, log in.

  • Add MQTT Device button is click.

  • Name: Enter device name. To remember, the Home Guest Room can be named like Temperature.

  • 1.Field Type: Select Field Type (First field is required)

  • 1.Field Name: Enter a field name (First field is required)

  • 2-8.Field Type: Select Field Type (Optional)

  • 2-8.Field Name: Enter a field name (Optional)

  • Label(s): Label(s) write please (Optional)

  • Website address: Please Website address.

  • Git Website address: Git Website address, for source code.

  • Show Location: The incoming data source is shown on the map.

  • Video address: Video URL address, If there is a promotional video, the address is written.

  • Description: Detailed description of the project can be written.

  • Enable: Active/Passive setting of the device is provided here.

  • Response: Response detail Enable/Disable (Return record ID is response False, else return all field value and timestamp)

  • Is Public: Share Device and data.

MQTT Device Add Sensor

For IoT systems, you must create the data fields you want to exist. Start importing data into these fields is added for. At least 1 field must be added. Sensors can be named as Humidity, Heat, Oxygen, Wind.

  • 1.Field Type: Select Field Type (First field is required)

  • 1.Field Name: Enter a field name (First field is required)

  • 2-8.Field Type: Select Field Type (Optional)

  • 2-8.Field Name: Enter a field name (Optional)

Send Data

HTTP Send Data

To send data, you must first add a device. Special read and write “API KEY” when the device is created Data processing is performed according to the access method (POST, GET, POST/GET) that is generated and determined.

For example; Let our device be in a structure that receives humidity, heat and light values. For this example, the device named “#100 - Demo Data HTTP” was created on iothook.com. IoThook .

Let the IoT device read the data from the sensors and send this data to us once every 15 seconds, a total of 100 times.

You can access the read and write API Keys created for the #100 iot device from the IoThook dashboard.

The API ENDPOINT address we will use to send data to IoThook servers with Python is https://iothook.com/api/update/. Writing api_key information is needed to send data. You can access this KEY from the device settings page.

There are 2 required fields to send data. These fields are api_key and field_1 fields. APIKEY your device ownership field_1 absolutely must be because it validates and must have at least one data field. Other fields defined even if they are not sent, they are recorded as None.

Send JSON Data in POST with Python

In this example, JSON data is sent to the device channel named “#100 - Demo Data HTTP” using the HTTP POST method with Python. When the data is sent successfully, Json REST output of the data is received. You can do this with the response.json() method, we are doing.

Example output:

>>> {'device': 650, 'field_1': '6', 'field_2': '3.49', 'field_3': '22', 'field_4': None, 'field_5': None, 'field_6': None, 'field_7': None, 'field_8': None, 'id': 502491, 'pub_date': '2019-08-31T01:07:29.438160', 'remote_address': '88.242.135.167&python-requests/2.18.4&HTTP/1.1'}
Send JSON Data in POST with Python Examples:

You can find this example and others at IoT Examples Github.

python-send-data.png
iot_post_json_update_post_1.py
"""
  Python ile IoThook REST Api Testi

  IoThook'da her cihazin bir kimlik numarasi APIKEY'i vardir.
  Bu APIKEY kullanilarak veriler IoThook'a POST metodu ile gonderilir.
  5 kere 15 saniyede bir random verileri iothook'a gonderir.

  Bu ornek IotHook servisine veri almak/gondermek icin baslangic seviyesinde
  testlerin yapilmasini amaclamaktadir.

  v1 : 11 Eylul 2017
  v2 : 19 Agustos 2019
  v3 : 31 Ekim 2022

  Sahin MERSIN - electrocoder

  Daha fazlasi icin

  http://www.iothook.com
  https://www.mesebilisim.com
  https://mesemekatronik.com
  https://electrocoder.blogspot.com
  https://github.com/meseiot/iotexamples

  sitelerine gidiniz.

  Yayin : http://mesebilisim.com

  Licensed under the Apache License, Version 2.0 (the "License").
  You may not use this file except in compliance with the License.
  A copy of the License is located at

  http://www.apache.org/licenses/
"""

import json
import pprint
import random
import time

import requests

headers = {'Content-type': 'application/json'}

# demo account API_KEY
# https://iothook.com/en/device/data/100/
# 100 - Demo Data HTTP
API_KEY = '9e722c4fc6c834b15ba01e86'  # write api key
url = 'http://iothook.com/api/update/'

for i in range(5):
    data = {  # write api key
        'api_key': API_KEY,  # demo hesap #100 - Demo Data HTTP
        'field_1': random.randint(1, 10),
        'field_2': round(random.uniform(0.0, 10.0), 2),
    }

    data_json = json.dumps(data)

    response = requests.post(url, data=data_json, headers=headers)
    pprint.pprint(response.json())
    time.sleep(15)
Send JSON Data in POST with Python Examples 2:

You can find this example and others at IoT Examples Json Post 1 Github.

python-send-data.png
iot_post_json_update_post_2.py
"""
  Python ile IoThook REST Api Testi

  IoThook'da her cihazin bir kimlik numarasi APIKEY'i vardir.
  Bu APIKEY kullanilarak veriler IoThook'a POST metodu ile gonderilir.
  100 kere 15 saniyede bir random verileri iothook'a gonderir.

  Bu ornek IotHook servisine veri almak/gondermek icin baslangic seviyesinde
  testlerin yapilmasini amaclamaktadir.

  v1 : 11 Eylul 2017
  v2 : 19 Agustos 2019
  v3 : 31 Ekim 2022

  Sahin MERSIN - electrocoder

  Daha fazlasi icin

  http://www.iothook.com
  https://www.mesebilisim.com
  https://mesemekatronik.com
  https://electrocoder.blogspot.com
  https://github.com/meseiot/iotexamples

  sitelerine gidiniz.

  Yayin : http://mesebilisim.com

  Licensed under the Apache License, Version 2.0 (the "License").
  You may not use this file except in compliance with the License.
  A copy of the License is located at

  http://www.apache.org/licenses/
"""

import json
import pprint
import random
import time

import requests

headers = {'Content-type': 'application/json'}

# demo account API_KEY
# https://iothook.com/en/device/data/100/
# 100 - Demo Data HTTP
API_KEY = '9e722c4fc6c834b15ba01e86'  # write api key
url = 'http://iothook.com/api/update/'

for i in range(100):
    data = {  # write api key
        'api_key': API_KEY,  # demo hesap #100 - Demo Data HTTP
        'field_1': random.randint(1, 10),
        'field_2': round(random.uniform(0.0, 10.0), 2),
    }

    data_json = json.dumps(data)

    response = requests.post(url, data=data_json, headers=headers)
    pprint.pprint(response.json())
    time.sleep(15)
Send JSON Data in POST with Python Examples 3:

You can find this example and others at IoT Examples Json Update 2 Github.

python-send-data.png
iot_post_json_update_post_3.py
"""
  Python ile IoThook REST Api Testi

  IoThook'da her cihazin bir kimlik numarasi APIKEY'i vardir.
  Bu APIKEY kullanilarak veriler IoThook'a POST metodu ile gonderilir.
  1000 kere 15 saniyede bir random verileri iothook'a gonderir.

  Bu ornek IotHook servisine veri almak/gondermek icin baslangic seviyesinde
  testlerin yapilmasini amaclamaktadir.

  v1 : 11 Eylul 2017
  v2 : 19 Agustos 2019
  v3 : 31 Ekim 2022

  Sahin MERSIN - electrocoder

  Daha fazlasi icin

  http://www.iothook.com
  https://www.mesebilisim.com
  https://mesemekatronik.com
  https://electrocoder.blogspot.com
  https://github.com/meseiot/iotexamples

  sitelerine gidiniz.

  Yayin : http://mesebilisim.com

  Licensed under the Apache License, Version 2.0 (the "License").
  You may not use this file except in compliance with the License.
  A copy of the License is located at

  http://www.apache.org/licenses/
"""

import json
import pprint
import random
import time

import requests

headers = {'Content-type': 'application/json'}

# demo account API_KEY
# https://iothook.com/en/device/data/100/
# 100 - Demo Data HTTP
API_KEY = '9e722c4fc6c834b15ba01e86'  # write api key
url = 'http://iothook.com/api/update/'

for i in range(1000):
    data = {  # write api key
        'api_key': API_KEY,  # demo hesap #100 - Demo Data HTTP
        'field_1': random.randint(0, 100),
        'field_2': random.randint(0, 100),
        'field_3': random.randint(0, 100),
        'field_4': random.randint(0, 100),
        'field_5': random.randint(0, 100),
        'field_6': random.randint(0, 100),
        'field_7': random.randint(0, 100),
        'field_8': random.randint(0, 100),
    }

    data_json = json.dumps(data)

    response = requests.post(url, data=data_json, headers=headers)
    pprint.pprint(response.json())
    time.sleep(15)

Send Data in GET with Python

With the IoThook Api v6 update, it allows sending data with the GET method.

To send data, you must first add a device. Special read and write “API KEY” when the device is created Data processing is performed according to the access method (POST, GET, POST/GET) that is generated and determined.

For example; Let our device be in a structure that receives humidity, heat and light values. For this example, the device named “#100 - Demo Data HTTP” was created on iothook.com. IoThook .

Let the IoT device read the data from the sensors and send this data to us once every 15 seconds, a total of 100 times.

You can access the read and write API Keys created for the #100 iot device from the IoThook dashboard.

The API ENDPOINT address we will use to send data to IoThook servers with Python is https://iothook.com/api/update/. Writing api_key information is needed to send data. You can access this KEY from the device settings page.

There are 2 required fields to send data. These fields are api_key and field_1 fields. APIKEY your device ownership field_1 absolutely must be because it validates and must have at least one data field. Other fields defined even if they are not sent, they are recorded as None.

Send Data in GET with Python Examples:

You can find this example and others at IoT Examples Get Write Github.

python-send-data.png
iot_get_write_1.py
"""
  Python ile IoThook REST Api Ornegi

  IoThook'da her cihazin bir kimlik numarasi APIKEY'i vardir.
  Bu APIKEY kullanilarak veriler IoThook'a GET metodu ile gonderilir.

  Bu ornek IoThook servisine veri almak/gondermek icin baslangic seviyesinde
  testlerin yapilmasini amaclamaktadir.

  v1 : 20 Eylul 2017
  v2 : 19 Agustos 2019
  v3 : 31 Ekim 2022

  Sahin MERSIN - electrocoder

  Daha fazlasi icin

  http://www.iothook.com
  https://www.mesebilisim.com
  https://mesemekatronik.com
  https://electrocoder.blogspot.com
  https://github.com/meseiot/iotexamples

  sitelerine gidiniz.

  Yayin : http://mesebilisim.com

  Licensed under the Apache License, Version 2.0 (the "License").
  You may not use this file except in compliance with the License.
  A copy of the License is located at

  http://www.apache.org/licenses/
"""

import pprint
import requests

# demo account API_KEY
# https://iothook.com/en/device/data/100/
# 100 - Demo Data HTTP
API_KEY = '9e722c4fc6c834b15ba01e86'  # write api key
url = 'http://iothook.com/api/update/?api_key=' + API_KEY

data = url + '&field_1=10&field_2=20&field_3=30'

response = requests.get(data)
pprint.pprint(response.json())
Send Data in GET with Python Examples 2:

You can find this example and others at IoT Examples Get Write 1 Github.

python-send-data.png
iot_get_write_2.py
"""
  Python ile IoThook REST Api Ornegi

  IoThook'da her cihazin bir kimlik numarasi APIKEY'i vardir.
  Bu APIKEY kullanilarak veriler IoThook'a GET metodu ile gonderilir.
  10 kere 15 saniyede bir random verileri iothook'a gonderir.


  Bu ornek IoThook servisine veri almak/gondermek icin baslangic seviyesinde
  testlerin yapilmasini amaclamaktadir.

  v1 : 20 Eylul 2017
  v2 : 19 Agustos 2019
  v3 : 31 Ekim 2022

  Sahin MERSIN - electrocoder

  Daha fazlasi icin

  http://www.iothook.com
  https://www.mesebilisim.com
  https://mesemekatronik.com
  https://electrocoder.blogspot.com
  https://github.com/meseiot/iotexamples

  sitelerine gidiniz.

  Yayin : http://mesebilisim.com

  Licensed under the Apache License, Version 2.0 (the "License").
  You may not use this file except in compliance with the License.
  A copy of the License is located at

  http://www.apache.org/licenses/
"""

import pprint
import requests
import time

# demo account API_KEY
# https://iothook.com/en/device/data/100/
# 100 - Demo Data HTTP
API_KEY = '9e722c4fc6c834b15ba01e86'  # write api key
url = 'http://iothook.com/api/update/?api_key=' + API_KEY

for i in range(10):
    data = url + '&field_1=10&field_2=20&field_3=30'

    response = requests.get(data)
    pprint.pprint(response.json())
    time.sleep(15)

Arduino and ESP8266

Arduino and ESP8266 HTTP Post Examples.

Arduino and ESP8266 HTTP POST Send Data

In this example, Arduino code is given for sending data to iothook with ESP8266 connected to Arduino Uno with RX and TX. In the example, random numbers between 0-100 were generated and the device was sent to the device with “#100 - Demo Data HTTP” on iothook.

You can find this example and others at IoT Examples ESP8266 Post Github.

arduino_esp8266_post_send_data.ino
/*
      Arduino ile ESP8266 Wifi Modul Testi

      Kod Arduino ya yuklendiginde Arduino IDE nin Serial Monitor u
      ile ESP8266 arasinda haberlesme gozlenebilir.

      Arduino ile ESP8266 arasindaki iletisim Baud ayari
      115200 olmalidir.

      Arduino 0 ile 100 arasinda uretmis oldugu Random sayıyı iothook a gonderir.

      Bu cihaza ait datalar
      https://iothook.com/en/device/data/19/
      adresinden gercek zamanli olarak izlenebilir.

      Bu ornek IOThook servisine veri gondermek icin baslangic ayarlarinin
      yapilmasini amaclamaktadir.

      24 Eylul 2017
      Güncelleme : 19 Agustos 2019
      Sahin MERSIN

      Daha fazlasi icin

      http://www.iothook.com
      ve
      https://github.com/electrocoder/IOThook

      sitelerine gidiniz.
      Sorular ve destek talepleri icin
      https://github.com/electrocoder/IOThook/issues
      sayfasina gidiniz.

      Yayin ve sahiplik http://mesebilisim.com
    */

    #include "SoftwareSerial.h"

    String ssid = "WIFI_ID";
    String password = "WIFI_PASSWORD";

    SoftwareSerial esp(10, 11);// RX, TX

    String data;

    String server = "iothook.com";

    String uri = "/api/update/";

    void setup() {

      esp.begin(115200);

      Serial.begin(115200);

      Serial.println("Arduino ile ESP8266 Wifi Modul Testi");
      Serial.println("          www.IOThook.com           ");
      Serial.println("");

      reset();

      connectWifi();

    }


    void reset() {

      esp.println("AT+RST");

      delay(2000);

      if (esp.find("OK") ) Serial.println("Modul Reset yapildi");
      else Serial.println("Module Reset yapılamadi");

    }


    void connectWifi() {

      String cmd = "AT+CWJAP=\"" + ssid + "\",\"" + password + "\"";

      esp.println(cmd);

      delay(4000);

      if (esp.find("OK")) {

        Serial.println("ESP8266 Wifi ye baglandi");

      }

      else {

        connectWifi();

        Serial.println("ESP8266 Wifi ye baglanamadı!");
      }

    }


    void loop () {

      // ID : 100 Demo Data HTTP

      data = "{\"api_key\":\"9e722c4fc6c834b15ba01e86\",\"field_1\":" + String(random(0, 100)) + "}";

      httppost();

      delay(5000);

    }


    void httppost () {

      esp.println("AT+CIPSTART=\"TCP\",\"" + server + "\",80");

      if ( esp.find("OK")) {

        Serial.println("TCP baglanti hazir");

      }
      else
        Serial.println("TCP baglanti hatali");

      delay(3000);

      String postRequest =

        "POST " + uri + " HTTP/1.0\r\n" +

        "Host: " + server + "\r\n" +

        "Accept: *" + "/" + "*\r\n" +

        "Content-Length: " + data.length() + "\r\n" +

        "Content-Type: application/x-www-form-urlencoded\r\n" +

        "\r\n" + data;

      String sendCmd = "AT+CIPSEND=";

      esp.print(sendCmd);

      esp.println(postRequest.length() );

      delay(1500);

      if (esp.find(">")) {
        Serial.println("Gonderiliyor...");
        esp.print(postRequest);

        if ( esp.find("SEND OK")) {
          Serial.println("Gonderildi :)");

          while (esp.available()) {

            String tmpResp = esp.readString();

            Serial.println(tmpResp);

          }

          esp.println("AT+CIPCLOSE");

        }
        else
          Serial.println("Gonderilemedi :(");

      }
      else
        Serial.println("Gonderim hatasi! ESP hazir degil!");
    }
Arduino and ESP8266 HTTP POST Send Data 2

In this example, Arduino code is given for sending data to iothook with ESP8266 connected to Arduino Uno with RX and TX. In the example, random numbers between 0-100 were generated and the device was sent to the device with “#100 - Demo Data HTTP” on iothook.

You can find this example and others at IoT Examples ESP8266 Post Send Github.

arduino_esp8266_post_send_data_2.ino
/*
      Arduino ile ESP8266 Wifi Modul Testi

      Kod Arduino ya yuklendiginde Arduino IDE nin Serial Monitor u
      ile ESP8266 arasinda haberlesme gozlenebilir.

      Arduino ile ESP8266 arasindaki iletisim Baud ayari
      115200 olmalidir.

      Arduino 0 ile 100 arasinda uretmis oldugu Random sayıyı iothook a gonderir.

      Bu cihaza ait datalar
      https://iothook.com/en/device/data/19/
      adresinden gercek zamanli olarak izlenebilir.

      Bu ornek IOThook servisine veri gondermek icin baslangic ayarlarinin
      yapilmasini amaclamaktadir.

      24 Eylul 2017
      Güncelleme : 19 Agustos 2019
      Sahin MERSIN

      Daha fazlasi icin

      http://www.iothook.com
      ve
      https://github.com/electrocoder/IOThook

      sitelerine gidiniz.
      Sorular ve destek talepleri icin
      https://github.com/electrocoder/IOThook/issues
      sayfasina gidiniz.

      Yayin ve sahiplik http://mesebilisim.com
    */

    #include "SoftwareSerial.h"

    String ssid = "WIFI_ID";
    String password = "WIFI_PASSWORD";

    SoftwareSerial esp(10, 11);// RX, TX

    String data;

    String server = "iothook.com";

    String uri = "/api/update/";

    void setup() {

      esp.begin(115200);

      Serial.begin(115200);

      Serial.println("Arduino ile ESP8266 Wifi Modul Testi");
      Serial.println("          www.IOThook.com           ");
      Serial.println("");

      reset();

      connectWifi();

    }


    void reset() {

      esp.println("AT+RST");

      delay(2000);

      if (esp.find("OK") ) Serial.println("Modul Reset yapildi");
      else Serial.println("Module Reset yapılamadi");

    }


    void connectWifi() {

      String cmd = "AT+CWJAP=\"" + ssid + "\",\"" + password + "\"";

      esp.println(cmd);

      delay(4000);

      if (esp.find("OK")) {

        Serial.println("ESP8266 Wifi ye baglandi");

      }

      else {

        connectWifi();

        Serial.println("ESP8266 Wifi ye baglanamadı!");
      }

    }


    void loop () {

      // ID : 100 Demo Data HTTP
      // https://iothook.com/en/device/settings/100/
      // https://iothook.com/en/device/data/100/
      data = "{\"api_key\":\"9e722c4fc6c834b15ba01e86\",\"field_1\":" + String(random(0, 100)) + "}";

      httppost();

      delay(5000);

    }


    void httppost () {

      esp.println("AT+CIPSTART=\"TCP\",\"" + server + "\",80");

      if ( esp.find("OK")) {

        Serial.println("TCP baglanti hazir");

      }
      else
        Serial.println("TCP baglanti hatali");

      delay(3000);

      String postRequest =

        "POST " + uri + " HTTP/1.0\r\n" +

        "Host: " + server + "\r\n" +

        "Accept: *" + "/" + "*\r\n" +

        "Content-Length: " + data.length() + "\r\n" +

        "Content-Type: application/x-www-form-urlencoded\r\n" +

        "\r\n" + data;

      String sendCmd = "AT+CIPSEND=";

      esp.print(sendCmd);

      esp.println(postRequest.length() );

      delay(1500);

      if (esp.find(">")) {
        Serial.println("Gonderiliyor...");
        esp.print(postRequest);

        if ( esp.find("SEND OK")) {
          Serial.println("Gonderildi :)");

          while (esp.available()) {

            String tmpResp = esp.readString();

            Serial.println(tmpResp);

          }

          esp.println("AT+CIPCLOSE");

        }
        else
          Serial.println("Gonderilemedi :(");

      }
      else
        Serial.println("Gonderim hatasi! ESP hazir degil!");
    }

Arduino, ESP8266, Nodemcu Send Data in GET

With the IOThook Api v1.4 update, it allows sending data with the GET method.

You can find this example and others at IOTHOOK Git

Here is an example of sending data using the Get method with Arduino, ESP8266, NodeMCU:

arduino_nodemcu_esp8266_temp_hum_send_data.ino
    // 18.09.2017
    // Guncelleme : 19.08.2019
    // nodemcu ile sicaklik ve nem takibi
    // electrocoder@gmail.com
    // sahin mersin
    // v1

    #include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino

    //needed for library
    #include <DNSServer.h>
    #include <ESP8266WebServer.h>
    #include <WiFiManager.h>          //https://github.com/tzapu/WiFiManager

    //for LED status
    #include <Ticker.h>

    #include <ESP8266HTTPClient.h>

    #include "DHT.h"

    #define DHTPIN 4     // what digital pin we're connected to   // D2 - GPIO4
    #define DHTTYPE DHT11

    DHT dht(DHTPIN, DHTTYPE);

    Ticker ticker;

    void tick()
    {
      //toggle state
      int state = digitalRead(BUILTIN_LED);  // get the current state of GPIO1 pin
      digitalWrite(BUILTIN_LED, !state);     // set pin to the opposite state
    }

    //gets called when WiFiManager enters configuration mode
    void configModeCallback (WiFiManager *myWiFiManager) {
      Serial.println("Entered config mode");
      Serial.println(WiFi.softAPIP());
      //if you used auto generated SSID, print it
      Serial.println(myWiFiManager->getConfigPortalSSID());
      //entered config mode, make led toggle faster
      ticker.attach(0.2, tick);
    }


    void setup() {
      // put your setup code here, to run once:
      Serial.begin(115200);

      //set led pin as output
      pinMode(BUILTIN_LED, OUTPUT);

      // start ticker with 0.5 because we start in AP mode and try to connect
      ticker.attach(0.6, tick);

      //WiFiManager
      //Local intialization. Once its business is done, there is no need to keep it around
      WiFiManager wifiManager;
      //reset settings - for testing
      //wifiManager.resetSettings();

      //set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode
      wifiManager.setAPCallback(configModeCallback);

      //fetches ssid and pass and tries to connect
      //if it does not connect it starts an access point with the specified name
      //here  "AutoConnectAP"
      //and goes into a blocking loop awaiting configuration
      if (!wifiManager.autoConnect("MeseIoT", "MeseIoT**")) {
        Serial.println("failed to connect and hit timeout");
        //reset and try again, or maybe put it to deep sleep
        ESP.reset();
        delay(1000);
      }

      //if you get here you have connected to the WiFi
      Serial.println("connected...yeey :)");
      ticker.detach();
      //keep LED on
      digitalWrite(BUILTIN_LED, LOW);

      dht.begin();
    }


    void loop() {
      // Wait a few seconds between measurements.
      delay(2000);

      // Reading temperature or humidity takes about 250 milliseconds!
      // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
      float h = dht.readHumidity();
      // Read temperature as Celsius (the default)
      float t = dht.readTemperature();
      // Read temperature as Fahrenheit (isFahrenheit = true)
      float f = dht.readTemperature(true);

      // Check if any reads failed and exit early (to try again).
      if (isnan(h) || isnan(t) || isnan(f)) {
        Serial.println("Failed to read from DHT sensor!");
        return;
      }

      // Compute heat index in Fahrenheit (the default)
      float hif = dht.computeHeatIndex(f, h);
      // Compute heat index in Celsius (isFahreheit = false)
      float hic = dht.computeHeatIndex(t, h, false);

      Serial.print("Humidity: ");
      Serial.print(h);
      Serial.print(" %\t");
      Serial.print("Temperature: ");
      Serial.print(t);
      Serial.print(" *C ");
      Serial.print(f);
      Serial.print(" *F\t");
      Serial.print("Heat index: ");
      Serial.print(hic);
      Serial.print(" *C ");
      Serial.print(hif);
      Serial.println(" *F");

      ///
      HTTPClient http;

      // configure server and url
      http.begin("http://iothook.com/api/update/?api_key=9e722c4fc6c834b15ba01e86&field_1=" + String(t) + "&field_2=" + String(h) + "");
      //http.begin("192.168.1.12", 80, "/test.html");

      Serial.print("[HTTP] GET...\n");
      // start connection and send HTTP header
      int httpCode = http.GET();
      if (httpCode > 0) {
        // HTTP header has been send and Server response header has been handled
        Serial.printf("[HTTP] GET... code: %d\n", httpCode);

        // file found at server
        if (httpCode == HTTP_CODE_OK) {

          // get lenght of document (is -1 when Server sends no Content-Length header)
          int len = http.getSize();

          // create buffer for read
          uint8_t buff[128] = { 0 };

          // get tcp stream
          WiFiClient * stream = http.getStreamPtr();

          // read all data from server
          while (http.connected() && (len > 0 || len == -1)) {
            // get available data size
            size_t size = stream->available();

            if (size) {
              // read up to 128 byte
              int c = stream->readBytes(buff, ((size > sizeof(buff)) ? sizeof(buff) : size));

              // write it to Serial
              Serial.write(buff, c);

              if (len > 0) {
                len -= c;
              }
            }
            delay(1);
          }

          Serial.println();
          Serial.print("[HTTP] connection closed or file end.\n");

        }
      } else {
        Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
      }

      http.end();
      ////
      delay(13000);
    }

NodeMCU Send Data in GET

With the IOThook Api v1.4 update, it allows sending data with the GET method.

You can find this example and others at IOTHOOK Git

Here is an example of sending data using the Get method with NodeMCU:

nodemcu_send_data_get.ino
// 04.05.2023
// NodeMCU Send Data GET Method
// NodeMCU ESP8266
// electrocoder@gmail.com
// sahin mersin
// v1
// mesebilisim.com

#include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino

#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>          //https://github.com/tzapu/WiFiManager

#include <Ticker.h>

#include <ESP8266HTTPClient.h>

Ticker ticker;

void tick()
{
  int state = digitalRead(BUILTIN_LED);  // get the current state of GPIO1 pin
  digitalWrite(BUILTIN_LED, !state);     // set pin to the opposite state
}


void configModeCallback (WiFiManager *myWiFiManager) {
  Serial.println("Entered config mode");
  Serial.println(WiFi.softAPIP());
  //if you used auto generated SSID, print it
  Serial.println(myWiFiManager->getConfigPortalSSID());
  //entered config mode, make led toggle faster
  ticker.attach(0.2, tick);
}


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

  pinMode(BUILTIN_LED, OUTPUT);

  ticker.attach(0.6, tick);

  WiFiManager wifiManager;
  //reset settings - for testing
  //wifiManager.resetSettings();

  wifiManager.setAPCallback(configModeCallback);

  if (!wifiManager.autoConnect("MeseIoT", "Mese")) {
    Serial.println("failed to connect and hit timeout");
    ESP.reset();
    delay(1000);
  }

  Serial.println("connected...yeey :)");
  ticker.detach();
  //keep LED on
  digitalWrite(BUILTIN_LED, LOW);

}


void loop() {
  delay(2000);

  HTTPClient http;

  String server = "http://iothook.com/api/update/?api_key=";
  String api_key = "9e722c4fc6c834b15ba01e86"; // #100 - Demo Data HTTP https://iothook.com/en/device/settings/100/

  Sting datas = "&field_1=1";

  http.begin(server+api_key+datas);

  Serial.print("[HTTP] GET...\n");

  int httpCode = http.GET();
  if (httpCode > 0) {

    Serial.printf("[HTTP] GET... code: %d\n", httpCode);

    if (httpCode == HTTP_CODE_OK) {

      int len = http.getSize();

      uint8_t buff[128] = { 0 };

      WiFiClient * stream = http.getStreamPtr();

      while (http.connected() && (len > 0 || len == -1)) {

        size_t size = stream->available();

        if (size) {
          int c = stream->readBytes(buff, ((size > sizeof(buff)) ? sizeof(buff) : size));

          Serial.write(buff, c);

          if (len > 0) {
            len -= c;
          }
        }
        delay(1);
      }

      Serial.println();
      Serial.print("[HTTP] connection closed or file end.\n");

    }
  } else {
    Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
  }

  http.end();

  delay(13000);
}

GO Send Data in GET

With the IOThook Api v1.4 update, it allows sending data with the GET method.

You can find this example and others at IOTHOOK Git

Here is an example of sending data using the Get method with Go Language:

Go Language Send Data with GET Method
send_data_in_get.go
// 04.05.2023
// GO language send data with GET method

package main

import (
	"io/ioutil"
	"log"
	"net/http"
)

func main() {
	resp, err := http.Get("http://iothook.com/api/update?api_key=9e722c4fc6c834b15ba01e86&field_1=10&field_2=2&field_3=3")
	if err != nil {
		log.Fatalln(err)
	}
	//We Read the response body on the line below.
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatalln(err)
	}
	//Convert the body to type string
	sb := string(body)
	log.Printf(sb)
}
Go Language Send Data with GET Method 2
send_data_in_get_2.go
// 04 Eylul 2017
// Guncelleme: 19 Agustos 2019
// Sahin MERSIN
// iothook.com
// postman kullanilarak olusturulmustur

package main

    import (
        "fmt"
        "net/http"
        "io/ioutil"
    )

    func main() {

        url := "http://iothook.com/api/update?api_key=9e722c4fc6c834b15ba01e86&field_1=10&field_2=2&field_3=3"

        req, _ := http.NewRequest("GET", url, nil)

        req.Header.Add("cache-control", "no-cache")

        res, _ := http.DefaultClient.Do(req)

        defer res.Body.Close()
        body, _ := ioutil.ReadAll(res.Body)

        fmt.Println(res)
        fmt.Println(string(body))

    }

PHP Send Data in GET

With the IOThook Api v1.4 update, it allows sending data with the GET method.

You can find this example and others at IOTHOOK Git

Here is an example of sending data using the Get method with PHP Lang.:

send_data_in_get.php
// 04 Eylul 2017
// Guncelleme: 19 Agustos 2019
// Sahin MERSIN
// iothook.com
// postman kullanilarak olusturulmustur

    <?php

    $request = new HttpRequest();
    $request->setUrl('http://iothook.com/api/update');
    $request->setMethod(HTTP_METH_GET);

	// https://iothook.com/en/device/data/100/
	// #100 - Demo Data HTTP

    $request->setQueryData(array(
      'api_key' => '9e722c4fc6c834b15ba01e86',
      'field_1' => '10',
      'field_2' => '2',
      'field_3' => '3'
    ));

    $request->setHeaders(array(
      'postman-token' => '791ba738-7cb8-a920-0e5c-883cfb3e4498',
      'cache-control' => 'no-cache'
    ));

    try {
      $response = $request->send();

      echo $response->getBody();
    } catch (HttpException $ex) {
      echo $ex;
    }

NodeJS Send Data in GET

With the IOThook Api v1.4 update, it allows sending data with the GET method.

You can find this example and others at IOTHOOK Git

Here is an example of sending data using the Get method with NodeJS:

send_data_in_get.js
// 04 Eylul 2017
// Guncelleme: 19 Agustos 2019
// Sahin MERSIN
// iothook.com
// postman kullanilarak olusturulmustur

var http = require("http");

var options = {
  "method": "GET",
  "hostname": "iothook.com",
  "port": null,
  "path": "/api/update?api_key=9e722c4fc6c834b15ba01e86&field_1=10&field_2=2&field_3=3",
  "headers": {
    "cache-control": "no-cache",
    "postman-token": "033da3c8-6196-cd49-f72d-1850a7d18500"
  }
};

var req = http.request(options, function (res) {
  var chunks = [];

  res.on("data", function (chunk) {
    chunks.push(chunk);
  });

  res.on("end", function () {
    var body = Buffer.concat(chunks);
    console.log(body.toString());
  });
});

req.end();

Javascript Jquery Ajax Send Data in GET

With the IOThook Api v1.4 update, it allows sending data with the GET method.

You can find this example and others at IOTHOOK Git

Here is an example of sending data using the Get method with Javascript Jquery Ajax:

send_data_in_get_javascript.js
    // 04 Eylul 2017
    // Guncelleme: 19 Agustos 2019
    // Sahin MERSIN
    // iothook.com
    // postman kullanilarak olusturulmustur

    var settings = {
      "async": true,
      "crossDomain": true,
      "url": "http://iothook.com/api/update?api_key=9e722c4fc6c834b15ba01e86&field_1=10&field_2=2&field_3=3",
      "method": "GET",
      "headers": {
        "cache-control": "no-cache",
      }
    }

    $.ajax(settings).done(function (response) {
      console.log(response);
    });
    

Java Unirest Send Data in GET

With the IOThook Api v1.4 update, it allows sending data with the GET method.

You can find this example and others at IOTHOOK Git

Here is an example of sending data using the Get method with Java:

send_data_in_get.java
// 04 Eylul 2017
// Guncelleme: 19 Agustos 2019
// Sahin MERSIN
// iothook.com
// postman kullanilarak olusturulmustur

HttpResponse<String> response = Unirest.get("http://iothook.com/api/update?api_key=9e722c4fc6c834b15ba01e86&field_1=10&field_2=2&field_3=3")
  .header("cache-control", "no-cache")
  .asString();

Java Request Send Data in GET 2

With the IOThook Api v1.4 update, it allows sending data with the GET method.

You can find this example and others at IOTHOOK Git

Here is an example of sending data using the Get method with Java:

send_data_in_get_2.java
// 04 Eylul 2017
// Guncelleme: 19 Agustos 2019
// Sahin MERSIN
// iothook.com
// postman kullanilarak olusturulmustur

OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder()
  .url("http://iothook.com/api/update?api_key=9e722c4fc6c834b15ba01e86&field_1=10&field_2=2&field_3=3")
  .get()
  .addHeader("cache-control", "no-cache")
  .build();

Response response = client.newCall(request).execute();

Arduino ESP32 ESP-C3-13 Request Send Data in GET

Data will be sent to IoThook with HTTP GET method with ESP32 on Arduino IDE.

The device used in this project is the ESP-C3-13 produced by ai-thinker. The features of the device and the settings for programming with Arduino IDE are as follows.

You can find this example and others at IOTHOOK Git

Here is an example of sending data using the Get method with C:

BasicHttpClient_ESP_C3_13.ino
/*
  Date: 02.09.2023
  Device: ESP-C3-13
  FCC ID: 2ATPO-ESP-C3-X C3-2M
  Device Doc.: https://docs.ai-thinker.com/_media/esp32/docs/esp-c3-12f_specification.pdf
  Arduino IDE Board Select: ESP32C3 Dev Module
  Arduino IDE CPU Frequency: 160MHZ
  Arduino IDE Flash Size: 2MB
  Arduino IDE Partition Schema: 2MB
  Arduino IDE MacOS Upload Speed: MacOS: 115200, Windows and Linux: 460800

  BasicHTTPClient.ino
  Created on: 24.05.2015

  MacOS Boud Rate Error:
    18:15:51.714 -> ESP-ROM:esp32c3-api1-20210207
    18:15:51.714 -> Build:Feb  7 2021
    18:15:51.714 -> rst:0x1 (POWERON),boot:0xc (SPI_FAST_FLASH_BOOT)
    18:15:51.714 -> SPIWP:0xee
    18:15:51.714 -> mode:QIO, clock div:1
    18:15:51.714 -> load:0x3fcd5810,len:0x438
    18:15:51.714 -> ets_loader.c 78 
 */

#include <WiFi.h>

const char* ssid = "ssid";       // Change this to your WiFi SSID
const char* password = "password";  // Change this to your WiFi password

const char* host = "iothook.com";  // This should not be changed
const int httpPort = 80;           // This should not be changed

void setup() {

  Serial.begin(115200);
  while (!Serial) { delay(100); }

  Serial.println();
  Serial.println("******************************************************");
  Serial.print("Connecting to ");
  Serial.println(ssid);

  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());

} // setup


void loop() {

  WiFiClient client;

  if (!client.connect(host, httpPort)) {
    return;
  }

  float field_1 = random(100);

  String footer = String(" HTTP/1.1\r\n") + "Host: " + String(host) + "\r\n" + "Connection: close\r\n\r\n";

  // HTTP Device Data List
  // # 100 - Demo Data HTTP-100
  // https://iothook.com/en/device/data/100/
  // Device Read API Key	b5d91b83c85276cddc84eb67
  // Read Device Data	https://iothook.com/api/device/?api_key=b5d91b83c85276cddc84eb67&results=2
  // Device Write API Key	9e722c4fc6c834b15ba01e86
  // Write Device Data	https://iothook.com/api/update/?api_key=9e722c4fc6c834b15ba01e86&field_1=10

  client.print("GET /api/update/?api_key=9e722c4fc6c834b15ba01e86&field_1=" + String(field_1) + footer);

  Serial.println(String(field_1) + " send ok");

  int maxloops = 0;
  //wait for the server's reply to become available
  while (!client.available() && maxloops < 1000)
  {
    maxloops++;
    delay(1); //delay 1 msec
  }
  if (client.available() > 0)
  {
    //read back one line from the server
    String line = client.readStringUntil('\r');
    Serial.println(line);
  }
  else
  {
    Serial.println("client.available() timed out ");
  }

  delay(5000);

} // loop

Arduino ESP32 ESP-C3-13 Request Send Data in GET

Data will be sent to IoThook with HTTP GET method with ESP32 on Arduino IDE.

The device used in this project is the ESP-C3-13 produced by ai-thinker. The features of the device and the settings for programming with Arduino IDE are as follows.

You can find this example and others at IOTHOOK Git

Here is an example of sending data using the Get method with C:

BasicHttpClient_ESP_C3_13.ino
/*
  Date: 02.09.2023
  Device: ESP-C3-13
  FCC ID: 2ATPO-ESP-C3-X C3-2M
  Device Doc.: https://docs.ai-thinker.com/_media/esp32/docs/esp-c3-12f_specification.pdf
  Arduino IDE Board Select: ESP32C3 Dev Module
  Arduino IDE CPU Frequency: 160MHZ
  Arduino IDE Flash Size: 2MB
  Arduino IDE Partition Schema: 2MB
  Arduino IDE MacOS Upload Speed: MacOS: 115200, Windows and Linux: 460800

  BasicHTTPClient.ino
  Created on: 24.05.2015

  MacOS Boud Rate Error:
    18:15:51.714 -> ESP-ROM:esp32c3-api1-20210207
    18:15:51.714 -> Build:Feb  7 2021
    18:15:51.714 -> rst:0x1 (POWERON),boot:0xc (SPI_FAST_FLASH_BOOT)
    18:15:51.714 -> SPIWP:0xee
    18:15:51.714 -> mode:QIO, clock div:1
    18:15:51.714 -> load:0x3fcd5810,len:0x438
    18:15:51.714 -> ets_loader.c 78 
 */

#include <WiFi.h>

const char* ssid = "ssid";       // Change this to your WiFi SSID
const char* password = "password";  // Change this to your WiFi password

const char* host = "iothook.com";  // This should not be changed
const int httpPort = 80;           // This should not be changed

void setup() {

  Serial.begin(115200);
  while (!Serial) { delay(100); }

  Serial.println();
  Serial.println("******************************************************");
  Serial.print("Connecting to ");
  Serial.println(ssid);

  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());

} // setup


void loop() {

  WiFiClient client;

  if (!client.connect(host, httpPort)) {
    return;
  }

  float field_1 = random(100);

  String footer = String(" HTTP/1.1\r\n") + "Host: " + String(host) + "\r\n" + "Connection: close\r\n\r\n";

  // HTTP Device Data List
  // # 100 - Demo Data HTTP-100
  // https://iothook.com/en/device/data/100/
  // Device Read API Key	b5d91b83c85276cddc84eb67
  // Read Device Data	https://iothook.com/api/device/?api_key=b5d91b83c85276cddc84eb67&results=2
  // Device Write API Key	9e722c4fc6c834b15ba01e86
  // Write Device Data	https://iothook.com/api/update/?api_key=9e722c4fc6c834b15ba01e86&field_1=10

  client.print("GET /api/update/?api_key=9e722c4fc6c834b15ba01e86&field_1=" + String(field_1) + footer);

  Serial.println(String(field_1) + " send ok");

  int maxloops = 0;
  //wait for the server's reply to become available
  while (!client.available() && maxloops < 1000)
  {
    maxloops++;
    delay(1); //delay 1 msec
  }
  if (client.available() > 0)
  {
    //read back one line from the server
    String line = client.readStringUntil('\r');
    Serial.println(line);
  }
  else
  {
    Serial.println("client.available() timed out ");
  }

  delay(5000);

} // loop

MQTT Send Data Publish

Hello; In this help file, we will try to do everything you need to know about the MQTT messaging protocol and any IO operations you need. These examples should be customized to your device and MQTT Broker. For this reason, you should thoroughly learn why you want to use it and how it is applied. In a nutshell, MQTT uses your Internet home network and Mobile GSM 3G, 4G, 4.5G and 5G networks to send and respond to messages to your IoT devices.

You can make your MQTT experiments on the IoThook MQTT MQTT Broker page here.

Arduino ESP32 ESP-C3-13 Send JSON Data Publish MQTT

In this example, JSON data is sent to the device channel named “#100 - Demo Data HTTP” using the HTTP POST method with Python. When the data is sent successfully, Json REST output of the data is received. You can do this with the response.json() method, we are doing.

You can find this example and others at IOTHOOK Git

Here is an example of sending data using the Get method with C:

esp32_c3_mqtt_iot.ino
/*
  Test MQTT Publish
  16.09.2023

  * Device: ESP-C3-13
  * FCC ID: 2ATPO-ESP-C3-X C3-2M
  * Device Doc.: https://docs.ai-thinker.com/_media/esp32/docs/esp-c3-12f_specification.pdf
  * Arduino IDE Board Select: ESP32C3 Dev Module
  * Arduino IDE CPU Frequency: 160MHZ
  * Arduino IDE Flash Size: 2MB
  * Arduino IDE Partition Schema: 2MB
  * Arduino IDE MacOS Upload Speed: MacOS: 115200, Windows and Linux: 460800

  REQUIRES the following Arduino libraries:
  DHT Sensor Library: https://github.com/adafruit/DHT-sensor-library
  Adafruit Unified Sensor Lib: https://github.com/adafruit/Adafruit_Sensor
  HX711 https://github.com/bogde/HX711
  Mqtt : https://github.com/256dpi/arduino-mqtt?ysclid=leihxfhhq6294250283
*/


#include <WiFi.h>
#include <MQTT.h>
#include "HX711.h"

#include <DHT.h>
#include <DHT_U.h>

#define DHTPIN 23
#define DHTTYPE DHT21

DHT_Unified dht(DHTPIN, DHTTYPE);

const char ssid[] = "SSID";
const char pass[] = "PASS";

WiFiClient net;
MQTTClient client;

const char BROKER[] = "iothook.com";
const char BROKERUSERNAME[] = "iothookpublic";
const char BROKERPASSWORD[] = "iothookpublic";

// ID 101 : https://iothook.com/en/device/pub-sub-mqtt/101/
const char PUBTOPIC[] = "iot/879ba3d9ab3df048f8b3299f/esp32test/r";
const char SUBTOPIC[] = "iot/879ba3d9ab3df048f8b3299f/esp32test/w/UID005";

const char UID[] = "UID005";


const int LED_RED = 3;

const int ldr = A0;

unsigned long lastMillis = 0;

#define DEBUG 1


void messageReceived(String &topic, String &payload) {

  if (DEBUG) Serial.println("messageReceived: " + topic + " - " + payload);

  String messageTemp;

  for (int i = 0; i < payload.length(); i++) {
    // Serial.print((char)payload[i]);
    messageTemp += (char)payload[i];
  }

  if (messageTemp == "led:on") {
    Serial.println(" led on ");
    digitalWrite(LED_RED, HIGH);
  } else if (messageTemp == "led:off") {
    Serial.println(" led off ");
    digitalWrite(LED_RED, LOW);
  }

}  // messageReceived


void setup() {

  Serial.begin(115200);

  pinMode(LED_RED, OUTPUT);

  WiFi.begin(ssid, pass);

  client.begin(BROKER, net);

  client.onMessage(messageReceived);

  connect();

  delay(100);

}  // setup


void connect() {

  Serial.print("checking wifi...");
  while (WiFi.status() != WL_CONNECTED) {
    if (DEBUG) Serial.print(".");
    delay(1000);
  }

  Serial.print("\nconnecting...");
  while (!client.connect(UID, BROKERUSERNAME, BROKERPASSWORD)) {
    if (DEBUG) Serial.print(".");
    delay(1000);
  }

  Serial.println("\nconnected!");

  client.subscribe(SUBTOPIC);

}  // connect


void loop() {

  client.loop();
  delay(10);

  if (!client.connected()) {
    delay(5000);
    connect();
  }

  if (millis() - lastMillis > 1000) {
    lastMillis = millis();
    send_data();
  }

  delay(100);

}  // loop


void send_data() {

  float field_1 = random(0, 2000);

  int isik = analogRead(ldr);

  String veriler = "{'weight':" + String(field_1) + ",'temperature':" + String(field_1) + ",'humidity':" + String(field_1) + ",'image':1,'ldr':" + String(isik) + ",'device_id':" + UID + "}";
  if (DEBUG) Serial.println("send_data " + veriler);

  client.publish(PUBTOPIC, veriler);

}  // send_data

Read Data

HTTP Read Data

We need API KEY information for retrieving the data of temperature, damp, voltage, light etc. values like that which are sending Iot device.Datas which are sending from your Iot device can monitore with mobile devices like Pi, Android, iOs or your website.

For example; Assume that our device’s name “Temperature sensor” and it will be in the device additionally assume that our sensors “temperature” and “humidity”

Data Retrieving with Python 2, Python 3 Json

Get Example with Python Json: The number of data specified by results was read,by using the requests.get method from the IOTHOOK server Up to 99 pieces of data can be read with the results variable. If the results variable is not specified, only 1 data can be read. The format of readed data is json

The following output is obtained, by running the following Python script.

>>> [{'id': 502483, 'device': 17, 'field_1': '46', 'field_2': '6.70', 'field_3': None, 'field_4': None, 'field_5': None, 'field_6': None, 'field_7': None, 'field_8': None, 'pub_date': '2019-08-31T00:57:27.086837', 'remote_address': '88.242.132.150&python-requests/2.12.4&HTTP/1.1'}]
>>> 1
>>> 502483

You can find this example and others on the `IOTHOOK Git`_ page.

get_json.py
# -*- coding: utf-8 -*-

"""
    IoThook REST Api Test with Python 2, Python 3 

    This example is at the beginner level for sending/receiving data to the IotHook service.
    it aims to carry out tests.

    10 May 2017
    Update: 19 August 2019
    Sahin MERSIN

    For more

    http://www.iothook.com
    and
    https://github.com/electrocoder/iotHook

    go to theese sites

    For questions and support requests
    https://github.com/electrocoder/iotHook/issues
    you can take support Mese Bilisim or above github page.
    

    Broadcasting : http://mesebilisim.com


    Licensed under the Apache License, Version 2.0 (the "License").
    You may not use this file except in compliance with the License.
    A copy of the License is located at

    http://www.apache.org/licenses/

"""

import requests

# read api key
API_KEY = 'b5d91b83c85276cddc84eb67' # demo account #100 Demo Data HTTP random test

url = 'http://iothook.com/api/device/?api_key=' + API_KEY + "&results=1"

response = requests.get(url)
data = response.json()
print(data)
print(len(data))
print(data[0]['id'])

Getting the First Data with Python 2, Python 3 Json

Python Getting the First Data, Get Example with Json:

You can find this example and others on the `IOTHOOK Git`_ page.

request_get.py
# -*- coding: utf-8 -*-

"""
    IoThook REST Api Test with Python 2, Python 3 

    This example is at the beginner level for sending/receiving data to the IotHook service.
    it aims to carry out tests.

    10 May 2017
    Update: 19 August 2019
    Sahin MERSIN

    For more

    http://www.iothook.com
    and
    https://github.com/electrocoder/iotHook

    go to theese sites


    For questions and support requests
    https://github.com/electrocoder/iotHook/issues
    you can take support Mese Bilisim or above github page.
    

    Broadcasting : http://mesebilisim.com

    Licensed under the Apache License, Version 2.0 (the "License").
    You may not use this file except in compliance with the License.
    A copy of the License is located at

    http://www.apache.org/licenses/

"""

import requests

# read api key
API_KEY = 'b5d91b83c85276cddc84eb67' # demo account #100 Demo Data HTTP Temperature sensor

url = 'https://iothook.com/api/device/?api_key=' + API_KEY + "&results=2"

response = requests.get(url)
data = response.json()
print(data)
print(data['datas'][0]['id'])
print(data['datas'][0]['pub_date'])
print(data['datas'][1]['id'])
print(data['datas'][1]['pub_date'])

Getting the Last Data with Python 2, Python 3 Json

Python Getting the Last Data, Get Example with Json:

You can find this example and others on the `IOTHOOK Git`_ page.

request_get_last_data.py
# -*- coding: utf-8 -*-

"""
    IoThook REST Api Test with Python 2, Python 3 

    This example is at the beginner level for sending/receiving data to the IotHook service.
    it aims to carry out tests.

    10 May 2017
    Update: 19 August 2019
    Sahin MERSIN

    For more

    http://www.iothook.com
    and
    https://github.com/electrocoder/iotHook

    go to theese sites

    For questions and support requests
    https://github.com/electrocoder/iotHook/issues
    
    you can take support Mese Bilisim or above github page.
    Broadcasting : http://mesebilisim.com

    Licensed under the Apache License, Version 2.0 (the "License").
    You may not use this file except in compliance with the License.
    A copy of the License is located at

    http://www.apache.org/licenses/

"""

import requests

# read api key
API_KEY = 'b5d91b83c85276cddc84eb67' # demo account #100 Demo Data HTTP Temperature sensor

url = 'https://iothook.com/api/device/?api_key=' + API_KEY

response = requests.get(url)
data = response.json()
print(data)
print(data['datas'][0]['id'])
print(data['datas'][0]['pub_date'])

Fetching Data in JSON Format with C#

It has been produced with the GET method using Postman so that the IoThook user can use the data of his device.

You can find this example and others on the `IOTHOOK Git`_ page.

c#/request_get_data.cs
/*
    Testing IoThook REST Api with C#

    In this example, device data is retrieved with CSharp with the get method.

    This example is at the beginner level for sending/receiving data to the IotHook service.
    it aims to carry out tests.

    29 July 2017
    Update: 19 August 2019
    Sahin MERSIN

    For more

    http://www.iothook.com
    and
    https://github.com/electrocoder/iotHook

    go to theese sites

    For questions and support requests
    https://github.com/electrocoder/iotHook/issues
    you can take support Mese Bilisim or above github page.

    Broadcasting : http://mesebilisim.com

    Licensed under the Apache License, Version 2.0 (the "License").
    You may not use this file except in compliance with the License.
    A copy of the License is located at

    http://www.apache.org/licenses/
*/

// demo account #100 Demo Data HTTP

var client = new RestClient("https://iothook.com/api/device/?api_key=9e722c4fc6c834b15ba01e86&results=1");
var request = new RestRequest(Method.GET);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Connection", "keep-alive");
request.AddHeader("Accept-Encoding", "gzip, deflate");
request.AddHeader("Host", "iothook.com");
request.AddHeader("Postman-Token", "ce2f06c2-817e-414a-8c7a-2c2fc59ad043,af31a3d8-02e4-49eb-b78f-05ebdce70149");
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("Accept", "*/*");
request.AddHeader("User-Agent", "PostmanRuntime/7.15.2");
IRestResponse response = client.Execute(request);

IOT Data Fetching with GO

It has been produced with the GET method using Postman so that the IoThook user can use the data of his device.

You can find this example and others on the `IOTHOOK Git`_ page.

request_get_data.go
// Go HTTP GET

package main

import (
    "fmt"
    "net/http"
    "io/ioutil"
)

func main() {

    url := "https://iothook.com/api/device/?api_key=9e722c4fc6c834b15ba01e86&results=1"

    req, _ := http.NewRequest("GET", url, nil)

    req.Header.Add("User-Agent", "PostmanRuntime/7.15.2")
    req.Header.Add("Accept", "*/*")
    req.Header.Add("Cache-Control", "no-cache")
    req.Header.Add("Postman-Token", "ce2f06c2-817e-414a-8c7a-2c2fc59ad043,8a0938fc-5c87-459a-9b9f-fa6aebe561f2")
    req.Header.Add("Host", "iothook.com")
    req.Header.Add("Accept-Encoding", "gzip, deflate")
    req.Header.Add("Connection", "keep-alive")
    req.Header.Add("cache-control", "no-cache")

    res, _ := http.DefaultClient.Do(req)

    defer res.Body.Close()
    body, _ := ioutil.ReadAll(res.Body)

    fmt.Println(res)
    fmt.Println(string(body))

}

IOT Data Fetching with JAVA

It has been produced with the GET method using Postman so that the IoThook user can use the data of his device.

You can find this example and others on the `IOTHOOK Git`_ page.

request_get_data.java
OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder()
    .url("https://iothook.com/api/device/?api_key=9e722c4fc6c834b15ba01e86&results=1")
    .get()
    .addHeader("User-Agent", "PostmanRuntime/7.15.2")
    .addHeader("Accept", "*/*")
    .addHeader("Cache-Control", "no-cache")
    .addHeader("Postman-Token", "ce2f06c2-817e-414a-8c7a-2c2fc59ad043,bdcd2494-5109-4621-8256-296e0c6a4fad")
    .addHeader("Host", "iothook.com")
    .addHeader("Accept-Encoding", "gzip, deflate")
    .addHeader("Connection", "keep-alive")
    .addHeader("cache-control", "no-cache")
    .build();

Response response = client.newCall(request).execute();

IOT Data Fetching with PHP

It has been produced with the GET method using Postman so that the IoThook user can use the data of his device.

You can find this example and others on the `IOTHOOK Git`_ page.

request_get_data.php
<?php

$request = new HttpRequest();
$request->setUrl('https://iothook.com/api/device/');
$request->setMethod(HTTP_METH_GET);

$request->setQueryData(array(
    'api_key' => 'b5d91b83c85276cddc84eb67',
    'results' => '1'
));

$request->setHeaders(array(
    'cache-control' => 'no-cache',
    'Connection' => 'keep-alive',
    'Accept-Encoding' => 'gzip, deflate',
    'Host' => 'iothook.com',
    'Postman-Token' => 'ce2f06c2-817e-414a-8c7a-2c2fc59ad043,dfad2e87-d4a1-4657-a5b6-183c4604c818',
    'Cache-Control' => 'no-cache',
    'Accept' => '*/*',
    'User-Agent' => 'PostmanRuntime/7.15.2'
));

try {
    $response = $request->send();

    echo $response->getBody();
} catch (HttpException $ex) {
    echo $ex;
}

IOT Data Fetching with Ruby

It has been produced with the GET method using Postman so that the IoThook user can use the data of his device.

You can find this example and others on the `IOTHOOK Git`_ page.

request_get_data.rb
require 'uri'
require 'net/http'

url = URI("https://iothook.com/api/device/?api_key=b5d91b83c85276cddc84eb67&results=1")

http = Net::HTTP.new(url.host, url.port)

request = Net::HTTP::Get.new(url)
request["User-Agent"] = 'PostmanRuntime/7.15.2'
request["Accept"] = '*/*'
request["Cache-Control"] = 'no-cache'
request["Postman-Token"] = 'ce2f06c2-817e-414a-8c7a-2c2fc59ad043,8fe93ff6-b857-4978-838e-2d8efac2e6b6'
request["Host"] = 'iothook.com'
request["Accept-Encoding"] = 'gzip, deflate'
request["Connection"] = 'keep-alive'
request["cache-control"] = 'no-cache'

response = http.request(request)
puts response.read_body

IOT Data Fetching with Javascript Ajax

It has been produced with the GET method using Postman so that the IoThook user can use the data of his device.

You can find this example and others on the `IOTHOOK Git`_ page.

request_get_data.js
var settings = {
    "async": true,
    "crossDomain": true,
    "url": "https://iothook.com/api/device/?api_key=9e722c4fc6c834b15ba01e86&results=1",
    "method": "GET",
    "headers": {
      "User-Agent": "PostmanRuntime/7.15.2",
      "Accept": "*/*",
      "Cache-Control": "no-cache",
      "Postman-Token": "ce2f06c2-817e-414a-8c7a-2c2fc59ad043,27a5bb35-4b13-48b2-8dbd-efe7188a68c6",
      "Host": "iothook.com",
      "Accept-Encoding": "gzip, deflate",
      "Connection": "keep-alive",
      "cache-control": "no-cache"
    }
  }

  $.ajax(settings).done(function (response) {
    console.log(response);
  });
  

IOT Data Fetching with Python PySide2

PySide2 is the official Python module that provides access to the Qt 5.12+ framework for Python projects. Before using PySide2, the following modules need to be installed

$ pip install matplotlib

$ pip install numpy

$ pip install PySide2

The installation of Python libraries has been done using pip. If pip is not installed on your system, you can visit the following address, https://bootstrap.pypa.io/get-pip.py, to download the file to your computer and run it.

Here, we will use PySide2 and Matplotlib to display the incoming data as a graph within a Window.

When the script is executed, we should see a window like the one shown below.

pyside2-matplotlib-iothook.png

In this example, the interface design was created using QT Designer. For the widget,*Promote to …* option was used with the MplWidget class. In prepearing this example manap.se Manap and yapayzekalabs.blogspot.com Yapayzekalabs used this sites. You can find more resources at these sites.

The test process was carried out with a device named 5 channel test with id number 230 in IoThook.

This device belongs to demo user

You can find this example and others on the `IOTHOOK Git`_ page.

iothook.ui folder:

iothook.ui
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>Form</class>
 <widget class="QWidget" name="Form">
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>689</width>
    <height>553</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Form</string>
  </property>
  <layout class="QGridLayout" name="gridLayout">
   <item row="0" column="0">
    <widget class="QLabel" name="label">
     <property name="text">
      <string>Read API KEY</string>
     </property>
    </widget>
   </item>
   <item row="0" column="1">
    <widget class="QLineEdit" name="lineEdit"/>
   </item>
   <item row="0" column="2">
    <widget class="QPushButton" name="pushButton">
     <property name="text">
      <string>Connect</string>
     </property>
    </widget>
   </item>
   <item row="1" column="0" colspan="3">
    <widget class="MplWidget" name="MplWidget" native="true"/>
   </item>
  </layout>
 </widget>
 <customwidgets>
  <customwidget>
   <class>MplWidget</class>
   <extends>QWidget</extends>
   <header>mplwidget.h</header>
   <container>1</container>
  </customwidget>
 </customwidgets>
 <resources/>
 <connections/>
</ui>

iothook.py folder:

iothook.py
"""
  Python ile IoThook REST Api Testi

  IoThook'da her cihazin bir kimlik numarasi APIKEY'i vardir.
  Bu APIKEY kullanilarak veriler IoThook'a GET metodu gonderilir ve cihaz detay verileri alinir.
  PySide2 ile arayuz olusturulmustur.

  Bu ornek IotHook servisine veri almak/gondermek icin baslangic seviyesinde
  testlerin yapilmasini amaclamaktadir.

  v1 : 19 Agustos 2019
  v2 : 31 Ekim 2022

  Sahin MERSIN - electrocoder

  Daha fazlasi icin

  http://www.iothook.com
  https://www.mesebilisim.com
  https://mesemekatronik.com
  https://electrocoder.blogspot.com
  https://github.com/meseiot/iotexamples

  sitelerine gidiniz.

  Yayin : http://mesebilisim.com

  Licensed under the Apache License, Version 2.0 (the "License").
  You may not use this file except in compliance with the License.
  A copy of the License is located at

  http://www.apache.org/licenses/
"""

import requests
from PySide2.QtWidgets import *
from PySide2.QtUiTools import QUiLoader
from PySide2.QtCore import QFile, QTimer

from matplotlib.backends.backend_qt5agg import (
    FigureCanvas, NavigationToolbar2QT as NavigationToolbar)

from matplotlib.figure import Figure

import numpy as np
import random


class MplWidget(QWidget):

    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        self.canvas = FigureCanvas(Figure())

        vertical_layout = QVBoxLayout()
        vertical_layout.addWidget(self.canvas)
        vertical_layout.addWidget(NavigationToolbar(self.canvas, self))

        self.canvas.axes = self.canvas.figure.add_subplot(111)
        self.setLayout(vertical_layout)


class MainWidget(QWidget):

    def __init__(self):
        QWidget.__init__(self)

        designer_file = QFile("iothook.ui")
        designer_file.open(QFile.ReadOnly)
        loader = QUiLoader()
        loader.registerCustomWidget(MplWidget)
        self.ui = loader.load(designer_file, self)
        designer_file.close()

        self.setWindowTitle("IOTHOOK")

        self.field_1_list = []
        self.field_2_list = []
        self.field_3_list = []
        self.field_4_list = []
        self.field_5_list = []
        self.field_6_list = []
        self.field_7_list = []
        self.field_8_list = []

        self.lineEdit = self.ui.findChild(QLineEdit, 'lineEdit')
        self.pushButton = self.ui.findChild(QPushButton, 'pushButton')

        self.pushButton.clicked.connect(self.result)

        grid_layout = QGridLayout()
        grid_layout.addWidget(self.ui)
        self.setLayout(grid_layout)

    def result(self):
        self.timer = QTimer()
        self.timer.setInterval(5000)
        self.timer.timeout.connect(self.status)
        self.timer.start()

    def status(self):
        print("update")
        # demo account API_KEY
        # https://iothook.com/en/device/data/100/
        # 100 - Demo Data HTTP
        # API_KEY = 'b5d91b83c85276cddc84eb67'  # read api key
        API_KEY = self.lineEdit.text()
        if API_KEY:
            self.pushButton.setText("Stop")
            url = 'http://iothook.com/api/device/?api_key=' + API_KEY + "&results=1"
            response = requests.get(url)
            data = response.json()
            print(data)

            try:
                self.ui.MplWidget.canvas.axes.clear()
                self.field_title_list = []

                if data[0]['field_1']:
                    self.field_title_list.append('field_1')
                    self.field_1_list.append(data[0]['field_1'])
                    self.ui.MplWidget.canvas.axes.plot(self.field_1_list)

                if data[0]['field_2']:
                    self.field_title_list.append('field_2')
                    self.field_2_list.append(data[0]['field_2'])
                    self.ui.MplWidget.canvas.axes.plot(self.field_2_list)

                if data[0]['field_3']:
                    self.field_title_list.append('field_3')
                    self.field_3_list.append(data[0]['field_3'])
                    self.ui.MplWidget.canvas.axes.plot(self.field_3_list)

                if data[0]['field_4']:
                    self.field_title_list.append('field_4')
                    self.field_4_list.append(data[0]['field_4'])
                    self.ui.MplWidget.canvas.axes.plot(self.field_4_list)

                if data[0]['field_5']:
                    self.field_title_list.append('field_5')
                    self.field_5_list.append(data[0]['field_5'])
                    self.ui.MplWidget.canvas.axes.plot(self.field_5_list)

                if data[0]['field_6']:
                    self.field_title_list.append('field_6')
                    self.field_6_list.append(data[0]['field_6'])
                    self.ui.MplWidget.canvas.axes.plot(self.field_6_list)

                if data[0]['field_7']:
                    self.field_title_list.append('field_7')
                    self.field_7_list.append(data[0]['field_7'])
                    self.ui.MplWidget.canvas.axes.plot(self.field_7_list)

                if data[0]['field_8']:
                    self.field_title_list.append('field_8')
                    self.field_8_list.append(data[0]['field_8'])
                    self.ui.MplWidget.canvas.axes.plot(self.field_8_list)

                self.ui.MplWidget.canvas.axes.legend((self.field_title_list), loc='upper right')
                self.ui.MplWidget.canvas.draw()

                self.repaint()
            except:
                pass


app = QApplication([])
window = MainWidget()
window.show()
app.exec_()

ESP32 Read Data in GET

ESP32 Read HTTP Data with GET method.

Arduino ESP32 ESP-C3-13 Request Read Data in GET

Data will be read to IoThook with HTTP GET method with ESP32 on Arduino IDE.

The device used in this project is the ESP-C3-13 produced by ai-thinker. The features of the device and the settings for programming with Arduino IDE are as follows.

You can find this example and others at IOTHOOK Git

Here is an example of sending data using the Get method with C:

Read_HttpClient_1_ESP_C3_13.ino
/*
  Date: 02.09.2023
  Device: ESP-C3-13
  FCC ID: 2ATPO-ESP-C3-X C3-2M
  Device Doc.: https://docs.ai-thinker.com/_media/esp32/docs/esp-c3-12f_specification.pdf
  Arduino IDE Board Select: ESP32C3 Dev Module
  Arduino IDE CPU Frequency: 160MHZ
  Arduino IDE Flash Size: 2MB
  Arduino IDE Partition Schema: 2MB
  Arduino IDE MacOS Upload Speed: MacOS: 115200, Windows and Linux: 460800

  MacOS Boud Rate Error:
    18:15:51.714 -> ESP-ROM:esp32c3-api1-20210207
    18:15:51.714 -> Build:Feb  7 2021
    18:15:51.714 -> rst:0x1 (POWERON),boot:0xc (SPI_FAST_FLASH_BOOT)
    18:15:51.714 -> SPIWP:0xee
    18:15:51.714 -> mode:QIO, clock div:1
    18:15:51.714 -> load:0x3fcd5810,len:0x438
    18:15:51.714 -> ets_loader.c 78 
 */

#include <WiFi.h>
#include <WiFiMulti.h>

#include <HTTPClient.h>

#include <Arduino_JSON.h>

WiFiMulti wifiMulti;

const int red = 3;
const int green = 4;
const int blue = 5;
const int cold_white = 18;
const int warm_white = 19;

void setup() {

  Serial.begin(115200);
  while (!Serial) { delay(100); }

  Serial.println();
  Serial.println("******************************************************");
  Serial.print("Connecting to ");

  wifiMulti.addAP("ssid", "password");

  pinMode(red, OUTPUT);
  pinMode(green, OUTPUT);
  pinMode(blue, OUTPUT);
  pinMode(cold_white, OUTPUT);
  pinMode(warm_white, OUTPUT);

  Serial.println("");

}  // setup


void loop() {

  if ((wifiMulti.run() == WL_CONNECTED)) {

    // HTTP Device Data List
    // # 100 - Demo Data HTTP-100
    // https://iothook.com/en/device/data/100/
    // Device Read API Key	b5d91b83c85276cddc84eb67
    // Read Device Data	https://iothook.com/api/device/?api_key=b5d91b83c85276cddc84eb67&results=2
    // Device Write API Key	9e722c4fc6c834b15ba01e86
    // Write Device Data	https://iothook.com/api/update/?api_key=9e722c4fc6c834b15ba01e86&field_1=10

    HTTPClient http;

    String serverPath = "http://iothook.com/api/device/?api_key=b5d91b83c85276cddc84eb67&results=1&format=json";

    http.begin(serverPath);

    int httpCode = http.GET();
    Serial.println(httpCode);

    if (httpCode > 0) {

      String payload = http.getString();

      JSONVar myObject = JSON.parse(payload);

      if (JSON.typeof(myObject) == "undefined") {
        Serial.println("Parsing input failed!");
        return;
      }

      Serial.println(myObject);
      JSONVar keys = myObject.keys();

      Serial.println(myObject[0]["field_1"]);
      Serial.println(myObject[0]["field_2"]);
      Serial.println(myObject[0]["field_3"]);
      Serial.println(myObject[0]["field_4"]);
      Serial.println(myObject[0]["field_5"]);
      Serial.println(myObject[0]["field_6"]);
      Serial.println(myObject[0]["field_7"]);
      Serial.println(myObject[0]["field_8"]);

      if (myObject[0]["field_1"] != null) {
        String answer = myObject[0]["field_1"];
        int field_1 = answer.toInt();
        Serial.print("field_1: ");
        Serial.println(field_1);
        analogWrite(red, field_1);
      }
      if (myObject[0]["field_2"] != null) {
        String answer = myObject[0]["field_2"];
        int field_2 = answer.toInt();
        Serial.print("field_2: ");
        Serial.println(field_2);
        analogWrite(green, field_2);
      }
      if (myObject[0]["field_3"] != null) {
        String answer = myObject[0]["field_3"];
        int field_3 = answer.toInt();
        Serial.print("field_3: ");
        Serial.println(field_3);
        analogWrite(blue, field_3);
      }
      if (myObject[0]["field_4"] != null) {
        String answer = myObject[0]["field_4"];
        int field_4 = answer.toInt();
        Serial.print("field_4: ");
        Serial.println(field_4);
        analogWrite(cold_white, field_4);
      }
      if (myObject[0]["field_5"] != null) {
        String answer = myObject[0]["field_5"];
        int field_5 = answer.toInt();
        Serial.print("field_5: ");
        Serial.println(field_5);
        analogWrite(warm_white, field_5);
      }
      if (myObject[0]["field_6"] != null) {
        String answer = myObject[0]["field_6"];
        int field_6 = answer.toInt();
        Serial.print("field_6: ");
        Serial.println(field_6);
      }
      if (myObject[0]["field_7"] != null) {
        String answer = myObject[0]["field_7"];
        int field_7 = answer.toInt();
        Serial.print("field_7: ");
        Serial.println(field_7);
      }
      if (myObject[0]["field_8"] != null) {
        String answer = myObject[0]["field_8"];
        int field_8 = answer.toInt();
        Serial.print("field_8: ");
        Serial.println(field_8);
      }


    } else {
      Serial.print("Error code: ");
      Serial.println(httpCode);
    }

    http.end();
  }

  delay(5000);

}  // loop

MQTT Read Data Subscriber

How to Find IoT Device IP Address

The IP address of the IoT (Internet of Things) device is the unique identifier of the device on the network. The IP address allows the device to connect to the network and allows it to communicate with other devices. In some cases, we need the Global IP address of the IoT device. In order to PING the device and monitor the device, it is necessary to know the IP address.

Here are some important functions of the IP address of the IoT device:

1. Communication: The IP address allows the IoT device to communicate with other devices. Using this address, the device can exchange data, receive commands or send data to other devices.

2. Authentication: The IP address provides the unique identity of an IoT device on the network. Other devices on the network can perform and confirm authentication processes using the IP address of the IoT device.

3. Discovery and Access: An IoT device’s IP address makes it easy to find and access by other devices on the network. Other devices can communicate and exchange data with it using the device’s IP address.

4. Management: The IP address can be used for the management of the IoT device. Administrative functions such as accessing the device’s configuration settings or receiving updates can be performed via the IP address.

5. Remote Access: Most IoT devices allow users to access their devices remotely. The IP address allows users to remotely access the device so that the device can be controlled or data monitored.

To summarize, the IP address of the IoT device provides the device’s unique identity on the network and able to communicate with other devices. It also simplifies device discovery, management, and remote access.

IoTHook IoT Device Get Global IP Address API

To find the IP address of the IoT device, you need to send a GET request from your Device to the IoTHook site. You can find the IoT IP address by making a GET request to https://iothook.com/api/find-ip-address/ or http://iothook.com/api/find-ip-address/ .

When IoTHook requests a GET, it can sample the IP address from JSON format as follows. {“ip”:”184.53.56.28”}

IoTHook IoT Device Get Global IP Address API Arduino Ethernet Shield

arduino_ethernet_shield_get_ip.ino
/*

  IoT Device Find Global IP Address
  electrocoder@gmail.com
  sahin@mesebilisim.com
  mesebilisim.com
  30.05.2023

*/

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


byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};

IPAddress ip(192, 168, 1, 177);
IPAddress myDns(192, 168, 1, 1);

EthernetClient client;

char server[] = "iothook.com";

unsigned long lastConnectionTime = 0;
const unsigned long postingInterval = 20 * 1000;

void setup() {

  Serial.begin(9600);
  while (!Serial) {
    ;
  }

  Serial.println("Initialize Ethernet with DHCP:");
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // Check for Ethernet hardware present
    if (Ethernet.hardwareStatus() == EthernetNoHardware) {
      Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
      while (true) {
        delay(1);
      }
    }
    if (Ethernet.linkStatus() == LinkOFF) {
      Serial.println("Ethernet cable is not connected.");
    }

    Ethernet.begin(mac, ip, myDns);
    Serial.print("My IP address: ");
    Serial.println(Ethernet.localIP());
  } else {
    Serial.print("  DHCP assigned IP ");
    Serial.println(Ethernet.localIP());
  }

  delay(1000);

}


void loop() {

  if (client.available()) {
    char c = client.read();
    Serial.write(c);
  }

  if (millis() - lastConnectionTime > postingInterval) {
    httpRequest();
  }

}


void httpRequest() {

  client.stop();


  if (client.connect(server, 80)) {
    Serial.println("connecting...");

    client.println("GET /api/find-ip-address/ HTTP/1.1");
    client.println("Host: www.iothook.com");
    client.println("User-Agent: arduino-ethernet");
    client.println("Connection: close");
    client.println();


    lastConnectionTime = millis();
  } else {
    Serial.println("connection failed");
  }
}

Finding location from IoT Device IP address

Finding the precise location of an IoT device based solely on its IP address can be challenging and often inaccurate. IP addresses are assigned to devices by internet service providers (ISPs) and generally provide information about the network or region to which the device is connected, rather than its physical location.

However, there are techniques that can be used to estimate the approximate location of an IP address. Here are a few methods:

1. Geolocation Databases: Some organizations maintain databases that map IP addresses to geographic locations. These databases are compiled using various sources such as user-reported data, ISP information, and publicly available data. By querying these databases, it’s possible to obtain an approximate location associated with an IP address.

2. Wi-Fi Network Mapping: In some cases, the IP address of an IoT device may be associated with a Wi-Fi network. By mapping the known locations of Wi-Fi networks, it’s possible to estimate the location of a device connected to a particular network. This method is typically more accurate in urban areas with denser Wi-Fi coverage.

3. Mobile Network Data: If the IoT device is connected to a mobile network, the IP address can provide information about the location of the mobile network’s serving gateway. However, this location may not correspond directly to the physical location of the IoT device, as mobile networks can cover large areas.

It’s important to note that these methods have limitations and may not always provide precise or reliable results. IP addresses can be dynamically assigned, and devices may connect through proxies or virtual private networks (VPNs), which can affect the accuracy of geolocation estimates.

For applications where accurate location information is crucial, IoT devices often incorporate additional positioning technologies such as GPS or triangulation using cellular tower signals to determine their precise location.

Getting Location by IoT Device IP Address with IoTHook

After finding the IP address of the IoT device, to get the Location information from the IP address https://iothook.com/api/get-ip-to-location-address/ or https://iothook.com/api/get-ip-to-location/ A GET request is sent to -address/. With the GET request, first the IoT device IP address is found, then the location is found and the location address is sent.

When a GET request is sent to IoTHook, first the IP address is found and then the location is found. The location example can be sampled in JSON format as follows. {“location”:”Yunusemre,Manisa,TR”}

/*

  Location by IoT Device IP Address
  electrocoder@gmail.com
  sahin@mesebilisim.com
  mesebilisim.com
  30.05.2023

*/

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


byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};

IPAddress ip(192, 168, 1, 177);
IPAddress myDns(192, 168, 1, 1);

EthernetClient client;

char server[] = "iothook.com";

unsigned long lastConnectionTime = 0;
const unsigned long postingInterval = 20 * 1000;

void setup() {

  Serial.begin(9600);
  while (!Serial) {
    ;
  }

  Serial.println("Initialize Ethernet with DHCP:");
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    // Check for Ethernet hardware present
    if (Ethernet.hardwareStatus() == EthernetNoHardware) {
      Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
      while (true) {
        delay(1);
      }
    }
    if (Ethernet.linkStatus() == LinkOFF) {
      Serial.println("Ethernet cable is not connected.");
    }

    Ethernet.begin(mac, ip, myDns);
    Serial.print("My IP address: ");
    Serial.println(Ethernet.localIP());
  } else {
    Serial.print("  DHCP assigned IP ");
    Serial.println(Ethernet.localIP());
  }

  delay(1000);

}


void loop() {

  if (client.available()) {
    char c = client.read();
    Serial.write(c);
  }

  if (millis() - lastConnectionTime > postingInterval) {
    httpRequest();
  }

}


void httpRequest() {

  client.stop();


  if (client.connect(server, 80)) {
    Serial.println("connecting...");

    client.println("GET /api/get-ip-to-location-address/ HTTP/1.1");
    client.println("Host: www.iothook.com");
    client.println("User-Agent: arduino-ethernet");
    client.println("Connection: close");
    client.println();


    lastConnectionTime = millis();
  } else {
    Serial.println("connection failed");
  }
}

MQTT Broker List

In this list, we have listed MQTT brokers that are open source and developed for commercial use.

Broker Service | Address | Websocket | Websocket SSL | TCP | TLS SSL |
————– | ——- | ——— | ————- | — | ——- |
iothook | iothook.com | 8083 | 8084 | 1883 | 8883 |
Mosquitto | test.mosquitto.org | 80 | 443-8081 | 1883 | 8883-8884 |
Mosquitto | iot.eclipse.org | 80 | 443 | 1883 | 8883 |
EMQX | broker.emqx.io | 8083 | 8084 | 1883 | 8883 |
Cassandana | | | | | |
Ejjaberd | | | | | |
HiveMQ | broker.hivemq.com | | 8000 | 1883 | |
mosca | test.mosca.io | 1883 | | | |
iiotmq | publicmqttbroker.iiotmq.com | | | 1883 | |
eclipse | mqtt.eclipse.org | | | 1883 | |
flespi | mqtt.flespi.io | 80 | 443 | 1883 | 8883 |
dioty | mqtt.dioty.co | 8080 | 8880 | 1883 | 8883 |
fluux | mqtt.fluux.io | | | 1883 | 8883 |
eclipse | mqtt.eclipse.org | 80 | 443 | 1883 | |
azure | Azure IoT SDKs | | 443 | | 8883 |
AWS | aws | | 443 | | 8883 |
CloudMQTT | cloudmqtt.com | | | | |
mqtthq | public.mqtthq.com | 8083 | | 1883 | |
eclipse | mqtt.eclipseprojects.io | 80 | 443 | 1883 | 8883 |