async def scanForPeripherals_(self, scan_options) -> List[CBPeripheral]:
        """
        Scan for peripheral devices
        scan_options = { service_uuids, timeout }
        """
        # remove old
        self.devices = {}
        service_uuids = []
        if "service_uuids" in scan_options:
            service_uuids_str = scan_options["service_uuids"]
            service_uuids = NSArray.alloc().initWithArray_(
                list(map(string2uuid, service_uuids_str)))

        timeout = 0
        if "timeout" in scan_options:
            timeout = float(scan_options["timeout"])

        self.central_manager.scanForPeripheralsWithServices_options_(
            service_uuids, None)

        if timeout > 0:
            await asyncio.sleep(timeout)

        self.central_manager.stopScan()
        while self.central_manager.isScanning():
            await asyncio.sleep(0.1)

        return []
    async def retrieveConnected_(self, scan_options) -> List[CBPeripheral]:
        self.devices = {}
        service_uuids = []
        if "service_uuids" in scan_options:
            service_uuids_str = scan_options["service_uuids"]
            service_uuids = NSArray.alloc().initWithArray_(
                list(map(string2uuid, service_uuids_str)))

        peripherals = self.central_manager.retrieveConnectedPeripheralsWithServices_(
            service_uuids)

        # Add all those peripherals:
        for peripheral in peripherals:
            uuid_string = peripheral.identifier().UUIDString()

            if uuid_string in self.devices:
                device = self.devices[uuid_string]
            else:
                address = uuid_string
                name = peripheral.name() or None
                details = peripheral
                device = BLEDeviceCoreBluetooth(address, name, details)
                self.devices[uuid_string] = device

            logger.debug("Connected device {}: {}".format(
                uuid_string, device.name))

        return []
Example #3
0
    async def scanForPeripherals_(self, scan_options) -> List[CBPeripheral]:
        """
        Scan for peripheral devices
        scan_options = { service_uuids, timeout }
        """
        service_uuids = []
        if "service_uuids" in scan_options:
            service_uuids_str = scan_options["service_uuids"]
            service_uuids = NSArray.alloc().initWithArray_(
                list(map(string2uuid, service_uuids_str)))

        timeout = None
        if "timeout" in scan_options:
            timeout = scan_options["timeout"]

        self.central_manager.scanForPeripheralsWithServices_options_(
            service_uuids, None)

        if timeout is None or type(timeout) not in (int, float):
            return

        await asyncio.sleep(timeout)
        self.central_manager.stopScan()

        return []
    def start_scan(self, scan_options):
        # remove old
        self.devices = {}
        service_uuids = []
        if "service_uuids" in scan_options:
            service_uuids_str = scan_options["service_uuids"]
            service_uuids = NSArray.alloc().initWithArray_(
                list(map(string2uuid, service_uuids_str)))

        self.central_manager.scanForPeripheralsWithServices_options_(
            service_uuids, None)
Example #5
0
def purify(obj):
    # This code ensures that certain data types are very definitely the ObjC versions
    d = dir(obj)
    if '__reversed__' in d:
        # list / NSArray
        return NSArray.alloc().initWithArray_(obj)
    elif 'items' in d:
        # dictionary / NSDictionary
        return NSDictionary.alloc().initWithDictionary_(obj)
    elif 'strip' in d:
        # string / NSString
        return NSString.alloc().initWithString_(obj)
    # Unhandled
    return obj
Example #6
0
    async def start_scan(self, scan_options) -> None:
        # remove old
        self.devices = {}
        service_uuids = None
        if "service_uuids" in scan_options:
            service_uuids_str = scan_options["service_uuids"]
            service_uuids = NSArray.alloc().initWithArray_(
                list(map(CBUUID.UUIDWithString_, service_uuids_str)))

        self.central_manager.scanForPeripheralsWithServices_options_(
            service_uuids, None)

        # The `isScanning` property was added in macOS 10.13, so before that
        # just waiting some will have to do.
        if objc.macos_available(10, 13):
            event = asyncio.Event()
            self._did_start_scanning_event = event
            if not self.central_manager.isScanning():
                await event.wait()
        else:
            await asyncio.sleep(0.1)
def reorderUnicodes(thisGlyph):
    defaultUnicode = Glyphs.glyphInfoForName(thisGlyph.name).unicode
    oldUnicodes = thisGlyph.unicodes
    if oldUnicodes:
        oldUnicodes = list(oldUnicodes)
        if len(oldUnicodes) > 1:
            if defaultUnicode:
                orderedUnicodes = []
                try:
                    i = oldUnicodes.index(defaultUnicode)
                    try:
                        orderedUnicodes.append(oldUnicodes.pop(
                            i))  # add the default as the first one
                        orderedUnicodes.extend(oldUnicodes)  # add the rest
                        if orderedUnicodes != oldUnicodes:
                            print("---> %s: %s" %
                                  (thisGlyph.name, ", ".join(orderedUnicodes)))
                            unicodeSet = NSArray.alloc().initWithArray_(
                                orderedUnicodes)
                            thisGlyph.setUnicodesArray_(unicodeSet)
                    except Exception as e:
                        print(e)
                        print()
                        import traceback
                        print(traceback.format_exc())
                except:
                    print(
                        "- %s: No default (%s) among unicodes (%s); left unchanged."
                        % (thisGlyph.name, defaultUnicode,
                           ", ".join(oldUnicodes)))
            else:
                print(
                    "- %s: No unicode defined in Glyph Info; left unchanged (%s)"
                    % (thisGlyph.name,
                       ", ".join(oldUnicodes) if oldUnicodes else "-"))
        else:
            print("- %s: Only one unicode set (%s); left unchanged." %
                  (thisGlyph.name, oldUnicodes[0]))
    else:
        print("- %s: No unicodes set, nothing to reorder." % (thisGlyph.name))
Example #8
0
    async def scanForPeripherals_(self, scan_options) -> List[CBPeripheral]:
        """
        Scan for peripheral devices
        scan_options = { service_uuids, timeout }
        """
        # remove old
        self.devices = {}
        service_uuids = []
        if "service_uuids" in scan_options:
            service_uuids_str = scan_options["service_uuids"]
            service_uuids = NSArray.alloc().initWithArray_(
                list(map(string2uuid, service_uuids_str))
            )

        timeout = 0
        if "timeout" in scan_options:
            timeout = float(scan_options["timeout"])

        self.central_manager.scanForPeripheralsWithServices_options_(
            service_uuids, None
        )

        if timeout > 0:
            await asyncio.sleep(timeout)

        self.central_manager.stopScan()

        # Wait a while to allow central manager to stop scanning.
        # The `isScanning` attribute is added in macOS 10.13, so before that
        # just waiting some will have to do. In 10.13+ I have never seen
        # bleak enter the while-loop, so this fix is most probably safe.
        if _IS_PRE_10_13:
            await asyncio.sleep(0.1)
        else:
            while self.central_manager.isScanning():
                await asyncio.sleep(0.1)

        return []
Example #9
0
def update_user_account(user_data):
    """
    Updates the user account. When being executed on a booted volume, updates
    via the Open Directory API. When being executed on a targeted volume,
    updates via the user account Property List.
    """

    name = user_data["name"]

    if is_booted_volume():
        node = get_od_node()

        if not node:
            print "Unable to look up OpenDirectory node, aborting..."
            exit(1)

        record, error = node.recordWithRecordType_name_attributes_error_(
            kODRecordTypeUsers, name, None, None)

        if error:
            print error
            exit(1)

        for attribute, value in user_data.items():

            # jpegphoto and ShadowHashData are data blobs, not strings, so a
            # little conversion is required
            if attribute == "jpegphoto" or attribute == "ShadowHashData":
                data = NSData.dataWithBytes_length_(value, len(value))
                value = NSArray.alloc().initWithObjects_(data)

            success, error = record.setValue_forAttribute_error_(
                value, attribute, None)

            if error:
                print error
                exit(1)

            # we don't want to spew out the data blobs to stdout, so we just
            # replace it with something simple. this is purely for formatting
            # reasons
            if attribute == "jpegphoto" or attribute == "ShadowHashData":
                value = "DATA"

            print "User account '" + name + "' updated attribute " + \
                attribute + ": " + str(value)
    else:  # Property List logic
        path = get_target() + get_user_plist_path() + name + ".plist"
        dictionary = plistlib.readPlist(path)

        for attribute, value in user_data.items():

            # jpegphoto and ShadowHashData are data blobs, not strings, so a
            # little conversion is required
            if attribute == "jpegphoto" or attribute == "ShadowHashData":
                value = plistlib.Data(value)

            dictionary[attribute] = [value]

            # we don't want to spew out the data blobs to stdout, so we just
            # replace it with something simple. this is purely for formatting
            # reasons
            if attribute == "jpegphoto" or attribute == "ShadowHashData":
                value = "DATA"

            print "User account '" + name + "' updated attribute " + \
                attribute + ": " + str(value)

        plistlib.writePlist(dictionary, path)
Example #10
0
def getRange(m1, m2):
    markers = NSArray.alloc().initWithObjects_(m1, m2)
    return getParameterizedAttributeValue(
        root, "AXTextMarkerRangeForUnorderedTextMarkers", markers)
Example #11
0
from common import getRootElement, findWebArea, elementToString, \
  getAttributeValue, getParameterizedAttributeValue, \
  findElemWithDOMIdentifier
from Foundation import NSDictionary, NSArray

root = findElemWithDOMIdentifier(getRootElement(name="Safari"), "image_1")
print(elementToString(root))
startMarker = getAttributeValue(root, "AXStartTextMarker")
endMarker = getAttributeValue(root, "AXEndTextMarker")
markers = NSArray.alloc().initWithObjects_(startMarker, endMarker)
r = getParameterizedAttributeValue(root,
                                   "AXTextMarkerRangeForUnorderedTextMarkers",
                                   markers)


def strFromRange(r):
    return getParameterizedAttributeValue(root, "AXStringForTextMarkerRange",
                                          r)


print(len(strFromRange(r)))

# nextMarker = startMarker
# index = 0
# while True:
#   nextMarker = getParameterizedAttributeValue(root, "AXNextTextMarkerForTextMarker", nextMarker)
#   leftWord = strFromRange(getParameterizedAttributeValue(root, "AXLeftWordTextMarkerRangeForTextMarker", nextMarker))
#   rightWord = strFromRange(getParameterizedAttributeValue(root, "AXRightWordTextMarkerRangeForTextMarker", nextMarker))
#   print("%d [%s] [%s] " % (index, leftWord, rightWord))
#   index += 1
#   if not nextMarker or nextMarker == endMarker: