Пример #1
0
def downloadStuff(uuid):

    uuid = 'a' + uuid.replace('-','').replace('\"','')
    
    table_name = uuid
    results = run_transaction(sessionmaker(bind=engine), lambda s: download(s, uuid))

    return Response({'Results' : (results)}, status=200)
Пример #2
0
def uuid_to_path(uuid):
    """ Converts a UUID into a path.

    Every 4 alphanumeric characters of the UUID become a folder name. """
    uuid = uuid.replace("-", "")
    path = [uuid[i:i + 4] for i in range(0, len(uuid), 4)]
    path = os.path.join(*path)
    LOGGER.debug("path %s", path)
    return path
Пример #3
0
def uuidencode(uuid, n=32):
    """Converts an UUID string to a list of values. Optional attribute *n* is the width
    of the values. A width of 32 bits can store 4 characters as a character
    always consumes 8 bits.
        >>> uuidencode('c715a069-7538-49dd-858a-f6f058a38a90')
        [892417891, ...]
    """
    uuid = str(uuid)  # Cast UUID object to string.
    assert re.match(
        '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$',
        uuid), "uuidencode() requires an UUID4 format string"
    raw = uuid.replace('-', '')  # Remove dashes.
    return bitsplit(int(raw, 16), requires(128, n), n)
Пример #4
0
 def _scan_windows_volume(self):
     execute_cmd('/usr/local/bin/ldmtool create all')  # 加载动态卷
     rev = execute_cmd('blkid |egrep "ntfs|vfat"')
     if rev[0] != 0:
         return
     for line in rev[1].strip().splitlines():
         uuid, device = '', ''
         uuid_match = UUID.search(line)
         if uuid_match:
             uuid = uuid_match.groups()[0]
         else:
             pass
         device = line.split(':')[0]
         self._windows_volumes.append((device, uuid.replace('-', '')))
     _logger.info('_windows_volumes:{}'.format(self._windows_volumes))
Пример #5
0
def insertSession():
    form = request.form

    roomid = form["id"]
    roomName = form["roomName"]
    uuid = form["uuid"]
    questions = form["questions"]

    uuid = 'a' + uuid.replace('-','').replace('\"','')
    table_name = uuid

    questions = json.loads(questions)


    addStuffTODB(roomid, roomName, uuid, questions)

    return "HELLO"
Пример #6
0
def getUUIDPath(uuid, depth = 3):
        """
        to prevent having a single directory with way too many files,
        instead put files into directories by their uuids
        """
        noStrings = uuid.replace("-", "")
        path = ["binary"]
        cnt = 0
        for c in uuid:
            path.append(c)
            cnt += 1;
            if cnt == depth:
                break

        path.append(uuid)

        return os.path.join(*path)
Пример #7
0
def set_jfs_uuid_and_label(filename, uuid, label):
    if len(label) > 16:
        raise ValueError('Volume label too long.')
    if uuid in ('random', 'rnd', 'new'):
        uuid_bin = generate_random_uuid()
    else:
        uuid = uuid.replace('-', '')
        if len(uuid) != 32:
            raise ValueError('Need 32 hex digits for UUID.')
        uuid_bin = uuid.decode('hex')
    if len(uuid_bin) != 16:
        raise ValueError('UUID must be 16 bytes long.')

    f = open(filename, 'r+')
    # TODO(pts): Check that size of the file is at least 16 * 1024 * 1024 bytes,
    # because util-linux blkid requires this.
    try:
        f.seek(0x8000)
        old_data = f.read(0xa8)
        if len(old_data) != 0xa8:
            raise IOError('Volume too short.')
        label += '\0' * (16 - len(label))
        if old_data[:4] == 'JFS1':
            # If JFS filesystem detected, don't modify anything else.
            f.seek(0x8088)
            f.write(uuid_bin[:32] + label[:16])
            #f.seek(0x8098)
            #f.write(label[:16])
        else:
            data = ''.join((
                'JFS1',
                old_data[0x4:0x10],
                # This is needed by util-linux blkid, it checks some numbers.
                '\1\0\0\0\0\0\0\0\1\0\0\0\0\0',
                old_data[0x1e:0x88],
                uuid_bin,
                label))
            assert len(data) == 0xa8
            f.seek(0x8000)
            f.write(data)
    finally:
        f.close()
def mc_uuid_to_username(uuid):
    if uuid not in UUID_CACHE:
        try:
            short_uuid = uuid.replace("-", "")
            mojang_response = requests.get(
                "https://api.mojang.com/user/profiles/{}/names".format(
                    short_uuid)).json()
            if len(mojang_response) > 1:
                # Multiple name changes
                player_username = mojang_response[-1]["name"]
            else:
                # Only one name
                player_username = mojang_response[0]["name"]
            UUID_CACHE[uuid] = player_username
            return player_username
        except Exception as e:
            log.error(e, exc_info=True)
            log.error(
                "Failed to lookup {}'s username using the Mojang API.".format(
                    uuid))
    else:
        return UUID_CACHE[uuid]
Пример #9
0
def app_update(appid, uuid=None):
    """
    application update
    :param appid:
    :param uuid:
    :return:
    """
    uuid = '1.1.0'
    device_app_version = request.json.get('device_app_version')
    update_available = True
    if float(device_app_version.replace('.', '')) >= float(
            uuid.replace('.', '')):
        update_available = False

    res = {
        'compatible_binary': True,
        'update_available': update_available,
        'update': {
            'uuid': uuid,
            'url': 'http://127.0.0.1:5000/api/update/get/www_%s.zip' % uuid
        }
    }
    return jsonify(res)
Пример #10
0
def main(argv=None):
    # option flags
    global verbose
    global simulate

    # default uuid, this is the uuid that the "Beacon Toolkit" iOS app uses
    # https://itunes.apple.com/us/app/beacon-toolkit/id728479775
    # can be overriden with environment variable
    uuid = os.getenv("IBEACON_UUID", "E20A39F473F54BC4A12F17D1AD07A961")

    # major and minor ids, can be overriden with environment variable
    major = int(os.getenv("IBEACON_MAJOR", "0"))
    minor = int(os.getenv("IBEACON_MINOR", "0"))

    # default to the first available bluetooth device
    device = "hci0"

    # default power level
    power = int(os.getenv("IBEACON_POWER", "200"))

    # regexp to test for a valid UUID
    # here the - separators are optional
    valid_uuid_match = re.compile(
        '^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$',
        re.I)

    # grab command line arguments
    if argv is None:
        argv = sys.argv

    # parse command line options
    try:
        try:
            opts, args = getopt.getopt(argv[1:], "hu:M:m:p:vd:nz", [
                "help", "uuid=", "major=", "minor=", "power=", "verbose",
                "device=", "simulate", "down"
            ])

        except getopt.error, msg:
            raise Usage(msg)

        for o, a in opts:
            if o in ("-h", "--help"):
                print
                __doc__
                return 0
            elif o in ("-n", "--simulate"):
                simulate = True
                verbose = True
            elif o in ("-u", "--uuid"):
                uuid = a
                if uuid == "random":
                    uuid = get_random_uuid()
            elif o in ("-M", "--major"):
                major = int(a)
            elif o in ("-m", "--minor"):
                minor = int(a)
            elif o in ("-p", "--power"):
                power = int(a)
            elif o in ("-v", "--verbose"):
                verbose = True
            elif o in ("-d", "--device"):
                temp_device = str(a)
                # devices can be specified as "X" or "hciX"
                if not temp_device.startswith("hci"):
                    device = "hci%s" % temp_device
                else:
                    device = temp_device
            elif o in ("-z", "--down"):
                if check_for_sudo():
                    if is_valid_device(device):
                        print
                        "Downing iBeacon on %s" % device
                        process_command("hciconfig %s noleadv" % device)
                        # process_command("hciconfig %s piscan" % device)
                        process_command("hciconfig %s down" % device)
                        return 0
                    else:
                        print
                        "Error: no such device: %s (try `hciconfig list')" % device
                        return 1
                else:
                    return 1

        # test for valid UUID
        if not valid_uuid_match.match(uuid):
            print
            "Error: `%s' is an invalid UUID." % uuid
            return 1

        # strip out - symbols from uuid and turn it into uppercase
        uuid = uuid.replace("-", "")
        uuid = uuid.upper()

        # bounds check major/minor ids
        if major < 0 or major > 65535:
            print
            "Error: major id is out of bounds (0-65535)"
            return 1
        if minor < 0 or minor > 65535:
            print
            "Error: minor id is out of bounds (0-65535)"
            return 1

        # bail if we're not running as superuser (don't care if we are simulating)
        if not simulate and not check_for_sudo():
            return 1

        # split the uuid into 8 bit (=2 hex digit) chunks
        split_uuid = hexsplit(uuid)

        # convert major/minor id into hex
        major_hex = hexify(major, 4)
        minor_hex = hexify(minor, 4)

        # create split versions of these (for the hcitool command)
        split_major_hex = hexsplit(major_hex)
        split_minor_hex = hexsplit(minor_hex)

        # convert power into hex
        power_hex = hexify(power, 2)

        # make sure we are using a valid hci device
        if not simulate and not is_valid_device(device):
            print
            "Error: no such device: %s (try `hciconfig list')" % device
            return 1

        # print status info
        print
        "Advertising on %s with:" % device
        print
        "       uuid: 0x%s" % uuid
        print
        "major/minor: %d/%d (0x%s/0x%s)" % (major, minor, major_hex, minor_hex)
        print
        "      power: %d (0x%s)" % (power, power_hex)

        # first bring up bluetooth
        process_command("hciconfig %s up" % device)
        # now turn on LE advertising (3 => non-connectable advertisement)

        # now turn off scanning
        process_command("hciconfig %s noscan" % device)

        # set up the beacon
        # 1E Number of bytes that follow in the advertisement
        # 02 Number of bytes that follow in first AD structure
        # 01 Flags AD type
        # 1A Flags value 0x1A = 000011010
        #   bit 0 (OFF) LE Limited Discoverable Mode
        #   bit 1 (ON) LE General Discoverable Mode
        #   bit 2 (OFF) BR/EDR Not Supported
        #   bit 3 (ON) Simultaneous LE and BR/EDR to Same Device Capable (controller)
        #   bit 4 (ON) Simultaneous LE and BR/EDR to Same Device Capable (Host)
        # 1A Number of bytes that follow in second (and last) AD structure
        # FF Manufacturer specific data AD type
        # 4C Company identifier code LSB
        # 00 Company identifier code MSB (0x004C == Apple)
        # 02 Byte 0 of iBeacon advertisement indicator
        # 15 Byte 1 of iBeacon advertisement indicator
        process_command(
            "hcitool -i %s cmd 0x08 0x0008 1E 02 01 1A 1A FF 4C 00 02 15 %s %s %s %s 00 >/dev/null"
            %
            (device, split_uuid, split_major_hex, split_minor_hex, power_hex))

        # https://esf.eurotech.com/docs/how-to-user-bluetooth-le-beacons
        # http://stackoverflow.com/questions/21124993/is-there-a-way-to-increase-ble-advertisement-frequency-in-bluez
        # 0-3  A0 00  min interval - A0 00 => 100ms => (100ms = 0x0A * 0.625ms), 40 06 => (1000ms = 0x0640 * 0.625ms)
        # 4-7  A0 00  max interval - A0 00 => 100ms => (100ms = 0x0A * 0.625ms), 40 06 => (1000ms = 0x0640 * 0.625ms)
        # 8-11 03 00  leadv 3
        #                                              0     4     8     12    16    20    24
        process_command(
            "hcitool -i %s cmd 0x08 0x0006 A0 00 A0 00 03 00 00 00 00 00 00 00 00 07 00"
            % device)

        # (0x08 0x000a) is "LE Set Advertise Enable"
        process_command("hcitool -i %s cmd 0x08 0x000a 01" % device)
Пример #11
0
    def __call__(self, cfg=None, json_data=None):

        if cfg is None:
            cfg = DEFAULT_CFG
        # if cfg.op is None:
        #     cfg.op = Pdp2Op.STORE
        if cfg.op != Pdp2Op.SEND and cfg.op != Pdp2Op.STORE:
            raise Exception(f'Operation {cfg.op} not recognized')
        if json_data is None:
            json_data = extract_user_data(self.user, profile_allowed_fields)
        if isinstance(json_data, dict):
            json_data = json.dumps(json_data).encode()
        if cfg.encryption_value == 'encrypted':
            if cfg.pub_key is not None:
                encrypted_json_data = encrypt_user_data(json_data,
                                                        pub_key=cfg.pub_key)
            elif cfg.op == Pdp2Op.STORE and self.active_pdp2_txn is not None and self.active_pdp2_txn.pub_key is not None:
                encrypted_json_data = encrypt_user_data(
                    json_data, pub_key=self.active_pdp2_txn.pub_key)
            # paicoin needs a different rpc call than bitcoin
            elif cfg.op == Pdp2Op.STORE and settings.CRYPTO_HOST == 'paicoin':
                pub_key = get_pub_key(self.pdp2_sub.pub_key_addr)
                cfg.pub_key = pub_key
                encrypted_json_data = encrypt_user_data(json_data,
                                                        pub_key=pub_key)

            else:
                # Here for legacy purposes; in actuality, we should make a call to
                # getaddressinfo and grab the public key from there; time is tight;
                # I'm deferring it to my own chagrin.
                priv_key = get_private_key(self.pdp2_sub.pub_key_addr)
                encrypted_json_data = encrypt_user_data(json_data, priv_key)
            uuid, info_hash = self.submit_data_to_torrent_providers(
                encrypted_json_data, cfg)
        else:
            data = encode_and_format(json_data)
            uuid, info_hash = self.submit_data_to_torrent_providers(data, cfg)

        if cfg.op == Pdp2Op.STORE:
            # TODO it would be silly if this were still necessary since we now
            #  transmit the uuid to the torrent client
            #  ... even more silly since a torrent client doesn't even exist anymore.
            self.validate_torrent_uuid_immutability(uuid)

        # It's easier to pass this around
        pdp2_txn = Pdp2Txn(
            pdp2_subscription=self.pdp2_sub,
            torrent_file_uuid=uuid,
            torrent_info_hash=info_hash,
            torrent_file_date_created=timezone.now(),
            is_store_op=cfg.op == Pdp2Op.STORE,
            is_pub_key_ours=cfg.is_pub_key_ours,
        )

        if cfg.pub_key is not None:
            pdp2_txn.pub_key = cfg.pub_key
        if cfg.pub_key_addr is not None:
            pdp2_txn.pub_key_addr = cfg.pub_key_addr
        else:
            pdp2_txn.pub_key_addr = self.pdp2_sub.pub_key_addr

        op_return_metadata = uuid.replace('-', '')

        txid, ref = None, None
        if cfg.op == Pdp2Op.SEND:
            txid, ref = self.pdp2_send(op_return_metadata, cfg.pub_key_addr,
                                       cfg.amount)
        # We only do a new store txn when it's a brand new profile.
        # All subsequent transactions will reference the same uuid so it
        # is unnecessary to do another store operation; if there is no
        # pdp2_txn to reference (i.e. self.active_pdp2_txn == None -> True),
        # then we do a store operation.
        elif cfg.op == Pdp2Op.STORE and self.active_pdp2_txn is None:
            txid, ref = self.pdp2_store(op_return_metadata)

        pdp2_txn.pdp2_op_return_txid = txid
        pdp2_txn.pdp2_op_return_ref = ref

        if cfg.op == Pdp2Op.STORE and self.active_pdp2_txn is None:
            pdp2_txn.is_active = True

        pdp2_txn = self.merge_txns(pdp2_txn)
        pdp2_transaction = self.db_store_txn(pdp2_txn)
        if cfg.op == Pdp2Op.STORE:
            self.change_txns_activation_status(old_txn=self.active_pdp2_txn,
                                               new_txn=pdp2_transaction)
        return pdp2_transaction
Пример #12
0
	def UUIDHexToInt(self, uuid):
		uuid = uuid.replace("-", "").decode("hex")
		return uuid
Пример #13
0
# def get_mac_address():
#     mac = uuid.UUID(int=uuid.getnode()).hex[-12:].upper()
#     return ":".join([mac[e:e + 2] for e in range(0, 11, 2)])
# #获取本机mac地址
# mac = get_mac_address()
# print(mac) # 我的电脑mac地址会随机生成,所以生成一次后需要保存进文件,不知道ros上面的会怎么样
# ROS_uuid = uuid.uuid3(uuid.NAMESPACE_DNS, mac)
# print(ROS_uuid)

# 方法二: 读取主板的UUID作为ros的UUID,但是需要root权限
# cmd = subprocess.Popen('dmidecode -s system-uuid'.split())
# print(cmd)

# 默认已经获取到uuid
uuid = "11d5cc68-03f9-e411-a26a-480fcfdf611a"
uuid = uuid.replace('-', '')
print(uuid)
# 定义传输数据格式
data = {
    "car_id": "",
    "current_position_x": 0,
    "current_position_y": 0,
    "current_velocity": 0,
    "tire_pressure_left_front": 0.0,
    "tire_pressure_right_front": 0.0,
    "tire_pressure_left_behind": 0.0,
    "tire_pressure_right_behind": 0.0,
    "camera_status": False,
    "lidar_status": False,
    "ibeo_status": False,
    "route": '[[34.258036686857494, 108.65009318120921]]',
Пример #14
0
def main(argv=None):

  # option flags
  global verbose
  global simulate

  # default uuid is the Digital2Go Media Networks UUID
  # can be overriden with environment variable
  uuid = os.getenv("IBEACON_UUID", "8D847D200116435F9A212FA79A706D9E")

  # major and minor ids, can be overriden with environment variable
  major = int(os.getenv("IBEACON_MAJOR", "0"))
  minor = int(os.getenv("IBEACON_MINOR", "0"))

  # default to the first available bluetooth device
  device = "hci0"

  # default minimum advertising interval (in milliseconds)
  min_adv = int(os.getenv("MIN_ADV_INTERVAL", "350"))

  # default maximum advertising interval (in milliseconds)
  max_adv = int(os.getenv("MAX_ADV_INTERVAL", "400"))

  # default power level
  power = int(os.getenv("IBEACON_POWER", "200"))

  # regexp to test for a valid UUID
  # here the - separators are optional
  valid_uuid_match = re.compile('^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$', re.I)

  # grab command line arguments
  if argv is None:
    argv = sys.argv

  # parse command line options
  try:
    try:
      opts, args = getopt.getopt(argv[1:], "hu:M:m:a:A:p:vd:nz", ["help", "uuid=", "major=", "minor=", "min_adv=","max_adv=","power=", "verbose", "device=", "simulate", "down"])

    except getopt.error, msg:
      raise Usage(msg)

    for o, a in opts:
      if o in ("-h", "--help"):
        print __doc__
        return 0
      elif o in ("-n", "--simulate"):
        simulate = True
        verbose = True
      elif o in ("-u", "--uuid"):
        uuid = a
        if uuid == "random":
          uuid = get_random_uuid()
      elif o in ("-M", "--major"):
        major = int(a)
      elif o in ("-m", "--minor"):
        minor = int(a)
      elif o in ("-a", "--minadv"):
        min_adv = int(a)
      elif o in ("-A", "--maxadv"):
        max_adv = int(a)
      elif o in ("-p", "--power"):
        power = int(a)
      elif o in ("-v", "--verbose"):
        verbose = True
      elif o in ( "-d", "--device"):
        temp_device = str(a)
        # devices can be specified as "X" or "hciX"
        if not temp_device.startswith("hci"):
          device = "hci%s" % temp_device
        else:
          device = temp_device
      elif o in ( "-z", "--down"):
        if check_for_sudo():
          if is_valid_device(device):
            print "Downing iBeacon on %s" % device
            process_command("hciconfig %s noleadv" % device)
            process_command("hciconfig %s piscan" % device)
            process_command("hciconfig %s down" % device)
            return 0
          else:
            print "Error: no such device: %s (try `hciconfig list')" % device
            return 1
        else:
          return 1

    # test for valid UUID
    if not valid_uuid_match.match(uuid):
      print "Error: `%s' is an invalid UUID." % uuid
      return 1

    # strip out - symbols from uuid and turn it into uppercase
    uuid = uuid.replace("-","")
    uuid = uuid.upper()

    # bounds check major/minor ids
    if major < 0 or major > 65535:
      print "Error: major id is out of bounds (0-65535)"
      return 1
    if minor < 0 or minor > 65535:
      print "Error: minor id is out of bounds (0-65535)"
      return 1

    # Bound the advertising intervals to 100ms - 3000ms
    # Also make sure that the max > min
    if min_adv < 100 or min_adv > 3000:
      print "Error: min_adv is out of bounds (100-3000)"
      return 1
    if max_adv < 100 or max_adv > 3000:
      print "Error: max_adv is out of bounds (100-3000)"
      return 1
    if min_adv > max_adv:
      print "Error: min_adv > max_adv"
      return 1

    # bail if we're not running as superuser (don't care if we are simulating)
    if not simulate and not check_for_sudo():
      return 1

    # split the uuid into 8 bit (=2 hex digit) chunks
    split_uuid = hexsplit(uuid)

    # convert major/minor id into hex
    major_hex = hexify(major, 4)
    minor_hex = hexify(minor, 4)

    # convert min_adv/max_adv into hex
    min_adv_hex = hexify(int(min_adv/0.625), 4)
    max_adv_hex = hexify(int(max_adv/0.625), 4)

    # create split versions of these (for the hcitool command)
    split_major_hex = hexsplit(major_hex)
    split_minor_hex = hexsplit(minor_hex)

    # create split versions with endian swap for advertising intervals
    split_min_adv_hex = hexsplit(endian_swap(min_adv_hex))
    split_max_adv_hex = hexsplit(endian_swap(max_adv_hex))
    print "split min/max %s/%s" % (split_min_adv_hex, split_max_adv_hex) 
    # convert power into hex
    power_hex = hexify(power, 2)

    # make sure we are using a valid hci device
    if not simulate and not is_valid_device(device):
      print "Error: no such device: %s (try `hciconfig list')" % device
      return 1
 
    # print status info
    print "Advertising on %s with:" % device
    print "       uuid: 0x%s" % uuid
    print "major/minor: %d/%d (0x%s/0x%s)" % (major, minor, major_hex, minor_hex)
    print "      power: %d (0x%s)" % (power, power_hex)
    print "min/max adv: %d/%d (0x%s/0x%s)" % (min_adv, max_adv, min_adv_hex, max_adv_hex)

    # first bring up bluetooth
    process_command("hciconfig %s up" % device)
    # now turn on LE advertising
    #process_command("hciconfig %s leadv" % device)
    # now turn off scanning
    process_command("hciconfig %s noscan" % device)
    # set up the beacon
    # pipe stdout to /dev/null to get rid of the ugly "here's what I did"
    # message from hcitool
    process_command("hcitool -i hci0 cmd 0x08 0x0008 1E 02 01 1A 1A FF 4C 00 02 15 %s %s %s %s 00 >/dev/null" % (split_uuid, split_major_hex, split_minor_hex, power_hex))
    process_command("hcitool -i hci0 cmd 0x08 0x0006 %s %s 03 00 00 00 00 00 00 00 00 07 00" % (split_min_adv_hex, split_max_adv_hex))
    process_command("hcitool -i hci0 cmd 0x08 0x000a 01")
Пример #15
0
def del_nav(uuid):
    db.nav.remove({'uuid':uuid.replace(' ', '+')})
def main(argv=None):

  # option flags
  global verbose
  global simulate

  # default uuid, this is the uuid that the "Beacon Toolkit" iOS app uses
  # https://itunes.apple.com/us/app/beacon-toolkit/id728479775
  # can be overriden with environment variable
  uuid = os.getenv("IBEACON_UUID", "E20A39F473F54BC4A12F17D1AD07A961")

  # major and minor ids, can be overriden with environment variable
  major = int(os.getenv("IBEACON_MAJOR", "0"))
  minor = int(os.getenv("IBEACON_MINOR", "0"))

  # default to the first available bluetooth device
  device = "hci0"

  # default power level
  power = int(os.getenv("IBEACON_POWER", "200"))

  # regexp to test for a valid UUID
  # here the - separators are optional
  valid_uuid_match = re.compile('^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$', re.I)

  # grab command line arguments
  if argv is None:
    argv = sys.argv

  # parse command line options
  try:
    try:
      opts, args = getopt.getopt(argv[1:], "hu:M:m:p:vd:nz", ["help", "uuid=", "major=", "minor=", "power=", "verbose", "device=", "simulate", "down"])

    except getopt.error, msg:
      raise Usage(msg)

    for o, a in opts:
      if o in ("-h", "--help"):
        print __doc__
        return 0
      elif o in ("-n", "--simulate"):
        simulate = True
        verbose = True
      elif o in ("-u", "--uuid"):
        uuid = a
        if uuid == "random":
          uuid = get_random_uuid()
      elif o in ("-M", "--major"):
        major = int(a)
      elif o in ("-m", "--minor"):
        minor = int(a)
      elif o in ("-p", "--power"):
        power = int(a)
      elif o in ("-v", "--verbose"):
        verbose = True
      elif o in ( "-d", "--device"):
        temp_device = str(a)
        # devices can be specified as "X" or "hciX"
        if not temp_device.startswith("hci"):
          device = "hci%s" % temp_device
        else:
          device = temp_device
      elif o in ( "-z", "--down"):
        if check_for_sudo():
          if is_valid_device(device):
            print "Downing iBeacon on %s" % device
            process_command("hciconfig %s noleadv" % device)
            process_command("hciconfig %s piscan" % device)
            process_command("hciconfig %s down" % device)
            return 0
          else:
            print "Error: no such device: %s (try `hciconfig list')" % device
            return 1
        else:
          return 1

    # test for valid UUID
    if not valid_uuid_match.match(uuid):
      print "Error: `%s' is an invalid UUID." % uuid
      return 1

    # strip out - symbols from uuid and turn it into uppercase
    uuid = uuid.replace("-","")
    uuid = uuid.upper()

    # bounds check major/minor ids
    if major < 0 or major > 65535:
      print "Error: major id is out of bounds (0-65535)"
      return 1
    if minor < 0 or minor > 65535:
      print "Error: minor id is out of bounds (0-65535)"
      return 1

    # bail if we're not running as superuser (don't care if we are simulating)
    if not simulate and not check_for_sudo():
      return 1

    # split the uuid into 8 bit (=2 hex digit) chunks
    split_uuid = hexsplit(uuid)

    # convert major/minor id into hex
    major_hex = hexify(major, 4)
    minor_hex = hexify(minor, 4)

    # create split versions of these (for the hcitool command)
    split_major_hex = hexsplit(major_hex)
    split_minor_hex = hexsplit(minor_hex)

    # convert power into hex
    power_hex = hexify(power, 2)

    # make sure we are using a valid hci device
    if not simulate and not is_valid_device(device):
      print "Error: no such device: %s (try `hciconfig list')" % device
      return 1
 
    # print status info
    print "Advertising on %s with:" % device
    print "       uuid: 0x%s" % uuid
    print "major/minor: %d/%d (0x%s/0x%s)" % (major, minor, major_hex, minor_hex)
    print "      power: %d (0x%s)" % (power, power_hex)

    # first bring up bluetooth
    process_command("hciconfig %s up" % device)
    # now turn on LE advertising
    process_command("hciconfig %s leadv" % device)
    # now turn off scanning
    process_command("hciconfig %s noscan" % device)
    # set up the beacon
    # pipe stdout to /dev/null to get rid of the ugly "here's what I did"
    # message from hcitool
    process_command("hcitool -i hci0 cmd 0x08 0x0008 1E 02 01 1A 1A FF 4C 00 02 15 %s %s %s %s 00 >/dev/null" % (split_uuid, split_major_hex, split_minor_hex, power_hex))
Пример #17
0
def set_xfs_uuid_and_label(filename, uuid, label):
    bytearray()
    if len(label) > 12:
        raise ValueError('Volume label too long.')
    label += '\0' * (12 - len(label))
    if uuid in ('random', 'rnd', 'new'):
        uuid_bin = generate_random_uuid()
    else:
        uuid = uuid.replace('-', '')
        if len(uuid) != 32:
            raise ValueError('Need 32 hex digits for UUID.')
        uuid_bin = uuid.decode('hex')
    if len(uuid_bin) != 16:
        raise ValueError('UUID must be 16 bytes long.')

    f = open(filename, 'r+')
    # TODO(pts): Check that size of the file is at least 1025 bytes,
    # because util-linux blkid requires this.
    try:
        old_data = f.read(160)
        if len(old_data) != 160:
            raise IOError('Volume too short.')
        # We could use a bytearray (from Python 2.6), but we want Python 2.4
        # compatibility.
        b = array.array('c', old_data)

        def set_b(i, j, x):
            x = array.array('c', x)
            assert len(x) == j - i
            b[i:j] = x

        label += '\0' * (12 - len(label))
        if b[:4].tostring() == 'XFSB':
            # If XFS filesystem detected, don't modify anything else.
            f.seek(32)
            f.write(uuid_bin[:32])
            f.seek(108)
            f.write(label[:12])
        else:
            set_b(32, 48, uuid_bin)  # UUID.
            set_b(108, 120, label)  # Label.
            # Only modify other headers if XFS fileystem was not detected.
            set_b(0, 4, 'XFSB')  # XFS_SB_MAGIC.
            # We need to set these so that util-linux blkid will recognize it as XFS.
            set_b(4, 24, '\0' * 20)  # blocksize = dblocks = rblocks = 0.
            set_b(128, 160,
                  '\0' * 32)  # icount = ifree = fdblocks = frextents = 0.
            set_b(88, 88 + 4, '\0\0\0\1')  # agcount = 1.
            set_b(102, 102 + 2, '\2\0')  # sectsize = 512.
            set_b(121, 121 + 1, '\x09')  # sectlog = 9.
            set_b(4, 4 + 4, '\0\1\0\0')  # blocksize = 65535.
            set_b(120, 120 + 1, '\x10')  # blocklog = 16.
            set_b(104, 104 + 2, '\1\0')  # inodesize = 256.
            set_b(122, 122 + 1, '\x08')  # inodelog = 8.
            set_b(123, 123 + 1, '\x08')  # inoplog = blocklog - inodelog  # 8.
            set_b(80, 80 + 4, '\0\0\0\1')  # rextsize = 1.
            set_b(8, 8 + 8, '\0\0\0\0\0\0\0\x40')  # dblocks = 64.
            set_b(84, 84 + 4, '\0\0\0\x40')  #  agblocks = 64.
            set_b(127, 127 + 1, '\1')  # imax_pct = 1.
            assert len(b) == 160
            f.seek(0)
            f.write(b.tostring())
    finally:
        f.close()