Пример #1
0
  def __init__(self):
    self.argparser = argparse.ArgumentParser(
      fromfile_prefix_chars="@",
      description="Test throughput over 2 serial D7 modems"
    )

    self.argparser.add_argument("-n", "--msg-count", help="number of messages to transmit", type=int, default=10)
    self.argparser.add_argument("-p", "--payload-size", help="number of bytes of (appl level) payload to transmit", type=int, default=50)
    self.argparser.add_argument("-sw", "--serial-transmitter", help="serial device /dev file transmitter node", default=None)
    self.argparser.add_argument("-sr", "--serial-receiver", help="serial device /dev file receiver node", default=None)
    self.argparser.add_argument("-r", "--rate", help="baudrate for serial device", type=int, default=115200)
    self.argparser.add_argument("-uid", "--unicast-uid", help="UID to use for unicast transmission, "
                                                              "when not using receiver "
                                                              "(in hexstring, for example 0xb57000009151d)", default=None)
    self.argparser.add_argument("-to", "--receiver-timeout", help="timeout for the receiver (in seconds)", type=int, default=10)
    self.argparser.add_argument("-v", "--verbose", help="verbose", default=False, action="store_true")
    self.config = self.argparser.parse_args()

    configure_default_logger(self.config.verbose)

    if self.config.serial_transmitter == None and self.config.serial_receiver == None:
      self.argparser.error("At least a transmitter or receiver is required.")

    if self.config.serial_receiver == None and self.config.unicast_uid == None:
      self.argparser.error("When running without receiver a --unicast-uid parameter is required.")

    if self.config.serial_transmitter == None:
      self.transmitter_modem = None
      print("Running without transmitter")
    else:
      self.transmitter_modem = Modem(self.config.serial_transmitter, self.config.rate, None)
      access_profile = AccessProfile(
        channel_header=ChannelHeader(channel_band=ChannelBand.BAND_868,
                                     channel_coding=ChannelCoding.PN9,
                                     channel_class=ChannelClass.NORMAL_RATE),
        sub_profiles=[SubProfile(subband_bitmap=0x01, scan_automation_period=CT(exp=0, mant=0)), SubProfile(), SubProfile(), SubProfile()],
        sub_bands=[SubBand(
          channel_index_start=0,
          channel_index_end=0,
          eirp=10,
          cca=86 # TODO
        )]
      )

      print("Write Access Profile")
      write_ap_cmd = Command.create_with_write_file_action_system_file(file=AccessProfileFile(access_profile=access_profile, access_specifier=0))
      self.transmitter_modem.execute_command(write_ap_cmd, timeout_seconds=1)

    if self.config.serial_receiver == None:
      self.receiver_modem = None
      print("Running without receiver")
    else:
      self.receiver_modem = Modem(self.config.serial_receiver, self.config.rate, self.receiver_cmd_callback)
      self.receiver_modem.execute_command(Command.create_with_write_file_action_system_file(DllConfigFile(active_access_class=0x01)), timeout_seconds=1)
      print("Receiver scanning on Access Class = 0x01")
Пример #2
0
 def setup_modem(self):
     # we use Modem here only for reading the modem information, not for parsing.
     # reading the bytes from serial (after initial connect) is not done using Modem but overridden here
     modem = Modem(self.config.device, self.config.rate, None)
     self.serial = modem.dev
     self.modem_uid = modem.uid
     modem.stop_reading()  # so we can read the serial stream ourself
Пример #3
0
    def listen(self):
        rospy.loginfo("Port %s with Baudrate %s", self.port, self.baudrate)
        while True:
            try:
		rospy.loginfo('make modem connection')
                self.modem = Modem(self.port, self.baudrate, receive_callback=self.received_command_callback, show_logging=self.verbose)
                self.modem.start_reading()
                while not rospy.is_shutdown():
                    pass
            except Exception, e:
                raise e            
Пример #4
0
def on_connect():
  global modem
  if modem == None:
    modem = Modem(config.device, config.rate, command_received_callback)

  logging.info("modem: " + str(modem.uid))
  emit('module_info', {
    'uid': modem.uid,
    'application_name': modem.firmware_version.application_name,
    'git_sha1': modem.firmware_version.git_sha1,
    'd7ap_version': modem.firmware_version.d7ap_version
  }, broadcast=True)
Пример #5
0
    def __init__(self):
        self.logs = []
        self.command = ""
        self.counter = 0

        argparser = argparse.ArgumentParser()

        argparser.add_argument("-s",
                               "--serial",
                               help="serial device /dev file",
                               default="/dev/tty.usbserial-FTGCT0HY")
        argparser.add_argument("-b",
                               "--baudrate",
                               help="baudrate for serial device",
                               type=int,
                               default=115200)

        config = argparser.parse_args()
        self.modem = Modem(config.serial, config.baudrate, show_logging=False)

        self.setup_screen()
Пример #6
0
  def __init__(self):
    argparser = argparse.ArgumentParser()
    argparser.add_argument("-d", "--device", help="serial device /dev file modem",
                           default="/dev/ttyACM0")
    argparser.add_argument("-di", "--device-id", help="gateway device-id", required=True)
    argparser.add_argument("-r", "--rate", help="baudrate for serial device", type=int, default=115200)
    argparser.add_argument("-v", "--verbose", help="verbose", default=False, action="store_true")
    argparser.add_argument("-b", "--broker", help="mqtt broker hostname",
                             default="localhost")
    argparser.add_argument("-t", "--topic", help="mqtt topic",
                             default="/gw/{}")

    self.serial = None
    self.modem_uid = None
    self.bridge_count = 0
    self.next_report = 0

    self.config = argparser.parse_args()
    configure_default_logger(self.config.verbose)

    self.modem = Modem(self.config.device, self.config.rate, self.on_command_received, skip_alp_parsing=True)
    self.modem.connect()
    self.connect_to_mqtt()
Пример #7
0
argparser.add_argument("-v",
                       "--verbose",
                       help="verbose",
                       default=False,
                       action="store_true")
argparser.add_argument(
    "-f",
    "--file_id",
    help="File where we're writing the interface configuration",
    default=0x1D)
argparser.add_argument("-t", "--timeout", help="timeout", type=int, default=0)
config = argparser.parse_args()
configure_default_logger(config.verbose)

modem = Modem(config.device,
              config.rate,
              unsolicited_response_received_callback=received_command_callback)
modem.connect()

# D7 Example
interface_file = InterfaceConfigurationFile(
    interface_configuration=InterfaceConfiguration(
        interface_id=InterfaceType.D7ASP,
        interface_configuration=Configuration(
            qos=QoS(resp_mod=ResponseMode.RESP_MODE_PREFERRED,
                    retry_mod=RetryMode.RETRY_MODE_NO,
                    stop_on_err=False,
                    record=False),
            dorm_to=CT(),
            addressee=Addressee(nls_method=NlsMethod.NONE,
                                id_type=IdType.UID,
count = 0

argparser = argparse.ArgumentParser()
argparser.add_argument("-d",
                       "--device",
                       help="serial device /dev file modem",
                       default="/dev/ttyUSB0")
argparser.add_argument("-r",
                       "--rate",
                       help="baudrate for serial device",
                       type=int,
                       default=115200)
argparser.add_argument("-v",
                       "--verbose",
                       help="verbose",
                       default=False,
                       action="store_true")
config = argparser.parse_args()

modem = Modem(config.device,
              config.rate,
              receive_callback=received_command_callback,
              show_logging=config.verbose)

modem.start_reading()

# Program loop
while True:
    pass
Пример #9
0
 def setup_modem(self):
   # we use Modem here only for reading the modem information, not for parsing.
   # reading the bytes from serial (after initial connect) is not done using Modem but overridden here
   modem = Modem(self.config.device, self.config.rate, None, show_logging=self.config.verbose)
   self.serial = modem.dev
   self.modem_uid = modem.uid
Пример #10
0
    def __init__(self):
        argparser = argparse.ArgumentParser()
        argparser.add_argument("-d",
                               "--device",
                               help="serial device /dev file modem",
                               default="/dev/ttyACM0")
        argparser.add_argument("-r",
                               "--rate",
                               help="baudrate for serial device",
                               type=int,
                               default=115200)
        argparser.add_argument("-v",
                               "--verbose",
                               help="verbose",
                               default=False,
                               action="store_true")
        argparser.add_argument("-t",
                               "--token",
                               help="Access token for the TB gateway",
                               required=True)
        argparser.add_argument("-tb",
                               "--thingsboard",
                               help="Thingsboard hostname/IP",
                               default="localhost")
        argparser.add_argument("-p",
                               "--plugin-path",
                               help="path where plugins are stored",
                               default="")
        argparser.add_argument("-bp",
                               "--broker-port",
                               help="mqtt broker port",
                               default="1883")
        argparser.add_argument(
            "-l",
            "--logfile",
            help="specify path if you want to log to file instead of to stdout",
            default="")
        argparser.add_argument(
            "-k",
            "--keep-data",
            help=
            "Save data locally when Thingsboard is disconnected and send it when connection is restored.",
            default=True)
        argparser.add_argument(
            "-b",
            "--save-bandwidth",
            help="Send data in binary format to save bandwidth",
            action="store_true")
        argparser.add_argument("-sf",
                               "--skip-system-files",
                               help="Do not read system files on boot",
                               action="store_true")

        self.bridge_count = 0
        self.next_report = 0
        self.config = argparser.parse_args()
        self.log = logging.getLogger()

        formatter = logging.Formatter(
            '%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
        if self.config.logfile == "":
            handler = logging.StreamHandler()
        else:
            handler = logging.FileHandler(self.config.logfile)

        handler.setFormatter(formatter)
        self.log.addHandler(handler)
        self.log.setLevel(logging.INFO)
        if self.config.verbose:
            self.log.setLevel(logging.DEBUG)

        self.tb = Thingsboard(self.config.thingsboard,
                              self.config.token,
                              self.on_mqtt_message,
                              persistData=self.config.keep_data)

        if self.config.plugin_path != "":
            self.load_plugins(self.config.plugin_path)

        self.modem = Modem(self.config.device, self.config.rate,
                           self.on_command_received,
                           self.config.save_bandwidth)
        connected = self.modem.connect()
        while not connected:
            try:
                self.log.warning("Not connected to modem, retrying ...")
                time.sleep(1)
                connected = self.modem.connect()
            except KeyboardInterrupt:
                self.log.info("received KeyboardInterrupt... stopping")
                self.tb.disconnect()
                exit(-1)
            except:
                exc_type, exc_value, exc_traceback = sys.exc_info()
                lines = traceback.format_exception(exc_type, exc_value,
                                                   exc_traceback)
                trace = "".join(lines)
                self.log.error(
                    "Exception while connecting modem: \n{}".format(trace))

        # switch to continuous foreground scan access profile
        self.modem.execute_command(
            Command.create_with_write_file_action_system_file(
                DllConfigFile(active_access_class=0x01)),
            timeout_seconds=1)

        if self.config.save_bandwidth:
            self.log.info("Running in save bandwidth mode")
            if self.config.plugin_path is not "":
                self.log.warning(
                    "Save bandwidth mode is enabled, plugin files will not be used"
                )

        # update attribute containing git rev so we can track revision at TB platform
        git_sha = subprocess.check_output(["git", "describe",
                                           "--always"]).strip()
        ip = self.get_ip()
        self.tb.sendGwAttributes({
            'UID': self.modem.uid,
            'git-rev': git_sha,
            'IP': ip,
            'save bw': str(self.config.save_bandwidth)
        })

        self.log.info("Running on {} with git rev {} using modem {}".format(
            ip, git_sha, self.modem.uid))

        # read all system files on the local node to store as attributes on TB
        if not self.config.skip_system_files:
            self.log.info("Reading all system files ...")
            for file in SystemFiles().files.values():
                self.modem.execute_command_async(
                    Command.create_with_read_file_action_system_file(file))
Пример #11
0
argparser = argparse.ArgumentParser()

argparser.add_argument("-s",
                       "--serial",
                       help="serial device /dev file",
                       default="/dev/tty.usbserial-FTGCT0HY")
argparser.add_argument("-b",
                       "--baudrate",
                       help="baudrate for serial device",
                       type=int,
                       default=115200)

config = argparser.parse_args()

modem = Modem(config.serial, config.baudrate, show_logging=False)

cmd = Command.create_with_return_file_data_action(
    file_id=0x40,
    data=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    interface_type=InterfaceType.D7ASP,
    interface_configuration=Configuration(qos=QoS(resp_mod=QoS.RESP_MODE_NO),
                                          addressee=Addressee(
                                              access_class=0,
                                              id_type=IdType.BCAST)))

last_message = 0

sent = 0
received = 0
Пример #12
0
    def __init__(self):
        argparser = argparse.ArgumentParser()
        argparser.add_argument("-d",
                               "--device",
                               help="serial device /dev file modem",
                               default="/dev/ttyACM0")
        argparser.add_argument("-r",
                               "--rate",
                               help="baudrate for serial device",
                               type=int,
                               default=115200)
        argparser.add_argument("-v",
                               "--verbose",
                               help="verbose",
                               default=False,
                               action="store_true")
        argparser.add_argument("-b",
                               "--broker",
                               help="mqtt broker hostname",
                               default="localhost")
        argparser.add_argument("-bp",
                               "--broker-port",
                               help="mqtt broker port",
                               default="1883")
        argparser.add_argument("-p",
                               "--plugin-path",
                               help="path where plugins are stored",
                               default="")
        argparser.add_argument(
            "-l",
            "--logfile",
            help="specify path if you want to log to file instead of to stdout",
            default="")

        self.bridge_count = 0
        self.next_report = 0
        self.mq = None
        self.mqtt_topic_incoming_alp = ""
        self.connected_to_mqtt = False

        self.config = argparser.parse_args()

        self.log = logging.getLogger()
        formatter = logging.Formatter(
            '%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
        if self.config.logfile == "":
            handler = logging.StreamHandler()
        else:
            handler = logging.FileHandler(self.config.logfile)

        handler.setFormatter(formatter)
        self.log.addHandler(handler)
        self.log.setLevel(logging.INFO)
        if self.config.verbose:
            self.log.setLevel(logging.DEBUG)

        if self.config.plugin_path != "":
            self.load_plugins(self.config.plugin_path)

        self.modem = Modem(self.config.device, self.config.rate,
                           self.on_command_received)
        self.connect_to_mqtt()

        # update attribute containing git rev so we can track revision at TB platform
        git_sha = subprocess.check_output(["git", "describe",
                                           "--always"]).strip()
        ip = self.get_ip()
        # TODO ideally this should be associated with the GW device itself, not with the modem in the GW
        # not clear how to do this using TB-GW
        self.publish_to_topic(
            "/gateway-info",
            jsonpickle.json.dumps({
                "git-rev": git_sha,
                "ip": ip,
                "device": self.modem.uid
            }))

        # make sure TB knows the modem device is connected. TB considers the device connected as well when there is regular
        # telemetry data. This is fine for remote nodes which will be auto connected an disconnected in this way. But for the
        # node in the gateway we do it explicitly to make sure it always is 'online' even when there is no telemetry to be transmitted,
        # so that we can reach it over RPC
        self.publish_to_topic(
            "sensors/connect",
            jsonpickle.json.dumps({"serialNumber": self.modem.uid}))

        self.log.info("Running on {} with git rev {} using modem {}".format(
            ip, git_sha, self.modem.uid))

        # read all system files on the local node to store as attributes on TB
        self.log.info("Reading all system files ...")
        for file in SystemFiles().files.values():
            self.modem.execute_command_async(
                Command.create_with_read_file_action_system_file(file))
Пример #13
0
#!/usr/bin/env python3

import logging
# import signal
import sys

from challenge_status import ChallengeState
from modem import modem_io
from modem.modem import Modem

logging.basicConfig(level=logging.CRITICAL)

# s = signal.signal(signal.SIGINT, signal.SIG_IGN)

# Having the call here is only necessary for debug
ChallengeState.get()

print("Connected to /dev/ttyACM0")
sys.stdout.flush()

try:
    modem = Modem(modem_io.ConsoleIO())
    modem.run()
except KeyboardInterrupt:
    raise
except:
    sys.exit(1)

# signal.signal(signal.SIGINT, s)
import argparse

from d7a.alp.command import Command
from d7a.alp.interface import InterfaceType
from d7a.d7anp.addressee import Addressee, IdType
from d7a.sp.configuration import Configuration
from d7a.sp.qos import QoS, ResponseMode
from d7a.system_files.uid import UidFile
from modem.modem import Modem


# This example can be used with a node running the gateway app included in OSS-7.
# The gateway is continuously listening for foreground frames.
# Messages pushed by other nodes (running for example the sensor_push app) will be received by the gateway node,
# transmitted over serial and the received_command_callback() function below will be called.

def received_command_callback(cmd):
  print cmd

argparser = argparse.ArgumentParser()
argparser.add_argument("-d", "--device", help="serial device /dev file modem",
                            default="/dev/ttyUSB0")
argparser.add_argument("-r", "--rate", help="baudrate for serial device", type=int, default=115200)
argparser.add_argument("-v", "--verbose", help="verbose", default=False, action="store_true")
config = argparser.parse_args()

modem = Modem(config.device, config.rate, unsolicited_response_received_callback=received_command_callback, show_logging=config.verbose)

while True:
  pass
Пример #15
0
argparser.add_argument("-v",
                       "--verbose",
                       help="verbose",
                       default=False,
                       action="store_true")
argparser.add_argument("-otaa",
                       "--over-the-air-activation",
                       help="Enable over the air activation",
                       default=False,
                       action="store_true")
config = argparser.parse_args()

configure_default_logger(config.verbose)

modem = Modem(
    config.device,
    config.rate,
)
modem.connect()
logging.info("Executing query...")
if (config.over_the_air_activation):
    result = modem.execute_command(
        alp_command=Command.create_with_read_file_action(
            file_id=0x40,
            length=8,
            interface_type=InterfaceType.LORAWAN_OTAA,
            interface_configuration=LoRaWANInterfaceConfigurationOTAA(
                request_ack=False,
                app_port=0x01,
                device_eui=[0xBE, 0X7A, 0X00, 0X00, 0X00, 0X00, 0X1B, 0X81],
                app_eui=[0xBE, 0X7A, 0X00, 0X00, 0X00, 0X00, 0X0D, 0X9F],
                app_key=[