Exemplo n.º 1
0
 def get_all(self):
     self.c.execute("SELECT id,name,ip,status FROM devices")
     list_devices = []
     for i in self.c:
         d = Device(i[0], i[1], i[2], i[3])
         list_devices.append(d)
     return list_devices
Exemplo n.º 2
0
def init_theano_devices():
  """
  Only for Theano.

  :rtype: list[Device.Device]|None
  """
  if not BackendEngine.is_theano_selected():
    return None
  from Util import TheanoFlags
  from Config import get_devices_init_args
  from Device import Device
  old_device_config = ",".join(config.list('device', ['default']))
  if config.value("task", "train") == "nop":
    return []
  if "device" in TheanoFlags:
    # This is important because Theano likely already has initialized that device.
    config.set("device", TheanoFlags["device"])
    print("Devices: Use %s via THEANO_FLAGS instead of %s." % (TheanoFlags["device"], old_device_config), file=log.v4)
  dev_args = get_devices_init_args(config)
  assert len(dev_args) > 0
  devices = [Device(**kwargs) for kwargs in dev_args]
  for device in devices:
    while not device.initialized:
      time.sleep(0.25)
  if devices[0].blocking:
    print("Devices: Used in blocking / single proc mode.", file=log.v4)
  else:
    print("Devices: Used in multiprocessing mode.", file=log.v4)
  return devices
Exemplo n.º 3
0
    def __init__(self,
                 number_of_edge=3,
                 number_of_user=3,
                 epsilon=0.01,
                 number_of_chs=None,
                 cpu=None,
                 d_cpu=None,
                 H=None):

        self.number_of_user = number_of_user
        self.users = []
        for n in range(self.number_of_user):
            self.users.append(
                Device(d_cpu[n],
                       n,
                       H[n],
                       transmission_power=random.uniform(0.5, 1),
                       epsilon=epsilon))

        self.number_of_edge = number_of_edge
        self.edges = []
        for k in range(self.number_of_edge):
            self.edges.append(
                EdgeCloud(k, cpu[k], number_of_chs=number_of_chs[k]))

        self.network = number_of_chs
Exemplo n.º 4
0
def ModifyDevices():
    conn = dbconn()
    device_obj = Device(conn)

    # retrieve all devices
    # devices = conn.execute_read_query("SELECT * FROM devices")

    if request.method == 'POST':
        device_plan_id = request.form['plan_id']
        device_name = request.form['name']
        device_type = request.form['type']
        device_owner = request.form['owner']

        device_obj.add_device(device_plan_id, device_name, device_type,
                              device_owner)

        # device = device_obj.view_device(device_name)

        # devices = conn.execute_read_query("SELECT * FROM devices")

        return redirect('/devices/list')

    else:

        return render_template('device.html')
Exemplo n.º 5
0
 def _init_devices(self, config):
     """
 Initiates the required devices for a config. Same as the funtion initDevices in
 rnn.py.
 :param config:
 :return: A list with the devices used.
 """
     oldDeviceConfig = ",".join(config.list('device', ['default']))
     if "device" in TheanoFlags:
         # This is important because Theano likely already has initialized that device.
         config.set("device", TheanoFlags["device"])
         print("Devices: Use %s via THEANO_FLAGS instead of %s." %
               (TheanoFlags["device"], oldDeviceConfig),
               file=log.v4)
     devArgs = getDevicesInitArgs(config)
     assert len(devArgs) > 0
     devices = [Device(**kwargs) for kwargs in devArgs]
     for device in devices:
         while not device.initialized:
             time.sleep(0.25)
     if devices[0].blocking:
         print("Devices: Used in blocking / single proc mode.", file=log.v4)
     else:
         print("Devices: Used in multiprocessing mode.", file=log.v4)
     return devices
Exemplo n.º 6
0
def initDevices():
    """
  :rtype: list[Device]
  """
    oldDeviceConfig = ",".join(config.list('device', ['default']))
    if BackendEngine.is_tensorflow_selected():
        if os.environ.get("TF_DEVICE"):
            config.set("device", os.environ.get("TF_DEVICE"))
            print("Devices: Use %s via TF_DEVICE instead of %s." %
                  (os.environ.get("TF_DEVICE"), oldDeviceConfig),
                  file=log.v4)
    if not BackendEngine.is_theano_selected():
        return None
    if config.value("task", "train") == "nop":
        return []
    if "device" in TheanoFlags:
        # This is important because Theano likely already has initialized that device.
        config.set("device", TheanoFlags["device"])
        print("Devices: Use %s via THEANO_FLAGS instead of %s." % \
                         (TheanoFlags["device"], oldDeviceConfig), file=log.v4)
    devArgs = getDevicesInitArgs(config)
    assert len(devArgs) > 0
    devices = [Device(**kwargs) for kwargs in devArgs]
    for device in devices:
        while not device.initialized:
            time.sleep(0.25)
    if devices[0].blocking:
        print("Devices: Used in blocking / single proc mode.", file=log.v4)
    else:
        print("Devices: Used in multiprocessing mode.", file=log.v4)
    return devices
Exemplo n.º 7
0
 def __init__(self):
     wx.Frame.__init__(self, None, wx.ID_ANY, "Tutorial", size=(500, 500))
     self.panel = wx.Panel(self)
     self.tbIcon = SystemTray(self)
     device = Device()
     self.tbIcon.addDevice(device)
     self.tbIcon.ShowBalloon("Test", "Test", 5, wx.ICON_WARNING)
     self.Bind(wx.EVT_CLOSE, self.onClose)
 def __init__(self, names, adb_path='adb'):
     Adb.setup(adb_path)
     mapping_file = load_json(op.join(ROOT_DIR, 'devices.json'))
     self._device_map = {n: mapping_file.get(n, None) for n in names}
     for name, device_id in self._device_map.items():
         if not device_id:
             raise ConfigError(name)
     self.devices = [Device(name, device_id) for name, device_id in self._device_map.items()]
Exemplo n.º 9
0
def main():
    global machine_list
    machine_list = []
    device_1 = Device(5, 20, 10000)
    device_2 = Device(7, 30, 10001)
    device_3 = Device(2, 15, 10002)
    CAP_1 = AccessPoint(10, 10, 10003)
    server_1 = Server(50, 70, 10004)
    machine_list.append(device_1)
    machine_list.append(device_2)
    machine_list.append(device_3)

    machine_list.append(CAP_1)
    machine_list.append(server_1)

    gui_process = Process(target=guiFunc())
    gui_process.start()
Exemplo n.º 10
0
 def insertDeviceData(self, devId, time, x, y, z, lat, long):
     connection = MongoClient('localhost:27017')#'mongodb://192.168.1.65:27017')
     db = connection.vandrico
     dev = Device(devId, time, x, y, z, lat, long)
     serializedDev = json.dumps(dev.__dict__)
     deserializedDev = json.loads(serializedDev)
     db.devices.insert_one(deserializedDev)
     connection.close()
Exemplo n.º 11
0
Arquivo: Vm.py Projeto: free-Zen/pvc
   def YieldAllDevices(self):
      """
      A generator that yields all of the devices that belong to the
      virtual machine.
      """

      for deviceManagedObject in self.managedObject.config.hardware.device:
         yield Device(vm=self, managedObject=deviceManagedObject)
Exemplo n.º 12
0
def Run(isDebugging=False):

    if isDebugging == False:

        device = Device("127.0.0.1:62001")
        device.Connect()
        profile = Profile("GaChien")
        profile.Load()
        gameManager = GameManager(device, profile)
        screenManager = ScreenManager()

        while True:
            screenshot = device.CaptureScreen()
            if screenshot.image is None:
                print("Can not capture screenshot. Retry...")
                time.sleep(5)
                continue

            screen = screenManager.GetScreen(screenshot)
            screen.ShowName()

            gameManager.SetScreen(screen)
            gameManager.Play()

            print("")
            time.sleep(5)

    else:

        device = Device(None)
        device.Connect()
        profile = Profile("GaChien")
        profile.Load()
        gameManager = GameManager(device, profile)
        screenManager = ScreenManager()

        print("Debugging...")
        filePath = os.path.abspath("PendingScreens/Screenshot.png")
        screenshot = ScreenShot(filePath)

        screen = screenManager.GetScreen(screenshot)
        screen.ShowName()

        gameManager.SetScreen(screen)
        gameManager.Play()
Exemplo n.º 13
0
    def testRentalCheckOut(self):
        for n in xrange(NUM_TESTS):
            # Create User
            user = User()
            user.first_name = self.v.validRandomString(MAX_STRING_LENGTH)
            user.family_name = self.v.validRandomString(MAX_STRING_LENGTH)
            user.group = randomGroupEnum()
            user.device_id = None
            user.start_datetime = None
            user_key = user.put()

            # Verify User has no device
            q = User.query().fetch(n + 1)
            self.assertEqual(q[n].first_name, user.first_name)
            self.assertEqual(q[n].family_name, user.family_name)
            self.assertEqual(q[n].group, user.group)
            self.assertEqual(q[n].device_id, user.device_id)
            self.assertEqual(q[n].start_datetime, user.start_datetime)

            # Create Device
            device = Device()
            device.color = randomColorEnum()
            device.model = randomDeviceModelEnum()
            device.serial_no = self.v.validRandomString(MAX_STRING_LENGTH)
            device_key = device.put()

            # Verify Device is not rented
            q = Device.query().fetch(n + 1)
            device_id = q[n].key.urlsafe()
            self.assertEqual(q[n].color, device.color)
            self.assertEqual(q[n].model, device.model)
            self.assertEqual(q[n].serial_no, device.serial_no)
            self.assertEqual(q[n].is_rented, False)

            # Add Device to User
            start_datetime = datetime.now()
            result = user.checkOutDevice(device_id, start_datetime)

            self.assertNotEqual(result, None)

            # Verify User has device ID
            q = User.query().fetch(n + 1)
            self.assertEqual(q[n].first_name, user.first_name)
            self.assertEqual(q[n].family_name, user.family_name)
            self.assertEqual(q[n].group, user.group)
            self.assertEqual(q[n].device_id, user.device_id)
            self.assertEqual(q[n].device_id, device_id)
            self.assertEqual(q[n].start_datetime, user.start_datetime)
            self.assertEqual(q[n].start_datetime, start_datetime)

            # Verify Device is rented
            q = Device.query().fetch(n + 1)
            device_id = q[n].key.urlsafe()
            self.assertEqual(q[n].color, device.color)
            self.assertEqual(q[n].model, device.model)
            self.assertEqual(q[n].serial_no, device.serial_no)
            self.assertEqual(q[n].is_rented, True)
Exemplo n.º 14
0
 def addComputer(self, name):
     device = Device('computer.jpg', name, 'computer', self)
     device.move(100, 65)
     device.show()
     self.deviceList.append(device)
     try:
         self.detailsWindow.updateDetails()
     except Exception as e:
         pass
Exemplo n.º 15
0
class MeasureDeviceConnect(BaseMeasureInfo):

    try:
        dev = Device()
        ldc = dev.get_ldc4005_instance()
        pm100 = dev.get_pm100_instance()
        BaseMeasureInfo.OUT_MSG += "Connections with device successful"
    except Exception as err:
        BaseMeasureInfo.logger.error(err)
        BaseMeasureInfo.OUT_MSG += ("Error %s" % err)
Exemplo n.º 16
0
 def selectDevicesFromDb(self, devID):
     connection = MongoClient('localhost:27017')#'mongodb://192.168.1.65:27017')
     db = connection.vandrico
     devices = []
     for doc in db.devices.find({"deviceID":devID}).sort("timestamp",1):
         dev = Device(str(doc['deviceID']),str(doc['timestamp']),str(doc['x']),str(doc['y']),
                      str(doc['z']),str(doc['latitude']),str(doc['longitude']))
         devices.append(dev)
     connection.close()
     return devices
    def dList_init(self, initial_conditions):
        """
        Initializes and instanciates all devices given their initial conditions; 
        initial_conditions is of the form [(x_0, y_0), (vx_0, vy_0), ..., (x_n, y_n), (vx_n, vy_n)] describing the initial parameters all devices (from 0 to n)
        """

        for dID, (pos, vel) in enumerate(initial_conditions):
            self.dList.append(Device(dID, pos, vel))
        
        return self.dList
Exemplo n.º 18
0
    def close_Button(self):
        self.window.destroy()

        Device().capture_screenshot()
        droid = AQMdroid(self.img_path, self.img_dim, self.filename)

        try:
            droid.getorigin()
        except Exception as e:
            print "\nFrame Clossed."
Exemplo n.º 19
0
 def update(self):
     device_names = self.hal_manager.GetAllDevices()
     self.manager.device = {}
     for name in device_names:
         device_dbus_obj = self.bus.get_object('org.freedesktop.Hal', name)
         properties = device_dbus_obj.GetAllProperties(
             dbus_interface="org.freedesktop.Hal.Device")
         d = Device(name, properties)
         self.manager.append_device(d)
         self.add_dev_sig_recv(name)
Exemplo n.º 20
0
def interfaceState():
    R = Device('R2')
    RTelnet = telnetlib.Telnet(GET_IP, 23, 60)
    RTelnet.write(GET_USERNAME + "\n")
    RTelnet.write(GET_PASSWORD + "\n")

    if verifyInterfaceState(RTelnet, 'lo0', state="up"):
        return 1
    else:
        return 0
Exemplo n.º 21
0
    def search_for_device(self):
        notificationSource = None
        controlPoint = None
        dataSource = None
        deviceID = None

        # TODO: use functional pattern to simplify the loop
        # characteristics = self.all_children(hci, "dev_")
        #   .filter(lambda x: (...).connected)
        #   .map(lambda x: self.all_children(x, "service"))
        #   .filter(lambda x: uuid == ancsID)
        # notificationSource = characteristics
        #   .first(lambda x: uuid == notificationSourceID)
        hci = self.bus.get_object("org.bluez", "%s" % self.path)
        for deviceID in self.all_children(hci, "dev_"):
            device = self.bus.get_object(
                "org.bluez", "%s/%s" % (self.path, deviceID))
            props = dbus.Interface(device, "org.freedesktop.DBus.Properties")
            connected = props.Get("org.bluez.Device1", "Connected")
            if not connected:
                continue
            for serviceID in self.all_children(device, "service"):
                service = self.bus.get_object(
                    "org.bluez", "%s/%s/%s" % (self.path, deviceID, serviceID))
                props = dbus.Interface(
                    service, "org.freedesktop.DBus.Properties")
                uuid = props.Get("org.bluez.GattService1", "UUID")
                if uuid != ancsID:
                    continue
                for characteristicID in self.all_children(service, "char"):
                    characteristic = self.bus.get_object(
                        "org.bluez", "%s/%s/%s/%s" % (self.path,
                                                      deviceID, serviceID,
                                                      characteristicID))
                    props = dbus.Interface(
                        characteristic, "org.freedesktop.DBus.Properties")
                    uuid = props.Get("org.bluez.GattCharacteristic1", "UUID")
                    if uuid == notificationSourceID:
                        notificationSource = characteristic
                        deviceID = deviceID
                    elif uuid == controlPointID:
                        controlPoint = characteristic
                    elif uuid == dataSourceID:
                        dataSource = characteristic

        if notificationSource is None \
                or controlPoint is None \
                or dataSource is None:
            return None
        return Device(self,
                      notificationSource,
                      controlPoint,
                      dataSource,
                      deviceID)
Exemplo n.º 22
0
def createDevice(deviceCount):
    devices = []

    with open('locs.csv', 'rb') as f:
        reader = csv.reader(f)
        locs = list(reader)

    for i in range(0, deviceCount):
        device = Device('TFP' + str(i + 1).zfill(4), locs[i][0], locs[i][1],
                        'Generic Sensor')
        devices.append(device)
    return devices
Exemplo n.º 23
0
    def addDeviceNoPar(self):
        nameRes = self.name.text()
        portRes = self.port.text()
        if self.checkStringForNumber(self.value.text()):
            valRes = int(self.value.text())
        else:
            self.showPopup("e", "Not a number",
                           "You have to enter a valid number")
            self.value.setText("0")
            return
        try:
            maxRollRes = float(self.maxRollLength.text())
        except:
            self.showPopup("e", "Not a number",
                           "You have to enter a valid number")
            self.value.setText("0")
            return

        self.name.setText("")
        self.port.setText("COM0")
        self.value.setText("0")
        self.maxRollLength.setText("0")

        if nameRes == "":
            self.showPopup("e", "Error: No name",
                           "New device can not be created without a name.")
            return

        for device in self.devices:
            if device.name == nameRes:
                self.showPopup("e", "Error: Duplicate names",
                               "There already is a device with this name.")
                self.name.setText("")
                return
        try:
            newDevice = Device(nameRes, portRes, self.sensorType, valRes,
                               maxRollRes)  # lightRes, tempRes)
            self.devices.append(newDevice)
            self.setCurrentDevice(self.devices[0].name)

            self.log.writeInLog(
                "i",
                "New device added: name: " + nameRes + " | Port: " + portRes +
                " | Sensor type: " + self.sensorType + " | Minimum value: " +
                str(valRes) + " | Max roll length: " + str(maxRollRes))
            self.showPopup("i", "New Device",
                           "Device with name: " + nameRes + " has been added!")
            self.updateMaingrid(self.MainWindow)
        except:
            self.log.writeInLog("w", "Could not add device: " + nameRes)
            self.showPopup("e", "Could not add device!",
                           "An error has occurred")
            newDevice = None
Exemplo n.º 24
0
    def __init__(self, manager=None):
        if manager != None:
            self.manager = manager
        else:
            self.manager = None

        DBusGMainLoop(set_as_default=True)

        self.bus = dbus.SystemBus()
        obj = self.bus.get_object('org.freedesktop.Hal',
                                  '/org/freedesktop/Hal/Manager')
        self.hal_manager = dbus.Interface(obj, 'org.freedesktop.Hal.Manager')

        try:
            self.hal_manager.connect_to_signal(
                'DeviceAdded', lambda *args: self.handle('DeviceAdded', *args))
        except:
            pass

        try:
            self.hal_manager.connect_to_signal(
                'DeviceRemoved',
                lambda *args: self.handle('DeviceRemoved', *args))
        except:
            pass

        try:
            self.hal_manager.connect_to_signal(
                'NewCapability',
                lambda *args: self.handle('NewCapability', *args))
        except:
            pass

        device_names = self.hal_manager.GetAllDevices()

        self.icon = gtk.StatusIcon()
        self.icon.set_from_stock(gtk.STOCK_INFO)

        for name in device_names:
            try:
                self.add_dev_sig_recv(name)
                device_dbus_obj = self.bus.get_object('org.freedesktop.Hal',
                                                      name)
                properties = device_dbus_obj.GetAllProperties(
                    dbus_interface="org.freedesktop.Hal.Device")

                d = Device(name, properties)
                if manager != None:
                    self.manager.append_device(d)

                self.add_dev_sig_recv(name)
            except:
                pass
Exemplo n.º 25
0
 def testInsertDevice(self):
     for n in xrange(NUM_TESTS):
         device = Device()
         device.color = randomColorEnum()
         device.model = randomDeviceModelEnum()
         device.serial_no = self.v.validRandomString(MAX_STRING_LENGTH)
         device_key = device.put()
         q = Device.query().fetch(n + 1)
         self.assertEqual(q[n].color, device.color)
         self.assertEqual(q[n].model, device.model)
         self.assertEqual(q[n].serial_no, device.serial_no)
         self.assertEqual(q[n].is_rented, False)
Exemplo n.º 26
0
def SetupDeviceConnection():
    deviceConnection = ServerlessDeviceConnection()
    BlinkyLEDDevice = Device()
    BlinkyLEDDevice.DeviceID = 444
    BlinkyLEDDevice.SetDeviceName('BlinkyLED')
    OnOffControls = ControlValue()
    OnOffControls.ControlName = 'LEDState'
    OnOffControls.ControlValueType = OnOffControls.OnOff
    OnOffControls.ControlID = 0
    BlinkyLEDDevice.ControlList.append(OnOffControls)
    deviceConnection.SetDeviceData(BlinkyLEDDevice)
    return deviceConnection
Exemplo n.º 27
0
def get_nearby_devices(task):
    cur_time = current_milli_time()
    nearby_idss = locations.find(
        {"timeStamp": {
            "$gte": cur_time - 10 * MINUTE,
            "$lte": cur_time
        }})
    nearby_idsss = [
        x['uid'] for x in nearby_idss
        if vincenty(x['location'], (task.latitude,
                                    task.longitude)).meters < task.radius
    ]

    mylogger.info("nearby users" + str(nearby_idsss))
    device_ids = list(
        set(nearby_idsss) - set(task.assignment_list) - set(task.waiting_pool))
    mylogger.info("after removing duplicates " + str(device_ids) + " stay")
    device_list = []
    for device_id in device_ids:

        loc = list(
            locations.find({
                "uid": device_id,
                "location": {
                    "$ne": [0, 0]
                },
                "timeStamp": {
                    "$gte": cur_time - 10 * MINUTE,
                    "$lte": cur_time
                }
            }).sort("timeStamp", -1).limit(1))
        if loc:
            device_loc = loc[0]['location']
            if vincenty(device_loc,
                        [task.latitude, task.longitude]).meters < task.radius:
                bat = db.Batteries.find_one({"_id": device_id})
                user = db.Users.find_one({'_id': device_id})
                token = user.get('token', '')
                selected_time = user.get('selected_times', 0)
                unpredictability = user.get('unpredictability', 0)
                if token != '':
                    device_list.append(
                        Device(id=device_id,
                               latitude=device_loc[0],
                               longitude=device_loc[1],
                               bat_level=float(bat["level"]),
                               bat_status=bat["status"],
                               selected_times=selected_time,
                               token=token,
                               unpredictability=unpredictability))

    return device_list
    def __init__(self, i2c, **kwargs):
        self._AS7265X_ADDR = AS7265X_ADDR

        self._mode = AS7265X_MEASUREMENT_MODE_6CHAN_ONE_SHOT  #Mode 4
        # TODO: Sanitize gain and integration time values
        self._gain = AS7265X_GAIN_64X  # 64x
        self._integration_time = AS7265X_POLLING_DELAY
        self._sensor_version = 0
        #Create I2C device
        if i2c is None:
            raise ValueError('An I2C object is required.')
        self._device = Device(AS7265X_ADDR, i2c)
        self._i2c = i2c
Exemplo n.º 29
0
	def screeninfo(self):
		"""Captures the Screenshot and displays it """
		Device().capture_screenshot()
		resolution = (self.width, self.height)
		droid = AQMdroid('image.png', resolution, self.filename)
		
		try:
			droid.getorigin()
		except Exception as e:
			ScriptGen(self.filename).log_checker(self.log_handler)
			ScriptGen(self.filename).log_checker(self.generate_log_file)
			print "\nExit Point Triggered."
			sys.exit()
Exemplo n.º 30
0
class MeasureDeviceConnect(BaseMeasureInfo):
    try:
        dev = Device()
        ldc = dev.get_ldc4005_instance()
        pm100 = dev.get_pm100_instance()
        BaseMeasureInfo.OUT_MSG += "Connections with device successful"
        BaseMeasureInfo.WAVELENGTH = str(pm100.get_current_wavelength_in_nm())
        BaseMeasureInfo.LD_CURRENT_LIMIT = str(
            ldc.get_current_limit_in_amper() * 1000)
    except Exception as err:
        BaseMeasureInfo.logger.error(err)
        BaseMeasureInfo.OUT_MSG = ""
        BaseMeasureInfo.OUT_MSG += ("Error %s" % err)