Managing Laurent Internet modules from RouterOS MikroTik

What are Mikrotik routers (MikroTik), nowadays it is known to almost everyone who is interested in network technologies a little more than just a user. Due to the reliable hardware and low cost, these routers are becoming increasingly popular not only in the professional environment of administrators of large networks, but also in office and home use. An important component of the success of this equipment among professionals and amateurs is the specialized RouterOS, ROS, common for all Mikrotik devices, a powerful operating system equipped with a convenient graphical WINBOX shell that allows you to configure the router flexibly and universally. Sometimes the capabilities of RouterOS are not limited to this ...

This article discusses the possibility of using the ROS MikroTik functionality to issue commands to KernelChip’s Laurent Internet modules that accept direct http requests through the integration of these devices into the network by creating special microprograms — ROS script functions.


image

Laurent2 Module


The Laurent2 module has “on board” a fairly rich “snap-in”, available on the terminal block pads at the edges of the board. The module includes:

  • optically isolated discrete input lines (6 pcs.)
  • powerful output discrete lines (12 pcs.)
  • analog - digital converters (for measuring voltage and connecting various sensors) -2
  • pulse counters (4 pcs.)
  • high voltage electromagnetic relays for switching various loads (4 pcs.)
  • PWM output
  • input for connecting a temperature sensor KTS-18B20
  • RS-232 serial port

Laurent112


Laurent112 looks more modest, not having the abovementioned variety of Laurent2 capabilities, but carrying “in compensation” 12 relays capable of switching the standard load of household electrical appliances.

To support these modules Mikrotik RouterOs me were written the following script functions:

FuncLaurent2REL - function with the Laurent2 relay module
FuncLaurent2OUT - function with the OUT-line module
FuncLaurent2PWM - setting power of the PWM signal
FuncLaurent2Status - Laurent2 status request
FuncLaurent112REL - function with the relay module Laurent112
FuncLaurent112Status - Laurent112 FuncPing status
request- the service function of requesting an IP address response to ping, used by all
FuncMail functions - an additional function of sending an arbitrary message to the mail.

For ease of use, the listed functions, together with some service and script examples of their call, are combined into a single file Laurent.rsc, which can be imported into the router with a terminal command

/import file=Laurent.rsc

(the import time may take from 20-30 seconds to 1 minute, depending on the performance of your Mikrotik router model).

If the Laurent script library file is not damaged and the script import to the repository is completed correctly, we will see the message “Script file loaded and executed successfully” in the console console of the WINBOX utility:

image

In addition to your existing scripts, the following should appear in the router repository: It is

image

easy to distinguish them by the label of the owner-creator (owner), where “Laurent” will be marked.

You can call Laurent functions from any other scripts as follows:
First you need to execute scripts that place the necessary functions in the form of global variables surrounded by variables of the router repository. For Laurent2 module, these are scriptsFunc_Laurent2_library , Func_Ping and Func_Mail (optional, but convenient "mail" function). For Laurent112, these are Func_Laurent112_REL , Func_Laurent112_Status , Func_Ping, and Func_Mail scripts .

These scripts can be run once, when these functions are needed. If they are used in constant work, it is convenient to launch their scripts immediately upon starting the router from the Router OS scheduler ( / system scheduler ). Or you can use the launch of a special script Laurent_START.rsc, which does everything necessary to install all the functions of both modules at once. After executing this script from WINBOX or console with the command
/system script run Laurent_START.rsc
library functions are surrounded by repository variables and part of the Jaga melody sounds.

A message is sent to the router’s log about the successful launch of the library:

image

Afterwards, you can edit the installation file so that only the functions you need are placed in the environment (respectively, the models of your Laurent board), or you can call them yourself, following the example from the text of the file Laurent_START.rsc

Now, in environment variables, we can see our functions defined in RouterOS as global variables (: global), ready for use:

image

After determining the functions you can call in your scripts, the scheduler of the router (for a scheduled performance) whether about any special cases (DHCP-server Alerts, PPP- profile scripts , etc.) announced their global-names in the calling script.

Please note that the functions of working with the relays of both modules, setting the output lines and PWM signal power of Laurent2 can only work in the “unprotected” mode of the modules. When the “protect” mode is enabled in the modules, these http commands are not executed with the corresponding error messages (see below). The status request functions of the modules work both in protected and in unprotected modes.

Consider the features and functionality of the Laurent2 module


FuncLaurent2REL - Laurent2 relay on / off / inversion

function. The function allows you to: turn on a given relay, turn off the relay, reset the relay for a given time.

The syntax of the function is as follows:

[$FuncLaurent2REL Ladr="IP-address" Lport="http-port" Rele="nRele" Action="m" Time="time s"]

where:

Ladr - IP address of the Laurent2 module on the network in the generally accepted format;

Lport - http-port module. In the current versions of all Laurent modules, only the standard http port 80 is used; no arbitrary port is configured. Therefore, the Lport parameter can be omitted;

Rele - number of the relay to which the function refers in the range from 1 to 4;

Action - an action performed on a relay. It can take the value (m) equal to 1, which is equivalent to turning on the relay (on) or 0 (off);

Time- time of action on the relay in seconds in the range allowed by the module firmware [1-255]. If not specified, the action is performed once. If the Time value is specified, then the relay is “rebooted" - the relay status changes to the time specified in the Action for Time seconds and returns to the opposite state.

The result of the function execution can be returned to the Lanswer string variable (this is the value of functions in contrast to simple commands).

For the result to be returned, you need to use the construction of the definition (: local or: global) or assigning the value (: set) to a previously defined variable, for example:

:local Lanswer [$FuncLaurent2REL Ladr="IP-address" Lport="http-port" Rele="nRele" Action="m" Time="time s"]

If the function succeeds, Lanswer will either return " DONE " or an error message will be returned. If the function succeeds, if Action = "1", the router equipped with a beeper emits one short beep. When the relay is turned off or inverted, two consecutive short beeps sound.

The following error messages can be returned by the function:

"> ERROR: rele range mismath" - if an invalid relay number is specified in the Rele variable;
"> ERROR: rele regime set mismatch" - in the case of an unspecified or incorrectly specified Action;
"> ERROR: time mismatch" - in case of an erroneous Time value (not in the range [1-255]);
"> ERROR: device not responded" - if Laurent does not respond to ping;
"> ERROR: command ROS" - in case of an error when executing the URL-command RouterOs / tool fetch (if Ladr is incorrectly set, but pinged, Lport is unreachable for service / tool fetch to a specific user Mikrotik, etc ...);
"> ERROR: device protect" - if the "device protected mode" is set and the command cannot be executed;
"> ERROR: command syntax" - syntax error in the command (* not all error options can be eliminated, script freezes may occur if the syntax is incorrect in the function, for example, if the Ladr and Lport formats are incorrectly specified or do not correspond at all)

FuncLaurent2REL function examples

Switching on relay No. 1 of Laurent2 module with IP address 192.168.0.101 with returning the response of the function to a variable:

:global FuncLaurent2REL;
:local Lanswer [$FuncLaurent2REL Ladr="192.168.0.101" Lport="80" Rele="1" Action="1"];
:if ([:find $Lanswer "DONE"]=0) do={:log warning $Lanswer}

Of course, instead of any direct values ​​of the function parameters indicated in quotation marks, you can use the Router OS variables with arbitrary names:

Invert relay No. 4 for 20 seconds without returning the response of the function:

:local LaurentIPadr "192.168.10.5"
:local LaurentRele 4
:local LTime 20
[$FuncLaurent2REL Ladr=$LaurentIPadr Lport="8021" Rele=$LaurentRele Action="1" Time=$Ltime]

The Laurent2 and Laurent112 functions can be applied to any constructs permitted by the Lua ROS language (loops, nesting, branching, etc ...).

That is, using a cycle, you can, for example, turn on all of the board's relays:

:for i from=1 to=4 do={[$FuncLaurent2REL Ladr="192.168.0.101" Lport="80" Rele=$i Action="1"];}

Or in a similar way to do group operations on i / o lines.

FuncLaurent2OUT - function for setting the status of output lines Laurent2

The function is exactly the same as the previous one. It has the same parameters, except for replacing the Rele parameter with the Line parameter, which can take values ​​in the range 1-12 (remember that Laurent2 has 12 output lines). When Action = "1" is specified, a high logic level is set on the line, while Action = "0" - low. Line inversion for a given time also works similarly to the FuncLaurent2REL function when setting the Time.

An example of a function call with setting output line No. 12 to "High level":

[$FuncLaurent2OUT Ladr=1"92.168.0.1" Line="12" Action="1"] 

The FuncLaurent2OUT function sends a “DONE” response if successful.

Error messages are similar to FuncLaurent2REL, but they report output lines:

"> ERROR: line range mismath" - if an invalid line number is specified in the Line variable;
"> ERROR: line regime set mismatch" - in case of unspecified or incorrectly specified Action;
"> ERROR: time mismatch" - in case of an erroneous Time value (not in the range [1-255]);
"> ERROR: device not responded" - if Laurent does not respond to ping;
"> ERROR: command ROS" - in case of an error when executing the RouterOs / tool fetch URL command;
"> ERROR: device protect"
"> ERROR: command syntax" - syntax error in command record.


FuncLaurent2PWM - PWM signal power adjustment

function The function sets the signal power at the PWM output, which can be used to adjust the brightness of lighting, for example, or the speed of the fan connected to this output.

The syntax of the function is as follows:

[$FuncLaurent2PWM Ladr="IP-address" Lport="http-port" PW="n(%)"]

In the PW parameter, you need to specify the power of the PWM signal in percent (without specifying the% sign), respectively, in the range 0-100.

If the PW parameter is incorrectly specified, the error "> ERROR: PWM range mismath" is generated, the remaining error messages are similar to those for FuncLaurent2REL and FuncLaurent2OUT.

FuncLaurent2Status - Laurent2 module status request

function. The function can request the full status of the module in various formats, separately for each of the parameters (all relays, all input lines, all output lines, temperature sensor readings, PWM output power, pulse counters, etc. .), as well as separately one of the elements of multi-element parameters (a specific relay or discrete line). Laurent modules allow you to request the status of the board, regardless of whether the “protect” mode is turned off or on.

The format of the function entry is as follows:

[$FuncLaurent2Status Ladr="IP-address" Lport="http-port" Type="all, xml or name" N="el. number"]

At the same time:

Ladr and Lport - IP address and http-port (port can be omitted) Laurent2 devices on the network;

Type - required parameter, which can take values ​​(systime, rele, in, out, adc1, adc2, count1, count2, count2, count4, temp, pwm) according to the technical description of the Laurent2 board. You can also set Type = "all" or Type = "xml", do not specify Type at all - it is unacceptable;

N is an optional parameter of the function. It is used only for multi-element Type (rele, in, out) and for them determines the number of the requested status element of the Type parameter (for rele N = [1-4], for out N = [1-12], for in N = [1 -6]);

Upon successful execution (without errors), the response of the function can be returned in the Lanswer variable, or in the same one-dimensional key array (if the entire status of the module is requested with Type = “all” (see below).

If Type = “xml” is set, the function returns the status the module is unchanged in the xml format given by the board. In Mikrotik RouterOS, this format is unlikely to be convenient, but this option is preserved.

With Type = "all", the function returns the full module status in the Lanswer one-dimensional key array. The status of individual elements can be extracted from it by name -keys . cops keys elements are named, respectively, a technical description of module status parameters (systime, rele, in, out , adc1, adc2, count1, count2, count2, count4, temp, pwm), where:

systime - the current system time of the module in seconds, calculated from the moment of power supply;

rele - state of the module relay in the form of a summary data line. The first character in the line corresponds to relay number 1, the second character of relay number 2, etc. 1 in the corresponding position corresponds to “relay on”, 0 - off;

in - states on all 6 discrete input lines as a summary data string. The first character in the line corresponds to line number 1, the second character line number 2, etc. “0” - a low logic level is set on the line, “1” - respectively, a high logical level;

out - similarly for 12 output lines;

adc1 - readings of channel measurements of the ADC-1 module in Volts;

adc2- readings of channel measurements of the ADC-2 module in Volts;

temp - temperature sensor readings in degrees Celsius;

count1 - value of the pulse counter No. 1, an integer in the range 0 –32766;

count2 - similarly for the other three pulse counters ...;
count3 -
count4 - ...

pwm - the output power of the signal at the PWM output. It can take values ​​from 0 to 100,
in percent.

As an example, we get the full status of the device and display only its individual parameters in the router’s log - the temperature sensor temperature (temp) and the status of all relays (rele):

Script example No. 1 of working with the FuncLaurent2Status function
:global FuncLaurent2Status;
;
#Запросить полный статус модуля Lanswer в ключевом массиве;
:local Lanswer [$FuncLaurent2Status Ladr="192.168.0.101" Type="all"];
# Выдать в лог все параметры статуса;
:log info "Полный статус Laurent2 в ключевом массиве с сортировкой по алфавиту имен-ключей:"; :log info $Lanswer;
:log info "";
;
# Выдать в лог только показания термодатчика и статус всех реле из полученного полного статуса:
:local termokey "temp"; :local relekey "rele"; :local Tsend "";
:set Tsend  ($Lanswer->$termokey); :log info ("Показания термодатчика: "."$Tsend"); :log info "";
:set Tsend  ($Lanswer->$relekey); :log info ("Строка-статус всех реле: "."$Tsend"); :log info "";
;
# Выдать в лог статус каждого реле по отдельности:
:log info ("Статус каждого реле:"."\n");
:local rezult; local Saction; :local Reletext;
:for i from=1 to 4 do {:set rezult [:pick $Tsend ($i-1) $i];
:if (rezult="0") do={:set Saction "< ВЫКЛЮЧЕНО >"} else={:set Saction "< ВКЛЮЧЕНО >"}
:log info ("Реле №"."$i"." "."$Saction"); :set Reletext ("$Reletext"."Реле №"."$i"." "."$Saction"."\n")}
:log info "";


The output of the above script to the router log:

image

* Note:

- In RouterOS, the elements of the key arrays are arranged in alphabetical order according to the names of the keys. This does not affect their selective output in any way; you can request the necessary elements of the array by name or in random order.
- The temperature sensor in this case shows -273 ° C (not connected).
- The status of all four built-in module relays (on / off) is clearly visible.

For multi-element parameters (such as rele, in or out) that contain in their line the status of all the corresponding elements, corresponding to their position number, only a certain element (the status of a specific relay, input line or output line) can be displayed. This is convenient when you need to obtain the status of individual heterogeneous parameters and elements or the status of a group of elements so as not to call the function of requesting the status of a particular element using the N parameter in the loop.

For example, from the already obtained full status of the module, we derive the state of only the input line No. 6:

# Вывод одного элемента заданного параметра;
:local numelem 6; # порядковый номер интересующего элемента в поле параметра;
:local Par ($Lanswer->"in")
:local elem [:pick $Par ($numelem-1) $numelem]
:log info $elem

You can also directly request not the full status of the board, but only the state of the desired parameter, for example, all output lines (out):

:local Lanswer [$FuncLaurent2Status Ladr="192.168.0.101" Type="out"];
:set Lanswer ("Статус всех выходных линий: "."$Lanswer");
:log info $Lanswer;

Or just one element of a multi-element parameter (let it be relay No. 7):

:local Lanswer [$FuncLaurent2Status Ladr="192.168.0.101" Type="rele" N="7"];
:log info $Lanswer;

For parameters with one element (such as temp, cont2, adc1, systime, etc.), N is not specified, and if specified, it is ignored.

For Type, for which N is possible (in, out, rele), but not specified, the status of the entire field specified in Type is returned as a string, say “0100011000” (taking into account the number of elements of this Type), where each position corresponds to a log 1 or log 0.

If a multielement parameter is requested and N is specified in the function, and it is not set correctly (N <1 or N> possible for this Type), the entire Type parameter is also rotated as a whole (an error of the wrong range N is not generated).

In case of unsuccessful login / execution, the function can log and return the following error messages to the Lanswser variable:

> ERROR: device not responded - if there is no Laurent module response to ping;
> ERROR: command ROS - in case of an error when executing the URL-command RouterOs / tool fetch;
> ERROR: TYPE MISMATCH - if the status parameter is incorrectly specified in the request (rele, out, in, all, etc. ...)

The following is an example script code that allows you to fully or selectively work with the status of the Laurent device. After analyzing the logic of his work, I hope you can write any of your own scripts requesting module status.

Script example No. 2 of working with the FuncLaurent2Status function
:global FuncLaurent2Status;
;
:local Ltype "out"; # all – вывод всего статуса или задать какой параметр статуса вывести (rele, out, temp ит.д..);
:local Npar ""; # - задать номер выводимого элемента для параметров с полем больше одного элемента или задать пусто ("");
:local PR "all"; #- задать "all" если нужно вывести все поле многоэлементного параметра или задать любое значение для вывода элемента № Npar; 
;
:local Lanswer [$FuncLaurent2Status Ladr="192.168.0.101" Lport="80" Type=$Ltype];
:if ($Lanswer=">ERROR: device protect") do={:log error "Команда не выполнена. Модуль в защищенном режиме"};
:if ([:find $Lanswer "ERROR"]=1) do={:log error $Lanswer;} else={
:local keytype [:toarray "systime, rele, in, out, adc1, adc2, count1, count2, count3, count4, temp, pwm"];
:local typepar {"systime"="1"; "rele"="4"; "in"="6"; "out"="12"; "adc1"="1"; "adc2"="1"; "count1"="1"; "count2"="1"; "count3"="1"; "count4"="1"; "temp"="1"; "pwm"="1"};
:local T; :local row; :local rezult;
:if ($Ltype="all") do={
:foreach i in=$keytype do={ :set row ($Lanswer->$i); log info ("$i"." = "."$row");}
} else={:set T ($typepar->"$Ltype");
:if ($PR="all") do={:set rezult $Lanswer} else={:set rezult ("уст. лог. ". "$[:pick $Lanswer ($Npar-1) $Npar]")}
:log info ("$Ltype"." всего "."$T"."; "."$Ltype "."$Npar".": "."$rezult");}}; :log info "";


Functions for Laurent112 Module


Laurent112 module is intended only for connecting loads, but the number of built-in relays is 12. Accordingly, to support its functionality, only two functions were created - FuncLaurent112REL relay settings and status request for FuncLaurent112Status module .

FuncLaurent112REL - the function of working with the relay of the Laurent112 module is completely similar to that for Laurent2 described above. The Rele parameter of this function can vary in the range [1-12].

FuncLaurent112Status - the Laurent112 status request function is limited to issuing only two status parameters - the system time elapsed from the power supply to the module (systime) in seconds and the relay status (rele).

Similar to the Laurent2 status request function, the FuncLaurent112Status function can display the full status of Laurent112 in the xml module format (when specifying Type = “xml”), the full status as a key array placed in Lanswer (with Type = “all”) or separately for systime and rele. For Type = "rele", the parameter N in the request is indicated in the request, indicating the relay number, the status of which must be requested. If N is not set, or is set in the wrong range of possible values ​​(from 1 to 12), the function returns a string containing the status of all relays, where the relay status is encoded with zeros (0) or units (1) in the corresponding relay number in the relay .

The format for accessing these functions and the returned error messages are similar to the corresponding functions of Laurent2 (see above).

How to use in practice the implemented integration of the Mikrotik router and Laurent Internet modules?


One of the important points of the results of integration of the Mikrotik router and the indicated Laurent Internet modules is autonomy - that is, the possibility of its existence between two network devices, none of which is a PC and each of which can work without the participation of a person (user, administrator). Moreover, the router is the main device of any local network and, as a rule, a gateway to the Internet. Given the capabilities of Router OS and the wide hardware range of RouterBoard, it’s hard to imagine all the possible applications of this integration, it all depends on the technical tasks and imagination of the applicator.

Most of the battery life of Laurent boards, after appropriate configuration, including CAT systems, can generally be performed independently.

The main applications of Laurent in integration with the Mikrotik router are the following:

  1. Protection of access to any important device, a component of the local area network for power.
  2. Turn on / off individual segments of a local or remote network (for example, a guest network, street access point)
  3. Reboot of “frozen” devices in the local network with additional control and notification from Mikrotik.
  4. "Health monitoring" of the Laurent modules themselves, individual indicators of their inputs / outputs, temperature sensor) with notification of the administrator about the events.
  5. Turning on / off household electrical appliances (lighting, heating, etc.), including according to the schedule with logging to the user by mail, services such as Telegram and to a mobile phone via SMS.

Next, we consider examples of the implementation of some of them.

1. “Physical protection” of access to an important network resource.

Suppose there is an important device in your local network that you would like to further protect against access from outside. There are a lot of network protections, as you know, for example, the port knoking method, the organization of various VPN tunnels, etc. ...
All of them are not bad, but almost all have been opened for a long time. Of course, if you are not a banker, then professionals will not hack into your network, and ordinary users, as a rule, can’t even crack light defenses.

Nevertheless, there are many facts of hacking remote desktops, file servers, etc ..., which is not very pleasant. What can our integration offer in this sense?
Mainly - the physical restriction of access to the resource over time, and this is one of the most important factors affecting the possibility of hacking the network from outside.

So, remember that all programmatic methods of network protection (for example, NAT and FIREWALL of the router itself) protect access to a network resource that is constantly working on the network.
By integrating the Mikrotik network relay (in this case, the Laurent module), you can, simply and conveniently, in addition to these protection methods, make a “physical block” of access to the device we need on the network. How to implement this?

The power supply of our protected device (for example, a secret file server with your personal archive of data about your company) is connected to one of the Laurent module relays, for example, to relay 1. We will configure any VPN server in the OS Mikrotika router, for example, one of the most popular is a pptp server . Router Oc allows you to flexibly configure individual PPP profiles for server client users (PPP-profile), individually for each VPN client or group of clients. For example, we have a configured PPP-profile for a VPN client named D_Ivanov. In addition to setting a login and password for client input and a host of other possible network settings for each PPP-profile, Router OS allows you to set the PPP-scripts “on Up” and “on Down” options, into which you can place directly executable script code.

Put the following code in these fields:

image

Then, when the D_Ivanov VPN client is connected to the router with its username and password (first level of protection), after 5 seconds, a script will be executed located on “On Up”, which, using the FuncLaurent2REL function, will enable relay No. 1 (remember that relay No. 1 the power of our “secret” file server is connected, our second stage of “physical protection”). The server’s power will be turned on, it will boot up and the client will get access to it “outside” via VPN. As soon as the VPN client breaks the tunnel (ends the session or the session is broken due to Internet traffic violations), the second script located in the “on Down” field will turn off the power of our file server and the server will become physically inaccessible. This allows the server (or some other device,

This double protection method is very effective because "Getting close" to the idle device, which is already behind the protected router, finding out its model, pinging ports is simply not possible, and it is very difficult to do this in the short time it works (after all, the cracker does not know when you decide to connect via VPN to your router). Of course, in the same fields of PPP profile scripts, you can add a code that sends messages to mail or a mobile phone about the VPN client logging in (which will additionally inform, in particular, the administrator about hacking the router’s VPN server, but not yet your secret file server! will quickly protect).

2. Turn on / off individual network segments.

Using the functions of working with relays or output lines (do not forget that you can also connect relays or relay blocks to them), you can, for example, physically turn on / off the daughter networks and subnets that are behind the router. Laurent2 module has 4 built-in relays and 12 output lines, if you use all of them (also connect relays or relay blocks to the output lines), you get 16 power outputs. Laurent112 carries 12 ready-made built-in relays. That is, having one of these Laurent modules, you can organize the separate inclusion of 16 or 12 respectively wifi access points, switches or similar network devices.
Thus, it is possible to regulate the operation of the network of an entire large office or enterprise, turning on / off, physically resetting “guest” networks, “street” access points, network bridge points, etc. And this can be done not by the network operator / administrator, but by the Mikrotik router in automatic mode, including according to a schedule or under any conditions.

For example, we turn on wifi-access point through our function. If it does not turn on, that is, it does not respond to ping, does not connect clients (this also checks our script) - turn off its power and turn on another, backup point, etc. ... This will also limit the traffic consumption and additionally ensure the security of certain network segments ( for example, street).

3. Monitoring Laurent modules and scheduled integration with Mikrotik

Since Laurent modules themselves "cannot" read time from exact time servers, scheduled work in them is very limited. Modules can only rely on their own system time, which begins the countdown from powering the board itself.
Router Mikrotik operates with a “real” daily time by date and can perform any actions in RouterOS according to an exact schedule by tracking this time with a script or in its own “scheduler” (in WINBOX it is available in the / system scheduler tab). There we can place scripts that use our Laurent module support functions by setting up the logic for them (you can “fire” when the router starts, when you start with the desired delay, at a certain time of the day, once or with regular repetition).

Using these capabilities, in addition to the CAT system of Laurent modules, you can not only manage any loads and lines, but also read the status of the module or its individual elements in RouterOS Mikrotika. Then you can make any decisions similar to the conditions of the CAT system, and also inform the administrator and users of the router about their events to their mailing addresses and / or mobile numbers via SMS. At the same time, you can use the free ability to forward a message from a mailing address to a mobile number, for example, sms.ru or the like. You can also send data from Mikrotik to Telegram bots. There are special instructions on how to configure this on the Internet.

As an example, below is the script for obtaining full status from the Laurent module with the formation of a convenient visual report and forwarding this report to the user's mail address (do not forget to replace the user address with your own in the Smail variable).

Laurent2 status request script with email report
# 
# Запрос статуса Laurent2 c отправкой на E-mail пользователя
#
;
# определяем переменные и функции
;
:global FuncMail; # - определение функции отправки почты;
:local Smail "user@mail.ru"; # - адрес почты для уведомления о выполненном запросе;
;
:global FuncLaurent2Status; # - определение функции запроса статуса Laurent2;
:local Sadr "192.168.1.101"; # - IP-адрес устройства;
:local Sport "80"; # - http-порт, если не стандартный
:local Stype "all"; # - запрашиваем полный статус
:local keytype [:toarray "systime, rele, in, out, adc1, adc2, count1, count2, count3, count4, temp, pwm"];
:local Tsend "";
;
# запросить полный статус Laurent;
;
:local Lanswer [$FuncLaurent2Status Ladr="192.168.0.101" Lport=$Sport Type=$Stype];
;
# сформировать полный отчет в переменной Mtext
;
:local Mtext; :local Stext; :local row;
:foreach i in=$keytype do={ :set row ($Lanswer->$i); :set Stext ("$i"." = "."$row"."\n"); :set Mtext ("$Mtext"."$Stext")}
;
# сформировать отдельный отчет-статус всех реле в переменной Reletext
;
:set Tsend  ($Lanswer->"rele"); :local rezult; local Saction; :local Reletext;
:for i from=1 to 4 do {:set rezult [:pick $Tsend ($i-1) $i];
:if (rezult="0") do={:set Saction "< ВЫКЛЮЧЕНО >"} else={:set Saction "< ВКЛЮЧЕНО >"}
:set Reletext ("$Reletext"."Реле №"."$i"." "."$Saction"."\n")}
;
# Выдать весь отчет в лог и отправить его по почте
;
:log info ("STATUS Laurent2 module IP "."$Sadr"."\n");
:log info $Mtext; :log info "";
:log info $Reletext;
:set Mtext ("Router "."$[/system identity get name]"." about STATUS Laurent2 module IP "."$Sadr"."\n"."\n"."$Mtext"."\n"."$Reletext");
[$FuncMail Email=$Smail Mailtext=$Mtext]


When executing the script code of the above example, a mail of the following type and content arrives at the mail.ru mail server:

image

You can improve and expand the given example of the script code as you wish.

The possibilities of implementing Mikrotik and Laurent injection are not limited to the examples described above. It is quite realistic to create almost any solutions, depending on the specific tasks of the user.

Conclusion


It is possible that during the operation of the first version of the library of scripts supporting the Laurent2 and Laurent112 modules, any errors will be detected, or users will have comments or suggestions. The author will be happy if you inform him about this, to improve the library scripts. It is also fundamentally possible to create support for other KernelChip modules that have a RJ45 network interface, for example, the JEROME Internet module.

Download library of scripts for managing Internet modules Laurent2 and Laurent112

Blog about managing Internet modules from Mikrotik Router OS



02/01/2018 Serkov Sergey Vladimirovich
serkov1375@mail.ru

Also popular now: