Manage Internet relays from RouterOS Mikrotik via API

MikroTik RODOS-8/9/10

A handy tool for managing PDUs in MikroTik routers


MikroTik company is known as a manufacturer of network equipment, characterized by high reliability at low cost and rich functionality. Software foundation for MikroTik products is RouterOS - the network operating system based on the Linux . It runs on RouterBOARD - a large line of hardware solutions, which includes both purely operator equipment and platforms for home use. RouterOS provides the administrator / user with a great deal of ability to configure and manage the router, allowing you to operate not only with the built-in functionality of the system, but also create your own versions of almost any solutions through script programming.

In this article I will look at how you can use the advanced functionality of MikroTik routers to issue power management commands using a PDU (Internet relay) directly from a router through script functions. As a PDU, I used the OLYMP RODOS-8/9/10 Ethernet relay (devices are absolutely identical in terms of control), which remained after several projects and were “at hand”.

RouterOS PDU Management Features


The advanced functionality of RouterOS can allow:

  • Remotely turn on / off the power of devices connected to the PDU
  • Remotely manage the PDU on the occurrence of various events on the network (for example, if there is no response from any device to ping, when a specific VPN client, a wifi network client, etc., connect to the router, depending on the time) (Scheduled)
  • To notify the administrator or users about the change of the relay status on the PDU by e-mail or phone number (by SMS)

Thus, it is possible to organize, for example, control of server equipment, turn on / off / restart “stuck” network equipment, turn on cooling or heating, lighting, manage any loads allowed by nominal power as part of Smart Home, and much more that can allow Your imagination.

The ability to control Internet relays from RouterOS is provided by the fetch router command , the syntax of which is described in detail at the link at the end of the article.

PDU control via the fetch router command


The RODOS-8/9/10 PDUs support the following URL referral format:

http: // [login]: [Password] @ [IP address] [/ protect] / rb [X-1] [action] .cgi
  • Login and password - the relevant data to access the device in "protected mode" (protect)
  • IP Address — The IP address of the device on the network.
  • / protect - access key in "protected mode". If the device is set to "open" access, / protect is not specified, also does not specify the login and password
  • [action] – совершаемое действие над реле: n-включить, f-выключить, s-выдать импульс длительностью 1 сек
  • X – номер реле, к которому происходит обращение, возможные значения зависят от модели устройства:
    1. RODOS-8 – не указывается, т.к. устройство имеет единственное реле
    2. RODOS-9 – X=1 или X=2
    3. RODOS-10 – X=[1-4]

Все указанные параметры передаются без скобок [].

Thus, to solve our problem in RouterOS, to enable the first relay of our PDU, the following entry is enough:

/tool fetch url="http://[логин:пароль]@192.168.1.20/protect/rb0n"

If we want the device to return a response, we should use:

/tool fetch url="http://[логин:пароль]@192.168.1.20/protect/rb0n" mode=http dst-path="Rodosanswer.txt"; :local Rodosanswer [/file get Rodosanswer.txt contents];

The PDU response in our case is returned using the json mechanism to the Rodosanswer variable in the following form:

  • “Success! "- in case of successful command execution
  • “Fault” - when the command is not executed (as a rule, when contacting without specifying the login and password of the PDU in the URL line, if the PDU is in the “protected” mode)

We create the PDU Rodos control function in the repository of the Mikrotik router


So let's get started. Let's create a relay control function using the RODOS-10 control example in the MikroTik router scripts repository under the name "Func_RODOS10rele":

Code "Func_RODOS10rele"
################ FuncRODOS10rele ####################### Функция установки состояния реле PDU RODOS-10#         by Sergej Serkov 23.12.2017######################################################## определяем функцию, устанавливающую реле 
:global FuncRODOS10rele do={
     :local Sport "";
     :if ([:len $Rport]=0) do={:set Sport "80";} else={:set Sport $Rport;}
     :global FuncPing; :local PingAnswer [$FuncPing PingAdr=$Radr];
         :if ($PingAnswer="OK") do={
         :local Rprotect; :local Wprotect; :local Rmode "0"; :local Nrele 0; :local Act;
         :if (([:len $Rlogin]=0) and ([:len $Rpass]=0)) do={:set Rprotect ""; set Wprotect "";} else={:set Rprotect ("$Rlogin".":"."$Rpass"."@"); set Wprotect "/protect";}
         :if ($Rstatus="on") do={:set Rmode "1"; :set Act "n"}
         :if ($Rstatus="off") do={:set Rmode "1"; :set Act "f"}
         :if ($Rstatus="inv") do={:set Rmode "1"; :set Act "s"} else={}
   :if ($Rmode="1") do={
            :set Nrele ([:tonum $Rrele] - 1);
            :if (($Nrele > -1 and ($Nrele < 4)) do={
            :local StrFetchRodos; :set StrFetchRodos ("http://"."$Rprotect"."$Radr".":"."$Sport"."$Wprotect"."/rb"."$Nrele"."$Act".".cgi");
              do { [/tool fetch url=$StrFetchRodos mode=http dst-path="Rodosanswer.txt";];
                    } on-error={: log info ""; :log error ("Call ERROR function <RODOS10rele> ERROR fetch command"); 
                      :local Rodosanswer "ERROR: command ROS <fetch>"; : log info ""; :return$Rodosanswer}
                 :log info "";
                 :log warning ("Сall "."$Wprotect "."function <RODOS10rele> set rele #"."$Rrele "."is ["."$Rstatus"."]");
                 :log info "";
                 :delay 2s;
                 :local Rodosanswer [/file get Rodosanswer.txt contents];
                  /file remove Rodosanswer.txt;
                 :return$Rodosanswer;
               } else={ :log info ""; :log error ("Сall ERROR"."$Wprotect "."function <RODOS10rele> set rele#"."$Rrele"." but NUMBER RELE MISMATCH"); :log info "";
               :local Rodosanswer "ERROR: rele range mismath"; :return$Rodosanswer;}
       } else={ :log info ""; :log error ("Сall ERROR"."$Wprotect "."function <RODOS10rele> set rele#"."$Rrele"." but RELE REGIME SET MISMATCH"); :log info "";
              :local Rodosanswer "ERROR: rele regime set mismatch"; :return$Rodosanswer;}
    } else={ :log info ""; :log error ("Сall ERROR"."$Wprotect "."function <RODOS10rele> but DEVICE NOT RESPONDED"); :log info "";
       :local Rodosanswer "ERROR: device not responded"; :return$Rodosanswer;}
}

The FuncRODOS10rele function also uses in its work another small ping network address checking function - FuncPing , which should be present in the environment of the router's repository variables when the main function is running.

Code "Func_Ping"
:global FuncPing do={
:local PingCount 3; # количество пингов;
:local Result [/ping $PingAdr count=$PingCount];
:delay 2s;
:local PingAnswer "";
:local MainIfInetOk false;
:set MainIfInetOk ((3*$Result) >= (2 * $PingCount))
:put "MainIfInetOk=$MainIfInetOk"if (!$MainIfInetOk) do={
:set PingAnswer "ERROR"
}
if ($MainIfInetOk) do={
:set PingAnswer "OK"
}
:return$PingAnswer;}

Application of relay control function


As parameters of the function FuncRODOS10rele, you need to pass the following:

  • Radr - device IP address
  • Rport - http port. If the standard port for http (80) is configured, this parameter can be omitted.
  • Rrele - the number of the relay over which we perform the action (for RODOS-10 [1-4]),
    for RODOS-9 [1-2], for RODOS-8 is not transmitted)
  • Rstatus - the action to be performed (“off” —disable; “on” —include; “inv” - to give an impulse)
  • Rlogin - login, Rpass - device access password
    (if they are not set, use the command call without "/ protect")

Example 1: a function call with access to the PDU through the standard http port when the "protected mode" is turned off in the module, the inclusion of relay No. 2:
[$FuncRODOS10rele Radr="192.168.1.20" Rrele="2" Rstatus="on"]

Example 2: function call with access to the PDU via the configured http 8021 port with the “protected mode” set, relay # 2 shutdown
[$FuncRODOS10rele Radr="192.168.1.20" Rport="8021" Rrele="2" Rstatus="off" Rlogin="login" Rpass="password"]

The function response can be returned in the string variable Rodosanswer .

Rodosanswer may contain the following text:
 • "Success! " - в случае успешного обращения и исполнения команды
 • "Fault" - в случае ошибочного обращения и неисполнения команды
 • "ERROR: rele range mismatch" - в случае указания недопустимого номера реле 
	в параметре функции Rrele для данной версии устройства
 • "ERROR: rele regime set mismatch" - в случае незаданного либо неверно 
    заданного параметра функции Rstatus ("on", "off", "inv")
 • "ERROR: device not responded" - в случае отсутствия ответа от устройства 
    на пинг
 • "ERROR: command ROS <fetch>" - в случае возникновения ошибки непосредственно
    при исполнении URL-команды RouterOS fetch (как правило, при неправильно
    указанном номере порта в Rport, неправильно указанных параметрах Rlogine
    и/или Rpass)

You can call the relay control function on the PDU from any of your other scripts as follows:

  1. First you need to execute the scripts that place the necessary functions in the environment of the variables of the router repository. This can be done only once, for example, when starting a router from the RouterOS Scheduler ( / system schеduler )

    # однократно запускаем скрипт функции для ее размещения в окружении
    /system script run Func_RODOS10rele; 
    # аналогично устанавливаем в окружение функцию «FuncPing» # (используется функцией FuncRODOS10rele)
    /system script run Func_Ping; 
  2. After the functions are defined, you can use them (in particular, call FuncRODOS10rele)

    As an example, let's call our function by applying a pulse to relay No. 4 PDU RODOS-10:

    :global FuncRODOS10rele;
    :local Rodosanswer [$FuncRODOS10rele Radr="192.168.1.20" Rport="8021" Rrele="4" Rstatus="inv" Rlogin="login" Rpass="password"];
    :log info $Rodosanswer;
    

    The answer will be returned to the variable Rodosanswer and, in this case, displayed in the log of the router.

    Ready library of functions for working with PDU


    For ease of use, I created a library of functions for Rodos PDU models 8, 9, 10, and 10 DIN versions (library version 1.0 dated December 25, 2017). Library scripts are combined into the Func_RODOS.rsc file, which can be imported to RouterOS with the following WINBOX utility terminal command:

    /import file= Func_RODOS.rsc

    The import process can take from 20 seconds to 1 minute depending on the model of the Mikrotik router (its speed).
    In this case, all the scripts that were previously available in the router are not affected, the functions and scripts of the Func_RODOS library are added to the existing repository scripts.

    The library Rodos.rsc version 1.0 contains the following scripts:
    • start_RODOS – запуск этого скрипта устанавливает все функции в Окружение переменных
    • Func_Ping – функция проверки адреса на «пинг»
    • Func_Mail – функция отправки произвольного сообщения на почту администратора роутера
    • Func_RODOS8rele – функция управления реле PDU RODOS-8
    • Func_RODOS8reset – функция сброса («перезагрузки») реле PDU RODOS-8
    • Func_RODOS9rele — … аналогично для указанных моделей …
    • Func_RODOS9reset
    • Func_RODOS10rele
    • Func_RODOS10reset
    • call_example […] – примеры вызовов функций библиотеки
    • Func_RODOS_lib – все функции PDU (кроме Ping и Maйл) в одном файле-скрипте

    After importing the library, you can delete unnecessary functions and scripts from the repository, leaving only the functions of your PDU model and scripts with FuncMail and FuncPing functions.

    In the library, for each of the supported PDU models, there are also convenient reset functions ("reloads") (labeled in the names as "~ reset"). The parameters of the reload functions are the same as the parameters of the relay installation functions, except for the “Rstatus” parameter, which is not used during the “reboot” and the additional optional parameter Rtime, which defines the time in seconds between switching off and switching on the switched relay (if Rtime is not transferred to the function, the default is time 5 seconds).

    Reboot functions work as follows:
    1. The specified relay is sent a command to turn off
    2. It then waits for Rtime seconds followed by an enable command. At the same time, the reset functions refer to the corresponding relay setting functions, which must be defined before calling the first

    Thus, if prior to the reset function call, a certain relay was turned on, it will be turned off and after a specified time it is turned on again (and the load connected to it is “reset”). A similar operation is performed on the switched off relay and after the function is run, the relay becomes on (that is, in this case, the function works as a function of switching on the relay). The reset functions are conveniently used for rebooting connected to the Rodos PDU of “hung” network equipment (access points, routers, switches, various servers, etc ...).

    The source code of the Rodos.rsc library (functions and scripts — examples of accessing them) are “commented on” in sufficient detail, which may be useful for those who want to understand the work of the library in detail (and perhaps even independently modify them, or write your own version).

    In the examples of the reboot function calls after the function has been worked out, messages are sent to the administrator’s email address of the router (you can specify your email address in the script variable settings). In this case, the scripts use the RouterOS mail service from / tool e-mail , the parameters of which should be correctly configured by you in advance.

    Future plans


    In the future, the library of scripts for the Rodos PDU will be expanded - it is planned to create functions for the RODOS-16 Internet weather station, which has “on board”, in addition to the relay, I / O lines and temperature / humidity / atmospheric pressure sensors. It is also planned to implement the logging of functions not only to the log of the router and to the mail, but also to the specified phone number of the user’s choice (by sending SMS messages via the router's modem).

    It is possible that in the process of using the library by users (including readers of this material) any errors will be revealed, which, as a rule, are unavoidable during any development. All errors, comments and suggestions please inform me for their correction.

    Link to the Fetch command description for MikroTik routers
    A link to the documentation for the used PDU
    A link to the library of script functions for the PDU Rodos

    Sergey V. Serkov, 12.26.2017

Also popular now: