async def write_gatt_char(self, _uuid: str, data: bytearray, response: bool = False) -> None: """Perform a write operation of the specified GATT characteristic. Args: _uuid (str or UUID): The uuid of the characteristics to write to. data (bytes or bytearray): The data to send. response (bool): If write-with-response operation should be done. Defaults to `False`. """ _uuid = await self.get_appropriate_uuid(_uuid) characteristic = self.services.get_characteristic(_uuid) if not characteristic: raise BleakError("Characteristic {} was not found!".format(_uuid)) value = NSData.alloc().initWithBytes_length_(data, len(data)) success = await cbapp.central_manager_delegate.connected_peripheral_delegate.writeCharacteristic_value_( characteristic.obj, value) if success: logger.debug("Write Characteristic {0} : {1}".format(_uuid, data)) else: raise BleakError( "Could not write value {0} to characteristic {1}: {2}".format( data, characteristic.uuid, success))
async def write_gatt_descriptor(self, handle: int, data: bytearray) -> None: """Perform a write operation on the specified GATT descriptor. Args: handle (int): The handle of the descriptor to read from. data (bytes or bytearray): The data to send. """ manager = self._device_info.manager().delegate() descriptor = self.services.get_descriptor(handle) if not descriptor: raise BleakError("Descriptor {} was not found!".format(handle)) value = NSData.alloc().initWithBytes_length_(data, len(data)) success = await manager.connected_peripheral_delegate.writeDescriptor_value_( descriptor.obj, value ) if success: logger.debug("Write Descriptor {0} : {1}".format(handle, data)) else: raise BleakError( "Could not write value {0} to descriptor {1}: {2}".format( data, descriptor.uuid, success ) )
def main(argv): p = optparse.OptionParser() p.set_usage("""Usage: %prog [options] userdata.plist [password]""") p.add_option("-v", "--verbose", action="store_true", help="Verbose output.") options, argv = p.parse_args(argv) if len(argv) not in (2, 3): print >>sys.stderr, p.get_usage() return 1 # Read the userdata.plist. plist = argv[1] plist_data = NSData.dataWithContentsOfFile_(plist) if not plist_data: print >>sys.stderr, "Couldn't read %s" % plist return 1 user_plist, plist_format, error = \ NSPropertyListSerialization.propertyListFromData_mutabilityOption_format_errorDescription_( plist_data, NSPropertyListMutableContainers, None, None) if error: print >>sys.stderr, "Can't read %s: %s" % (plist, error) return 1 # Use password on commandline, or ask if one isn't provided. try: password = argv[2] except IndexError: while True: password = getpass.getpass() verify_password = getpass.getpass("Password again: ") if password == verify_password: break else: print "Passwords don't match!" # Hash password with all available methods. hashed_passwords = dict() for k, m in hash_methods.items(): hashed_pwd = m(password) pwd_data = NSData.alloc().initWithBytes_length_(hashed_pwd, len(hashed_pwd)) hashed_passwords[k] = pwd_data # Serialize hashed passwords to a binary plist. serialized_passwords = serialize_hash_dict(hashed_passwords) if not serialized_passwords: return 2 # Write back userdata.plist with ShadowHashData. user_plist["ShadowHashData"] = list() user_plist["ShadowHashData"].append(serialized_passwords) plist_data, error = \ NSPropertyListSerialization.dataFromPropertyList_format_errorDescription_( user_plist, plist_format, None) plist_data.writeToFile_atomically_(argv[1], True) return 0
async def write_gatt_char( self, char_specifier: Union[BleakGATTCharacteristic, int, str, uuid.UUID], data: bytearray, response: bool = False, ) -> None: """Perform a write operation of the specified GATT characteristic. Args: char_specifier (BleakGATTCharacteristic, int, str or UUID): The characteristic to write to, specified by either integer handle, UUID or directly by the BleakGATTCharacteristic object representing it. data (bytes or bytearray): The data to send. response (bool): If write-with-response operation should be done. Defaults to `False`. """ manager = self._central_manager_delegate if not isinstance(char_specifier, BleakGATTCharacteristic): characteristic = self.services.get_characteristic(char_specifier) else: characteristic = char_specifier if not characteristic: raise BleakError("Characteristic {} was not found!".format(char_specifier)) value = NSData.alloc().initWithBytes_length_(data, len(data)) success = ( await manager.connected_peripheral_delegate.writeCharacteristic_value_type_( characteristic.obj, value, CBCharacteristicWriteWithResponse if response else CBCharacteristicWriteWithoutResponse, ) ) if success: logger.debug( "Write Characteristic {0} : {1}".format(characteristic.uuid, data) ) else: raise BleakError( "Could not write value {0} to characteristic {1}: {2}".format( data, characteristic.uuid, success ) )
def generate(image_path): try: # check if image_path is an image if imghdr.what(image_path) is None: raise ImageUtilException( u'"{0}" is not a valid picture'.format(image_path)) # build temporary image file temp_image = os.path.join( os.path.sep, 'private/var/tmp', os.path.splitext(os.path.basename(image_path))[0] + '.jpg') # convert image_path to jpeg with 72 dpi and max. width/height 512 px cmd = [ '/usr/bin/sips', '-s', 'format', 'jpeg', '%s' % image_path, '-s', 'formatOptions', 'high', '-s', 'dpiHeight', '72', '-s', 'dpiWidth', '72', '--resampleHeightWidthMax', '512', '--out', temp_image ] try: retcode = subprocess.call(cmd) if retcode: raise ImageUtilException(u'sips command failed') # check if temporary image exists and is not blank if is_non_zero_file(temp_image): with open(temp_image, 'rb') as image_file: # convert temporary image to a base64 encoded string return NSData.alloc().initWithBase64EncodedString_options_( base64.b64encode(image_file.read()), 0) else: raise ImageUtilException( u'Could not convert "{0}" to a jpeg file)'.format( image_path)) finally: if os.path.exists(temp_image): os.unlink(temp_image) except IOError as e: raise ImageUtilException( u'Cannot open "{0}" (I/O error {1}: {2})'.format( image_path, e.errno, e.strerror))
def _convert_int_to_uuid(i: int) -> str: UUID_bytes = i.to_bytes(length=16, byteorder="big") UUID_data = NSData.alloc().initWithBytes_length_(UUID_bytes, len(UUID_bytes)) UUID_cb = CBUUID.alloc().initWithData_(UUID_data) return UUID_cb.UUIDString()
def main(argv): p = optparse.OptionParser() p.set_usage("""Usage: %prog [options] userdata.plist [password]""") p.add_option("-v", "--verbose", action="store_true", help="Verbose output.") options, argv = p.parse_args(argv) if len(argv) not in (2, 3): print >> sys.stderr, p.get_usage() return 1 # Read the userdata.plist. plist = argv[1] plist_data = NSData.dataWithContentsOfFile_(plist) if not plist_data: print >> sys.stderr, "Couldn't read %s" % plist return 1 user_plist, plist_format, error = \ NSPropertyListSerialization.propertyListFromData_mutabilityOption_format_errorDescription_( plist_data, NSPropertyListMutableContainers, None, None) if error: print >> sys.stderr, "Can't read %s: %s" % (plist, error) return 1 # Use password on commandline, or ask if one isn't provided. try: password = argv[2] except IndexError: while True: password = getpass.getpass() verify_password = getpass.getpass("Password again: ") if password == verify_password: break else: print "Passwords don't match!" # Hash password with all available methods. hashed_passwords = dict() for k, m in hash_methods.items(): hashed_pwd = m(password) pwd_data = NSData.alloc().initWithBytes_length_( hashed_pwd, len(hashed_pwd)) hashed_passwords[k] = pwd_data # Serialize hashed passwords to a binary plist. serialized_passwords = serialize_hash_dict(hashed_passwords) if not serialized_passwords: return 2 # Write back userdata.plist with ShadowHashData. user_plist["ShadowHashData"] = list() user_plist["ShadowHashData"].append(serialized_passwords) plist_data, error = \ NSPropertyListSerialization.dataFromPropertyList_format_errorDescription_( user_plist, plist_format, None) plist_data.writeToFile_atomically_(argv[1], True) return 0
def setServerCertificateFromPEM_(self, pem): cert_b64 = "".join(pem.decode().split("\n")[1:-2]) data = NSData.alloc().initWithBase64EncodedString_options_(cert_b64, 0) self.serverCert = SecCertificateCreateWithData(None, data)
def loadAndSetInterfaceData(self): def setDefaults(interfaceData): if not interfaceData: # first start ever self.view.SetClientSize(self.view.wx.Size(1200, 700)) self.view.Center(self.view.wx.BOTH) self.setCurrentEditorStyle(self.defaultEditorStyle) return # fine grain tuning try: self.view.SetSize(interfaceData["Size"]) self.view.SetPosition(interfaceData["Position"]) self.view.splitter.SetSashPosition(interfaceData["SplitterSashPosition"]) except: # set UI defaults self.view.SetClientSize(self.view.wx.Size(1200, 700)) self.view.Center(self.view.wx.BOTH) # at least try to set the editor style try: self.setCurrentEditorStyle(interfaceData["editorStyle"]) self.toggleMenuItemByStyleName(interfaceData["editorStyle"]) except: # no editor style on file self.setCurrentEditorStyle(self.defaultEditorStyle) # Needs to be None interfaceData = None theFile = os.path.join(self.model.getApplicationSupportDir(), ".makerUISettings") if os.path.isfile(theFile): try: interfaceData = readDataFromFile(theFile) self.view.SetSize(interfaceData["Size"]) self.view.SetPosition(interfaceData["Position"]) self.view.splitter.SetSashPosition(interfaceData["SplitterSashPosition"]) try: self.setCurrentEditorStyle(interfaceData["editorStyle"]) self.toggleMenuItemByStyleName(interfaceData["editorStyle"]) except: # no editor style on file self.setCurrentEditorStyle(self.defaultEditorStyle) try: # enable security-scoped-bookmarks for use in this session for item in interfaceData["bookmarks"]: nsdata = NSData.alloc().initWithBytes_length_(item, len(item)) url = NSURL.URLByResolvingBookmarkData_options_relativeToURL_bookmarkDataIsStale_error_(nsdata, NSURLBookmarkResolutionWithSecurityScope, None, None, None) theURL = url[0] # save again to bookmarks but only if this project # is still linked if theURL.path() in self.model.linkedProjectPaths: self.model.bookmarks.append(item) theURL.startAccessingSecurityScopedResource() self.model.securityScopedResources.append(theURL) except: print "Unable to resolve security-scoped-bookmarks" try: # open all files that had been open in last session for sessionFile in interfaceData["sessionFiles"]: self.autoLoadProject(sessionFile[2]) #self.model.load(sessionFile[2]) item = (self.model.getActiveProject()).projectController.findTreeItem(sessionFile[0], sessionFile[1]) (self.model.getActiveProject()).projectController.selectTreeItemAndLoad(item) # set scroll position ed = ((self.model.getActiveProject()).getCurrentFile()).fileController.editor ed.GotoPos(sessionFile[3]) # make last open file current file for sessionFile in interfaceData["sessionFiles"]: if sessionFile[-1] == "True": self.autoLoadProject(sessionFile[2]) item = (self.model.getActiveProject()).projectController.findTreeItem(sessionFile[0], sessionFile[1]) (self.model.getActiveProject()).projectController.selectTreeItemAndLoad(item) # set scroll position ed = ((self.model.getActiveProject()).getCurrentFile()).fileController.editor ed.GotoPos(sessionFile[3]) self.view.Refresh() return # otherwise defaults will be loaded except Exception, e: print str(e) except Exception, e: print str(e)