Ejemplo n.º 1
0
def getDeviceForDynAnalysis():
    dev_list = Device.get_devices_list()
    
    devNum = len(dev_list)
    
    if devNum <= 0:
        logger.error("No device has been detected! Connect your device and restart the application!")
        return None
    
    if devNum == 1:
        return Device.get_device(dev_list[0])
    
    choice = None
    if devNum > 1:
        print "Select the device to use for analysis:\n"
        for i in xrange(0, devNum):
            print "%d. %s\n" % ((i + 1), dev_list[i])
        
        while not choice:
            try:
                choice = int(raw_input())
                if choice not in range(1, devNum+1):
                    choice = None
                    print 'Invalid choice! Choose right number!'
            except ValueError:
                print 'Invalid Number! Choose right number!'
        
        
    return Device.get_device(dev_list[choice - 1])
Ejemplo n.º 2
0
def init( ):
    """ Initialise the device handle, boot to NAND flash.
        @returns: a device handle, i.e. a class Device instance.
    """

    print "  Initialising the device."
    print "  (Device will be powercycled in 60 secs if unresponsive)"
    power.power(1)
    t = threading.Timer( 60, powercycle )
    t.start()
    dev = Device( devtype = "hidav" )
    wait_networking( dev )    
    t.cancel()

    # set currently used partitions to the first partitions, 
    # so upgrade (detecting this) will use the other partitions
    dev.bootconfig = { "kernel" : 2, "rootfs" : 4 } 

    print "  Firmware version: %s" % dev.firmware_version
    print "  Boot config (current):"
    print "     Kernel:      /dev/mtd%s" % dev.bootconfig["kernel"]
    print "     rootfs: /dev/romblock%s" % dev.bootconfig["rootfs"]
    print "     epoch :             #%s" % dev.bootconfig["epoch"]

    print "  Booting into NAND..."
    dev.reboot( to_nand = True )
    wait_networking( dev )    
    return dev
Ejemplo n.º 3
0
 def observed_devices(self, user_id):
     dev_ids = self.find_by('where user_id = ?', user_id)
     devices = []
     dev = Device()
     for dev_id in dev_ids:
         devices.append(dev.get(dev_id.device_id))
     return devices
def main():
    '''

    Main loop to retrieve data

    :return:
    '''
    args = getargs()

    username = args.user

    if not username:
        username = raw_input("Device Username:")

    password = getpass.getpass('Device password:'******'ip' )

    print 'Traffic flowing from %s to %s will use physical interface %s' % (args.source, args.destination, result)
Ejemplo n.º 5
0
    def __init__(self, name):
        Device.__init__(self, name)
        self.ControlPanelClass = AudioTestGenControlPanel

        self.freqs = ObservableVariable([1000, 1000])
        self.freqs.changed.connect(self.change_freqs)

        caps = Gst.caps_from_string(self.SINGLE_CHANNEL_AUDIO_CAPS)

        self.src0 = Gst.ElementFactory.make('audiotestsrc', None)
        self.bin.add(self.src0)
        self.src0.set_property('is-live', True)

        self.src1 = Gst.ElementFactory.make('audiotestsrc', None)
        self.bin.add(self.src1)
        self.src1.set_property('is-live', True)

        self.interleave = Gst.ElementFactory.make('interleave', None)
        self.bin.add(self.interleave)

        self.src0.link_filtered(self.interleave, caps)
        self.src1.link_filtered(self.interleave, caps)

        self.add_output_audio_port_on(self.interleave, "src")

        self.change_freqs(self.freqs.get_value())
Ejemplo n.º 6
0
    def __init__(self, name, pattern=0):
        Device.__init__(self, name)
        self.ControlPanelClass = VideoTestGenControlPanel

        self.pattern = ObservableVariable(pattern)
        self.pattern.changed.connect(self.change_pattern)

        self.src = Gst.ElementFactory.make('videotestsrc', None)
        self.bin.add(self.src)
        self.src.set_property('pattern', self.pattern.get_value())

        self.convert = Gst.ElementFactory.make('videoconvert', None)
        self.bin.add(self.convert)

        self.text_overlay = Gst.ElementFactory.make('textoverlay', None)
        self.bin.add(self.text_overlay)
        self.text_overlay.set_property("text", self.name)
        self.text_overlay.set_property("shaded-background", True)

        self.caps_filter = Gst.ElementFactory.make('capsfilter', None)
        self.bin.add(self.caps_filter)

        caps = Gst.caps_from_string(Device.DEFAULT_VIDEO_CAPS)
        self.caps_filter.set_property('caps', caps)

        self.src.link(self.text_overlay)
        self.text_overlay.link(self.convert)
        self.convert.link(self.caps_filter)

        self.add_output_video_port_on(self.caps_filter, "src")
Ejemplo n.º 7
0
    def __init__(self,
                 diamondx,
                 diamondy,
                 specphi,
                 speczoom,
                 specfocus,
                 yagzoom,
                 yagfocus,
                 cspadx,
                 objName="madsen",
                 pvBase=None,
                 presetsfile=None):
        Device.__init__(self, objName, pvBase, presetsfile)
        self.diamondx = diamondx
        self.diamondy = diamondy
        self.specphi = specphi
        self.speczoom = speczoom
        self.specfocus = specfocus
        self.yagzoom = yagzoom
        self.yagfocus = yagfocus
        self.cspadx = cspadx

        self.motors = {
            "diamondx": diamondx,
            "diamondy": diamondy,
            "specphi": specphi,
            "speczoom": speczoom,
            "specfocus": specfocus,
            "speczoom": yagzoom,
            "specfocus": yagfocus,
            "cspadx": cspadx
        }
        pass
Ejemplo n.º 8
0
def long_connection(d: device.Device) -> None:
    """
    Maintain a long connection with a device.
    :param sock:
    :param addr:
    :return:
    :exception:
    """
    heartbeat_cnt = 0
    while True:
        data = d.readline()
        if data:
            logger.info('{}: receive a message from {}: {}'.format(
                __file__, str(d.ip_mac), data))
            # Put Msg to MQ
            redis_mq.put(str(data))
            heartbeat_cnt = 0
        else:
            heartbeat_cnt += 1

        if heartbeat_cnt >= (cfg.PING_PERIOD / 0.5):
            logger.info('{}:heart beat with {}'.format(__file__,
                                                       str(d.ip_mac)))
            if d.heartbeat() is False:
                logger.warning('{}:heart beat fail with {}, delete it.'.format(
                    __file__, str(d.ip_mac)))
                dsp.set_alive(
                    d.sn, False
                )  # Fail to heartbeat_cnt, delete it from devices alive.
                break
            logger.info('{}:heart beat succeed with {}.'.format(
                __file__, str(d.ip_mac)))
            heartbeat_cnt = 0
        gevent.sleep(0.5)
Ejemplo n.º 9
0
def active_device(mac, ip='0.0.0.0', name='', time_stamp = datetime.datetime.now()):
    device_list = load_db()

    #time_stamp = datetime.datetime.now()

    mac_list = []
    for d in device_list:
        mac_list.append(d._mac)

    if not mac in mac_list:
        #have not found this device previously
        if len(name) < 1:
            #FIXME: should be more automated - no input should really be required
            name = input('What is the name of this machine? ('+ip+', '+mac+') ')

        from device import Device

        unkn_d = Device(name, mac)

        unkn_d.add_ip(ip)
        unkn_d.add_ts(time_stamp)

        #print("Adding new DEVICE to DB")
        device_list.append(unkn_d)

    else:
        # already part of the db - only add time stamp
        #print("Updating existing DEVICE in DB")

        index = mac_list.index(mac)
        device_list[index].add_ip(ip)
        device_list[index].add_ts(time_stamp)

    save_db(device_list)
Ejemplo n.º 10
0
    def __init__(self, device, format=None, parents=None,
                 exists=True, size=None, major=None, minor=None,
                 sysfsPath='', serial=None, model="", vendor="", bus=""):
        """ Create a Disk instance.

            Arguments:

                device -- the device name (generally a device node's basename)

            Keyword Arguments:

                size -- the device's size (units/format TBD)
                major -- the device major
                minor -- the device minor
                sysfsPath -- sysfs device path
                format -- a DeviceFormat instance
                parents -- a list of required Device instances
                removable -- whether or not this is a removable device

            Disk always exist.
        """
        Device.__init__(self, device, format=format, size=size,
                        major=major, minor=minor, exists=exists,
                        model=model, serial=serial, vendor=vendor,bus=bus,
                        sysfsPath=sysfsPath, parents=parents)
Ejemplo n.º 11
0
 def do_postsend_operations(self, action, actionexec):
     if isinstance(action, ActionStatechange
                   ) and action.newstate != DevicePrimelan.GET_STATE_ACTION:
         actionexec.insert_action(
             ActionStatechange(self, DevicePrimelan.GET_STATE_ACTION), 1)
     else:
         Device.do_postsend_operations(self, action, actionexec)
Ejemplo n.º 12
0
 def validate(self):
     dev = Device()
     if not dev.creator(self.device_id):
         return False
     if self.duration <=0:
         return False
     return True
def sendProjectData():
    result = instance.read()

    while result is None:
        pass

    temp = round(
        (random.uniform(result.temperature + 0.1, result.temperature + 0.9)),
        1)
    humi = round(
        (random.uniform(result.humidity + 0.1, result.humidity + 0.9)), 1)

    total = str(round((temp + humi), 1))
    if (".0" in total):
        total = round(total) + 0.1
    else:
        total = round(float(total), 1)

    projectData = ProjectData(
        "Testing", datetime.datetime.today(),
        [Device("AABC1", temp), Device("AABC2", humi)], total,
        round((total * 0.28434517), 1), "Selangor")

    try:
        print(API.sendProjectData(keypair, projectData))
        time.sleep(60)
        sendProjectData()

    except Exception as e:
        print(e)
Ejemplo n.º 14
0
def boss_join_guild_and_set_aid(dev: Device,
                                guild_name: str,
                                boss: list = BOSS):
    try:
        if login(dev, boss) is fail:
            dev.log.warning('错误[000]大号登录失败')
            exit()
            return fail
        if join_guild(dev, guild_name, error_logout=False) is fail:
            dev.log.warning('错误[000]大号已加入行会')
            if dev.ocr_exists(guild_name,
                              is_full_matching=False,
                              is_accurate=True):
                pass
            else:
                exit()
                return fail
        dev.click_byCv('btn_aid_set')
        if dev.cv_exists('btn_aid_set'):
            dev.click_byCv('btn_aid_set')
        dev.click_byCv('iv_add_aid_city', select_upper_left=True)
        # select_role(dev, 'iv_aid')  # 大号上架支援
        select_combat_highest_role(dev)
        dev.click_byCv('btn_set_blue_small', 'btn_ok_blue')
        logout(dev)
    except device.GameError as e:
        dev.log.warning(e)
        logout(dev)
        boss_join_guild_and_set_aid(dev, guild_name, boss)
Ejemplo n.º 15
0
class DeviceTest(unittest.TestCase):
    def setUp(self):
        self.block_size = 1
        self.blocks = 100
        self.dev = Device("data", self.block_size, self.blocks)
        self.data = [randrange(0, 256) for i in range(0, self.blocks)]
        for i, block in enumerate(self.data):
            self.dev.write_block(i, chr(block))

    def test_memory_read(self):
        self.should_preserve_data(self.dev)

    def test_file_read(self):
        self.dev.close()
        dev = Device("data", self.block_size, self.blocks)
        self.should_preserve_data(dev)

    def should_preserve_data(self, dev):
        for i, block in enumerate(self.data):
            read = dev.read_block(i)
            self.assertEqual(read, chr(block))

    @unittest.expectedFailure
    def test_fail_to_write_data_bigger_than_block(self):
        self.dev.write_block(0, b'aa')

    @unittest.expectedFailure
    def test_fail_with_out_of_bounds(self):
        self.dev.write_block(self.blocks + 1, b'a')

    def tearDown(self):
        self.dev.close()
Ejemplo n.º 16
0
def main():

    switch = Device(ip='172.23.193.210', username='******', password='******')
    switch.open()

    checkroutes(switch)
    stp_detail(switch)
    protocols = get_ip_protocols(switch)
    for proto in protocols:
        print "Switch is running " + proto
    ospf_interfaces = []
    eigrp_interfaces = []
    bgp_interfaces = []
    if "ospf" in protocols:
        ospf_interfaces = get_ospf_interfaces(switch)
    if "eigrp" in protocols:
        eigrp_interfaces = get_eigrp_interfaces(switch)
    if "bgp" in protocols:
        bgp_interfaces = get_bgp_interfaces(switch)
    if len(ospf_interfaces) >= 1:
        print "OSPF has peers on interface(s): " + str(ospf_interfaces)
    if len(eigrp_interfaces) >= 1:
        print "EIGRP has peers on interface(s): " + str(eigrp_interfaces)
    if len(bgp_interfaces) >= 1:
        print "BGP has peers on interface(s): " + str(bgp_interfaces)
    vpc_vlan_list = get_vpc_vlans(switch)
    check_vlan_vpc(ospf_interfaces, vpc_vlan_list)
    check_vlan_vpc(eigrp_interfaces, vpc_vlan_list)
    check_vlan_vpc(bgp_interfaces, vpc_vlan_list)
Ejemplo n.º 17
0
    def __init__(self, maxy, maxx, install_config):
        self.maxx = maxx
        self.maxy = maxy
        self.win_width = maxx - 4
        self.win_height = maxy - 4
        self.install_config = install_config
        self.path_checker = []

        self.win_starty = (self.maxy - self.win_height) // 2
        self.win_startx = (self.maxx - self.win_width) // 2

        self.text_starty = self.win_starty + 4
        self.text_height = self.win_height - 6
        self.text_width = self.win_width - 6
        self.cp_config = {}
        self.cp_config['partitionsnumber'] = 0
        self.devices = Device.refresh_devices_bytes()
        self.has_slash = False
        self.has_remain = False
        self.has_empty = False

        self.disk_size = []
        self.disk_to_index = {}
        for index, device in enumerate(self.devices):
            self.disk_size.append((device.path, int(device.size) / 1048576))
            self.disk_to_index[device.path] = index

        self.window = Window(self.win_height,
                             self.win_width,
                             self.maxy,
                             self.maxx,
                             'Welcome to the Photon installer',
                             False,
                             can_go_next=False)
        Device.refresh_devices()
Ejemplo n.º 18
0
    def mqtt_on_message(self, client, userdata, msg):
        Device.mqtt_on_message(self, client, userdata, msg)
        sub = self.mqtt_sub(msg.topic)
        try:
            if sub == "backup":
                if len(msg.payload):
                    try:
                        out = json.loads(msg.payload)
                    except:  # noqa: E722
                        out = msg.payload
                    if isinstance(out, dict):
                        topic = out["topic"]
                        convert = 'convert' not in out or out['convert']
                    else:
                        topic = out
                        convert = False

                    event.EventManager.fire(eventname='ExtInsertAction',
                                            hp=(self.host, self.port),
                                            cmdline="",
                                            action=ActionBackup(
                                                self, topic, convert))
            elif sub == "learn" or sub == "emit":
                _LOGGER.info("topic " + msg.topic + " [" + b2s(msg.payload) +
                             "]")
                learnk = json.loads(msg.payload)
                keyall = []
                for d in learnk:
                    ksing = ('' if d['key'][0] == '@' or d['key'][0] == '$'
                             else (d["remote"] + ':')) + d["key"]
                    # _LOGGER.info("KSING "+ksing+" "+str(type(ksing)))
                    if 'a' in d and 'remote' in d and len(d['remote']):
                        event.EventManager.fire(
                            eventname='ExtInsertAction',
                            hp=(self.host, self.port),
                            cmdline="",
                            action=ActionInsertKey(
                                self, d['remote'], d['key'], d['a'], {
                                    k: v
                                    for k, v in d.items()
                                    if k not in ['a', 'remote', 'key']
                                }))
                    else:
                        keyall.append(ksing)
                if len(keyall):
                    tall = tuple(keyall)
                    if sub == "learn":
                        if keyall[0][0] == '@':
                            tall = tuple(keyall[1:])
                            action = ActionCreatesh(self, keyall[0][1:], *tall)
                        else:
                            action = ActionLearnir(self, *tall)
                    else:
                        action = ActionEmitir(self, *tall)
                    event.EventManager.fire(eventname='ExtInsertAction',
                                            hp=(self.host, self.port),
                                            cmdline="",
                                            action=action)
        except:  # noqa: E722
            _LOGGER.warning(f"{traceback.format_exc()}")
Ejemplo n.º 19
0
def main():

    switch = Device(ip='172.31.217.136', username='******', password='******')
    switch.open()

    show_boot_config = copy_bootflash(switch)
    print show_boot_config
Ejemplo n.º 20
0
def main():

    switch = Device(ip='172.31.217.133',username='******',password='******')
    switch.open()

    mac_table = get_mac(switch)
    arp_table = get_arp(switch)

    print "Will parse the following MAC and ARP tables obtained from the switch:"
    print json.dumps(mac_table, indent=4)   
    print json.dumps(arp_table, indent=4)
    
    # Loop through the MAC address table
    for mac_entry in mac_table:
        # If the MAC address is present in the ARP table
        if mac_entry in arp_table:

            #Attempt name resolution.  gethostbyaddr will throw an exception if host is not found
            try:
                
                ip_address = arp_table[mac_entry]
                interface_name = mac_table[mac_entry]
                
                hostname = gethostbyaddr(ip_address)
                
                print hostname[0] + " (" + ip_address + ") is on " + interface_name
                
                # Pass the result to write_descript to apply the hostname to the NX-OS interface
                write_descript(switch,interface_name,hostname[0])
                
            except:
                # For simplicity, we will assume that any exception is a host not found and move on
                print "No hostname for " + ip_address + " was found... skipping"
Ejemplo n.º 21
0
    def __init__(self, id_):
        Device.__init__(self, id_)
        self.endpoint_for_router = None

        self.bits_sent_graph_tag = globals_.stats_manager.new_graph(
                title='Total Bits Sent by %s' % self.id_,
                ylabel='Total Bits'
        )
        self.bit_rate_sent_graph_tag = globals_.stats_manager.new_graph(
                title='Rate of Data Sent by %s' % self.id_,
                ylabel='Rate (bits/sec)',
                is_rate=True
        )
        self.bits_received_graph_tag = globals_.stats_manager.new_graph(
                title='Total Bits Received by %s' % self.id_,
                ylabel='Total Bits'
        )
        self.bit_rate_received_graph_tag = globals_.stats_manager.new_graph(
                title='Rate of Data Received by %s' % self.id_,
                ylabel='Rate (bits/sec)',
                is_rate=True
        )

        self.bits_sent = 0
        self.bits_received = 0
Ejemplo n.º 22
0
    def get_active_device(self) -> Optional[Device]:
        if ctx.now - self.last_joystick_refresh > 1.0:
            pg.joystick.quit()
            self.last_joystick_refresh = ctx.now

        pg.joystick.init()
        devices: List[Device] = list()

        pg.event.pump()

        device_names: List[str] = list()
        if self.done_players == 0:
            device_names = [config.device1, config.device2]
        elif self.done_players == 1:
            device_names = [config.device2, config.device1]

        for device_name in device_names:
            if self.controls[device_name]["type"] == "keyboard":
                devices += [Device(device_name)]
            elif self.controls[device_name]["type"] == "joystick":
                for j in range(pg.joystick.get_count()):
                    devices += [Device(device_name, j)]

        inputs: List[Input] = list()
        for device in devices:
            inputs += [Input(device)]

        for input in inputs:
            if input.update():
                return input.device

        return None
Ejemplo n.º 23
0
def crawlDevice(ip_address,user,pw):
	sw1 = Device(ip=ip_address, username=user, password=pw)
	sw1.open()

	# Getting everything into dicts
	sh_vrf = get_vrf(sw1)
	int_brief = get_ip_int_b(sw1)
	int_status = get_int_status(sw1)
	hostname,proccesor_ID,version = get_hostname_serial_version(sw1)
	neighbors = get_cdp_info(sw1)
	port_channels = get_portchannel_sum(sw1)
	# Adding all data into objs
	LocalDevice = root_Device(hostname,proccesor_ID,version,ip_address,user,pw)

	for singleVrf in sh_vrf:
		vrf = Vrf(singleVrf["vrf-name-out"])
		if "TABLE_prefix" in singleVrf["TABLE_addrf"][ "ROW_addrf"].keys():
			for prefixes in singleVrf["TABLE_addrf"][ "ROW_addrf"]["TABLE_prefix"]["ROW_prefix"]:
				vrf.addPrefix(prefixes["ipprefix"])
			LocalDevice.addVrf(vrf)

	for ipInter in int_brief:
		LocalDevice.addIp(ipInter["ROW_intf"]["prefix"])

	LocalDevice.addPortChannel(port_channels)
	for interface in int_status:
		LocalDevice.addIp(interface)

	for neighbor in neighbors:
		neighEntry = Neighbors(root_Device,neighbor)
		LocalDevice.addNeighbor(neighEntry)



	return LocalDevice
Ejemplo n.º 24
0
    def __init__(self, name):
        Device.__init__(self, name)
        self.ControlPanelClass = DskControlPanel

        self.file = ObservableVariable()
        self.file.changed.connect(self.file_changed)

        self.alpha = ObservableVariable(0)
        self.alpha.changed.connect(self.alpha_changed)

        # While input convert doesn't seem explicitly necessary, it seems to
        # give better performance.  Not sure why.
        self.inputconvert = self.add_element('videoconvert')
        self.mixer = self.add_element('videomixer')
        self.outputconvert = self.add_element('videoconvert')

        self.add_input_video_port_on(self.inputconvert)
        self.inputconvert.link(self.mixer)

        self.mixer.link(self.outputconvert)
        self.add_output_video_port_on(self.outputconvert)

        self.mixer.get_static_pad('sink_0').set_property('zorder', 0)

        self.alpha.set_value(1.0)
Ejemplo n.º 25
0
def lambda_handler(request, context):
    global umap, device

    print('-  Lambda_handler request:')
    print(json.dumps(request))
    print('-  Lambda_handler context:')
    print(context)

    response = validate_request(
        request)  # IF THERE IS NO ERROR, this returns a 'None' object
    if response is not None:
        return send_response(response.get())

    #database_url = None     # use environment variable DATABASE_URL (defaults to 'sqlite:///:memory:')
    database_url = 'mysql://*****:*****@100.101.102.103:3306/customers'
    print('Using Database: ', database_url)

    try:
        if database_url is None:
            db = dataset.connect()
        else:
            db = dataset.connect(database_url)
    except Exception as e:
        print("EXCAPTION: Could not connect to database; " + str(e))
        response = get_error_response('DATABASE_ERROR',
                                      'Could not connect to database.')
        return send_response(response.get())
    umap = UserMap(db)  # you must always call setup() after this
    table_exists = umap.setup()
    if (not table_exists):
        response = get_error_response('DATABASE_ERROR',
                                      'User table is missing.')
        return send_response(response.get())
    device = Device(db)  # you must always call setup()
    table_exists = device.setup()
    if (not table_exists):
        response = get_error_response('DATABASE_ERROR',
                                      'Device table is missing.')
        return send_response(response.get())

    (namespace, name) = get_name_and_space(request)

    if namespace == 'Alexa.Authorization':  # the user has just enabled the skill
        if name == 'AcceptGrant':
            response = handle_grant(request)
            return send_response(response.get())

    if namespace == 'Alexa.Discovery':
        if name == 'Discover':
            response = handle_discovery(request)
            return send_response(response.get())

    if namespace == 'Alexa.PowerController':
        response = handle_power_state(request)
        return send_response(response.get())

    # None of the above
    response = get_error_response('INVALID_DIRECTIVE',
                                  'Invalid Alexa request; Unknown directive')
    return send_response(response.get())
Ejemplo n.º 26
0
    def __init__(self, maxy, maxx, install_config):
        self.maxx = maxx
        self.maxy = maxy
        self.win_width = maxx - 4
        self.win_height = maxy - 4
        self.install_config = install_config
        self.path_checker = []

        self.win_starty = (self.maxy - self.win_height) // 2
        self.win_startx = (self.maxx - self.win_width) // 2

        self.text_starty = self.win_starty + 4
        self.text_height = self.win_height - 6
        self.text_width = self.win_width - 6
        self.install_config['partitionsnumber'] = 0
        self.devices = Device.refresh_devices_bytes()
        self.has_slash = False
        self.has_remain = False
        self.has_empty = False

        self.disk_size = []
        for index, device in enumerate(self.devices):
            self.disk_size.append((device.path, int(device.size) / 1048576))

        self.window = Window(self.win_height, self.win_width, self.maxy, self.maxx,
                             'Welcome to the Photon installer', False, can_go_next=False)
        Device.refresh_devices()
Ejemplo n.º 27
0
 def __init__(self,
              hp=('', 0),
              mac='',
              root=None,
              timeout=DEFAULT_RESUBSCRIPTION_TIMEOUT,
              name='',
              sec1900=0,
              lsa_timeout=DEFAULT_RESUBSCRIPTION_STIMEOUT,
              **kw):
     Device.__init__(self, hp, mac, root, name)
     if root is None:
         self.subscribe_time = 0
         self.resubscription_timeout = timeout
         self.last_subs_action_timeout = lsa_timeout
         self.sec1900 = int(
             ((datetime.now() -
               datetime(1900, 1, 1, 0, 0, 0, 0)).total_seconds() -
              (datetime.utcnow() - datetime.now()).total_seconds() -
              sec1900) * 1000)
     else:
         self.subscribe_time = int(root.attributes['sst'].value)
         self.sec1900 = int(root.attributes['sec1900'].value)
         self.resubscription_timeout = int(root.attributes['rtime'].value)
         self.last_subs_action_timeout = int(root.attributes['stime'].value)
     self.last_subs_action = 0
     self.get_reversed_mac()
     self.rawtables = None
     self.tablever = None
     self.timer_off_after_on = None
     self.timezone = None
Ejemplo n.º 28
0
    def __init__(self, width, height, fullscreen):
        print "glut::__init__()"
        Device.__init__(self)

        self.size = (width, height)
        self.fullscreen = fullscreen

        glutInit(sys.argv)
        glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH)

        if self.fullscreen:
            glutGameModeString("%dx%d:32@70" % self.size )
            self.windowID = glutEnterGameMode()
        else:
            glutInitWindowSize(self.size[0], self.size[1])
            glutInitWindowPosition(0,0)
            self.windowID = glutCreateWindow("")

        glutSetWindow(self.windowID)

        glutReshapeFunc(self.reSizeGLScene)
        glutMouseFunc(self.onMouse)
        glutMotionFunc(self.onMotion)
        glutPassiveMotionFunc(self.onMotion)
        glutKeyboardFunc(self.onKeyDown)
        glutKeyboardUpFunc(self.onKeyUp)
        glutSpecialFunc(self.onSpecialDown)
        glutSpecialUpFunc(self.onSpecialUp)

        self.graphicsDevice = OpenGLGraphics(self.size)
Ejemplo n.º 29
0
def main():
    #TODO: grab date from the database to get settings on startup
    global logFile

    Log.initialize()
    setupBoard()
    time.sleep(5)

    db = DbConnection()

    #CycleIrrigation(3, "by barn","random notes", 12, 5, 10, "2020-03-09T19:44:18", "2020-03-09T06:44:18") #TODO: test data
    #Irrigation(3, "barn irrigation", "random notes", 16, [1, 4, 5],{"2020-03-08T01:54:57":3600,"2020-04-08T01:52:51":10}) #TODO: test data
    Device.turnMainStateOn()

    socket = SocketCom()
    thread = threading.Thread(target=socket.start)
    thread.start()

    while True: 
        if Device.isAllOn():
            for device in Device.deviceList:
                device.run()
        else:
            Device.turnAllOff()
    cleanup()
    Log.close()
Ejemplo n.º 30
0
    def query(self, payload):
        # Unpack request id.
        request_id = payload['requestId']
        self.request_id = request_id

        #Get the device state from the db for this user.
        device = Device()
        query = Query(field='assigned_user', op_string='==', value=self.docid)
        device_results = device.query(query)['results']
        logging.debug(f"Found devices: {device_results}")

        query_device_state = []
        for query_device in payload['inputs'][0]['payload']['devices']:
            device_id = query_device['id']
            try:
                current_state = device_results[0][device_id]['state']
            except:
                current_state = {}
            query_device_state.append({device_id: current_state})
        response_payload = {
            'requestId': request_id,
            'payload': {
                'agentUserId': self.docid,
                'devices': query_device_state
            }
        }
        return response_payload
Ejemplo n.º 31
0
 def __init__(self, port, dimension=10, emulator=False):
     Device.__init__(self, "Cube", port)
     self.array = numpy.array([[\
             [0]*dimension]*dimension]*dimension, dtype='bool')
     self.dimension = dimension
     self.emulator = emulator
     self.name = "Cube"
Ejemplo n.º 32
0
def performer(idx, model, SIMULATOR):
    # allocate a device
    n_gpu = t.cuda.device_count()
    if n_gpu > 0:
        Device.set_device(idx % n_gpu)

    q_network = deepcopy(model)
    q_network.to(Device.get_device())
    q_network.eval()

    simulator = SIMULATOR()

    state = simulator.reset()
    episode_reward = 0

    terminal = False
    while not terminal:
        action = q_network(as_tensor(state)).argmax().item()

        next_state, reward, terminal = simulator.step(action)

        episode_reward += reward
        state = next_state

    return episode_reward
Ejemplo n.º 33
0
 def __init__(self, port, dimension=10, emulator=False):
     Device.__init__(self, "Cube", port)
     self.array = numpy.array([[\
             [0]*dimension]*dimension]*dimension, dtype='bool')
     self.dimension = dimension
     self.emulator = emulator
     self.name = "Cube"
Ejemplo n.º 34
0
 def callModule(self, modulename, board_number, number, function, params = []):
     """
     Call one function: function for module: modulename in board: board_name
     with handler: number (only if the module is pnp, else, the parameter is
     None) with parameteres: params
     """
     try:
         board = self._bb[board_number]
         if board.devices.has_key(number) and (board.devices[number].name == modulename):
             return board.devices[number].call_function(function, params)
         else:
             if modulename in self._openables:
                 if modulename in board.get_openables_loaded():
                     number = board.get_device_handler(modulename)
                 else:
                     board.add_openable_loaded(modulename)
                     dev = Device(board, modulename)
                     number = dev.module_open()
                     dev.add_functions(self._drivers_loaded[modulename])
                     board.add_device(number, dev)
                 return board.devices[number].call_function(function, params)
             else:
                 if self._debug:
                     print 'no open and no openable'
                 return ERROR
     except Exception, err:
         if self._debug:
             print 'error call module', err
         return ERROR
Ejemplo n.º 35
0
    def __init__(self, width, height, fullscreen, mode=P2D):
        Device.__init__(self)

        self.mode = mode
        self.size = (width, height)

        pygame.init()
        pygame.key.set_mods(KMOD_NONE)
        pygame.mouse.set_visible(0)

        if mode == PygameDevice.P2D:
            flags = 0
            if fullscreen:
                flags = flags | pygame.locals.FULLSCREEN | pygame.locals.SWSURFACE

            self.graphicsDevice = PygameGraphics(self.size, flags)

        elif mode == PygameDevice.OGL:
            from openglgraphics import OpenGLGraphics
            
            flags = pygame.locals.OPENGL | pygame.locals.DOUBLEBUF
            if fullscreen:
                flags = flags | pygame.locals.FULLSCREEN

            self.graphicsDevice = OpenGLGraphics(self.size, flags, pygame.display.set_mode(self.size, flags))

        else:
            raise device.DeviceException("Invalid Graphics Mode Specified")
Ejemplo n.º 36
0
    def __init__(self,
                 path,
                 format=None,
                 size=None,
                 exists=None,
                 parents=None):
        """ Create a FileDevice instance.

            Arguments:

                path -- full path to the file

            Keyword Arguments:

                format -- a DeviceFormat instance
                size -- the file size (units TBD)
                parents -- a list of required devices (Device instances)
                exists -- indicates whether this is an existing device
        """
        Device.__init__(self,
                        path,
                        format=format,
                        size=size,
                        exists=exists,
                        parents=parents)
Ejemplo n.º 37
0
def open_device_connection(ctx: object):
    port = ctx.obj['port']
    simulation = ctx.obj["simulation"]
    custom = ctx.obj["custom"]

    default_args = {
        'log': ctx.obj['log'],
        'verbose': ctx.obj['verbose'],
        'timeout': ctx.obj['timeout']
    }

    if (custom):
        dev = Device(0,
                     _custom_connect="{log} /bin/sh -c \"" + custom + "\"",
                     **default_args)
    elif (port):
        dev = Device(port, **default_args)
    else:
        console_path = os.path.abspath(
            "{}/console.sh".format(DEFAULT_DEVICE_PATH))
        dev = Device(console_path, simulation, **default_args)

    try:
        with dev:
            yield dev
    except (SerialConnectionError, DeviceCommandFailed) as err:
        if (ctx.obj['verbose']):
            raise err
        raise click.ClickException(str(err))
Ejemplo n.º 38
0
 def __init__(self):
     Device.__init__(self)
     self.name = 'arm'
     self.params = self.robot_params[self.name]
     self.motor_rad_2_arm_m = self.params['chain_pitch'] * self.params[
         'chain_sprocket_teeth'] / self.params['gr_spur'] / (math.pi * 2)
     self.motor = Stepper('/dev/hello-motor-arm')
     self.status = {
         'pos': 0.0,
         'vel': 0.0,
         'force': 0.0,
         'motor': self.motor.status,
         'timestamp_pc': 0
     }
     # Default controller params
     self.stiffness = 1.0
     self.i_feedforward = self.params['i_feedforward']
     self.vel_r = self.translate_to_motor_rad(
         self.params['motion']['default']['vel_m'])
     self.accel_r = self.translate_to_motor_rad(
         self.params['motion']['default']['accel_m'])
     self.i_contact_neg = self.translate_force_to_motor_current(
         self.params['contact_thresh_N'][0])
     self.i_contact_pos = self.translate_force_to_motor_current(
         self.params['contact_thresh_N'][1])
     self.motor.set_motion_limits(
         self.translate_to_motor_rad(self.params['range_m'][0]),
         self.translate_to_motor_rad(self.params['range_m'][1]))
Ejemplo n.º 39
0
 def __init__(self,
              hp=('', 0),
              mac='',
              root=None,
              name='',
              key=PK_KEY,
              password='',
              deviceid='',
              clientsessionid='',
              hp2=('', 0)):
     Device.__init__(self, hp, mac, root, name)
     ManTimerManager.__init__(self, root)
     IrManager.__init__(self, hp, mac, root, name)
     self.key = key
     self.fid = 0
     if len(clientsessionid) == 0:
         self.clientSessionId = generatestring(32)
     else:
         self.clientSessionId = clientsessionid
     if root is None:
         self.password = password
         self.deviceId = deviceid
         self.localPort = hp2[1]
         self.localIp = hp2[0]
     else:
         self.password = root.attributes['password'].value
         self.deviceId = root.attributes['deviceId'].value
         self.localPort = root.attributes['localPort'].value
         self.localIp = root.attributes['localIp'].value
Ejemplo n.º 40
0
    def paramIni(self):
        self.hour = int(datetime.datetime.now().strftime('%H'))
        self.outLog('param initialize')
        paramPath = "configure.yaml"
        confirmConfigureFile = QFile(paramPath)
        if not confirmConfigureFile.exists():
            QMessageBox.critical(self, 'Critical', '配置文件丢失!')
            exit(0)

        self.yamlTool = Yaml_Tool()
        self.params = self.yamlTool.getValue(paramPath)

        ######## initializi robot && socket#########
        self.isCheckDeviceOnline = {}
        self.devices = {}
        self.onlineDeviceIp = {}
        self.ipSocket = {}
        self.workshop = self.params['workshop']

        self.stateMachine = StateMachine()
        for _device in self.params['devices'].keys():
            self.isCheckDeviceOnline[_device] = False
            newDevice = Device(self.params['devices'][_device])
            newDevice.bind(DeviceState.OFFLINE,
                           self.stateMachine.getFsm(DeviceState.OFFLINE))
            self.devices[_device] = newDevice
            newDevice.stateChanged.connect(self.processDeviceStateChanged)
        pass
Ejemplo n.º 41
0
 def show_item(self, mac, port):
     self.monitor.setText(mac)
     self.monitor.show()
     self.label.show()
     self.socket_.bind(QHostAddress(self.ip), port)
     self.socket_.readyRead.connect(self.show_video)
     self.detail_device = Device(monitor=self)
Ejemplo n.º 42
0
    def __init__(self,
                 name,
                 format=None,
                 size=None,
                 dmUuid=None,
                 target=None,
                 exists=None,
                 parents=None,
                 sysfsPath=''):
        """ Create a DMDevice instance.

            Arguments:

                name -- the device name (generally a device node's basename)

            Keyword Arguments:

                target -- the device-mapper target type (string)
                size -- the device's size (units/format TBD)
                dmUuid -- the device's device-mapper UUID
                sysfsPath -- sysfs device path
                format -- a DeviceFormat instance
                parents -- a list of required Device instances
                exists -- indicates whether this is an existing device
        """
        Device.__init__(self,
                        name,
                        format=format,
                        size=size,
                        exists=exists,
                        parents=parents,
                        sysfsPath=sysfsPath)
        self.target = target
        self.dmUuid = dmUuid
Ejemplo n.º 43
0
    def sync(self, payload):
        # Unpack request id.
        request_id = payload['requestId']
        self.request_id = request_id

        # Get all devices assigned to user.
        device = Device()
        query = Query(field='assigned_user', op_string='==', value=self.docid)
        device_results = device.query(query)['results']
        logging.debug(f"Found devices: {device_results}")

        # Build device payload.
        devices_payload = []
        for d in device_results:
            device_id = list(d.keys())[0]
            device_payload = d[device_id]['attributes']['google']
            device_payload.update({'id': device_id})
            devices_payload.append(device_payload)

        response_payload = {
            'requestId': request_id,
            'payload': {
                'agentUserId': self.docid,
                'devices': devices_payload
            }
        }
        return response_payload
Ejemplo n.º 44
0
def main():
	'''Call the show_ip_int_brief function and read in from file'''
	
	#check they entered a filename
	if len(sys.argv) <= 1:
		print "You must enter a filename: int_brief.py <filename>"
		sys.exit()
	
	else:
		#check if the file name is correct and can be opened
		try:
			script, filename = sys.argv
			with open(filename, 'r') as fp:	#with will close file
				for line in fp:				#loop through the lines
					switch_admin = []
					if len(line.split()) == 3:	#check if there are three variables per line

						for word in line.split():	#loop through the words and add them to a list
							#fill a list with the items in the line - should be three
							switch_admin.append(word)
						
						#create the switch object
						switch = Device(ip=switch_admin[0], username=switch_admin[1], password=switch_admin[2])
						switch.open()
						#call the  function
						show_ip_int_brief(switch, switch_admin[0])
					else:
						print "Your file variables are incorrect. It should be <ip address> <username> <password> per line."
						sys.exit()
		except IOError:
			print "Your file was mistyped! Please try again."
			sys.exit()
Ejemplo n.º 45
0
def getDeviceForDynAnalysis():
    dev_list = Device.get_devices_list()

    devNum = len(dev_list)

    if devNum <= 0:
        logger.error(
            "No device has been detected! Connect your device and restart the application!"
        )
        return None

    if devNum == 1:
        return Device.get_device(dev_list[0])

    choice = None
    if devNum > 1:
        print "Select the device to use for analysis:\n"
        for i in xrange(0, devNum):
            print "%d. %s\n" % ((i + 1), dev_list[i])

        while not choice:
            try:
                choice = int(raw_input())
                if choice not in range(1, devNum + 1):
                    choice = None
                    print 'Invalid choice! Choose right number!'
            except ValueError:
                print 'Invalid Number! Choose right number!'

    return Device.get_device(dev_list[choice - 1])
Ejemplo n.º 46
0
   def __init__(self):

      self.gjdb = pymongo.MongoClient("mongodb://localhost:8888/")['gamejackyer']

      self.app = Flask(__name__, static_url_path='/', static_folder='res')
      self.app.after_request(self.after_request)
      
      self.app.add_url_rule('/', 'hello_world', self.hello_world)
      self.app.add_url_rule('/imageList','image_list', self.image_list)
      self.app.add_url_rule('/imageList/bboxName/<bboxName>','image_list_by_bbox', self.image_list_by_bbox)
      self.app.add_url_rule('/imageList/sceneList/<sList>','image_list_by_scene_list', self.image_list_by_scene_list)
      self.app.add_url_rule('/image/<uuid>','image_by_uuid',self.image_by_uuid)
      self.app.add_url_rule('/update/image','update_image',self.update_image,methods=['POST'])
      self.app.add_url_rule('/delete/images','delete_images',self.delete_images,methods=['POST'])
      self.app.add_url_rule('/update/imagescenes','update_imagescenes',self.update_imagescenes,methods=['POST'])
      self.app.add_url_rule('/device/screen/<rnd>','device_screen',self.device_screen)
      self.app.add_url_rule('/devices','device_list',self.device_list)
      self.app.add_url_rule('/device/input','device_input',self.device_input,methods=['POST'])
      self.app.add_url_rule('/device/screenctrl/<cmd>','device_screen_record',self.device_screen_record)
      self.app.add_url_rule('/device/mirror/<cmd>','device_screen_mirror',self.device_screen_mirror)
      self.app.add_url_rule('/predict/image/<uuid>','image_predict_by_uuid',self.image_predict_by_uuid)
      self.app.add_url_rule('/engine/act','engine_act_step',self.engine_act_step)

      self.dev = Device(self.gjdb)
      self.prd = Predictor()
      self.ge = GameEngine(self.dev,self.prd)
      self.screen_dump = False
Ejemplo n.º 47
0
 def __init__(self, name, major=None, minor=None, exists=None,
              format=None, parents=None, sysfsPath='', vendor="",
              model=""):
     Device.__init__(self, name, format=format,
                     major=major, minor=minor, exists=True,
                     parents=parents, sysfsPath=sysfsPath,
                     vendor=vendor, model=model)
Ejemplo n.º 48
0
 def observed_devices(self, user_id):
     dev_ids = self.find_by('where user_id = ?', user_id)
     devices = []
     dev = Device()
     for dev_id in dev_ids:
         devices.append(dev.get(dev_id.device_id))
     return devices
Ejemplo n.º 49
0
 def validate(self):
     dev = Device()
     if not dev.creator(self.device_id):
         return False
     if self.duration <= 0:
         return False
     return True
Ejemplo n.º 50
0
 def __init__(self, identifier):
     Device.__init__(self, identifier)
     self.link = None
     self.flows = {}
     self.clock = None
     self.event_scheduler = None
     self.logger = None
     self.payload_packet_trackers = {}
Ejemplo n.º 51
0
    def testDeviceStatusUpdate(self):
        d = Device('a', 'abcdefgh', True, OFFLINE)
        p = Person('A', [d])

        self.assertFalse(p.is_home())

        d.status = ONLINE
        self.assertTrue(p.is_home())
Ejemplo n.º 52
0
def getneighbors(ip,username,password):
    devices = [ ip ]
    devicecount=0
    while devicecount != len(devices):
        dev = Device(ip=devices[devicecount], username=username, password=password)
        dev.open()
        devices = devices + show_cdwneighbors(dev,devices)
        devicecount+=1
    return devices
Ejemplo n.º 53
0
def main():
	file = open("test.xml","r")
	line = file.readline()

	while not startDevices(line):
		line = file.readline()

	line = file.readline().strip()
	
	devices = []
	device = ""
	group = ""
	capability = ""
	
	while not endDevices(line):
		if beginDevice(line):
			line = deleteTags(line,"<device ",">")
			att_id = getAttrId(line)
			att_user = getAttrUser(line)
			att_fall = getAttrFall(line)
			
			device = Device(att_id, att_user, att_fall)
			line = file.readline()

		if endDevice(line):
			devices.append(device)
			line = file.readline()

		if beginGroup(line):
			line = deleteTags(line,"<group ",">")
			att_id = getAttrId(line)

			group = Group(att_id)
			group.setDevice(device)
			line = file.readline()

		if endGroup(line):
			device.addGroup(group)
			line = file.readline()

		if beginCapability(line):
			line = deleteTags(line, "<capability ", "/>")
			att_name = getAttrName(line)
			att_value = getAttrValue(line)

			capability = Capability(att_name, att_value)
			capability.setGroup(group)
			group.addCapability(capability)
			line = file.readline()

	print "Devices\n"
	printDevices(devices)
	print "End Devices\n"
	
	file.close()
	return 0
Ejemplo n.º 54
0
def connect_pulldata(ipaddr, uname, pword):

  switch = Device(ip=ipaddr, username=uname, password=pword)
  switch.open()

  vtp_facts = ipaddr + ',' + vtp_info(switch)

  csvwriter = csv.writer(open("vtp.csv", "a"))

  csvwriter.writerow([vtp_facts])
Ejemplo n.º 55
0
    def setup(self, intf=None, orig=False):
        Device.setup(self, orig=orig)
        if self.format and self.format.exists and not self.format.status:
            self.format.device = self.path

        for parent in self.parents:
            if orig:
                parent.originalFormat.setup()
            else:
                parent.format.setup()
Ejemplo n.º 56
0
def main():

    switch = Device(ip='172.31.217.134', username='******', password='******')
    switch.open()

    ver = show_dev_version(switch)

    print json.dumps(ver, indent=4)

    ver_check = check_version(switch)
Ejemplo n.º 57
0
 def read(self, limits):
     """Read minimum from one line and <block_size> chars"""
     Device.read(self, limits)
     line = self._readLine()
     if len(line) < self.block_size:
         line += " " * (self.block_size - len(line))
     else:
         line = line[:self.block_size]
     bytes = map(Device._ord, line)
     return bytes