Read a Modbus TCP Slave Sensor and send an alarm email

This SDK Script will read out a Integer Register at Modbus TCP Slave Temperatur Sensor. If the Temperatur is above a define threshold we will send out a alarm email.

Device Setup

The thermometer is connected to the NB1600 via Ethernet.

Please also define a email smtp account in the serivces→Email Page

Modbus Config

According to the Manual auf the TH2E the Integer Value is stored in the Register 0x0001. The Value stores also the first decimal digit. Therefore we need to devide the value by 10.

SDK Script

Use the Script with a periodicle Trigger, based on your needs. The script will be execute after than and in case the temperatur is over a specified threshold a email will be send out.

Configuration

The Script needs to be configured for your Installation. Customize the email adress where the alarm email is send to. Please define the IP of the Modbus Sensor, the threshold temperatur and the Modbus Register to read from.

modbus-temp-alarm.are
/* DESC: This Script reads a temperature at a modbus sensor and send a alarm in case a threshold temp is reached
 * Copyright (C) 2017 NetModule AG, Switzerland
 */
 
// Email Setting
EMAILTO="my@alarm.de";
EMAILSUBJECT="Temperature Alarm";
 
//Alarming Setting
MAXTEMP=38; 
 
//The Modbus Sensor we read from
MBHOST="192.168.1.253";
MBPORT=502;
// The Register to read from
MBREGISTER=1;

The Script

Please paste the script below into the sdk script Webpage of your router.

modbus-temp-alarm.are
/* DESC: This Script reads a temperature at a modbus sensor and send a alarm in case a threshold temp is reached
 * Copyright (C) 2017 NetModule AG, Switzerland
 */
 
// Email Setting
EMAILTO="my@alarm.de";
EMAILSUBJECT="Temperature Alarm";
 
//Alarming Setting
//lets Monitor a fridge
MAXTEMP=7; 
 
//The Modbus Sensor we read from
MBHOST="192.168.1.253";
MBPORT=502;
// The Register to read from
MBREGISTER=1;
 
 
 
 
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock < 0) {
    print("unable to open socket\n");
    exit(1);
}
 
if (connect(sock, MBHOST, MBPORT) < 0){
    printf("Could not connect to %s (port %d)\n", MBHOST, MBPORT);
    close(sock);
    exit(1);
}
 
// Register the socket to the Modbus subsystem
nb_modbus_register(sock,MODBUS_TYPE_TCP);
 
// Get the Value from Modbus Sensor, we only request 1 address
payload=nb_modbus_read_input_regs(sock, MBREGISTER,1);
if (length(payload)==1) {
    // lets devide the Temperatur by 10 to get a float value
    temp=(float) payload[0] / 10;
    if (temp>MAXTEMP) {
        nb_syslog("We have a high temperature: %2.2f° C. Sending alarm email",temp);   
        ret = nb_email_send(EMAILTO, EMAILSUBJECT, sprintf("Alarm. Temperatur is to high: %2.2f° C",temp));
        if (ret == 0) {
            nb_syslog("Successfully sent E-Mail to %s", EMAILTO);
        } else {
            nb_syslog("Unable to send E-Mail");
        }
 
}
 
 
  }
nb_modbus_unregister(sock);
close(sock);    
exit(0);