Skip to content

Commit

Permalink
incorporated nats scripts
Browse files Browse the repository at this point in the history
  • Loading branch information
dania-tii committed Nov 28, 2023
1 parent b04be33 commit 26709cd
Show file tree
Hide file tree
Showing 5 changed files with 117 additions and 44 deletions.
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import json
import subprocess
import threading

Expand All @@ -9,6 +10,7 @@
import asyncio
import numpy as np
import util
import nats_client
import options
from options import Options
from log_config import logger
Expand Down Expand Up @@ -172,38 +174,33 @@ def start_jamming_scripts(args, osf_ipv6_address) -> None:
raise Exception(e)


def get_device_identity(args) -> None:
async def get_device_identity() -> None:
"""
Request device identity
"""
# Store the current working directory
current_directory = os.getcwd()

try:
# Change the directory to the scripts_path
os.chdir(args.nats_scripts_path)

# Define the commands to execute
command = ["python", "_cli_command_get_identity.py"]

# Execute the command
max_retries = 3

for retry_count in range(max_retries):
try:
subprocess.run(command, check=True)
break # Break if successful
except subprocess.CalledProcessError as e:
if retry_count < max_retries - 1:
logger.error(f"Retrying _cli_command_get_identity.py...")
time.sleep(2)
else:
logger.error(f"Error executing command {command}: {e}")
exit(0)

finally:
# Change back to the original directory after executing the commands
os.chdir(current_directory)
# Connect to NATS!
nc = await nats_client.connect_nats()

cmd_dict = {"api_version": 1, "cmd": "GET_IDENTITY"}
cmd = json.dumps(cmd_dict)
rep = await nc.request("comms.identity",
cmd.encode(),
timeout=2)
logger.error(rep.data)

parameters = json.loads(rep.data.decode())
print(json.dumps(parameters, indent=2))

if "identity" in parameters["data"]:
with open("identity.py", "w") as f:
f.write(f"MODULE_IDENTITY=\"{parameters['data']['identity']}\"\n")
else:
logger.error("No identity received!")
await nc.close()
except subprocess.CalledProcessError as e:
logger.error(f"Error get_device_identity")
time.sleep(2)


def validate_configuration(args) -> bool:
Expand Down Expand Up @@ -260,8 +257,8 @@ async def main():

# Get device identity
logger.info("1. Get device identity")
get_device_identity(args)
await asyncio.sleep(3)
await get_device_identity()
await get_device_identity()

# Switch to starting frequency
logger.info("2. Switch to starting frequency")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import ssl
import os
import nats
from nats.aio.client import Client
import nats_config

client_cert = "/etc/ssl/certs/comms_auth_cert.pem"
key = "/etc/ssl/private/comms_auth_private_key.pem"
ca_cert = "/etc/ssl/certs/root-ca.cert.pem"


async def connect_nats():
if os.path.exists(client_cert) and \
os.path.exists(key) and \
os.path.exists(ca_cert):

ssl_context = ssl.create_default_context()
ssl_context.load_cert_chain(certfile=client_cert, keyfile=key)
ssl_context.load_verify_locations(cafile=ca_cert)

nats_client = await nats.connect(f"{nats_config.MODULE_IP}:{nats_config.MODULE_PORT}",
tls=ssl_context)

else:
nats_client = await nats.connect(f"{nats_config.MODULE_IP}:{nats_config.MODULE_PORT}")

return nats_client


async def connect(nats_client: Client, recon_cb=None, closed_cb=None, max_reconnection_attempts=None):
if os.path.exists(client_cert) and \
os.path.exists(key) and \
os.path.exists(ca_cert):

ssl_context = ssl.create_default_context()
ssl_context.load_cert_chain(certfile=client_cert, keyfile=key)
ssl_context.load_verify_locations(cafile=ca_cert)

await nats_client.connect(f"{nats_config.MODULE_IP}:{nats_config.MODULE_PORT}",
tls=ssl_context,
reconnected_cb=recon_cb,
closed_cb=closed_cb,
max_reconnect_attempts=max_reconnection_attempts)

else:
await nats_client.connect(f"{nats_config.MODULE_IP}:{nats_config.MODULE_PORT}",
reconnected_cb=recon_cb,
closed_cb=closed_cb,
max_reconnect_attempts=max_reconnection_attempts)

return None
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
"""
This file contains the configuration for the NATS client.
"""
try:
from identity import MODULE_IDENTITY as IDENTITY
except ImportError:
IDENTITY = "no_identity"
print("No identity found!!!!!!!!!!!!!!!!!!!!!!!!")
print("Please run _cli_command_get_identity.py to get the identity (creates identity.py)")

MODULE_IP = "10.10.20.2" # or 192.168.1.x - brlan ip address
MODULE_PORT = "4222"

# IPv6 connection example
# MODULE_IP = "[2001:db8:1234:5678:2e0:4cff:fe68:7a73]"
# MODULE_PORT = "6222"

MODULE_ROLE = "drone" # drone, sleeve or gcs
MODULE_IDENTITY = IDENTITY # messages are sent to this device
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ def __init__(self):
self.channels5: List[int] = [36, 40, 44, 48, 149, 153, 157, 161]
self.osf_interface: str = 'tun0'
self.scan_interface: str = 'wlp1s0'
self.debug: bool = True
self.debug: bool = False
self.min_rows: int = 16
self.periodic_scan: float = 60
self.periodic_recovery_switch: float = 20
Expand All @@ -21,4 +21,3 @@ def __init__(self):
# Path to JSON file containing mean and std for spectral scan data normalization
self.col_mean_std_path: str = '/opt/mesh_com/modules/sc-mesh-secure-deployment/src/2_0/features/jamming/normalization_data/cols_mean_std.json'
self.traced_model_path: str = "/opt/mesh_com/modules/sc-mesh-secure-deployment/src/2_0/features/jamming/my_traced_model.pt"
self.nats_scripts_path: str = '/opt/mesh_com/modules/sc-mesh-secure-deployment/src/nats/scripts'
31 changes: 19 additions & 12 deletions modules/sc-mesh-secure-deployment/src/2_0/features/jamming/util.py
Original file line number Diff line number Diff line change
@@ -1,34 +1,41 @@
import sys
import os
import pathlib
import random
import re
import ssl
import subprocess
import asyncio
import json
import time
from enum import Enum
from typing import Tuple

import netifaces
import numpy as np
import pandas as pd
import nats
from nats.aio.client import Client
from enum import Enum
from typing import Tuple

import nats_client
import nats_config
from options import Options
from log_config import logger

args = Options()

sys.path.append(args.nats_scripts_path)
import client
import config

# Channel to frequency and frequency to channel mapping
CH_TO_FREQ = {1: 2412, 2: 2417, 3: 2422, 4: 2427, 5: 2432, 6: 2437, 7: 2442, 8: 2447, 9: 2452, 10: 2457, 11: 2462,
36: 5180, 40: 5200, 44: 5220, 48: 5240, 52: 5260, 56: 5280, 60: 5300, 64: 5320, 100: 5500, 104: 5520,
108: 5540, 112: 5560, 116: 5580, 120: 5600, 124: 5620, 128: 5640, 132: 5660, 136: 5680, 140: 5700,
149: 5745, 153: 5765, 157: 5785, 161: 5805}

FREQ_TO_CH = {v: k for k, v in CH_TO_FREQ.items()}

# Ath10k scan features
FEATS_ATH10K = ['max_magnitude', 'total_gain_db', 'base_pwr_db', 'rssi', 'relpwr_db', 'avgpwr_db', 'snr', 'cnr', 'pn', 'ssi', 'pd', 'sinr', 'sir', 'mr', 'pr']

# Certificates
client_cert = "/etc/ssl/certs/comms_auth_cert.pem"
key = "/etc/ssl/private/comms_auth_private_key.pem"
ca_cert = "/etc/ssl/certs/root-ca.cert.pem"


class Band(Enum):
BAND_24GHZ = "2.4GHz"
Expand Down Expand Up @@ -120,13 +127,13 @@ async def switch_frequency(frequency: str) -> None:
logger.info(f"Moving to {frequency} MHz ...")

# Connect to NATS
nc = await client.connect_nats()
nc = await nats_client.connect_nats()

cmd_dict = {"frequency": frequency, "radio_index": args.radio_index}
cmd = json.dumps(cmd_dict)

try:
await nc.request(f"comms.channel_change.{config.MODULE_IDENTITY}", cmd.encode(), timeout=10)
await nc.request(f"comms.channel_change.{nats_config.MODULE_IDENTITY}", cmd.encode(), timeout=10)
logger.info(f"Published to comms.channel_change: {cmd}")
await asyncio.sleep(15)
except Exception as e:
Expand Down

0 comments on commit 26709cd

Please sign in to comment.