Commit 9638e441 authored by Rostislav Spinar's avatar Rostislav Spinar
Browse files

setter: remove dep of iqd-gw-01

- hosts and hostname files handled via base-config
- iqrf-gateway.json also via base-config
parent bb7617d3
DESCRIPTION = "Basic configuration for IQRF images"
LICENSE = "CLOSED"
S = "${WORKDIR}"
SRC_URI = "file://hosts \
file://hostname \
file://iqrf-gateway.json \
"
do_install_append () {
install -d ${D}${sysconfdir}
install -m 0755 ${S}/hosts ${D}${sysconfdir}
install -m 0755 ${S}/hostname ${D}${sysconfdir}
install -m 0755 ${S}/iqrf-gateway.json ${D}${sysconfdir}
}
127.0.0.1 iqube localhost
::1 iqube localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
{
"gwProduct":"IQD-GW-02A",
"gwManufacturer":"MICRORISC s.r.o.",
"gwId":"FFFFFFFFFFFFFFFF",
"gwToken":"iqube-ffffffffffffffff",
"gwHost":"iqube-ffffffffffffffff.local",
"gwImage":"iqube-yocto-v1.2.2"
}
From f77bc298f9a59268e20e9d18a8cbafe1e8e4ff87 Mon Sep 17 00:00:00 2001
From: Rostislav Spinar <rostislav.spinar@iqrf.com>
Date: Wed, 23 Dec 2020 12:00:48 +0100
Subject: [PATCH] Patch for Yocto image
---
scripts/iqrf-gateway-setter.py | 19 ++++++++++++++++---
scripts/iqrf-gateway-setter.service | 3 ---
2 files changed, 16 insertions(+), 6 deletions(-)
diff --git a/scripts/iqrf-gateway-setter.py b/scripts/iqrf-gateway-setter.py
index 21bbf9a..6a0fd0b 100644
--- a/scripts/iqrf-gateway-setter.py
+++ b/scripts/iqrf-gateway-setter.py
@@ -80,7 +80,7 @@ def change_hostname(hostname):
:type hostname: str
"""
os.system('echo iqube > /etc/hostname')
- os.system('hostname -F /etc/hostname')
+ os.system('hostname `cat /etc/hostname`')
os.system('sed -i \'s/iqdgw02-/' + 'iqube' + '/g\' /etc/hosts')
os.system('hostnamectl set-hostname %s' % 'iqube')
@@ -301,7 +301,17 @@ def systemd_stop_service(name):
os.system('systemctl stop ' + name + '.service')
+def touch(path):
+ with open(path, 'a'):
+ os.utime(path, None)
+
+
def main():
+ # don't run when we have flag set
+ if os.path.exists("/data/setter"):
+ print('Setter was started. Exit')
+ return 0
+
# wait a bit to have all services ready, safety
for i in range(10):
time.sleep(6)
@@ -348,8 +358,8 @@ def main():
set_uuid('enx001e101f0000')
# resolv.conf managed by nm (wlan0) and resolvconf (eth0)
- os.system('rm -f /etc/resolv.conf')
- os.system('ln -s /etc/resolvconf/run/resolv.conf /etc/resolv.conf')
+ #os.system('rm -f /etc/resolv.conf')
+ #os.system('ln -s /etc/resolvconf/run/resolv.conf /etc/resolv.conf')
# set daemon insId and IDE hostname and MQTT topics with client Id
os.system('sed -i \'s/iqrfgd2-default/' + hostname[:-6] + '/g\' /etc/iqrf-gateway-daemon/iqrf__JsonSplitter.json')
@@ -372,6 +382,9 @@ def main():
# copy default cfg to enable restore function
backup_configuration()
+ # create flag
+ touch("/data/setter")
+
# disable wlan0 completely, only for certification if needed, user can enable wifi on its own by webapp
# os.system('ifconfig wlan0 down')
# for module in ['xradio_wlan', 'mac80211', 'cfg80211']:
diff --git a/scripts/iqrf-gateway-setter.service b/scripts/iqrf-gateway-setter.service
index 7283da2..d026c4f 100644
--- a/scripts/iqrf-gateway-setter.service
+++ b/scripts/iqrf-gateway-setter.service
@@ -6,9 +6,6 @@ After=network.target iqrf-gateway-daemon.service rc-local.service
Type=oneshot
User=root
ExecStart=/usr/bin/python3 /usr/bin/iqrf-gateway-setter.py
-TimeoutStopSec=60
-ExecStop=/bin/systemctl stop iqrf-gateway-setter.service
-ExecStop=/bin/systemctl disable iqrf-gateway-setter.service
StandardOutput=syslog
StandardError=syslog
--
2.9.0.windows.1
#!/usr/bin/env python3
# Copyright 2018-2019 IQRF Tech s.r.o.
# 2019 MICRORISC s.r.o.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import os
import random
import time
import uuid
import netifaces
from websocket import create_connection
IQRF_GW_DIR = '/etc/'
IQRF_GW_CONFIG = IQRF_GW_DIR + 'iqrf-gateway.json'
def load_config():
"""Loads the configuration
:return: Loaded configuration
"""
with open(IQRF_GW_CONFIG, 'r') as f:
cfg = json.load(f)
return cfg
def write_config(cfg):
"""Writes the configuration
:param cfg: Configuration to write
"""
with open(IQRF_GW_CONFIG, 'w') as f:
f.seek(0)
json.dump(cfg, f)
f.truncate()
def backup_configuration():
"""Backups the critical configurations
"""
# Create directories
backup_dir = '/usr/share/iqrf-gateway/default/'
if not os.path.isdir(backup_dir):
os.makedirs(backup_dir)
if not os.path.isdir(backup_dir + 'daemon'):
os.makedirs(backup_dir + 'daemon')
if not os.path.isdir(backup_dir + 'controller'):
os.makedirs(backup_dir + 'controller')
if not os.path.isdir(backup_dir + 'nm'):
os.makedirs(backup_dir + 'nm')
# Copy GW daemon configuration
os.system('cp -rfp /etc/iqrf-gateway-daemon/* ' + backup_dir + 'daemon/')
os.system('cp -rfp /var/cache/iqrf-gateway-daemon/metaData ' + backup_dir + 'daemon/')
os.system('cp -rfp /var/cache/iqrf-gateway-daemon/scheduler ' + backup_dir + 'daemon/')
# Copy GW controller configuration
os.system('cp -rfp /etc/iqrf-gateway-controller/* ' + backup_dir + 'controller/')
# Copy NetworkManager configuration
os.system('cp -fp /etc/NetworkManager/NetworkManager.conf ' + backup_dir + 'nm/')
os.system('cp -rfp /etc/NetworkManager/system-connections ' + backup_dir + 'nm/')
def change_hostname(hostname):
"""
Changes the hostname
:param hostname: Hostname
:type hostname: str
"""
os.system('hostname `cat /etc/hostname`')
os.system('hostnamectl set-hostname %s' % 'iqube')
def configure_tr(ws):
"""Configures coordinator
:param ws: WebSocket client
"""
for i in range(3):
ws.settimeout(10)
ws.send(create_write_tr_json_req(0, 7, 7))
try:
response = json.loads(ws.recv())
print(response)
break
except Exception:
print('Receive timeout, %d' % i)
continue
# only if write tr is ok
if response['data']['status'] == 0 and response['data']['rsp']['restartNeeded']:
for i in range(3):
ws.settimeout(10)
ws.send(create_iqrf_json_req('iqrfEmbedOs_Restart', 0))
try:
json_rst_restart_rsp = json.loads(ws.recv())
print(json_rst_restart_rsp)
break
except Exception:
print('Receive timeout, %d' %i)
continue
def create_iqrf_json_req(m_type, addr):
"""Creates IQRF JSON request
:param m_type: Message type
:type m_type: str
:param addr: Network address
:type addr: int
:return: IQRF JSON request
"""
request = {
'mType': m_type,
'data': {
'msgId': str(uuid.uuid4()),
'req': {
'nAdr': addr,
'param': {}
},
'returnVerbose': True
}
}
return json.dumps(request)
def create_write_tr_json_req(addr, tx_power, rx_filter):
"""Creates IQRF IQMESH Write TR JSON request
:param addr: Network address
:type addr: int
:param tx_power: TX power
:type tx_power: int
:param rx_filter: RX filter
:type rx_filter: int
:return: IQRF IQMESH JSON request
"""
request = {
'mType': 'iqmeshNetwork_WriteTrConf',
'data': {
'msgId': str(uuid.uuid4()),
'req': {
'deviceAddr': addr,
'txPower': tx_power,
'rxFilter': rx_filter
},
'returnVerbose': True
}
}
return json.dumps(request)
def generate_cert():
"""Generates self-signed certificate
"""
daemon_path = '/etc/iqrf-gateway-daemon/certs/core/'
webapp_path = '/etc/iqrf-gateway-webapp/certs/'
if not os.path.isdir(daemon_path):
os.makedirs(daemon_path)
files = ['cert.pem', 'privkey.pem']
for file in files:
if os.path.exists(daemon_path + file):
os.remove(daemon_path + file)
if os.path.exists(webapp_path + file):
os.remove(webapp_path + file)
os.system('openssl ecparam -name secp384r1 -genkey -param_enc named_curve -out ' + daemon_path + '/privkey.pem')
os.system('openssl req -new -x509 -sha256 -nodes -days 3650 '
'-subj "/CN=IQRF Gateway/C=CZ/ST=Hradec Kralove Region/L=Jicin/O=IQRF Tech s.r.o." '
'-key ' + daemon_path + '/privkey.pem -out ' + daemon_path + '/cert.pem')
for file in files:
os.chmod(daemon_path + file, 600)
os.system('ln -s ' + daemon_path + file + ' ' + webapp_path + file)
def generate_gwid(ws):
"""Generates GW ID from MAC and MIC of coordinator
:param ws: Websocket client
:return: GW ID or 1 for NO json rsp value
"""
address = netifaces.ifaddresses('eth0')[netifaces.AF_LINK]
mac = address[0]['addr'].replace(':', '')
for i in range(12):
ws.settimeout(10)
ws.send(create_iqrf_json_req('iqrfEmbedOs_Read', 0))
try:
response = json.loads(ws.recv())
print(response)
break
except Exception:
print('Receive timeout, %d' % i)
continue
# only if os read is ok
if response['data']['status'] == 0:
mid = response['data']['rsp']['result']['mid']
mid12 = mid & 0xffff
# mid2 = (mid & 0xff00) >> 8
# mid3 = mid & 0xff0000
# mid4 = mid & 0xff000000
return mac[:6] + format(mid12, '04x') + mac[6:]
else:
# otherwise generate random
#n1 = random.randrange(0, 256, 2)
#n2 = random.randrange(0, 256, 2)
#rn = (n2 << 8) + n1
#return mac[:6] + format(rn, '04x') + mac[6:]
# no status ok
return 1
def generate_token(id):
"""Generates token from gwId
:param id: Gateway id
:type id: str
"""
left1 = id[0:3]
left2 = id[4:7]
left3 = id[8:11]
left4 = id[12:15]
return left2 + left4 + left3 + left1
def set_mac_uuid(interface):
"""Sets MAC and UUID
:param interface: Interface name
:type interface: str
"""
config = '/etc/NetworkManager/system-connections/' + interface
uuid_iface = os.popen('uuidgen ' + interface).read().rstrip()
os.system('sed -i \'s/uuid=/uuid=' + uuid_iface + '/g\' ' + config)
address = netifaces.ifaddresses(interface)[netifaces.AF_LINK]
mac = address[0]['addr']
os.system('sed -i \'s/mac-address=/mac-address=' + mac + '/g\' ' + config)
def set_uuid(interface):
"""Sets UUID
:param interface: Interface name
:type interface: str
"""
config = '/etc/NetworkManager/system-connections/' + interface
uuid_iface = os.popen('uuidgen ' + interface).read().rstrip()
os.system('sed -i \'s/uuid=/uuid=' + uuid_iface + '/g\' ' + config)
def systemd_disable_service(name):
"""Disables the systemd service
:param name: Service name
:type name: str
"""
os.system('systemctl disable ' + name + '.service')
def systemd_restart_service(name):
"""Restarts the systemd service
:param name: Service name
:type name: str
"""
os.system('systemctl restart ' + name + '.service')
def systemd_stop_service(name):
"""Stops the systemd service
:param name: Service name
:type name: str
"""
os.system('systemctl stop ' + name + '.service')
def touch(path):
"""Creates flag file
:param name: Path
:type name: str
"""
with open(path, 'a'):
os.utime(path, None)
def main():
# don't run when we have flag set
if os.path.exists("/data/setter/bootpart"):
print('Setter was started. Exit')
return 0
# wait a bit to have all services ready, safety
for i in range(10):
time.sleep(6)
try:
ws = create_connection("ws://localhost:1338")
print('Connected.')
break
except Exception:
ws = None
print('Receive timeout, %d' % i)
if ws is None:
print('Not connected.')
return 1
gwid = generate_gwid(ws)
print('gwId: %s' % gwid)
if gwid == 1:
return 1
gwtoken = generate_token(gwid)
print('gwToken: %s' % gwtoken)
# set id, token, host
cfg = load_config()
cfg['gwId'] = gwid.upper()
cfg['gwToken'] = "iqube-" + gwtoken
cfg['gwHost'] = "iqube-" + gwid + ".local"
print('Setting gwId, gwToken and gwHost')
write_config(cfg)
# set hostname
hostname = cfg['gwHost']
change_hostname(hostname)
# set token
token = cfg['gwToken']
os.system('echo ' + token + ' > /etc/gwman/customer_id')
# network manager
set_mac_uuid('eth0')
os.system('nmcli connection up eth0')
os.system('nmcli connection delete Wired\\ connection\\ 1')
#set_mac_uuid('wlan0')
set_uuid('enx001e101f0000')
os.system('nmcli connection up enx001e101f0000')
os.system('nmcli connection delete Wired\\ connection\\ 2')
# set daemon insId and IDE hostname and MQTT topics with client Id
os.system('sed -i \'s/iqrfgd2-default/' + hostname[:-6] + '/g\' /etc/iqrf-gateway-daemon/iqrf__JsonSplitter.json')
# set to iqube
#os.system('sed -i \'s/iqdgw02-/' + hostname[:-6] + '/g\' /etc/iqrf-gateway-daemon/iqrf__IdeCounterpart.json')
os.system('sed -i \'s/iqdgw02-/' + hostname[-22:-6] + '/g\' /etc/iqrf-gateway-daemon/iqrf__MqttMessaging.json')
# configure tr via daemon websocket, txPower 7, rxFilter 7
configure_tr(ws)
ws.close()
# regenerate certificate
generate_cert()
#timezone setting
os.system('timedatectl set-timezone Europe/Prague')
# restart services
for service in ['avahi-daemon', 'resolvconf', 'NetworkManager', 'iqrf-gateway-daemon', 'nginx', 'gwman-client']:
systemd_restart_service(service)
time.sleep(1)
# copy default cfg to enable restore function
backup_configuration()
# create flag, do not run again
touch("/data/setter/bootpart")
# disable wlan0 completely, only for certification if needed, user can enable wifi on its own by webapp
# os.system('ifconfig wlan0 down')
# for module in ['xradio_wlan', 'mac80211', 'cfg80211']:
# os.system('rmmod ' + module)
return 0
if __name__ == "__main__":
main()
[Unit]
Description=IQRF Gateway Setter
After=network.target iqrf-gateway-daemon.service rc-local.service
[Service]
Type=simple
User=root
ExecStart=/usr/bin/python3 /usr/bin/iqrf-gateway-setter.py
StandardOutput=syslog
StandardError=syslog
[Install]
WantedBy=multi-user.target
LICENSE = "Apache-2.0"
DESCRIPTION = "Basic setting for IQRF images"
LICENSE = "CLOSED"
RDEPENDS_${PN} = "python3 python3-netifaces python3-websocket-client python3-paho-mqtt python3-posix-ipc python3-six util-linux-uuidgen openssl-bin"
inherit systemd
require recipes-iqrf/iqd-gw-01/iqd-gw-01.inc
SYSTEMD_SERVICE_${PN} = "iqrf-gateway-setter.service"
SRC_URI_append = " file://0001-Setter-yocto-fixes.patch \
SRC_URI_append = "file://iqrf-gateway-setter.py \
file://iqrf-gateway-setter.service \
"
S = "${WORKDIR}/iqd-gw-01"
S = "${WORKDIR}"
FILES_${PN} += "/usr/bin/* /usr/share/*"
......@@ -20,14 +18,12 @@ do_compile[noexec] = "1"
do_install() {
install -d ${D}${systemd_unitdir}/system
install -m 644 ${S}/scripts/iqrf-gateway-setter.service ${D}${systemd_unitdir}/system/
install -m 644 ${S}/iqrf-gateway-setter.service ${D}${systemd_unitdir}/system/
install -d ${D}${bindir}
install -m 644 ${S}/scripts/iqrf-gateway-setter.py ${D}${bindir}
install -d ${D}${sysconfdir}
install -m 644 ${S}/conf/hosts ${D}${sysconfdir}
install -m 644 ${S}/conf/iqrf-gateway-iqube-yocto.json ${D}${sysconfdir}/iqrf-gateway.json
install -m 644 ${S}/iqrf-gateway-setter.py ${D}${bindir}
install -d ${D}/usr/share/iqrf-gateway
}
SYSTEMD_SERVICE_${PN} = "iqrf-gateway-setter.service"
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment