Project

General

Profile

aMG 4-20 mA to WIFI Data Logger

Click to visit aMG 4-20mA to WiFi Data Logger product page.

Hardware Connections

The following pictures show aMG 4-20 mA to WIFI Data Logger and its components.

Component Functions Description
A Sensor input ports aMG 4-20 mA to WIFI Data Logger consists of four channels allowing the user to connect upto four sensors simultaneously. Each channel consist of two ports namely I in and I out that should be connected to a 4-20mA signal wire. Note that correct polarity must be observed.
B Power supply ground Both ports are interconnected and should be connected to the power supply GND.
C Power supply VCC Both ports are interconnected and should be connected to the power supply VCC (9-24 VDC).
D Status LED Power status indicator. Only one (bottom right) LED is functional. Other three LED are not in service.
E WIFI Antenna Antenna input connection.
F Enclosure locks This groove on either side of the device could be used to open the casing in order to access the SD card or any other internal component.

Technical Specifications

Electrical Specifications

  • Power supply: 9 - 24 VDC
  • Minimum supply current: 100mA

WIFI Specifications

  • Protocols: 802.11 b/g/n (802.11n up to 150Mbps)
  • Frequency Range: 2.4GHz ~2.5GHz

Inputs

  • Number of channels: 4
  • Range: 4 - 20 mA

SD card slot

  • Micro SD card
  • Maximum size: upto 32GB (FAT file system)

Minimum requirements

  1. A WIFI access point to which aMG 4-20 mA to WIFI Data Logger will be connected, to sent data to a database server.
  2. A database server with RESTful API ready to receive data from aMG 4-20 mA to WIFI Data Logger.

How the device work

aMG 4-20 mA to WIFI Data Logger has two operating modes:

  1. Configuration mode
  2. Running mode

Configuration mode

aMG 4-20 mA to WIFI Data Logger always automatically enters this mode for at least 30 seconds after power up. This mode is for a user to configure aMG 4-20 mA to WIFI Data Logger as explained in Setting up the device section.

Therefore, whenever a user wants to edit configuration settings, power aMG 4-20 mA to WIFI Data Logger OFF and then ON again, by disconnecting and re-connecting the power supply, to enter configuration mode.

Running mode

When aMG 4-20 mA to WIFI Data Logger is powered on, it will enter Configuration mode automatically. The device will switch to Running mode as a result of one of the following,

  • When there is no connect to aMG 4-20 mA to WIFI Data Logger's WIFI hotspot within a 30-seconds period.
  • When a user connects to the device in Configuration mode and the configuration web page remains idle (without any mouse movement, key presses or touch input) for a period of 30 seconds.
  • Immediately after a user log-out of aMG 4-20 mA to WIFI Data Logger's WIFI hotspot.

In Running mode, aMG 4-20 mA to WIFI Data Logger will read the user defined configuration parameters and set it up accordingly. After the setup, aMG 4-20 mA to WIFI Data Logger will perform the following steps:

  1. Take measurements of ALL four input channels at the specified sample time.
  2. Convert the 4-20 mA raw readings to physical values as specified by the data conversion settings.
  3. Save both raw and converted data to the database in aMG 4-20 mA to WIFI Data Logger's SD card.
  4. Send both raw and converted data to the remote database server specified in settings.

Connect to aMG 4-20 mA to WIFI Data Logger

To configure aMG 4-20 mA to WIFI Data Logger, a user must connect to its WIFI hotspot which becomes available only in Configuration mode.
To enter Configuration mode, a user has to cycle the device power OFF then ON. The WIFI hotspot SSID for aMG 4-20 mA to WIFI Data Logger will become visible in any smartphone or computers WIFI scan.

  • The default SSID for aMG 4-20 mA to WIFI Data Logger is 4-20mA-[ device uid ]. The uid for each device can be found on the device enclosure.
  • The default password for aMG 4-20 mA to WIFI Data Logger WiFi hotspot network is 12345678

As an example, if the uid of the device is 8caab59f1d80, the SSID will be 4-20mA-8caab59f1d80.

Note: DO NOT wait until the status of the WIFI connection is set to be " Connected " in the smartphone or the notebook computer. Once WIFI connection to the device is made, enter the following IP address 192.168.10.10 in a web browser right away. The connection takes time because the host system may look for internet connection, which is not possible with aMG 4-20 mA to WIFI Data Logger.

To login to aMG 4-20 mA to WIFI Data Logger, use the following username and password.

  • Username: admin
  • Password: 1234

The current aMG 4-20 mA to WIFI Data Logger firmware does not allow changes to SSID, password, username and password.

Setting up the device

To setup aMG 4-20 mA to WIFI Data Logger, connect to it as described in Connect to aMG 4-20 mA to WIFI Data Logger.

The following configurations should be completed to setup aMG 4-20 mA to WIFI Data Logger.

  1. WIFI setting (So that aMG 4-20 mA to WIFI Data Logger can post data to database server. - Not needed if there is no need to log data to a database server.)
  2. Target server setting¶ (Specify web service API of the database server. - Not needed if there is no need to log data to a database server.)
  3. 4-20 mA conversion setting (To convert raw 4 - 20 mA measurements to meaningful physical values.)
  4. System setting (To set the measurement sample time and other parameters.)

WIFI setting

The WIFI settings can be configured using the WIFI configuration page as shown below. The user have to provide the SSID, password and other IP settings of a WIFI access point.
This feature allows aMG 4-20 mA to WIFI Data Logger to send data to any " RESTful API webservice enabled " database server that is connected to the same network.

Target server setting

The URL of the database server with RESTful API should be provided in this Target Server page

Note: If there is a secret key for the RESTful API database server, it should be provided in the Secret key section. The final URL of the server will be [ server url ]/[ secret key ]. If there is no secret key, the final server URL will be [ server url ]
If there is no database server or the target server setting is incorrect, data will not be sent to the database server and aMG 4-20 mA to WIFI Data Logger will only operate as a local data logger to its local SQLite database stored in the SD card.

4-20 mA conversion setting

This configuration section is used to define a conversion formula (in linear relationship format) that converts measured raw current data (4-20mA) to physically meaningful values. Conversion formulas are generally available and vary with sensor types. Consult the manufacturer of your sensor for this information. The configuration page is shown below.

Each channel has its own conversion setting. As an example consider the data conversion relationship of the SMC ISE30A-C6H-A pressure switch shown in the datasheet below.

If the pressure range is -0.1 - 1MPa, the required data to the above page is as below.

Note: The conversion assumes linear relationship.

System setting

This configuration page is used to setup system sample time interval, which is used for:

  1. Taking sensor readings.
  2. Logging data to the SD card.
  3. Uploading data to a database server.

This version of the firmware does not allow the setup of independent sample time for each channel. All three functions above are performed at the same sample time for all four channels.

Additionally, the two parameters setting of JSON data format, namely, organization id and table, corresponds to table name of the database server.

Note: Each sample time that the data is logged to the SD card and to the database server, the timestamp is stored in UNIX format.

Advanced topics

Example database server setup with Node Js and SQLite database

This is NodeJS example for creating a web service to store data submitted from client to SQLite database.
Client posts data to server at URL: http://localhost:8080/U4tfcUMqnwMxWrGLwNZKdWDMx2XGYfGgb2LzpZJdY6dVdQQ9ReJ377aJEBht6Rkk/insert (This url is only for local testing. http://localhost:8080 should be changed to correct URL.).
The data is in JSON format as shown below

{
  "id": "esp32",
  "table": "test_table",
  "column": [
    "c1",
    "c2" 
  ],
  "rows": [
    {
      "c1": 1,
      "c2": 982
    },
    {
      "c1": 2,
      "c2": 985
    },
    {
      "c1": 3,
      "c2": 988
    }
  ]
}

id is organization ID
table is table name
column is columns of data in rows.
rows is data to be inserted into table

**NodeJS must be installed.

To run this code:
1. extract web_service.zip
2. install sqlite3 using command: npm install sqlite3
3. start server using command: node server.js

To keep this web service running on server:
1. install pm2 on server using command npm install pm2
2. start the process using command pm2 start server.js

In web_server.zip,
./esp32/db/database.db
./server.js

In this case, the organization ID is parent folder that contains the SQLite database named database.db. Server.js is nodeJS code for creating web service.

In server.js:

const http = require('http');
const url = require('url');
const sqlite3 = require('sqlite3').verbose();

http.createServer(function(req, res){
    var qpath = url.parse(req.url, true).pathname;
    var data = "";
    res.setHeader("Access-Control-Allow-Origin", '*');
    req.on('data', chunk=> {
        data += chunk;
    }).on('end', ()=> {
        data = JSON.parse(data);
        if (qpath == '/U4tfcUMqnwMxWrGLwNZKdWDMx2XGYfGgb2LzpZJdY6dVdQQ9ReJ377aJEBht6Rkk/insert') {
            var params = [], values = [];
            data.rows.forEach(function(row) {
                params = params.concat(data.column.map(d=>row[d]));
                values = values.concat('('+data.column.map(d=>'?')+')');
            });
            var db = new sqlite3.Database("./"+data.id+"/db/database.db");
            db.run(`INSERT INTO ${data.table} (${data.column}) VALUES ${values}`, params, (err)=>{
                if(err) {
                    res.write("Failture: "+err.message);
                } else {
                    res.write("Success");
                }
                res.end();
            });
            db.close();
        } else {
            res.write(null);
            res.end();
        }
    });
}).listen(8080);

refs
https://www.npmjs.com/package/sqlite3
https://www.npmjs.com/package/pm2
https://nodejs.org/en/download/

Example database server setup with PHP and MySQL database

This is a PHP example for creating a web service to store data submitted from client to MySQL database.
Client posts data to server at URL: 127.0.0.1:8080/[work directory] (This url is only for local testing. http://l127.0.0.1:8080 should be changed to correct URL.).
The data is in JSON format as shown below

{
  "id": "esp32",
  "table": "test_table",
  "column": [
    "c1",
    "c2" 
  ],
  "rows": [
    {
      "c1": 1,
      "c2": 982
    },
    {
      "c1": 2,
      "c2": 985
    },
    {
      "c1": 3,
      "c2": 988
    }
  ]
}

id is organization ID
table is table name
column is columns of data in rows.
rows is data to be inserted into table

To install PHP and MySQL:
- on Window : https://codebriefly.com/how-to-setup-apache-php-mysql-on-windows-10/
- on Ubuntu : https://www.hostway.co.th/lamp/

To run this code:
1. Go to the working directory.
2. Start server using command: php -S 127.0.0.1:8080

In index.php:
To receive and decode posted data to query string example:

PHP service for one by one (one hardware one table)

<?php

# databaseconnect
$servername = "localhost:3306";
$username = "root";
$password = "test1234";
$dbname = "test_db";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

header('Access-Control-Allow-Origin: *');

if ($_SERVER['REQUEST_METHOD'] == "POST") {
    if ($_GET["id"] == "Du81QXQGE6uswzRxXUnagKarauJL80w6/insert") {

        # input json
        $inputJSON = file_get_contents('php://input');
        $data = json_decode($inputJSON, TRUE); //convert JSON into array

        # convert data
        $column = "";
        $values = [];
        $values_string = "";

        $column = implode(", ", $data['column']);

        foreach ($data['rows'] as $row) {
            $r = "";
            foreach ($data['column'] as $i => $col) {
                if ($i + 1 === count($data['column'])) {
                    $r .= '"' .  $row[$col] . '")';
                    array_push($values, $r);
                } else if ($i === 0) {
                    $r .= '("' . $row[$col] . '",';
                } else {
                    $r .= '"' . $row[$col] . '",';
                }
            }
        }

        $values_string = implode(", ", $values);

        # query sql
        $sql = 'INSERT INTO ' . $data['table'] . ' (' . $column . ') VALUES ' . $values_string;
        // print_r($sql);

        # insert to db mysql
        if (count((array)$data['rows'][0]) > 0) {
            if ($conn->query($sql) === TRUE) {
                echo "New record created successfully";
            } else {
                echo "Error: " . $sql . "<br>" . $conn->error;
            }
        }
    }
}

$conn->close();

PHP service more hardware for one table

<?php

# databaseconnect
$servername = "localhost:3306";
$username = "root";
$password = "test1234";
$dbname = "test_db";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
//echo 'Connected successfully';

header('Access-Control-Allow-Origin: *');

if ($_SERVER['REQUEST_METHOD'] == "POST") {
    if ($_GET["id"] == "Du81QXQGE6uswzRxXUnagKarauJL80w6/insert") {
        # input json
        $inputJSON = file_get_contents('php://input');
        $data = json_decode($inputJSON, TRUE); //convert JSON into array

        # convert data
        $column = "";
        $values = [];
        $values_string = "";

        $new_str = substr($data['table'], 11);

        array_push($data['column'], "hw_id");

        if (count((array)$data['rows'][0]) > 0) {
            for ($i = 0; $i < count($data['rows']); $i++) {
                $data['rows'][$i]['hw_id'] = $new_str;
            }
        }

        $column = implode(", ", $data['column']);

        foreach ($data['rows'] as $row) {
            $r = "";
            foreach ($data['column'] as $i => $col) {
                if ($i + 1 === count($data['column'])) {
                    $r .= '"' .  $row[$col] . '")';
                    array_push($values, $r);
                } else if ($i === 0) {
                    $r .= '("' . $row[$col] . '",';
                } else {
                    $r .= '"' . $row[$col] . '",';
                }
            }
        }

        $values_string = implode(", ", $values);

        # query sql
        $sql = 'INSERT INTO ' . substr($data['table'], 0, 10) . ' (' . $column . ') VALUES ' . $values_string;

        # insert to db mysql
        if (count((array)$data['rows'][0]) > 0) {
            if ($conn->query($sql) === TRUE) {
                echo "New record created successfully";
            } else {
                echo "Error: " . $sql . "<br>" . $conn->error;
            }
        }
    }
}

$conn->close();

. htaccess for rewrite URL


RewriteEngine On

RewriteBase /esp32_multi
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?id=$1 [L,QSA]

Default JSON format for web service messages

The JSON format of the data which sends from the device to the database server is as below.

{
   "id":"esp32",
   "table":"test_table",
   "column":[
      "datetime",
      "CH1_raw",
      "CH1_conv",
      "CH2_raw",
      "CH2_conv",
      "CH3_raw",
      "CH3_conv",
      "CH4_raw",
      "CH4_conv" 
   ],
   "rows":[
      {
         "datetime":"1606190122",
         "CH1_raw":0.000,
         "CH1_conv":0.000,
         "CH2_raw":0.000,
         "CH2_conv":0.000,
         "CH3_raw":0.000,
         "CH3_conv":0.000,
         "CH4_raw":0.000,
         "CH4_conv":0.000
      }
   ]
}
  • id: Organization ID, by default it will be esp32. This can be changed in System Configuration page in the Configuration mode.
  • table: The name of the table in the database server which the data is being inserted. This can be changed in System Configuration page in the Configuration mode.
  • column : Column names of the table in the database server. Those columns cannot be customized. Columns should be datetime , CH1_raw , CH1_conv , CH2_raw , CH2_conv , CH3_raw , CH3_conv , CH4_raw , CH4_conv
    The data types of each column as below
    • datetime: TEXT
    • CH1_raw: TEXT
    • CH1_conv: TEXT
    • CH2_raw: TEXT
    • CH2_conv: TEXT
    • CH3_raw: TEXT
    • CH3_conv: TEXT
    • CH4_raw: TEXT
    • CH4_conv: TEXT
  • rows: Includes the row data with corresponding column names. It can be an array of multiple row data.
  • datetime: datetime represents in the UNIX format.

How to upgrade device's firmware

A new firmware may be provided on the corresponding product page to improve its functionalities or fix bugs.
To upgrade the firmware, the user have to be in Configuration mode. Once logged in to the device, go to firmware upgrade page as shown below.

Then browse the provided .bin file using file explorer by clicking on ADD FILE.

Once the file is selected click on Upgrade firmware button to upgrade.

It will automatically upgrade the firmware and reboot the device once the firmware upgrade button is clicked.

How to retrieve data from the SD card

Retrieve data using DB Browser for SQLite

aMG 4-20 mA to WIFI Data Logger is shipped with a SD card that is used to store both system data and measurement data ( data_table table in database.db) in SQLite databases.

Since web services may be interrupted, the data database stored in the SD card serves as a backup and can be accessed anytime by following the steps below.

  1. Remove the SD card from the device as described in How to replace the SD card
  2. Attach the SD card to a SD card reader and connect it to the computer.
  3. Download and install DB Browser for SQLite
  4. Open DB Browser for SQLite.
  5. Click Open Database . Browse and select the .../systems/system1/database.db file in the SD card.

  6. Click the Browse Data tab and select the Table : data_table. Here you can find the saved data from the device.
  7. To use an SQL query to filter data, click Execute SQL tab, type the command and click run icon

NOTE: The data stored in SD card are always stored with UNIX timestamp. The following SQL command is an example of retrieving data using human-readable date time format.

select timestamp,CH1_raw
from data_table
where datetime(timestamp, 'unixepoch', 'localtime')
between '2020-10-22 18:15:30' and '2020-10-22 18:18:30';

Export the database as a CSV file

Measurement data is stored in data_table table of the database.db, which can be exported as a CSV file using the following steps.

  1. Open the database.db file with DB Browser for SQLite.
  2. Select File->Export->Table(s) as CSV file...
  3. Select the table: data_table and click Save .
  4. A window will pop up where you could select the name and location of the CSV file to be saved.
  5. The user could use Microsoft Excel or any other similar software to open the CSV file.

How to replace the SD card

aMG 4-20 mA to WIFI Data Logger is shipped with a SD card. To replace the SD card with a new one, perform the following steps.

  1. Format a new SD card using FAT32 file system.
  2. Follow the instructions in How to remove the SD card, to remove the SD card.
  3. Copy all files and folders from the old SD card as shown in the following picture to the new SD card. If not all files and folders appear as shown in the picture, try view hidden file in Windows Explorer setting.
  4. Insert the new SD card to the device and reattach the casing.

NOTE: All files in the SD card are important for the functionality of aMG 4-20 mA to WIFI Data Logger and are 'hidden' by default except for the database.db file. Do not manually alter the content of any files because this can break the functioning of the device. In case if any files are accidentally deleted or damaged, the user can replace everything by downloading and extracting AMG_4-20mA.7z file inside the root of the SD card. Do Not put the extracted files within a subfolder in the SD card.

How to remove the SD card

To remove the SD card:
  1. Power off the device
  2. Open the casing from point F and remove the FiO Glide ESP32 board from the main board.
  3. At the back of the FiO Glide ESP32 is where the SD card is attached. Push the SD card to remove it as shown in the follwoing picture.

Also available in: PDF HTML TXT