Exemplo n.º 1
0
  def try_parse_system_file(self):
    # when reading a known system files we store the parsed data and filename
    try:
      systemfile_type = SystemFiles().files[SystemFileIds(self.operand.offset.id)]
    except:
      return

    if systemfile_type is not None and systemfile_type.length == self.operand.length:
      self.systemfile_type = systemfile_type
      self.file_data_parsed = systemfile_type.parse(ConstBitStream(bytearray(self.operand.data)))
Exemplo n.º 2
0
  def __str__(self):
    # when reading a known system files we output the parsed data
    if isinstance(self.operation, ReturnFileData):
      try:
        systemfile_type = SystemFiles().get_all_system_files()[SystemFileIds(self.operand.offset.id)]
        if systemfile_type is not None and systemfile_type.length == self.operand.length:
          systemfile = systemfile_type.parse(ConstBitStream(bytearray(self.operand.data)))
          return "op=ReturnFileData, systemfile={}: {}".format(systemfile_type.__class__.__name__, systemfile)
      except:
        pass # not a SystemFile, do nothing

    return "op={}, operand={}({})".format(type(self.operation).__name__, type(self.operand).__name__, self.operand)
Exemplo n.º 3
0
 def try_parse_system_file(self):
   # when reading a known system files we store the parsed data and filename
   try:
     systemfile_type = SystemFiles().files[SystemFileIds(self.operand.offset.id)]
   except:
     return
   # if the file size is between allocated and original length, try to parse it
   if (systemfile_type is not None) and (systemfile_type.length >= self.operand.length.value):
     self.systemfile_type = systemfile_type
     try:
       self.file_data_parsed = systemfile_type.parse(ConstBitStream(bytearray(self.operand.data)))
     except:
       self.systemfile_type = None
       self.file_data_parsed = None
Exemplo n.º 4
0
def get_system_files():
    options = []
    for file in SystemFiles().get_all_system_files():
        options.append({
            "file_id": file.value,
            "file_name": file.name,
            "data": ""
        })

    return jsonify(options)
Exemplo n.º 5
0
def index():
  return render_template('index.html',
                         systemfiles=SystemFiles().get_all_system_files(),
                         qos_response_modes=ResponseMode.__members__,
                         id_types=IdType.__members__)
Exemplo n.º 6
0
argparser.add_argument("-t", "--type", choices=parser_types, required=True)
argparser.add_argument("-f",
                       "--file-id",
                       help="the ID of the system file to parse",
                       type=int)
argparser.add_argument('data',
                       help="The data to be parsed, input as an hexstring")
args = argparser.parse_args()

hexstring = args.data.strip().replace(' ', '')
data = bytearray(hexstring.decode("hex"))
if args.type == "alp":
    print AlpParser().parse(ConstBitStream(data), len(data))
    exit(0)
if args.type == "serial":
    parser = SerialParser()
if args.type == "fg":
    parser = DllFrameParser(frame_type=FrameType.FOREGROUND)
if args.type == "bg":
    parser = DllFrameParser(frame_type=FrameType.BACKGROUND)
if args.type == "systemfile":
    file = SystemFileIds(args.file_id)
    file_type = SystemFiles().files[file]
    print(file_type.parse(ConstBitStream(data)))
    exit(0)

cmds, info = parser.parse(data)
for cmd in cmds:
    print cmd

print info
Exemplo n.º 7
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))
Exemplo n.º 8
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))