コード例 #1
0
ファイル: app.py プロジェクト: NateB313/dog_crate
def main():
    heater = device.Device("heater")
    fan = device.Device("fan")

    while True:
        current_temp = get_temperature()
        print("The current temperature is {} degrees.".format(current_temp))
        time.sleep(2)

        if current_temp > MAX_TEMP:
            fan.set_power(True)
            time.sleep(1)
            heater.set_power(False)
            time.sleep(1)
            print("\n")
        elif current_temp < MIN_TEMP:
            fan.set_power(False)
            time.sleep(1)
            heater.set_power(True)
            time.sleep(1)
            print("\n")
        else:
            fan.set_power(False)
            time.sleep(1)
            heater.set_power(False)
            time.sleep(1)
            print("\n")
        
        time.sleep(5)
コード例 #2
0
    def __init__(self, json_data):

        print json_data
        
        self.sender = device.Device('my laptop')
        self.receiver = device.Device(json_data['receiver'])
        self.command = json_data['command']
コード例 #3
0
ファイル: send.py プロジェクト: faizan-k/Sync-App
    def __init__(self, appcommand,message):

        #print json_data
        
        self.sender = device.Device('My laptop')
        self.receiver = device.Device('Mobile')
        self.command = appcommand
        self.write(message)
コード例 #4
0
    def __init__(self, json_data):

        print "json data = " + `json_data[0]`
        self.received_data = json_data[0]

        self.sender = device.Device(json_data[0]['receiver'])
        self.receiver = device.Device(json_data[0]['receiver'])
        self.req_id = json_data[0]['data']['requestId']
        self.command = json_data[0]['command']
コード例 #5
0
ファイル: lldp.py プロジェクト: voidloop/snmp-lldp
def gettree(host, trunk="id", branches="children"):
    '''
    returns None if SNMP failed, or a dict with device info and neighbours.
    '''
    # List of devices we've already checked.
    global checked
    c = {trunk: host}

    try:
        d = device.Device(host)
        d.snmpConfig(oid, snmpVersion, args.community)
    except:
        return c

    neighbours = d.getNeighbours()
    if not neighbours:
        return c

    children = []

    # Have we already checked this device? Loop prevention.
    for x in neighbours.values():
        if x and (x not in checked):
            logger.debug("%s has neighbour %s", host, x)
            # Recurse!
            checked.append(x)
            children.append(gettree(x))
    if children:
        c[branches] = children
    return c
コード例 #6
0
    def gather_roku_devices(self, makeonlydevicecurrent):
        print("Looking for Roku devices...")
        if self.connection:
            ips = self.connection.get_devices()
            self.devices = []

            # Create devices
            # send each device its most recent state and apps
            if len(ips) == 0:
                self.current_device = None
                return

            for i in ips:

                # Get device info
                apps = appgetter.doparse(
                    self.connection.send_command(i, "query/apps", True))
                info = appgetter.doparsedeviceinfo(
                    self.connection.send_command(i, "query/device-info", True))

                # Create a Device
                self.devices.append(device.Device(i, apps, info))

                # d.set_state(state)
                # d.set_apps(apps)

                # print(info)
                # print(apps)

            if makeonlydevicecurrent:
                if len(self.devices) == 1:
                    self.select_roku_device(self.devices[0])
コード例 #7
0
def set_mute(dev, is_mute):
    '''
    get device whether mute
    @param dev: a device path
    @param is_mute: whether is mute, a bool type
    '''
    device.Device(dev).set_mute(is_mute)
コード例 #8
0
def handle_cmd():
    appdb.collect_apps("../apks/")

    serial = sys.argv[1]
    cmd = sys.argv[2]
    args = sys.argv[3:]

    dev = device.Device(serial=serial, no_uimon=True)

    if cmd == "clear":
        if args[0] == 'all':
            for app in appdb.apps:
                clear(dev, appdb.get_app(app))
        else:
            clear(dev, appdb.get_app(args[0]))
    elif cmd == "install":
        appname = args[0]
        install(dev, appname)
    elif cmd == "uninstall":
        appname = args[0]
        uninstall(dev, appname)
    elif cmd == "version":
        appname = args[0]
        apk_version(appname)
    elif cmd == "dver":
        appname = args[0]
        ret = check_dev_version(dev, appname)
        if ret:
            sys.exit(0)
        else:
            sys.exit(1)
コード例 #9
0
def get_mute(dev):
    '''
    get device whether mute
    @param dev: a device path
    @return: a bool type
    '''
    return device.Device(dev).get_mute()
コード例 #10
0
def init_dev_list(dev_list, dev_type):
    global PA_DEVICE
    global PA_CHANNELS
    global PA_CARDS
    for d in dev_list:
        dev = device.Device(d)
        if dev_type == 'sink':
            if not dev.get_ports() and d != CURRENT_SINK: # if the device does not have any ports, ignore it
                continue
        else:
            if not dev.get_ports() and d != CURRENT_SOURCE: # if the device does not have any ports, ignore it
                continue
        PA_DEVICE[d] = dev
        dev_channels = {}
        channels = PA_DEVICE[d].get_channels()
        dev_channels["channel_num"] = len(channels)
        dev_channels["left"] = []
        dev_channels["right"] = []
        dev_channels["other"] = []
        i = 0
        while i < dev_channels["channel_num"]:
            if channels[i] in LEFT_CHANNELS:
                dev_channels["left"].append(i)
            elif channels[i] in RIGHT_CHANNELS:
                dev_channels["right"].append(i)
            else:
                dev_channels["other"].append(i)
            i += 1
        try:
            cards = dev.get_card()
            PA_CARDS[cards][dev_type].append(dev)
        except:
            traceback.print_exc()
        PA_CHANNELS[d] = dev_channels
コード例 #11
0
 def get_individual_host(self, name):
     self.ip = resolveUser.resolveUser(name)
     self.url = 'https://%s/api/v1/host?hostIp=%s' \
         % (settings.dnacIP, self.ip)
     self.response_json = self.get_api(self.url)
     self.message = ''
     for host in self.response_json['response']:
         #print host
         self.message += 'User is connected to Network ' + u'\u2705' \
             + ' \n'
         self.message += '[Host IP: ' + host['hostIp'] \
             + ', Host Mac: ' + host['hostMac'] + '] \n'
         try:
             apic_device = device.Device()
             self.connected_device = \
                 apic_device.resolve_device_id(host['connectedNetworkDeviceId'
                     ])
             del apic_device
             self.message += 'Connected to device: %s \n' \
                 % self.connected_device
             if host['connectedInterfaceName']:    
                 self.message += 'Connected to port: %s \n' \
                 % host['connectedInterfaceName']
             if host['vlanId']:
                 self.message += 'Connected to vlan: %s \n' \
                 % host['vlanId']
             else:
                 self.message += ' '           
         except:
             print "No Attached Device"
     return self.message
コード例 #12
0
def get_device_list(db_conn, devices_conf_dir):
    devices = {}
    config_parser = ConfigParser()

    for conf_file in os.listdir(devices_conf_dir):
        if conf_file.startswith("."):
            continue
        conf = StringIO.StringIO()
        conf.write('[__main__]\n')
        conf.write(open(os.path.join(devices_conf_dir, conf_file)).read())
        conf.seek(0)
        config_parser.readfp(conf)
        device_name = config_parser.get("__main__", "hostname")
        reset_command = config_parser.get("__main__", "hard_reset_command")
        off_command = config_parser.get("__main__", "power_off_cmd")
        serial_command = config_parser.get("__main__", "connection_command")
        devices[device_name] = device.Device(device_name, reset_command,
                                             off_command, serial_command)
        db_cursor = db_conn.cursor()
        try:
            db_cursor.execute("INSERT INTO devices VALUES (?)",
                              (device_name, ))
            db_cursor.execute("INSERT INTO reservations VALUES (?, ?, ?, ?)",
                              (device_name, 0, None, 0))
            db_conn.commit()
        except sqlite3.IntegrityError:
            pass
        finally:
            db_cursor.close()
    return devices
コード例 #13
0
    def cleanup_workers(self, include_calibrators=False):
        self.poll()

        for miner_name in self.miners.keys():
            for algorithm in self.miner_state[miner_name]['algorithms']:
                kill = True

                if not include_calibrators and len(algorithm['pools']) > 0:
                    login = algorithm['pools'][0]['login']

                    user, password = login.split(':')

                    if user[-5:] == 'CALIB':
                        kill = False

                if kill:
                    if len(algorithm['workers']) > 0:
                        nvidia.Nvidia().set_default_profile(
                            device.Device({
                                "id":
                                int(algorithm['workers'][0]['device_id'])
                            }))

                    self.miners[miner_name].do_command(
                        'algorithm.remove', [str(algorithm['algorithm_id'])])
コード例 #14
0
def main():
    dev = device.Device('192.168.1.123', 'admin', 'Cisco.com', 'FakeTest2')
    cmd_mgr = cmdmgr.CommandManager()
    commands = cmd_mgr.get_commands()

    facts = Facts(dev, commands)
    facts.process_facts()
コード例 #15
0
def monitor_devices():
    print("do the monitor thing!")

    while globVar.continueProcessing == 1:
        # Get list of devices
        result = subprocess.check_output(["arp-scan", "-l"])

        # Parse list so it's in the form we want
        result = result.partition(")\n")[2]
        result = result.partition("\n\n")[0]

        machines = result.split("\n")
        for machine in machines:
            sections = machine.split("\t")
            mac = sections[1]
            name = sections[2]

            if already_in_lists(
                    mac
            ) == 0:  # If it's not in the lists already, add to grey list
                d = device.Device(mac, name)
                globVar.greyListMutex.acquire()
                try:
                    globVar.greyList.append(d)
                finally:
                    globVar.greyListMutex.release()

                # Also add it to the database
                globVar.dbMutex.acquire()
                try:
                    dbStuff.add_to_table(2, d)
                finally:
                    globVar.dbMutex.release()
コード例 #16
0
def set_colors(*colordef):
    l = list(colordef)

    defs = {}

    while len(l) > 0:
        key_target = l.pop(0).split(",")
        col = l.pop(0)

        for tgt in key_target:
            if tgt == '--':
                # special: applies color to all yet unused colors
                for keycode in keys.others(defs.keys()):
                    defs[keycode] = colors.get(col)
            for keycode in keys.get(tgt):
                if keycode is None:
                    continue
                defs[keycode] = colors.get(col)

    if len(defs) == 0:
        raise Exception("could not determine any color definitions")

    COLOR_PAYLOAD = []
    for keycode, color in defs.items():
        COLOR_PAYLOAD += [keycode]
        COLOR_PAYLOAD += color

    with device.Device() as dev:
        dev.send_colors(COLOR_PAYLOAD)
コード例 #17
0
    def test_part_one(self):
        "Test part one example of Device object"

        # 1. Create Device object from text
        myobj = device.Device(text=aoc_16.from_text(PART_ONE_TEXT))

        # 2. Check the part one result
        self.assertEqual(myobj.part_one(verbose=False), PART_ONE_RESULT)
コード例 #18
0
    def __init__(self, args):
        super().__init__()
        self.device = dev.Device(args.dev, args.cfg)

        if not self.device.cfg:
            if __debug__:
                log.error('Config was not loaded')
            exit(-1)
コード例 #19
0
    def test_part_two(self):
        "Test part two example of Device object"

        # 1. Create Device object from text
        myobj = device.Device(part2=True, text=aoc_16.from_text(PART_TWO_TEXT))

        # 2. Check the part two result
        self.assertEqual(myobj.part_two(verbose=False), PART_TWO_RESULT)
コード例 #20
0
ファイル: stack.py プロジェクト: xhaa123/alps
    def __init__(self, context, prev, next, install):
        Gtk.VBox.__init__(self)
        self.prev = prev
        self.next = next
        self.install = install
        self.context = context

        intro_card = intro.Intro(self.context)
        device_card = device.Device(self.context)
        partition_card = partition.Partition(self.context)
        timezone_card = timezone.Timezone(self.context)
        locale_card = locale.Locale(self.context)
        user_card = user.User(self.context)
        root_card = root.Root(self.context)
        finalinfo_card = finalinfo.FinalInfo(self.context)
        status_card = status.Status(self.context)

        self.card_names = [
            'intro_card', 'device_card', 'partition_card', 'timezone_card',
            'locale_card', 'user_card', 'root_card', 'finalinfo_card',
            'status_card'
        ]
        self.cards = [
            intro_card, device_card, partition_card, timezone_card,
            locale_card, user_card, root_card, finalinfo_card, status_card
        ]

        self.the_stack = Gtk.Stack()
        self.the_stack.set_hexpand(True)
        self.the_stack.set_vexpand(True)

        self.context['the_stack'] = self.the_stack

        self.pack_start(self.the_stack, True, True, 0)
        self.set_name('stack')

        # add the cards to the stack

        self.the_stack.add_titled(intro_card, 'intro_card', 'Introduction')
        self.the_stack.add_titled(device_card, 'device_card', 'Device')
        self.the_stack.add_titled(partition_card, 'partition_card',
                                  'Partition')
        self.the_stack.add_titled(timezone_card, 'timezone_card', 'Timezone')
        self.the_stack.add_titled(locale_card, 'locale_card', 'Locale')
        self.the_stack.add_titled(user_card, 'user_card', 'User')
        self.the_stack.add_titled(root_card, 'root_card', 'Root')
        self.the_stack.add_titled(finalinfo_card, 'finalinfo_card',
                                  'Confirmation')
        self.the_stack.add_titled(status_card, 'status_card', 'Status')

        self.prev.connect('clicked', self.nav_prev)
        self.next.connect('clicked', self.nav_next)

        self.current_card = self.card_names[0]
        self.current_index = 0

        self.prev.set_sensitive(False)
        self.install.set_sensitive(False)
コード例 #21
0
ファイル: main.py プロジェクト: APO-ACI-PRP/RP-01
def main():
    cmd_mgr = cmdmgr.CommandManager()
    commands = cmd_mgr.get_commands()
    devices = cmd_mgr.get_devices()
    for currentDevice in devices:
    	dev = device.Device(currentDevice['IP'],currentDevice['User'],currentDevice['Password'],currentDevice['DeviceName'])
    	print dev

    	devFactsRetriever = facts.Facts(dev, commands)
        devFactsRetriever.process_facts()
コード例 #22
0
def populate_lists():
    conn = sqlite3.connect('compSec_db.sqlite')
    cur = conn.cursor()
    # cur.execute('DROP TABLE greyList')
    # conn.commit()

    # Create the tables if they don't exist
    cur.execute('CREATE TABLE IF NOT EXISTS blackList(macAddress VARCHAR, name VARCHAR)')
    conn.commit()
    cur.execute('CREATE TABLE IF NOT EXISTS allowedList(macAddress VARCHAR, name VARCHAR)')
    conn.commit()
    cur.execute('CREATE TABLE IF NOT EXISTS greyList(macAddress VARCHAR, name VARCHAR)')
    conn.commit()

    # Populate blackList
    cur.execute('SELECT * FROM blackList')
    data = cur.fetchall()
    for datum in data:
        macAddress = datum[0]
        name = datum[1]
        d = device.Device(macAddress, name)
        globVar.blackList.append(d)

    # Populate allowedList
    cur.execute('SELECT * FROM allowedList')
    data = cur.fetchall()
    for datum in data:
        macAddress = datum[0]
        name = datum[1]
        d = device.Device(macAddress, name)
        globVar.allowedList.append(d)

    # Populate greyList
    cur.execute('SELECT * FROM greyList')
    data = cur.fetchall()
    for datum in data:
        macAddress = datum[0]
        name = datum[1]
        d = device.Device(macAddress, name)
        globVar.greyList.append(d)

    conn.close()
コード例 #23
0
    def test_empty_init(self):
        "Test the default Device creation"

        # 1. Create default Device object
        myobj = device.Device()

        # 2. Make sure it has the default values
        self.assertEqual(myobj.part2, False)
        self.assertEqual(myobj.text, None)
        self.assertEqual(myobj.obs, None)
        self.assertEqual(myobj.program, None)
コード例 #24
0
    def test_text_init(self):
        "Test the Device object creation from text"

        # 1. Create Device object from text
        myobj = device.Device(text=aoc_16.from_text(EXAMPLE_TEXT))

        # 2. Make sure it has the expected values
        self.assertEqual(myobj.part2, False)
        self.assertEqual(len(myobj.text), 9)
        self.assertEqual(len(myobj.obs), 1)
        self.assertEqual(len(myobj.program), 3)
コード例 #25
0
ファイル: main.py プロジェクト: flyfloh/datscha
def init(cfg, channel):
    dev = device.Device(cfg.get("room"))

    sensors = load_sensors(cfg)
    for s in sensors:
        room = cfg.get("room")
        channel.sensor_init(sensor_id=s.id(),
                            device=dev.template(),
                            templates=s.templates(dev.id(), room),
                            room=room)

    return sensors
コード例 #26
0
ファイル: uievent.py プロジェクト: marklang1993/appflow
def print_uievents(serial):
    #    mon = monitor.monitor_cmd(["adb", "shell", "uiautomator", "events"],
    #                              functools.partial(event_output_cb, cb))
    import device
    dev = device.Device(serial, no_uimon=True)
    mon = monitor_uievent(print_event, dev=dev)
    while True:
        cmd = input(">")
        if cmd == 'q':
            mon.kill()
            os._exit(0)
        else:
            mon.input(cmd)
コード例 #27
0
def check_act_once(serial):
    subprocess.call("adb -s %s shell input keyevent HOME" % serial, shell=True)
    dev = device.Device(serial=serial, no_uimon=True)
    actname = sense.grab_actname(dev)
    if actname is None:
        print("can't get activity name")
        return False
    if 'launcher' in actname:
        print("at launcher")
        return True
    else:
        print("at %s, not launcher" % actname)
        return False
コード例 #28
0
    def __init__(self, cores):
        self.device = device.Device(cores)
        self.dirs = []
        self.files = {'/ctrl': self.device.ctrl}
        for i in range(cores):
            self.dirs.append('/unit{}'.format(i))
            self.files[self.dirs[-1] + '/lram'] = self.device.units[i].lram
            self.files[self.dirs[-1] + '/pram'] = self.device.units[i].pram

        creation_time = time.time()
        common_fields = dict(st_uid=os.getuid(), st_gid=os.getgid(), **{x:creation_time for x in ['st_ctime', 'st_mtime', 'st_atime']})
        self.dir_stat = dict(st_mode=(S_IFDIR | 0o755), st_nlink=1, **common_fields)
        self.file_stat = dict(st_mode=(S_IFREG | 0o644), st_nlink=1, st_size=0, **common_fields)
コード例 #29
0
    def move_to_blacklist():
        #get selection
        index = greyTab.curselection()[0]
        selection = greyTab.get(index)

        #remove from grey tab, add to black tab
        greyTab.delete(index)
        blackTab.insert(tkinter.END, selection)

        #remove from grey data table, add to black data table
        device_info = selection.split(" ", 1)
        obj = device.Device(device_info[0], device_info[1])
        dbStuff.remove_from_table(2, obj)
        dbStuff.add_to_table(0, obj)
コード例 #30
0
 def del_device(self):
     """
     delete all devices
     """
     global deviceList
     deviceList = []
     common.Log.info("delete all devices")
     deviceObj = device.Device(app_type)
     deviceObj.del_device()
     for i in range(2):
         self.device.setItem(i, 0, QTableWidgetItem(""))
         for j in range(2):
             self.device.setItem(i, j, QTableWidgetItem(""))
     self.statusEdit.setText("")