creates device, internal use only
327518
def __create_device(self):
        
        # retrieve netengine dictionary from memory or from network
        device_dict = getattr(self, 'netengine_dict', self.netengine.to_dict())
        device = Device()
        device.node_id = self.node_id
        device.name = device_dict['name']
        device.type = device_dict['type']
        device.status = DEVICE_STATUS.get('reachable')
        device.os = device_dict['os']
        device.os_version = device_dict['os_version']
        # this is the first time the device is seen by the system because we are just adding it
        device.first_seen = now()
        # and is also the latest
        device.last_seen = now()
        device.full_clean()
        device.save()

        # add routing protocols
        for routing_protocol in device_dict['routing_protocols']:
            # retrieve routing protocol from DB
            try:
                rp = RoutingProtocol.objects.filter(
                    name__iexact=routing_protocol['name'],
                    version__iexact=routing_protocol['version']
                )[0]
            # create if doesn't exist yet
            except IndexError:
                rp = RoutingProtocol(
                    name=routing_protocol['name'],
                    version=routing_protocol['version']
                )
                rp.full_clean()
                rp.save()
            # add to device
            device.routing_protocols.add(rp)

        for interface in device_dict['interfaces']:
            interface_object = False
            vap_object = False
            # create interface depending on type
            if interface['type'] == 'ethernet':
                interface_object = Ethernet(**{
                    'device': device,
                    'name': interface['name'],
                    'mac': interface['mac_address'],
                    'mtu': interface['mtu'],
                    'standard': interface['standard'],
                    'duplex': interface['duplex'],
                    'tx_rate': interface['tx_rate'],
                    'rx_rate': interface['rx_rate']
                })
            elif interface['type'] == 'wireless':
                interface_object = Wireless(**{
                    'device': device,
                    'name': interface['name'],
                    'mac': interface['mac_address'],
                    'mtu': interface['mtu'],
                    'mode': interface['mode'],
                    'standard': interface['standard'],
                    'channel': interface['channel'],
                    'channel_width': interface['channel_width'],
                    'output_power': interface['output_power'],
                    'dbm': interface['dbm'],
                    'noise': interface['noise'],
                    'tx_rate': interface['tx_rate'],
                    'rx_rate': interface['rx_rate']
                })

                for vap in interface['vap']:
                    vap_object = Vap(
                        essid=vap['essid'],
                        bssid=vap['bssid'],
                        encryption=vap['encryption']
                    )

            if interface_object:
                interface_object.full_clean()
                interface_object.save()

                if vap_object:
                    vap_object.interface = interface_object
                    vap_object.full_clean()
                    vap_object.save()

                for ip in interface['ip']:
                    ip_object = Ip(**{
                        'interface': interface_object,
                        'address': ip['address'],
                    })
                    ip_object.full_clean()
                    ip_object.save()

        if HARDWARE_INSTALLED:
            # try getting device model from db
            try:
                device_model = DeviceModel.objects.filter(name__iexact=device_dict['model'])[0]
            # if it does not exist create it
            except IndexError as e:
                # try getting manufacturer from DB
                try:
                    manufacturer = Manufacturer.objects.filter(name__iexact=device_dict['manufacturer'])[0]
                # or create
                except IndexError as e:
                    manufacturer = Manufacturer(name=device_dict['manufacturer'])
                    manufacturer.full_clean()
                    manufacturer.save()

                device_model = DeviceModel(
                    manufacturer=manufacturer,
                    name=device_dict['model']
                )
                device_model.ram = device_dict['RAM_total']

            device_model.full_clean()
            device_model.save()

            # create relation between device model and device
            rel = DeviceToModelRel(device=device, model=device_model)
            rel.full_clean()
            rel.save()

        return device
249785
def create(configs):
    
    if not configs:
        raise Error(ANDROID_DEVICE_EMPTY_CONFIG_MSG)
    elif configs == ANDROID_DEVICE_PICK_ALL_TOKEN:
        ads = get_all_instances()
    elif not isinstance(configs, list):
        raise Error(ANDROID_DEVICE_NOT_LIST_CONFIG_MSG)
    elif isinstance(configs[0], dict):
        # Configs is a list of dicts.
        ads = get_instances_with_configs(configs)
    elif isinstance(configs[0], basestring):
        # Configs is a list of strings representing serials.
        ads = get_instances(configs)
    else:
        raise Error('No valid config found in: %s' % configs)
    valid_ad_identifiers = list_adb_devices() + list_adb_devices_by_usb_id()

    for ad in ads:
        if ad.serial not in valid_ad_identifiers:
            raise DeviceError(ad, 'Android device is specified in config but'
                              ' is not attached.')
    _start_services_on_ads(ads)
    return ads
1371469
def create(plm, address, cat, subcat, firmware=None):
    """"""
    from insteonplm.devices.ipdb import IPDB
    ipdb = IPDB()
    product = ipdb[[cat, subcat]]
    deviceclass = product.deviceclass
    device = None
    if deviceclass is not None:
        device = deviceclass(plm, address, cat, subcat,
                             product.product_key,
                             product.description,
                             product.model)
    return device
530923
private function init()
    {
        $devicePatcher           = new Device\Xml\DevicePatcher();
        $deviceRepositoryBuilder = new Device\DeviceRepositoryBuilder(
            $this->getPersistenceStorage(),
            $this->getUserAgentHandlerChain(),
            $devicePatcher,
            $this->getLogger()
        );

        $this->deviceRepository = $deviceRepositoryBuilder->build(
            $this->getWurflConfig()->wurflFile,
            $this->getWurflConfig()->wurflPatches,
            $this->getWurflConfig()->capabilityFilter
        );
    }
174891
function SerialDevice(port, settings, Connection) {

  // call super class
  Device.call(this, Connection);

  this.set('portName', port);
  this.set('settings', settings);

  this.set('state', 'close');
}
514577
def create_device(args, display_types=None):
    
    device = None
    if display_types is None:
        display_types = get_display_types()

    if args.display in display_types.get('oled'):
        import luma.oled.device
        Device = getattr(luma.oled.device, args.display)
        Serial = getattr(make_serial(args), args.interface)
        device = Device(Serial(), **vars(args))

    elif args.display in display_types.get('lcd'):
        import luma.lcd.device
        import luma.lcd.aux
        Device = getattr(luma.lcd.device, args.display)
        spi = make_serial(args).spi()
        device = Device(spi, **vars(args))
        luma.lcd.aux.backlight(gpio=spi._gpio, gpio_LIGHT=args.gpio_backlight, active_low=args.backlight_active == "low").enable(True)

    elif args.display in display_types.get('led_matrix'):
        import luma.led_matrix.device
        from luma.core.interface.serial import noop
        Device = getattr(luma.led_matrix.device, args.display)
        spi = make_serial(args, gpio=noop()).spi()
        device = Device(serial_interface=spi, **vars(args))

    elif args.display in display_types.get('emulator'):
        import luma.emulator.device
        Device = getattr(luma.emulator.device, args.display)
        device = Device(**vars(args))

    return device
1150482
def put_device(self, pin, state, momentary=None, times=None, pause=None):
        
        url = self.base_url + '/device'

        payload = {
            "pin": pin,
            "state": state
        }

        if momentary is not None:
            payload["momentary"] = momentary

        if times is not None:
            payload["times"] = times

        if pause is not None:
            payload["pause"] = pause

        try:
            r = requests.put(url, json=payload, timeout=10)
            return r.json()
        except RequestException as err:
            raise Client.ClientError(err)
536378
def run_init(device_type, args):
    """"""
    util.setup_logging(verbosity=args.verbose)
    log.warning('This GPG tool is still in EXPERIMENTAL mode, '
                'so please note that the API and features may '
                'change without backwards compatibility!')

    verify_gpg_version()

    # Prepare new GPG home directory for hardware-based identity
    device_name = os.path.basename(sys.argv[0]).rsplit('-', 1)[0]
    log.info('device name: %s', device_name)
    homedir = args.homedir
    if not homedir:
        homedir = os.path.expanduser('~/.gnupg/{}'.format(device_name))

    log.info('GPG home directory: %s', homedir)

    if os.path.exists(homedir):
        log.error('GPG home directory %s exists, '
                  'remove it manually if required', homedir)
        sys.exit(1)

    check_call(['mkdir', '-p', homedir])
    check_call(['chmod', '700', homedir])

    agent_path = util.which('{}-gpg-agent'.format(device_name))

    # Prepare GPG agent invocation script (to pass the PATH from environment).
    with open(os.path.join(homedir, 'run-agent.sh'), 'w') as f:
        f.write(r"""#!/bin/sh
export PATH={0}
{1} \
-vv \
--pin-entry-binary={pin_entry_binary} \
--passphrase-entry-binary={passphrase_entry_binary} \
--cache-expiry-seconds={cache_expiry_seconds} \
$*
""".format(os.environ['PATH'], agent_path, **vars(args)))
    check_call(['chmod', '700', f.name])
    run_agent_script = f.name

    # Prepare GPG configuration file
    with open(os.path.join(homedir, 'gpg.conf'), 'w') as f:
        f.write("""# Hardware-based GPG configuration
agent-program {0}
personal-digest-preferences SHA512
default-key \"{1}\"
""".format(run_agent_script, args.user_id))

    # Prepare a helper script for setting up the new identity
    with open(os.path.join(homedir, 'env'), 'w') as f:
        f.write("""#!/bin/bash
set -eu
export GNUPGHOME={0}
COMMAND=$*
if [ -z "${{COMMAND}}" ]
then
    ${{SHELL}}
else
    ${{COMMAND}}
fi
""".format(homedir))
    check_call(['chmod', '700', f.name])

    # Generate new GPG identity and import into GPG keyring
    pubkey = write_file(os.path.join(homedir, 'pubkey.asc'),
                        export_public_key(device_type, args))
    verbosity = ('-' + ('v' * args.verbose)) if args.verbose else '--quiet'
    check_call(keyring.gpg_command(['--homedir', homedir, verbosity,
                                    '--import', pubkey.name]))

    # Make new GPG identity with "ultimate" trust (via its fingerprint)
    out = check_output(keyring.gpg_command(['--homedir', homedir,
                                            '--list-public-keys',
                                            '--with-fingerprint',
                                            '--with-colons']))
    fpr = re.findall('fpr:::::::::([0-9A-F]+):', out)[0]
    f = write_file(os.path.join(homedir, 'ownertrust.txt'), fpr + ':6\n')
    check_call(keyring.gpg_command(['--homedir', homedir,
                                    '--import-ownertrust', f.name]))

    # Load agent and make sure it responds with the new identity
    check_call(keyring.gpg_command(['--homedir', homedir,
                                    '--list-secret-keys', args.user_id]))
36492
function Device() {
    this.available = false;
    this.platform = null;
    this.version = null;
    this.uuid = null;
    this.cordova = null;
    this.model = null;
    this.manufacturer = null;
    this.isVirtual = null;
    this.serial = null;

    var me = this;

    channel.onCordovaReady.subscribe(function() {
        me.getInfo(function(info) {
            //ignoring info.cordova returning from native, we should use value from cordova.version defined in cordova.js
            //TODO: CB-5105 native implementations should not return info.cordova
            var buildLabel = cordova.version;
            me.available = true;
            me.platform = info.platform;
            me.version = info.version;
            me.uuid = info.uuid;
            me.cordova = buildLabel;
            me.model = info.model;
            me.isVirtual = info.isVirtual;
            me.manufacturer = info.manufacturer || 'unknown';
            me.serial = info.serial || 'unknown';
            channel.onCordovaInfoReady.fire();
        },function(e) {
            me.available = false;
            utils.alert("[ERROR] Error initializing Cordova: " + e);
        });
    });
}
559931
def init_device(self):
        """"""
        start_time = time.time()
        Device.init_device(self)
        self._pb_id = ''
        LOG.debug('init PB device %s, time taken %.6f s (total: %.2f s)',
                  self.get_name(), (time.time() - start_time),
                  (time.time() - self._start_time))
        self.set_state(DevState.STANDBY)
943778
function Device(options) {

  EventEmitter.call(this);

  // Check required fields.
  if(!options || !options.id) {
    throw new Error('ID is required.');
  }

  this.options = options;
  this.id = options.id;

  // Default the options and remove whitespace.
  options.id = (options.id || '').replace(/ /g, '');
  options.key = (options.key || '').replace(/ /g, '');
  options.secret = (options.secret || '').replace(/ /g, '');

  // The MQTT topics that this device will use.
  this.commandTopic = util.format(config.topicFormatCommand, options.id);
  this.stateTopic = util.format(config.topicFormatState, options.id);

  this.mqtt = options.mqtt || new MQTT();
  this.mqtt.on('message', this.handleMessage.bind(this));

  // Only want 'connect' to be emitted the first time. Every time after
  // will only emit the reconnected event.
  var firstConnect = true;
  this.mqtt.on('connect', (function() {
    this.handleConnect();
    if(firstConnect) {
      firstConnect = false;
      this.emit('connect');
    }
    else {
      this.emit('reconnected');
    }
  }).bind(this));

  this.mqtt.on('reconnect', (function() {
    this.emit('reconnect');
  }).bind(this));

  this.mqtt.on('close', (function() {
    this.emit('close');
  }).bind(this));

  this.mqtt.on('offline', (function() {
    this.emit('offline');
  }).bind(this));

  this.mqtt.on('error', (function(err) {
    this.emit('error', err);
  }).bind(this));
}
269474
def create(self, key, value=None, dir=False, ttl=None, timeout=None):
        """"""
        return self.adapter.set(key, value, dir=dir, ttl=ttl,
                                prev_exist=False, timeout=timeout)
170239
def create_x10(plm, housecode, unitcode, feature):
    """"""
    from insteonplm.devices.ipdb import IPDB
    ipdb = IPDB()
    product = ipdb.x10(feature)
    deviceclass = product.deviceclass
    device = None
    if deviceclass:
        device = deviceclass(plm, housecode, unitcode)
    return device
1116331
def add_x10_device(self, housecode, unitcode, feature='OnOff'):
        
        device = insteonplm.devices.create_x10(self, housecode,
                                               unitcode, feature)
        if device:
            self.devices[device.address.id] = device
        return device
1365127
def DeviceFactory(id, lib=None):
    
    lib = lib or Library()
    if lib.tdGetDeviceType(id) == const.TELLSTICK_TYPE_GROUP:
        return DeviceGroup(id, lib=lib)
    return Device(id, lib=lib)
435698
def add(name, address)
      device = Device.new(name: name, address: address)
      self << device
      device
    end
116173
def new_device(device_json, abode):
    """"""
    type_tag = device_json.get('type_tag')

    if not type_tag:
        raise AbodeException((ERROR.UNABLE_TO_MAP_DEVICE))

    generic_type = CONST.get_generic_type(type_tag.lower())
    device_json['generic_type'] = generic_type

    if generic_type == CONST.TYPE_CONNECTIVITY or \
       generic_type == CONST.TYPE_MOISTURE or \
       generic_type == CONST.TYPE_OPENING:
        return AbodeBinarySensor(device_json, abode)
    elif generic_type == CONST.TYPE_CAMERA:
        return AbodeCamera(device_json, abode)
    elif generic_type == CONST.TYPE_COVER:
        return AbodeCover(device_json, abode)
    elif generic_type == CONST.TYPE_LIGHT:
        return AbodeLight(device_json, abode)
    elif generic_type == CONST.TYPE_LOCK:
        return AbodeLock(device_json, abode)
    elif generic_type == CONST.TYPE_SWITCH:
        return AbodeSwitch(device_json, abode)
    elif generic_type == CONST.TYPE_VALVE:
        return AbodeValve(device_json, abode)
    elif generic_type == CONST.TYPE_UNKNOWN_SENSOR:
        return _new_sensor(device_json, abode)

    return None