def register(): request_data = request.get_json() try: ip_list = tuple(request_data['ip_list']) hostname = request_data['hostname'] except TypeError: return '"ip_list" or "hostname" key is missing or wrong datatype', 400 # Bad Request unique_id = request_data.get('unique_id', None) remote_ip = get_remote_ip(request) network = networks.get(remote_ip, Network(remote_ip)) key = unique_id if unique_id else hostname if key in network: network[key].update_timestamp() network[key].ip_list = ip_list network[key].hostname = hostname else: network[key] = Device(ip_list, hostname, unique_id) networks[remote_ip] = network return ''
def __create_device(self) -> Device: firmware = self.__get_firmware() protocol = self.__get_protocol() errors = self.__get_errors() return Device(name='Advanced Sample Device', firmware=firmware, protocol=protocol, errors=errors)
def check_bluetooth_presence(mac_address): bluetooth_ping_cmd = ['l2ping', mac_address, '-c', '1'] ret = subprocess.call(bluetooth_ping_cmd, shell=False) devices = Device.selectBy(mac_address=mac_address) if devices.count(): device = devices.getOne() else: device = Device(mac_address=mac_address) Scan(timestamp=float(time.time()), device=device, present=not ret)
def get_faulty_devices_for_user(self, user_id): faulty_devices = self.repositories.device_repository.get_faulty_devices() house_id = self.collection.get_houses_for_user(user_id)[0].house_id target_devices = [] fault_check = False for device in faulty_devices: if device.house_id == house_id: fault_check = True target_devices.append(Device(device)) self.collection.update_one({'_id': user_id}, {"$set": {'faulty': fault_check}}, upsert=False) return target_devices
def get_devices(self): """Return a list of devices with Spotify players running. Returns: list: The Devices. """ results = self.get_api_v1("me/player/devices") if results and "devices" in results: return tuple(Device(device) for device in results['devices']) else: return []
def getResults(resultsDir, build, version, pipeline, commiter): testResults = [] date = time.strftime('%x') for subdir, dirs, files in os.walk(resultsDir, topdown=True): testList = prepareTestList(files, subdir) if testList: deviceMeta = getDeviceMeta(subdir) device = Device(deviceMeta[0], build, version, pipeline, deviceMeta[3], deviceMeta[2], "00:00", date, commiter, "Android, " + deviceMeta[1], testList) testResults.append(device) return testResults
def load_devices(cls): cls.devicenamelist = [] for device in cls.config['Devices']: deviceobject = Device(device['deviceid']) deviceobject.devicename = device['devicename'] deviceobject.serverport = device['serverport'] deviceobject.bootstrapport = device['bootstrapport'] deviceobject.platformname = device['platformname'] deviceobject.platformversion = device['platformversion'] deviceobject.server = device['server'] cls.devices[deviceobject.deviceid] = deviceobject cls.devicenamelist.append(device['devicename']) Log.logger.info(u"配置yaml列表中一共有 %s 台设备" % len(cls.devices))
def get_device_by_id(self, device_id): device = self.collection.find_one({'_id': device_id}) if device is None: return None device_type = device['device_type'] if 'device_type' in device else None if device_type == "thermostat": return Thermostat(device) elif device_type == "motion_sensor": return MotionSensor(device) elif device_type == "light_switch": return LightSwitch(device) elif device_type == "open_sensor": return OpenSensor(device) return Device(device)
def create_tables(self, device_id): engine = create_engine('sqlite:///%s' % self.db_file) # 创建表结构 model.Base.metadata.create_all(engine) session = self.get_session() device = session.query(Device).first() if device is None: device = Device(id=device_id, status='idle') else: device.id = device_id device.status = 'idle' session.add(device) session.commit() session.close()
def load_devices(cls): cls.device_name_list = [] for device in cls.config['Devices']: device_object = Device(device['deviceid']) device_object.device_name = device['devicename'] device_object.server_port = device['serverport'] device_object.bootstrap_port = device['bootstrapport'] device_object.platform_name = device['platformname'] device_object.platform_version = device['platformversion'] device_object.server = device['server'] cls.devices[device_object.device_id] = device_object cls.device_name_list.append(device['devicename']) Log.logger.info("There are %s devices in the configuration list" % len(cls.devices))
def createSpineIFDs(self, pod, spines): devices = [] interfaces = [] for spine in spines: user = spine.get('user') password = spine.get('pass') device = Device(spine['name'], pod.spineDeviceType, user, password, 'spine', spine['mac_address'], spine['mgmt_ip'], pod) devices.append(device) portNames = util.getPortNamesForDeviceFamily(device.family, self.conf['deviceFamily']) for name in portNames['ports']: # spine does not have any uplink/downlink marked, it is just ports ifd = InterfaceDefinition(name, device, 'downlink') interfaces.append(ifd) self.dao.createObjects(devices) self.dao.createObjects(interfaces)
def old_xml_import(xmlfile, user, request_form): filename = xmlfile.filename data = xmlfile.readlines() if isinstance(data[0], bytes): data = [str(x.decode('utf-8')) for x in data] data[0] = data[0] + "<sml>" data.append("</sml>") filematch = re.match( r'log-([A-F0-9]{16})-\d{4}-\d{2}-\d{2}T\d{2}_\d{2}_\d{2}-\d+\.xml', filename) if not filematch: flash("illegal filename: '%s'" % filename, 'error') return serial_number = filematch.group(1) tree = objectify.fromstring("\n".join(data).encode('utf-8')) move = parse_move(tree) move.source = filename move.import_module = __name__ device = Device.query.filter_by(serial_number=serial_number).scalar() if not device: device = Device() device.serial_number = serial_number db.session.add(device) if Move.query.filter_by(user=user, date_time=move.date_time, device=device).scalar(): flash("%s at %s already exists" % (move.activity, move.date_time), 'warning') else: move.user = user move.device = device db.session.add(move) for sample in parse_samples(tree.Samples.iterchildren(), move): db.session.add(sample) postprocess_move(move) db.session.commit() return move
def createLeafIFDs(self, pod, leafs): devices = [] interfaces = [] for leaf in leafs: user = leaf.get('user') password = leaf.get('pass') device = Device(leaf['name'], pod.leafDeviceType, user, password, 'leaf', leaf['mac_address'], leaf['mgmt_ip'], pod) devices.append(device) portNames = util.getPortNamesForDeviceFamily(device.family, self.conf['deviceFamily']) for name in portNames['uplinkPorts']: # all uplink IFDs towards spine ifd = InterfaceDefinition(name, device, 'uplink') interfaces.append(ifd) for name in portNames['downlinkPorts']: # all downlink IFDs towards Access/Server ifd = InterfaceDefinition(name, device, 'downlink') interfaces.append(ifd) self.dao.createObjects(devices) self.dao.createObjects(interfaces)
def get_all_devices(self): devices = self.collection.find() target_devices = [] for device in devices: target_devices.append(Device(device)) return target_devices
def get_devices_for_room(self, room_id): devices = self.collection.find({'room_id': room_id}) target_devices = [] for device in devices: target_devices.append(Device(device)) return target_devices
def get_devices_for_house(self, house_id): devices = self.collection.find({'house_id': house_id}) target_devices = [] for device in devices: target_devices.append(Device(device)) return target_devices
def __init__(self, config): ApplicationSession.__init__(self, config) self.payload = {} self.user = User() self.device = Device() self.statusDevice = {}
def create_device(): device = Device() device.name = GPX_DEVICE_NAME device.serial_number = GPX_DEVICE_SERIAL return device
def __create_device() -> Device: return Device(name='Sample Device', firmware=0xa2c3f, protocol='SAMPLE', errors=[0x0000])
def parse_device(tree): device = Device() device.name = tree.DeviceLog.Device.Name.text device.serial_number = tree.DeviceLog.Device.SerialNumber.text return device
def collectLldpAndMatchDevice(self): if (self.configurationInProgressCache.checkAndAddDevice( self.deviceIp)): # for real device the password is coming from pod tmpDevice = Device(self.deviceIp, None, 'root', self.pod.getCleartextPassword(), 'leaf', None, self.deviceIp, None) tmpDevice.id = self.deviceIp self.updateSelfDeviceContext(tmpDevice) logger.debug('Started two stage configuration for %s' % (self.deviceIp)) for i in range(1, self.attempt + 1): # wait first: this will replace the original delay design logger.debug('Wait for %d seconds...' % (self.interval)) # don't do unnecessary context switch if self.interval > 0: self.stopEvent.wait(self.interval) if self.stopEvent.is_set(): return logger.debug('Connecting to %s: attempt %d' % (self.deviceIp, i)) try: self.connectToDevice() logger.debug('Connected to %s' % (self.deviceIp)) break except Exception as exc: pass if self.deviceConnectionHandle is None: logger.error('All %d attempts failed for %s' % (self.attempt, self.deviceIp)) self.configurationInProgressCache.doneDevice(self.deviceIp) raise DeviceConnectFailed('All %d attempts failed for %s' % (self.attempt, self.deviceIp)) try: self.device.family = self.deviceConnectionHandle.facts[ 'model'].lower() self.device.serialNumber = self.deviceConnectionHandle.facts[ 'serialnumber'] self.runPreLldpCommands() lldpData = self.collectLldpFromDevice() except Exception as exc: logger.error('Failed to execute deleteVcpPorts for %s, %s' % (self.deviceIp, exc)) raise DeviceRpcFailed( 'Failed to execute deleteVcpPorts %s' % (self.deviceIp), exc) uplinksWithIfds = self.filterUplinkAppendRemotePortIfd( lldpData, self.device.family) self.updateSpineStatusFromLldpData( [x['ifd2'] for x in uplinksWithIfds]) device = self.findMatchedDevice(uplinksWithIfds) if device is None: logger.info('Did not find good enough match for %s' % (self.deviceIp)) self.configurationInProgressCache.doneDevice(self.deviceIp) return self.fixInterfaces(device, self.device.family, uplinksWithIfds) # persist serialNumber device.serialNumber = self.device.serialNumber self._dao.updateObjectsAndCommitNow(self._session, [device]) self.updateSelfDeviceContext(device) try: try: self.runPostLldpCommands() except SkipCommit: self.updateDeviceConfigStatus('good') return self.updateDeviceConfigStatus('processing') self.updateDeviceConfiguration() self.updateDeviceConfigStatus('good') except DeviceRpcFailed as exc: logger.error('Two stage configuration failed for %s, %s' % (self.deviceLogStr, exc)) self.updateDeviceConfigStatus(None, error=exc) raise except Exception as exc: logger.error('Two stage configuration failed for %s, %s' % (self.deviceLogStr, exc)) self.updateDeviceConfigStatus('error', str(exc)) raise finally: self.releaseConfigurationInProgressLock(self.deviceIp) logger.debug('Ended two stage configuration for %s' % (self.deviceLogStr)) else: logger.debug( 'Two stage configuration is already in progress for %s', (self.deviceLogStr))