Controlling NetPing Devices through API Using MikroTik Routers

  • Published In: Tutorial
  • Created Date: 2017-11-01
  • Hits: 3900

To start with, let me tell you a few words about what is MikroTik. It is a Latvian manufacturer of network equipment that is distinguished by affordable price and vast functionality. Router OS is a basis for MikroTik products  it is a network operating system based on Linux. This OS also exists as an x86-distributive, so that any individual who wants to assemble a powerful router on the basis of a regular PC for an affordable price can do that. The same OS in a variety of versions is installed to RouterBOARD that is a line of hardware solutions of MikroTik that includes both operator's equipment and SOHO solutions.

MikroTik routers may be equipped with backup WAN channels that can be a GSM modem in addition to the wired Internet network. In this case, there is a possibility to launch scripts on MikroTik via SMS. This feature enables controlling NetPing devices that do not have a built-in GSM modem. Also, this feature may be urgent when a web interface of NetPing devices is unavailable via a common Ethernet network, or if a modem of a NetPing device got frozen.

As far as we know, Router OS has a huge functionality including the ability to control various functions through the script programming. Particularly, it is possible to get access from a router directly to functions of NetPing devices by the company NetPing east Co Ltd.

Settings and parameters described below can be used for all models of NetPing devices. 

General appearance of RouterOS

Such possibility is provided by the command ROS fetch, syntax of which is described in https://wiki.mikrotik.com/wiki/Manual:Tools/Fetch in details.

In within the framework of our task we have to switch a built-in relay of a NetPing device, it is enough to use the next record:

/tool fetch url="http://adress:port/relay.cgi\?rN=X" mode=http user=visor password=ping dst-path="NPanswer.txt";

Where:

adress:port is address and port of a NetPing device, for example, 192.168.0.100. If the port is a standard one - 80, it is possible not to indicate it;
N – is a relay number that depends on a model of a device (from 1 to 8);
X – the action that needs to be executed with a relay, where 1 means switch it on, 0 means switch it off;
User, password – are login and password of a NetPing administrator, default ones are indicated;
dst-path – is a file to which a response from a device will be recorded.

A response is recorded to an indicated file and looks like below:

relay_result('ok') – if the execution was successful;
relay_result('error') – if the command was not executed, for example when transferred parameters were incorrect.

So, let's start.

Let's create several self-made functions that demonstrate features of controlling a NetPing device from a MikroTik router:

  1. NPstart – setting variables for NetPing;
  2. FuncNPSetrele – setting a relay (switching on/ switching off/ changing a controlling channel);
  3. FuncNPGetrele – receiving a status of a relay state;
  4. FuncNPTermo – is a function of polling a temperature sensor;
  5. FuncNPHamidity – is a function of polling a temperature and humidity sensor

To avoid repeating the same parameters in scripts, let's create global variables that are visible for all scripts in a router:

################ NPStart #####################

# setting variables

#############################################

:global NPuser "visor"; # login of a NetPing user

:global NPpass "ping"; # password of a user

:global NPadr "192.168.0.100"; # address of a NetPing device

Then, let's write our functions:

################ FuncNPSetrele ###############

# A function of setting a relay for PDU NetPing devices

#     by Sergej Serkov 25.09.2017

#############################################
# Incoming parameters:

# Nrele – a relay number

# Rstatus – an action for a relay (1-switch on, 0-switch off)

# An example of calling a function:

# [$FuncNPSetrele Nrele="2" Rstatus="1"]

# a result of executing a function is returned in a $NPanawer variable

# let's determine the function of installing a relay:

:global FuncNPSetrele do={:global NPuser; :global NPpass; : global NPadr; :local StrFetchRele; :set StrFetchRele ("http://"."$NPadr"."/relay.cgi\?r"."$Nrele"."="."$Rstatus"); [/tool fetch url=$StrFetchRele mode=http user=$NPuser password=$NPpass dst-path="NPanswer.txt";];

:delay 2s;

:local NPanswer [/file get NPanswer.txt contents];

/file remove NPanswer.txt;

:return $NPanswer}

Now, if a function is executed with consequent assigning of the result to a variable, an action for a relay will be executed. Thus, it will be possible to read the response from a device.

An example of calling a function FuncNPSetrele:

:global FuncNPSetrele; # let's declare a function when calling it;

:local NPanswer [$FuncNPSetrele Nrele="2" Rstatus="1"]; # a relay №2 will be switched on, a response of a device is sent to a $NPanswer variable.

:log info $NPanswer; # that can be read, for example, in a log of a MikroTik router: 

When using a FuncNPSetrere function through a parameter Rstatus, it is also possible to install a channel for controlling a relay according to a documentation for a device. Values of channels are described in the next function.

############## FuncNPGetrele ###############

# a function of polling a status of a PDU NetPing relay

#     by Sergej Serkov 22.09.2017

###########################################


# Incoming parameter – a relay number Nrele

# An example of calling a function:

# [$FuncNPGetrele Nrele="2"]

# a response is returned in a $NPanswer parameter

# a function also sets the next global variables:

# -----------------------------------------------------------------------------

# $relechannel – is a source of control for a relay, according to a NetPing documentation:

# 0 - switched off manually

# 1 - switched on manually

# 2 – works from «Watchdog» channel

# 3 - a source of control is «Schedule»

# 4 - Schedule + Watchdog

# 5 – controlled by a module «Logic»

# 6 – Logic + Schedule

# relestatus – a current status of a relay:

# 0 - switched off

# 1 - switched on

# Let's define a function:

:global FuncNPGetrele do={:global NPuser; :global NPpass; global NPadr; :local StrFetchRele; :set StrFetchRele ("http://"."$NPadr"."/relay.cgi\?r"."$Nrele"); [/tool fetch url=$StrFetchRele mode=http user=$NPuser password=$NPpass dst-path="NPanswer.txt";];

:delay 2s;

:local NPanswer [/file get NPanswer.txt contents];

/file remove NPanswer.txt;

:local endLoc;

:set $endLoc [:find $NPanswer ","];

:global relechannel [:pick $NPanswer ($endLoc+2) ($endLoc+3)]; # Control channel;

:global relestatus [:pick $NPanswer ($endLoc+5) ($endLoc+6)]; # Current status;

:return $NPanswer}

Calling a function FuncNPGetrele may look like below (if we want to poll the first relay):

:global FuncNPGetrele; # do not forget to declare a function when calling it

:global relechannel; # and its operating variables

:global relestatus;

:local NPanswer [$FuncNPGetrele Nrele="1"]; # a function will be executed and a response of a device is sent to a variable $NPanswer.

:log info $NPanswer; # whch can also be read, for example, in a log of a router.

We will send to a log the information about settings and a relay status that is convenient to understand:

local R 1

:log info "";

:log info "------------------------------";

:log warning ("Реле"."$R")

:log info ("Control source: ". "$relechannel");

:if ($relestatus=0) do={:log info "Relay switched off"} else={:log info "Relay switched on"}

:log info "------------------------------";

:log info "";

Below is what we will see in a log of a router:

MikroTik log

It goes without saying control channels can be described as well. In this case, «3» - meas that the first relay is controlled by the schedule. 

################ FuncNPTermo ###############

# A function of poling a temperature sensor PDU  NetPing

#     by Sergej Serkov 25.09.2017

#############################################
# To make the function work in NPtr, there is a need to send a number of polled sensor

# A response is regularly returned in a variable $NPanswer

# An example of using the second sensor with polling:

# [$FuncNPTermo NPtr="2"]

# The function of polling a temperature sensor:

:global FuncNPTermo do={:global NPuser; :global NPpass; :local StrFetchTermo; :global NPadr; :set StrFetchTermo ("http://"."$NPadr"."/thermo.cgi?t"."$NPtr"); [/tool fetch url=$StrFetchTermo mode=http user=$NPuser password=$NPpass dst-path="NPanswer.txt";];

:delay 2s;

:local NPanswer [/file get NPanswer.txt contents];

/file remove NPanswer.txt;

:return $NPanswer}

Let's call our function and get the temperature value:

:global FuncNPTermo;

:local NPanswer [$FuncNPtermo NPtr="2"];

:log info $NPanswer; # let's display a response in a log:

i.e. a temperature value on the second sensor is 17 degrees.

Among announced plan, the onoy function left is the polling function temperature and humidity sensor combined. At the same time, to make the operation of the script correct, I had to declare a humidity sensor number as «0» (there were four 1-wire temperature sensors and one a temperature and humidity sensor combined connected to my device NetPing 4/PWR-220 v4/SMS).

################ FuncNPhumidity ###############

# Functions of polling a temperature and humidity sensor PDU  NetPing

#     by Sergej Serkov 25.09.2017

##############################################
# Input parameter Nhd "0"; # when calling a function, this variable must contain a number of a humidity sensor;

# Calling functions, respectively: [$FuncNPHtr Nhd="0"] и [$FuncNPHhd Nhd="0"]

# Returned data in variables:

# $NPhd – humidity;

# $NPtr – temperature;

# Define the function of requesting temperature from a sensor:

:global FuncNPHtr do={:global NPuser; :global NPpass; :global NPadr; :local StrFetchTR; :set StrFetchTR ("http://"."$NPadr"."/relhum.cgi?t"."$Nhd"); [/tool fetch url=$StrFetchTR mode=http user=$NPuser password=$NPpass dst-path="NPanswer.txt";];

:delay 2s;

:local NPtr [/file get NPanswer.txt contents];

/file remove NPanswer.txt;

:return $NPtr}

 # Humidity function:

:global FuncNPHhd do={:global NPuser; :global NPpass; :global NPadr; :local StrFetchHD; :set StrFetchHD ("http://"."$NPadr"."/relhum.cgi?h"."$Nhd"); [/tool fetch url=$StrFetchHD mode=http user=$NPuser password=$NPpass dst-path="NPanswer.txt";];

:delay 2s;

:local NPhd [/file get NPanswer.txt contents];

/file remove NPanswer.txt;

:return $NPhd}

Calling our functions:

:global FuncNPHtr;

:global FuncNPHhd;

:local NPtr [$FuncNPHtr Nhd="0"];

:delay 5s;

:local NPhd [$FuncNPHhd Nhd="0"];

:log info $NPtr;

:log info $NPhd;

 In a log of a router, we see sending of two requests to our sensor and two responses. The first one shows the temperature of 13 degrees, the second one shows humidity of 91%.

Log of a router Information about temperature

Therefore, the tasks that were set are solved. We can control a relay of a NetPing device directly from scripts of a router and receive values from its sensors.

Several Helpful Notes

There is a need to remember that the Router OS has service characters. If you use these characters in a password or a name of a device, then they must be screened in a script. For example, if a password is represented as a line $ergey, then there is a need to screen the first character by the symbol «\» in the script to send it correcrly. I.e. in our case, NPpass="\$ergey".

Before calling functions of NetPing, there is a need to check is a NetPing device is available in the network in the moment by testing ping. In a Router OS this is executed the next way (a script is found on the Internet and tested):

:local PingCount 3; # number of pings;

:local PingAdr $NPadr; # address of a NetPing device we'll get from NPadr

:local Iface "ether-2master"; # an interface name of you internal network;

:local Result [/ping $PingAdr count=$PingCount  interface=$Iface];

:local MainIfInetOk false;

:set MainIfInetOk ((3*$Result) >= (2 * $PingCount))

:put "MainIfInetOk=$MainIfInetOk"

if (!$MainIfInetOk) do={

/log error "NetPing device is unavailable in the network"

}

if ($MainIfInetOk) do={

/log warning "NP Connect OK"

/system script run NPstart;

… here we call necessary functions

}

Using Our Functions May Be Very Different:

  • For example, if we plug the power of your MikroTik through a NetPing relay, then a router will be able to switch itself off using a script function FuncNPSetrele when the specified critical events happen. A script with testing these events must be sent to the Scheduler of a router:

An example of switching a router off that is powered from a relay 1 of a NetPing device, when the temperature on a board of a router is exceeded:

:if ([/system health get temperature] >50) do { global Nrele "1"; $FuncNPSetrele}

A router will switch off when a temperature on a board exceeds 50 degrees. In the example the comparison is given conditionally, because the string temperature value on a board of a router received from /system health must be converted to a number.

  • In addition, it is possible to switch on any device in the network, for example, a file server, after connecting a VPN-client to a router from an external network. After a VPN session of a user is overa file server can also be swtiched off by our function. This enhances the protection of important data because a file server will be physically switched off until a VPN client does not set a connection with a server.
  • When there is no GSM modem in a certain model of a NetPing device, it is possible to use a USB modem of a router by connecting it to MikroTik for sending responses to a NetPing device via SMS.

It is possible to implement functions for other possibilities of NetPing devices, including controlling IO lines. Functions are better be united into one common library (one script) and define right after a router is loaded, and call as needed.

Block of Functions for Controlling NetPing Input-Output Lines

A block contains everything that is supported by URL-commands of work with input/output lines of NetPing devices, namely:

  • configuring the mode of a line (input/output/logic output);
  • configuring a line (logic 0, 1, line inversion);
  • a line inversion for specified time in seconds;
  • polling a line status
################ Functions NetPing Library ###############
# Library of functions for the work with the lines 
# input/output IOv2 NetPing
# version 1.0
# by Sergej Serkov 01.12.2017
######################################################

# FuncNPmodeIO - sets the operation mode of an input/output line
# FuncNPSetIO - switches on/switches off/inverts a line in the outout mode
# FuncNPinvtimeIO - inverts a line on IOtime seconds in the output mode
# FuncNPGetIO - requests a line status

# common variables for all NetPing functions
# access to a device

:global NPuser "visor"; # administrator of a NetPing-device 
:global NPpass "ping"; # password for access to a device
:global NPadr "192.168.0.100"; # address of a NetPing device;


################ FuncNPmodeIO #################
# Function of configuring an I/O line PDU NetPing
# by Sergej Serkov 01.12.2017
###############################################
# Usage:
# there is a need to transmit a number of an input/output line as parameters for the function in Nio 
# in IOmode - a set line mode (0-input; 1-output; 2-logic output)
# Calling a function
# [$FuncNPmodeIO Nio="2" IOmode="1"]
# an execution response is returned to $NPanswer

# define a function that sets a NetPing line
:global FuncNPmodeIO do={:global NPuser; :global NPpass; : global NPadr; :local StrFetchIO; 
:set StrFetchIO ("http://"."$NPadr"."/io.cgi\?io"."$Nio"."&mode="."$IOmode"); [/tool fetch url=$StrFetchIO mode=http user=$NPuser password=$NPpass dst-path="NPanswer.txt";];
:delay 2s;
:local NPanswer [/file get NPanswer.txt contents];
/file remove NPanswer.txt;
:return $NPanswer}

################ FuncNPSetIO ###############
# A function of setting the status of an I/O line PDU NetPing
# by Sergej Serkov 01.12.2017
#############################################

# a line under setup must be configured as an output line!

# usually, an inverse logic of lines is used in NetPing devices:
# a load is turned on when there is logic 0 on a line
# a load is turned off when there is logic 1 on a line
# for such devices, there is a need to uncomment commented lines
# this function, see below

# Usage:
# There is a need to transmit a number of an input/output line as parameters of the function in Nio 
# in IOstatus - a performed action (0-turn off; 1-turn on; f-invert)
# Calling a function
# [$FuncNPSetIO Nio="2" IOstatus="1"]
# a response of execution is returned to $NPanswer


# define a function that sets a NetPing line
:global FuncNPSetIO do={:global NPuser; :global NPpass; : global NPadr; :local StrFetchIO;

# invert a status line (for NetPing devices with an inverse logic);
#:if ($IOstatus=0) do={:set $IOstatus 1} else={:set $IOstatus 0}

:set StrFetchIO ("http://"."$NPadr"."/io.cgi\?io"."$Nio"."="."$IOstatus"); [/tool fetch url=$StrFetchIO mode=http user=$NPuser password=$NPpass dst-path="NPanswer.txt";];
:delay 2s;
:local NPanswer [/file get NPanswer.txt contents];
/file remove NPanswer.txt;
:return $NPanswer}


################ FuncNPinvtimeIO ###################################
# Function of inverting the status of an I/O line of PDU NetPing for certain time
# (pulse issue)
# by Sergej Serkov 01.12.2017
##################################################################

# a setup line must be configured as an output line!

# usually, an inverse logic of lines is used in NetPing devices:
# a load is turned on when there is logic 0 on a line
# a load is turned off when there is logic 1 on a line
# for such devices, there is a need to uncomment commented lines
# for this function, see below

# Usage:
# there is a need to transmit a number of an input/output line as a parameter of the function in Nio 
# in IOtime - time of inversion in seconds
# Caling a function
# [$FuncNPSetIO Nio="2" IOtime="5"]
# a response of execution is returned to $NPanswer

# define a function that sets a NetPing line
:global FuncNPinvtimeIO do={:global NPuser; :global NPpass; : global NPadr; :local StrFetchIO; 
:set StrFetchIO ("http://"."$NPadr"."/io.cgi\?io"."$Nio"."=f,"."$IOtime"); [/tool fetch url=$StrFetchIO mode=http user=$NPuser password=$NPpass dst-path="NPanswer.txt";];
:delay 2s;
:local NPanswer [/file get NPanswer.txt contents];
/file remove NPanswer.txt;
:return $NPanswer}


############## FuncNPGetIO ###############
# Function of polling a status of an I/O line of PDU NetPing
# by Sergej Serkov 01.12.2017
###########################################

# usually, in NetPing devices, an inverse logic of lines is used:
# a load is turned on when there is logic 0 on a line
# a load is turned off when there is logic 1 on a line
# for such devices, there is a need to uncomment commented lines
# for this function - see below

# Usage:
# there is a need to transmit a number of an input/output line as a parameter for the function Nio 
# For example, the second line is polled:
# [$FuncNPGetIO Nio="2"]

# returns a NetPing response to $NPanswer

# also returns as a global variable:
# -----------------------------------------------------------------------------

# IOstatus - is a line status
# 0 - turned off;
# 1 - turned on;


# define a function that returns a response from an I/O line of NetPing
:global FuncNPGetIO do={:global NPuser; :global NPpass; global NPadr; :local StrFetchIO; :set StrFetchIO ("http://"."$NPadr"."/io.cgi\?io"."$Nio"); [/tool fetch url=$StrFetchIO mode=http user=$NPuser password=$NPpass dst-path="NPanswer.txt";];
:delay 2s;
:local NPanswer [/file get NPanswer.txt contents];
/file remove NPanswer.txt;
:local endLoc;
:set $endLoc [:find $NPanswer ","];
:global IOstatus [:tonum [:pick $NPanswer ($endLoc+6) ($endLoc+7)]]; # line status;

# inverting a line status (for NetPing devices with an inverse logic);
# :if ($IOstatus=0) do={:set $IOstatus 1} else={:set $IOstatus 0}

:return $NPanswer
}

Ready Script Files

Here it is possible to download a ready file of scripts with a library of functions NetPing for a MikroTik router.

To send them to a router, there is a need to drag the file funcNetping.rsc by a mouse in router files in a popular utility for a MikroTik winbox router (or send it here by FTP).

Then, there is a need to type a command in a terminal of a router:

/import file=funcNetping.rsc
  • Func_NP_libIO.rsc - contains the library of operation functions and input-output lines in the same script and every function separately, as well as the examples of calling functions in scripts. It is recommended to use them with a NetPing IO v2 monitoring unit 
  • Func_NP_library.rsc - is a library of all functions (including the ones that were written before, such as work with relays, temperature and humidity sensors, and new sensors for work with I/O lines all in one script as a library and each function in separate scripts, plus examples of calling functions).

Functions as separate scripts for all library in one script and examples of their calling will be imported to a repository of scripts of a MikroTik router.


Author: Serkov Sergei Vladimirovich

serkov1375@mail.ru


Tags: All Devices
comments powered by Disqus