Wirenboard6:InstallingOnTheRemoteSite/en: различия между версиями

Материал из Wiren Board
(Новая страница: «route del default dev ppp0 2>/dev/null route add default dev ppp0 metric 100 2>/dev/null </pre> The first command removes the default gateway, in case it was crea…»)
(Новая страница: «If one of them falls, the traffic will be transmitted through the other and Vice versa. Start ping 8.8.8.8 and then remove and insert the RJ-45 plug:»)
Строка 178: Строка 178:
[[Special:MyLanguage/Файл:Two_def_gateways.png|||| ]]
[[Special:MyLanguage/Файл:Two_def_gateways.png|||| ]]


При падении одного из их трафик будет передаваться через другой и наоборот.
If one of them falls, the traffic will be transmitted through the other and Vice versa.
Запустим ping 8.8.8.8, а затем  вынем и вставим вилку RJ-45:  
Start ping 8.8.8.8 and then remove and insert the RJ-45 plug:  


[[Special:MyLanguage/Файл:Channel_switch.png|||| ]]
[[Special:MyLanguage/Файл:Channel_switch.png|||| ]]

Версия 19:24, 27 июня 2019

Другие языки:

Внимание: Отображаемое название «Wiren Board 6: Installing On The Remote Site» переопределяет ранее заданное отображаемое название «WirenBoard6:InstallingOnTheRemoteSite».


This article highlights the network aspects of professional installation of the controller in industrial and commercial facilities.


Choosing a network configuration controller

The Wiren Board 6 controllers come with a different set of network devices. It is necessary to understand in what conditions the controller will be operated and what equipment will be optimal.


Minimum equipment

Controllers Wiren Board 6 have two Ethernet-interfaces 100 Mbit/s (eth0, eth1) on board in any configuration.


Advanced features

Optionally, the controllers come with Wi-Fi interface (wlan0) (802.11 bgn 2.4 G), 3G modem (WCDMA/HSPA, GSM/GPRS/EDGE) or 2G modem (GPRS). With any of them you can connect the controller to the Internet, and with Ethernet and Wi-Fi — also connect to the local network. 3G-modem is implemented on SIMCom SIM5300E chip, 2G-modem is implemented on SIMCom SIM800 or Neoway M660A chips, Wi-Fi — on Realtek 8723BU chip.


Factory configuration of network devices

Ethernet

In the factory configuration, both Ethernet interfaces and Wi-Fi and loopback are configured in the controller. The network settings file is /etc/network/interfaces. Interfaces eth0/1 have no fixed address and get Sammie settings via DHCP.


Wi-Fi

On Wi-Fi interface wlan0 by default is the open hotpoint with the fixed address 192.168.42.1, clients receive addresses on DHCP which are distributed by dnsmasq daemon in the range of 192.168.42.50 — 192.168.42.150. The SSID of the wireless controller network is formed from the prefix “WirenBoard-” and the serial number of the controller printed on the side sticker. In a wireless network, the controller has not only an IP address, but also DNS aliases for easy connection, wiren, wiren.local, wiren_board, wirenboard.local, wirenboard.


GPRS

Cellular data connection is not enabled by default and requires configuration. The controller has slots for installation of SIM-cards, but currently the software is only supported first.

Optionally, the controller is equipped with 3G or 2G-modems (modems are non-removable and soldered on the Board at the factory).


3G-модем

The modem is represented in the system by two devices: /dev/ttyGSM (link to one of the console ports ttymxc), connected to the UART-interface of the modem chip, and a composite USB-device /dev/ttyACM0-6, used for communication ttyACM0. The limitations of the UART port do not allow to realize the full potential of data transfer rate in 3G networks (theoretically up to 7.2 Mbit/s for reception and up to 5.76 Mbps for transmission). The port ttyACM0 is limited only by the transmission speed of USB2.0 (theoretically, up to 280 Mbps).

The presence of two interfaces allows you to simultaneously use the first device (/dev/ttyGSM) to send AT-commands (to know the level of the cellular signal, send SMS, USSD-balance request etc) through minicom or gammu programs, and the second is (/dev/ttyACM0) for network communication.

hardware control in the controller is represented by turning on/off the modem through its PWRKEY input, the state of which is controlled by one of the GPIOs of the processor. For the user, the modem power management interface provides the command wb-gsm with the options on, off, reset, restart_if_broken.


2G-modem

The maximum data transfer rate in GPRS is 85.6 kbit/s, which is clearly not enough to transfer large amounts of data. The GPRS channel can be used to access the command line interface (ssh) or to send SMS. 2G modems are represented in the system by one device, /dev/ttyGSM. Simultaneous transmission of data and AT commands in the 2G modem is not implemented.


GSM-antennas

The controller is optionally equipped with one of two GSM antennas: a remote one, on a 2.5 m cable, with a gain of 3.5 dB, or - a short pin antenna screwed directly onto the SMA(female)-controller connector. When mounting the controller in metal boxes, use an external antenna. Regular antennas of the controller provide communication in conditions of good reception. In difficult radio conditions, it is necessary to purchase antennas with high gain or directional antennas. Frequency range of 3G-antennas — 1900-2100 MHz, 2G — 900/1800 MHz. Antenna cable connector — SMA(male).


Network interface configuration

Ethernet interface configuration

It is often necessary for the controller to have a permanent address on the local network. This is achieved either by configuring the DNCP server (binding the IP address to the MAC address of the network interface of the controller) or by explicitly specifying the IP address in the network settings.

Let's take a closer look at how to set a fixed address on the Ethernet interface.

For static address settings, specify the following configuration:

       
 auto eth0
 iface eth0 inet static
 address 192.0.2.7
 netmask 255.255.255.0
 gateway 192.0.2.254
 hostname Wirenboard


By default, if the address is static, the DNS servers listed in the /etc/resolv.conf file are used, and there is a symbolic link to /mnt/data/etc/resolv.conf.

You can add your DNS servers:

 nameserver 192.168.0.1
 nameserver 8.8.8.8
 nameservеr 8.8.4.4

These servers use the dnsmasq service, which serves local DNS queries on the controller. To understand what upstream server are used by dnsmasq at the moment, run the command

 service dnsmasq stop
 dnsmasq --no-daemon --log-queries
 ^C
 service dnsmasq start  

The dnsmasq program displays in the console which servers are used, for example:

 dnsmasq: using nameserver 192.168.0.1#53
 dnsmasq: using nameserver 8.8.8.8#53
 dnsmasq: using nameserver 8.8.4.4#53


Wi-Fi Setting

The settings of the access point are determined by the daemon hostapd (settings file /etc/hostapd.conf). To connect to the controller via Wi-Fi over a secure channel, write to the end of the file/etc/hostapd.conf the following configuration:

wpa=2
wpa_passphrase=your_password
wpa_key_mgmt=WPA-PSK
wpa_pairwise=TKIP CCMP
rsn_pairwise=TKIP CCMP

Restart hostapd: /etc/init.d/hostapd restart, after which connection to the controller via Wi-Fi will be possible only with the passwordyour_password.

An example of how to configure Wi_Fi adapter to connect to a local network can be found in our wiki.


PPP settings

The pppd daemon is pre-installed on the controller, which is used to create a connection to the provider's network via 3G/2G modem. The PPP daemon creates when you connect the network interface ppp (ppp0 is the default). In the factory configuration settings for the ppp0 port is commented out, and there is no connection with the mobile provider. In our Wiki we recommend using the following settings for the ppp0 interface in the /etc/network/interfacesfile:

 auto ppp0
 iface ppp0 inet ppp
 provider mts
 #Restart modem if it's frozen
 pre-up wb-gsm restart_if_broken  
 #Then wait for it to load and find the network.
 pre-up sleep 10

Even if the modem is in a hung or disconnected state, the pre-up wb-gsm restart_if_broken command will reboot the modem and make sure it is available before starting the connection. A ten-second delay (pre-up sleep 10) before connection is usually enough to establish a network connection from the first time.

String provider makes pppd find the settings file for a specific provider in the directory /etc/ppp/peers, in this example it is the file /etc/ppp/peers/mts. For compatibility reasons, this file specifies that the modem device /dev/ttyGSMshould be used as the modem device in the factory setting. If you have a 3G modem installed on your controller, replace it with a faster one /dev/ttyACM0.

To ensure that the controller does not stop trying to communicate when the connection is lost, the options in the provider settings file /etc/ppp/peers/ must be uncommented

persist
maxfail 0

The packet data Protocol parameters and connection numbers for each provider are stored in the /etc/chatscripts directory. In most cases, you do not have to change anything in these files.


PPP is for a primary and backup Internet access

The easiest way to provide access to the Internet, if ppp0 — the only WAN-interface. The ppp0 interface is configured as described above, and then, with the ifup ppp0 command, an Internet connection is established through the network of the cellular operator.

Difficulties begin when the controller is connected to Ethernet and has a default gateway in one network, and also connects to a cellular data network.

In this configuration, we are faced with the following feature: the PPP Protocol provides a point-to-point connection and does not assume a default gateway.

In the case of a PPP connection where there is no default gateway (for example, we have not connected an Ethernet cable), pppd will add the IP address of the ppp partner as the default gateway to the routing table in the system. If a default gateway is already specified, a new default gateway is not added to the routing table. And then when the main Ethernet channel falls, the Internet connection is lost, despite the active connection. In this case, you must add a second default gateway through the ppp0 interface. The metric of any new gateway must be different from the metrics available, so we explicitly specify the metric when creating a new default gateway.

To ensure failover of connections we need to provide for any procedure for raising and fall of the interfaces. The task is to provide communication regardless of the order of raising the interfaces and switching when one of them crushes.

The default gateway with metric 0 in the routing table is created for the eth0 interface, which we will consider to be the primary interface for Internet access. Set the default gateway via the ppp0 interface to 100 metric (or any metric other than 0). The daemon uses the /etc/ppp/ip-up directory to execute commands after any ppp interface is initialized.d. The name of the ppp interface is also passed to the script as command-line parameters (in our case, there is only one such interface — ppp0).

Create the add_routes script in the /etc/ppp/ip-up directory.d and make it executable (chmod +x /etc/ppp/ip-up.d/add_routes):

#!/bin/sh

route del default dev ppp0 2>/dev/null
route add default dev ppp0 metric 100 2>/dev/null

The first command removes the default gateway, in case it was created with metric 0. The second adds a default gateway with a metric of 100 for the ppp0 interface. Therefore, we have two default gateways with different metrics:

|||

If one of them falls, the traffic will be transmitted through the other and Vice versa. Start ping 8.8.8.8 and then remove and insert the RJ-45 plug:

|||

Как показал опыт, иногда возникает проблема с доступностью DNS-серверов провайдера. Для всех соединений прописываем общедоступные сервера Google и OpenDNS.

eth0: Из файла /etc/dhcp/dhclient.conf из параметра request удаляем параметр domain-name-servers, а после параметра request указываем открытые DNS-сервера Google и OpenDNS:

prepend domain-name-servers 8.8.4.4, 8.8.8.8, 208.67.222.222, 208.67.220.220;

ppp0: В директории /etc/ppp/ip-up.d создаем скрипт (и даем ему права на выполнение), который добавит DNS-сервера Google и OpenDNS в файл resolv.conf при поднятии интерфейса.

if [ ! -e /etc/resolv.conf ]; then
  : > /etc/resolv.conf
fi

#OpenDNS
printf '%s\n%s\n' "nameserver 208.67.222.222" "$(cat /etc/resolv/conf)" >/etc/resolv.conf
printf '%s\n%s\n' "nameserver 208.67.220.220" "$(cat /etc/resolv.conf)" >/etc/resolv.conf
#Google DNS
printf '%s\n%s\n' "nameserver 8.8.8.8" "$(cat /etc/resolv.conf)" >/etc/resolv.conf
printf '%s\n%s\n' "nameserver 8.8.4.4" "$(cat /etc/resolv.conf)" >/etc/resolv.conf


VPN

Для удаленного доступа к контроллеру будем использовать OpenVPN. Предполагается, что сервер уже есть и настроен, необходимо установить и настроить клиент на контроллере.

Чтобы обеспечить большую надежность, на сервере с 2 IP-адресами запускается два серверных процесса, один из которых слушает на порту 1194 TCP на IP1, а второй — на порту 1194 UDP на IP2. (Это не обязательно, вы можете использовать один серверный процесс).

На контроллере мы поднимаем 2 OpenVPN-клиента и явно задаем маршрут для IP2 через интерфейс ppp0 для одного из них.

Установка OpenVPN — стандартная, с использованием open-rsa.

Для этого на контроллере устанавливаем openvpn и easy-rsa:

apt-get install openvpn easy-rsa

Копируем

cp -R /usr/share/easy-rsa /etc/openvpn/

Копируем сертификат удостоверяющего центра ca.crt на контроллер в директорию /etc/openvpn/easy-rsa/keys

В директории /etc/openvpn/easy-rsa создаем поддиректорию keys:

mkdir keys && chmod 600 keys && cd keys

Создаем запрос на подписывание сертификата (с именем, соответствующим серийному номеру контроллера, в данном случае A7ZO7UCC):

cd /etc/openvpn/easy-rsa/
source ./vars
ln -s openssl-1.0.0.cnf openssl.cnf
./build-req A7ZO7UCC

Копируем полученный запрос A7ZO7UCC.csr на сервер в произвольную директорию и подписываем его.

cd /etc/openvpn/easy-rsa
source ./vars
./sign-req /root/certs/A7ZO7UCC

Подписанный сертификат A7ZO7UCC.crt копируем на контроллер в директорию /etc/openvpn/easy-rsa/keys.

На сервере в конфигурационном файле (/etc/vpn/server.conf) смотрим, какой файл соответствия клиент-адрес указан в параметре ifconfig-pool-persists и в этот файл добавляем адрес для клиента-контроллера из диапазона сетевых адресов, описанного в параметре server конфигурационного файла.

Например,

service openvpn stop
mcedit /etc/openvpn/ipp.txt

Добавляем строку A7ZO7UCC,10.8.0.48

service openvpn start


Для второго экземпляра сервера такую же операцию выполняем с его конфигурационными файлами, IP-адреса должны различаться, например, добавляем запись A7ZO7UCC,10.9.0.48


Конфигурационные файлы для клиента на контроллере для двух соединений будем хранить в файлах /etc/openvpn/client.conf и /etc/openvpn/client1.conf.

Содержимое файла настройки клиента:

client
dev tun
proto udp
remote vpn.mydomain.com 1194
resolv-retry infinite
nobind
persist-key
persist-tun
ca /etc/openvpn/easy-rsa/keys/ca.crt
cert /etc/openvpn/easy-rsa/keys/A7ZO7UCC.crt
key /etc/openvpn/easy-rsa/keys/A7ZO7UCC.key
remote-cert-tls server
verb 3
link-mtu 1542
keysize 128
#keysize 128 -- для совместимости с имеющимися клиентами

В файле конфигурации второго vpn-подключения сlient1.conf замените proto udp на proto tcp и укажите второй IP-адрес сервера в параметре remote.

Автозагрузка сервиса OpenVPN на контроллере включается командой:

update-rc.d openvpn defaults

Проверяем доступность сервера ping 10.8.0.1


AutoSSH

Еще одно резервное подключение к контроллеру сделаем на основе AutoSSH. Механизм работы таков: с контроллера устанавливается ssh-соединение к серверу, при этом ssh-порт контроллера пробрасывается на один из свободных портов на localhost сервера. Сервис аutossh следит за тем, что ssh-соединение не разорвано, и в случае разрыва восстанавливает его. Восстановление происходит не мгновенно — какое-то время порт, используемый на localhost сервера удерживается демоном sshd.

Устанавливаем на контроллере apt-get install autossh. Генерируем пару ключей для пользователя root:

ssh-keygen 

Пароль — пустой.

Для обслуживания удаленных подключений создаем пользователя remote на сервере с оболочкой /bin/false:

adduser --home /home/remote --shell /bin/false remote 

В файл /home/remote/.ssh/authorized_keys на сервере добавляем созданный на контроллере ключ /root/.ssh/id_rsa.pub с преамбулой

no-agent-forwarding,no-X11-forwarding,permitopen="localhost:62001"

что обеспечит дополнительную безопасность сервера при подключении контроллера. Порт 62001 — порт localhost-сервера, на который будет перенаправлен ssh-порт данного контроллера.

Первый раз подключаемся с контроллера на сервер вручную:

ssh remote@vpn.mydomain.com 

На контроллере создаем файл \etc\systemd\system\autossh.service для запуска autossh в качестве сервиса:


[Unit]
Description=Keeps an ssh tunnel to remote host open
After=network.target

[Service]
User=root
# -p [PORT]
# -l [user]
# -M 0 --> no monitoring
# -N Just open the connection and do nothing (not interactive)
# LOCALPORT:IP_ON_EXAMPLE_COM:PORT_ON_EXAMPLE_COM
ExecStart=/usr/bin/autossh  -M 0 -N -o ServerAliveInterval=15 -o ServerAliveCountMax=5 -o ExitOnForwardFailure=yes -R 62001:127.0.0.1:22 -p 22 remote@vpn.mydomain.com
#ExecStop=/usr/bin/killall -9 autossh
RestartSec=5
Restart=always

[Install]
WantedBy=multi-user.target

Включаем сервис а автозагрузку на контроллере:

systemctl enable autossh.service

После запуска сервиса мы можем подключиться к контроллеру на сервере с помощью команды

ssh 127.0.0.1 -p 62001


Передача данных с контроллера в облако

Для передачи MQTT-сообщений с контроллера в облачный сервис используется MQTT-бридж, конфигурация которого настраивается на контроллере в файле \mnt\data\etc\mosquitto\conf.d\bridge.conf

connection wb_devices_cloud.wb_A7ZO7UCC
address cloud_server.com
notifications true
notification_topic /client/wb_A7ZO7UCC/bridge_status

topic /devices/#  both 2 "" /client/wb_A7ZO7UCC
topic /config/#  both 2 "" /client/wb_A7ZO7UCC
topic /rpc/#  both 2 "" /client/wb_A7ZO7UCC

username wb_A7ZO7UCC
password your_mqtt_cloud_password

Затем выполните команду

service mosquitto restart


Если вы хотите передавать данные на несколько серверов одновременно, создайте несколько разделов connection.


Возможные неполадки GPRS-соединения

Возможных причин отсутствия GPRS-подключения может быть несколько.

  • Закончился оплаченный лимит трафика.
  • Низкий уровень сигнала, плохой контакт антенны.
  • СИМ-карты некоторых операторов рассчитаны только на 4G-сети, 3G-подключение установить с ними не получится.
  • Проверьте, правильно ли вставлена СИМ-карта в слот.
  • Возможно, СИМ-карта нерабочая.
  • Ваш тарифный план не предусматривает пакетную передачу данных.

Прежде чем идти в личный кабинет и звонить провайдеру, можно выполнить ряд простых проверок.


Запустите команду

gammu networkinfo
Network state        : home network
Network              : 250 01 (MTS, Russian Federation), LAC 18A6, CID 796B11
Name in phone        : "MTS RUS"
Packet network state : home network
Packet network       : 250 01 (MTS, Russian Federation), LAC 18A6, CID 796B11
Name in phone        : "MTS RUS"
GPRS                 : attached

Важно, что контроллер подключен к пакетной сети передачи данных

(GPRS                 : attached)

и GPRS-соединение установлено.

После этого оцените уровень сигнала в minicom командой AT+CSQ Вы получите результат в виде 13,99

Первая цифра показывает мощность сигнала: > 9 — удовлетворительный, > 14 — хороший, > 19 — отличный. Низкие и нестабильные значения CSQ означают, что антенна плохо расположена, неаккуратно подключена, радиообстановка неблагоприятная.

Если обе проверки пройдены, но связи нет, обратитесь к провайдеру (загляните в личный кабинет), можете проверить СИМ-карту в смартфоне.