📜 ⬆️ ⬇️

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. The software foundation for MikroTik products is RouterOS , a Linux-based network operating system. 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:


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] - performed action on the relay: n-turn on, f-turn off, s-give a pulse of 1 sec duration
  • X is the number of the relay that is accessed, the possible values ​​depend on the device model:
    1. RODOS-8 - not specified, because the device has a single relay
    2. RODOS-9 - X = 1 or X = 2
    3. RODOS-10 - X = [1-4]

All specified parameters are passed without brackets [].

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:


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:


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!" - in the case of successful treatment and execution of the command

  • "Fault" - in case of erroneous handling and non-execution of the command

  • "ERROR: rele range mismatch" - in case of specifying an invalid relay number 
	 in the Rrele function parameter for this device version

  • "ERROR: rele set set mismatch" - in case of unspecified or incorrect 
     the specified parameter of the function Rstatus ("on", "off", "inv")

  • "ERROR: device not responded" - in case of no response from the device 
     on ping

  • "ERROR: command ROS <fetch>" - in case of an error directly
     when executing the RouterOS fetch URL command (as a rule, when
     the specified port number in Rport, incorrectly specified Rlogine parameters
     and / or 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 - running this script sets all functions in the environment of variables
    • Func_Ping - the function of checking the address to "ping"
    • Func_Mail - the function of sending an arbitrary message to the mail of the administrator of the router
    • Func_RODOS8rele - PDU RODOS-8 relay control function
    • Func_RODOS8reset - reset function ("reset") relay PDU RODOS-8
    • Func_RODOS9rele - ... similarly for the models mentioned ...
    • Func_RODOS9reset
    • Func_RODOS10rele
    • Func_RODOS10reset
    • call_example [...] - examples of library function calls
    • Func_RODOS_lib - all PDU functions (except Ping and Mail) in one script file

    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, before calling the reset function, a certain relay was turned on, it will be turned off and after a specified time it is turned back on (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
    Link to the documentation for the PDUs used
    Link to Rodos PDU script library

    Serkov Sergey Vladimirovich, 12.26.2017

Source: https://habr.com/ru/post/410107/