Exemple #1
0
def wind(fs, plotname="clock.svg"):
    """
    `wind(fs)` winds the clock and spawns a thread for each function `f` in
    `fs` which is of type `Clock_i -> ()`. `wind` returns the showing function
    which you can call to plot the clock.
    """
    num_threads = len(fs)
    ids = range(num_threads)
    (shower_tx, shower_rx) = channel.channel()
    channels = {i: {} for i in ids}

    for (i, j) in itertools.combinations(ids, 2):
        (chan0, chan1) = channel.bichannel()
        channels[i][j] = chan0
        channels[j][i] = chan1

    for (i, f) in enumerate(fs):
        def ticktock(f, clock):
            f(clock)
            clock.done_()

        clock = Clock_i(i, channels[i], shower_tx.copy())
        threading.Thread(target=ticktock, args=(f, clock)).start()

    return lambda: plot(num_threads, shower_rx, plotname)
Exemple #2
0
 def __init__(self, planes):
     cl = 'cls' if (platform.system() == 'Windows') else 'clear'
     clear = lambda: os.system(cl)
     clear()
     ch = channel()
     atc = ATC()
     timestamp = 0
     traffic = len(planes)
     rrtimer = 0
     while True:
         timestamp += 1
         print tabulate(map(self.new, planes),
                        headers=[
                            'Name', 'State', 'Latitude', 'Longitude',
                            'Distance', 'Altitude', 'Heading', 'Speed',
                            'Query', 'Acknowledged', 'Collision'
                        ])
         query = ''
         if msvcrt.kbhit():
             key = msvcrt.getch()
             if (key == 'q') or (key == 'Q'):
                 clear()
                 exit()
         if timestamp == 5:
             if rrtimer == traffic - 1:
                 rrtimer = 0
             atc.command(planes[rrtimer])
             rrtimer += 1
             timestamp = 0
         ch.printlast()
         t.sleep(1)
         clear()
Exemple #3
0
def wind(fs, plotname="clock.svg"):
    """
    `wind(fs)` winds the clock and spawns a thread for each function `f` in
    `fs` which is of type `Clock_i -> ()`. `wind` returns the showing function
    which you can call to plot the clock.
    """
    num_threads = len(fs)
    ids = range(num_threads)
    (shower_tx, shower_rx) = channel.channel()
    channels = {i: {} for i in ids}

    for (i, j) in itertools.combinations(ids, 2):
        (chan0, chan1) = channel.bichannel()
        channels[i][j] = chan0
        channels[j][i] = chan1

    for (i, f) in enumerate(fs):

        def ticktock(f, clock):
            f(clock)
            clock.done_()

        clock = Clock_i(i, channels[i], shower_tx.copy())
        threading.Thread(target=ticktock, args=(f, clock)).start()

    return lambda: plot(num_threads, shower_rx, plotname)
Exemple #4
0
 def __init__(self, planes):
     cl = 'cls' if (platform.system() == 'Windows') else 'clear'
     clear = lambda: os.system(cl)
     clear()
     ch = channel()
     while True:
         print tabulate(map(self.new, planes),
                        headers=[
                            'Name', 'State', 'Latitude', 'Longitude',
                            'Distance', 'Altitude', 'Heading', 'Speed',
                            'Query', 'Acknowledged', 'Collision'
                        ])
         query = ''
         if msvcrt.kbhit():
             key = msvcrt.getch()
             if key == '\r':
                 #query = raw_input('\n\n>>>')
                 query = audio.listen()
                 ch.sendquery(query)
             elif (key == 'q') or (key == 'Q'):
                 clear()
                 exit()
         ch.printlast()
         t.sleep(1)
         clear()
Exemple #5
0
	def __init__(self):
		self.userSet = set()	    #No users on startup
		self.serverSock = None
		self.encoding = 'UTF-8'	    #UTF-8 is used universally for IRC nowadays
		self.channelSet = set()	    #assign empty set
		self.channelSet.add(channel.channel(set(), '#general'))	#add in channel "#general"
		return
	def build_channels(self):
		channel_list = [] 

		for i in range(self.channel_num):
			channel_list.append(channel())

		return channel_list
Exemple #7
0
 def gui(self, planes):
     done = False
     ch = channel()
     while not done:
         self.screen.fill((0, 20, 0))
         temp = map(self.new, planes)
         name = [x[0] for x in temp]
         state = [x[1] for x in temp]
         lat = [x[2] for x in temp]
         lon = [x[3] for x in temp]
         alt = [x[4] for x in temp]
         head = [x[5] for x in temp]
         collision = [x[10] for x in temp]
         lat = map(self.scaley, lat)
         lon = map(self.scalex, lon)
         for event in pygame.event.get():
             if event.type == pygame.KEYDOWN and (
                 (event.key == pygame.K_q) or
                 (event.key == pygame.K_ESCAPE)):
                 done = True
             #move map
             elif event.type == pygame.KEYDOWN and event.key == pygame.K_KP2:
                 self.ceny -= 50 if self.ceny >= 200 else 0
             elif event.type == pygame.KEYDOWN and event.key == pygame.K_KP8:
                 self.ceny += 50 if self.ceny <= self.resy - 200 else 0
             elif event.type == pygame.KEYDOWN and event.key == pygame.K_KP6:
                 self.cenx -= 50 if self.cenx >= 200 else 0
             elif event.type == pygame.KEYDOWN and event.key == pygame.K_KP4:
                 self.cenx += 50 if self.cenx <= self.resx - 200 else 0
             elif event.type == pygame.KEYDOWN and event.key == pygame.K_KP5:
                 self.cenx = self.resx / 2 - 200
                 self.ceny = self.resy / 2
             #zoom
             elif event.type == pygame.KEYDOWN and event.key == pygame.K_KP7:
                 self.zoom += 5 if self.zoom <= 90 else 0
             elif event.type == pygame.KEYDOWN and event.key == pygame.K_KP1:
                 self.zoom -= 5 if self.zoom > 5 else 0
             #panel scroll
             elif event.type == pygame.KEYDOWN and event.key == pygame.K_KP3:
                 self.scroll += 1 if not self.scroll > (len(planes) -
                                                        9) else 0
             elif event.type == pygame.KEYDOWN and event.key == pygame.K_KP9:
                 self.scroll -= 1 if not self.scroll < 1 else 0
             #get input
             elif event.type == pygame.KEYDOWN and event.key == pygame.K_KP_ENTER:
                 audio.speak('Speak now')
                 query = audio.listen()
                 #query = raw_input()
                 ch.sendquery(query)
             else:
                 pass
         self.terrain()
         self.panel()
         map(self.panelitems, planes, map(planes.index, planes))
         map(self.predictor, planes)
         map(self.plot, lon, lat, alt, name, state, collision)
         pygame.display.flip()
         pygame.display.update()
         t.sleep(0.1)
Exemple #8
0
def remote_command_capture(device_info):
	try:
		print("{} : Trying SSH ...".format(device_info['alias']))
		remote_ssh = channel.channel(str(device_info['host']),str(device_info['username']),str(device_info['password']))
		print("{} : Remote Shell acquired.".format(device_info['alias']))
		invoke_command_scheduled(remote_ssh,device_info)
	except Exception as error:
		print("{} : {}, not able to capture ".format(device_info['alias'],error))
Exemple #9
0
def build_channel_map():
    bw = 50
    bw_len = np.arange(bw)
    num_channels = 5
    data_chunks = np.array_split(bw_len, num_channels)
    for freq_list in data_chunks:
        c = channel(freq_list[0], freq_list[-1])
        channels.append(c)
Exemple #10
0
 def grabChannelData(self):
     channels = []
     self.channels = {}
     for b in self.bots:
         channels.extend(self.bots[b]['channels'])
     channels = list(set(channels))
     
     for c in channels:
         self.channels[c] = channel(c)        
 def __init__(self, ibd, nchan, bdofs, com):
     #id of board
     self.ibd = ibd
     #number of channels
     self.nchan = nchan
     #channels on this board
     self.chlist = []
     for ich in range(self.nchan):
         self.chlist.append(channel(self.ibd, ich, bdofs, com))
Exemple #12
0
	def __init__(self,N0):
		self.ChannelCoef = [
			0.04043988737137,  0.02305723651795,  0.02835846576427,  0.03333274714846,
    	0.03779347565539,  0.04140897746597,   0.0439442278272,  0.04524606440035,
    	0.04524606440035,   0.0439442278272,  0.04140897746597,  0.03779347565539,
    	0.03333274714846,  0.02835846576427,  0.02305723651795,  0.04043988737137
		]

		self.chanFilter = Fir.Fir(self.ChannelCoef,len(self.ChannelCoef))
		self.chan = channel.channel(32,N0)
Exemple #13
0
def apply_configuration(switch_data, conf_data):
    for switch in switch_data.keys():
        details = switch_data[switch]
        chosen = details[-1]
        con = None

        try:
            address = chosen[CSV_SWITCH_HEADERS[1]]
            port = None
            if not chosen[CSV_SWITCH_HEADERS[2]] == '':
                port = chosen[CSV_SWITCH_HEADERS[2]]
            username = chosen[CSV_SWITCH_HEADERS[3]]
            password = chosen[CSV_SWITCH_HEADERS[4]]

            for conf in conf_data.keys():
                if switch == conf:
                    conf_details = conf_data[conf]
                    switch_details = dict(
                        filter(
                            lambda elem: elem[0] not in logger_ignore_values,
                            chosen.items()))
                    logger.debug(
                        'switch details - ({})'.format(switch_details))

                    logger_file_name = "_".join(['device', switch, address])
                    custom_logger = logging.handlers.TimedRotatingFileHandler(
                        os.path.join(BASE_DIR, 'logs',
                                     '{}.log'.format(logger_file_name)),
                        'midnight')
                    custom_formatter = logging.Formatter(
                        fmt='%(asctime)s - %(levelname)s - %(message)s')

                    custom_logger.setFormatter(custom_formatter)
                    logger.addHandler(custom_logger)
                    # Register custom device logger for seperate logging
                    try:
                        logger.info('Connecting to {} - {}'.format(
                            switch, address))
                        con = channel(address=address,
                                      port=port,
                                      username=username,
                                      password=password)
                        configure_sequence(con, conf_details)
                    except Exception as err:
                        logger.error(err)

                    # Unregister custom logger to stop further logging
                    logger.removeHandler(custom_logger)

        except Exception as err:
            logger.error(err)
        finally:
            if con:
                con.closeSession()
Exemple #14
0
	def addChannel(self, __name, __description, __publicRead, __publicWrite):
		"""
		Add a channel object to channels dictionary

		__name -- channel name
		__description -- channel description
		__publicRead -- bool, if true channel can be read by everyone, if false it can be read only by mods/admins
		__publicWrite -- bool, same as public read but relative to write permissions
		"""

		self.channels[__name] = channel.channel(__name, __description, __publicRead, __publicWrite)
Exemple #15
0
    def addChannel(self, __name, __description, __publicRead, __publicWrite):
        """
		Add a channel object to channels dictionary

		__name -- channel name
		__description -- channel description
		__publicRead -- bool, if true channel can be read by everyone, if false it can be read only by mods/admins
		__publicWrite -- bool, same as public read but relative to write permissions
		"""

        self.channels[__name] = channel.channel(__name, __description,
                                                __publicRead, __publicWrite)
Exemple #16
0
 def new(self, plane):
     if plane.name == 'TOWER':
         plane.getquery()
         return plane.name, plane.state, plane.latitude, plane.longitude, 0, plane.altitude, plane.heading, 0, plane.query, plane.acknowledge(
         ), 0
     else:
         ch = channel()
     ack = plane.acknowledge()
     if ((plane.state == 'taxi') or (plane.state == 'takeoff')):
         plane.getlatitude(120)
         plane.getlongitude(120)
     else:
         if not (plane.newhead == plane.heading):
             plane.changeheading(plane.newhead)
         plane.getlatitude(plane.heading)
         plane.getlongitude(plane.heading)
     dist = plane.getdistance()
     if dist < 0.001:
         dist = 0
     updatecluster(plane)
     analys = analysquery()
     new, attr = analys.analysquery(plane)
     if (not ack):
         if new:
             if attr == 'H':
                 plane.changeheading(new)
             elif attr == 'A':
                 plane.changealtitude(new)
             elif attr == 'S':
                 plane.changespeed(new)
             elif attr == 'T':
                 if plane.speed >= 150 and plane.distance >= 50:
                     if (not plane.heading
                             == new % 1000) and plane.altitude > 200:
                         plane.changeheading(new % 1000)
                     if not plane.altitude == new / 1000:
                         plane.changealtitude(new / 1000)
             elif attr == 'G':
                 audio.speak(plane.getquery())
         else:
             ch.clearchannel()
             plane.getquery()
     else:
         plane.getquery()
     return plane.name, plane.state, plane.latitude, plane.longitude, dist, plane.altitude, plane.heading, plane.speed, plane.query, ack, checkcollision(
         plane)
Exemple #17
0
		def joinMsg(prefix, sender, args, msg):
			destName = args[0]
			if destName[0] is not '#':
				destName = '#' + destName
			
			#find channel with same name
			for destChan in self.channelSet:
				if destChan.name == destName:
					destChan.addUser(sender)
					destChan.forwardMsg(prefix + ' ' + msg)
					destChan.forwardMsg(prefix + ' PRIVMSG ' + destChan.name + ' :' + sender.nick + ' has joined the channel.\r\n')
					return
			
			#no channel with same name, make a new one
			destChan = channel.channel({sender}, destName)
			destChan.forwardMsg(prefix + ' ' + msg)
			return
Exemple #18
0
 def command(self, plane):
     #print 'hello',plane.name,plane.latitude,plane.longitude,plane.heading,plane.altitude
     ch = channel()
     if plane.state == 'taxi' and not ch.getrunway():
         ch.sendquery(plane.name + ' takeoff')
         ch.lockrunway()
         return
     elif plane.state == 'takeoff' and plane.altitude >= 3000 and ch.getrunway(
     ):
         plane.state = 'outound'
         ch.releaserunway()
         return
     elif plane.state == 'inbound' and plane.distance <= 100:
         if ch.getrunway():
             print 'goarround'
         else:
             ch.lockrunway()
     ch.sendquery(plane.name + ' hello')
Exemple #19
0
    def __init__(self):
        self.control = 0x07654321
        self.irq_en = 0  # 0 or 1
        self.channel_irq_en = 0
        self.channel_irq_flags = 0
        self.force_irq = 0  # 0 or 1
        self.irq_dummy = 0

        self.channels = [
            channel(),
            channel(),
            channel(),
            channel(),
            channel(),
            channel(),
            channel()
        ]
Exemple #20
0
def wind(fs, plotname="clock.svg"):
    num_threads = len(fs)
    ids = range(num_threads)
    (shower_tx, shower_rx) = channel.channel()
    channels = {i: {} for i in ids}

    for (i, j) in itertools.combinations(ids, 2):
        (chan0, chan1) = channel.bichannel()
        channels[i][j] = chan0
        channels[j][i] = chan1

    for (i, f) in enumerate(fs):

        def ticktock(f, clock):
            f(clock)
            clock.done_()

        clock = Clock_i(i, channels[i], shower_tx.copy())
        threading.Thread(target=ticktock, args=(f, clock)).start()

    return lambda: plot(num_threads, shower_rx, plotname)
Exemple #21
0
def sr_api(request):
    '''Runs sr:s api and catches song, artist and time it played. Catches also channel name'''
    request = request.query['channel']
    channel_name = channel(request)
    url = "http://api.sr.se/api/v2/playlists/rightnow?channelid=" + request + "&format=json"
    response = urlopen(url)
    sr_json = load(response)
    try:
        song = sr_json['playlist']['song']['description']
        text = 'Right now on ' + channel_name
        time = song_time(sr_json)
        return (song, text, time)
    except KeyError:
        try:
            song = sr_json['playlist']['previoussong']['description']
            text = 'Nothing playing right now, previous song on ' + channel_name + ' was'
            time = song_time(sr_json)
            return (song, text, time)
        except KeyError:
            song = sr_json['playlist']['nextsong']['description']
            text = 'Nothing playing right now, next song on ' + channel_name + ' is'
            time = song_time(sr_json)
            return (song, text, time)
Exemple #22
0
def sr_api(request):
	'''Runs sr:s api and catches song, artist and time it played. Catches also channel name'''
	request = request.query['channel']
	channel_name = channel(request)
	url = "http://api.sr.se/api/v2/playlists/rightnow?channelid="+request+"&format=json"
	response = urlopen(url)
	sr_json = load(response)
	try:
		song = sr_json['playlist']['song']['description']
		text = 'Right now on ' + channel_name
		time = song_time(sr_json)
		return (song, text, time)
	except KeyError:
		try:
			song = sr_json['playlist']['previoussong']['description']
			text = 'Nothing playing right now, previous song on ' + channel_name + ' was'
			time = song_time(sr_json)
			return (song, text, time)
		except KeyError:
			song = sr_json['playlist']['nextsong']['description']
			text = 'Nothing playing right now, next song on ' + channel_name + ' is'
			time = song_time(sr_json)
			return (song, text, time)
Exemple #23
0
    def __init__(self, **kwargs):
        self.bs_id = "b_" + str(uuid.uuid4())
        self.n_count = 6
        self.all_ch_count = 6

        self.coordinates = {"x": randrange(540, 590), "y": randrange(450, 500)}
        self.dimensions = {"x": 1000, "y": 1000}

        for key, value in kwargs.items():
            setattr(self, key, value)

        self.bs_nodes = [
            node(**{"parent_bs": self}) for i in range(0, self.n_count)
        ]
        self.global_pool = [
            channel(**{
                "availability": True,
                "power": 12000
            }) for i in range(0, self.all_ch_count)
        ]

        self.ch_allocations = {}

        # Calculating Network Metrics
        self.channel_capacity = 5000
        self.num_of_reqs = 0
        self.num_of_blocked_reqs = 0
        self.num_of_transmitted_pkts = 0
        self.total_bandwidth = self.channel_capacity * self.all_ch_count
        self.utilized_channels = 0
        self.num_control_msg = 0
        self.packet_size = 500
        self.control_msg_size = 50

        self.throughput = 0.0
        self.blocking_rate = 0.0
        self.channel_utilization = 0.0
Exemple #24
0
 def terrain(self):
     for i in xrange(30):
         pygame.draw.line(self.screen, (0, 30, 0),
                          (self.cenx - (5 * i * self.zoom), 0),
                          (self.cenx - (5 * i * self.zoom), self.resy), 1)
         pygame.draw.line(self.screen, (0, 30, 0),
                          (0, self.ceny - (5 * i * self.zoom)),
                          (self.resx, self.ceny - (5 * i * self.zoom)), 1)
         pygame.draw.line(self.screen, (0, 30, 0),
                          (self.cenx + (5 * i * self.zoom), 0),
                          (self.cenx + (5 * i * self.zoom), self.resy), 1)
         pygame.draw.line(self.screen, (0, 30, 0),
                          (0, self.ceny + (5 * i * self.zoom)),
                          (self.resx, self.ceny + (5 * i * self.zoom)), 1)
     for i in xrange(30):
         pygame.draw.circle(self.screen, (0, 30, 0), (self.cenx, self.ceny),
                            5 * (i + 1) * self.zoom, 1)
     i = 1
     while i < 40:
         pygame.draw.circle(self.screen, (0, 204, 0),
                            (self.cenx, self.ceny), 10 * i * self.zoom, 1)
         i *= 2
     ch = channel()
     if not ch.getrunway():
         pygame.draw.line(
             self.screen, (0, 204, 0),
             (self.cenx - 0.43 * self.zoom * numpy.sin(60 * pi / 180),
              self.ceny - 0.43 * self.zoom * numpy.cos(60 * pi / 180)),
             (self.cenx + 0.43 * self.zoom * numpy.sin(60 * pi / 180),
              self.ceny + 0.43 * self.zoom * numpy.cos(60 * pi / 180)), 3)
     else:
         pygame.draw.line(
             self.screen, (204, 0, 0),
             (self.cenx - 0.43 * self.zoom * numpy.sin(60 * pi / 180),
              self.ceny - 0.43 * self.zoom * numpy.cos(60 * pi / 180)),
             (self.cenx + 0.43 * self.zoom * numpy.sin(60 * pi / 180),
              self.ceny + 0.43 * self.zoom * numpy.cos(60 * pi / 180)), 3)
Exemple #25
0
def parseChannelConfig():

	cfg_file = globals.CFG_FILE

	config = configparser.ConfigParser()
	
	if os.path.exists(cfg_file) == False:
	
		print(f"{ui.RED_MINUS} Could not locate redViper configuration file.")
		sys.exit(1)

	else:
		
		config.read(cfg_file)
		
		channel_list = []
		for key in config.keys():
		
			if "master" in key:
		
				account = config[key]
				account_id = key.split("-")[1]
				user = account[ account_id + "_USER" ]
				passwd = account[ account_id + "_PASS" ]
				secret = account[ account_id + "_SECRET" ]
				client = account[ account_id + "_CLIENT" ]
				subreddits = account[ account_id + "_SUBS" ].split(",")
				
				newAccount = master_account(user, passwd, secret, client)

				for sub in subreddits:
					newChannel = channel(sub, newAccount)
					channel_list.append(newChannel)


		return channel_list
Exemple #26
0
    def connect_channel_pfb(self, channel_rate, freq):

        source_id = None

        if self.scan_mode == False:
            for i in self.sources.keys():
                if abs(freq - self.sources[i]['center_freq']
                       ) < self.sources[i]['samp_rate'] / 2:
                    source_id = i
                    break

            if source_id == None:
                raise Exception('Unable to find source for frequency %s' %
                                freq)

        source_center_freq = self.sources[source_id]['center_freq']
        source_samp_rate = self.sources[source_id]['samp_rate']
        source = self.sources[source_id]['block']

        offset = freq - source_center_freq

        if freq < 10000000:
            offset = freq  #scan mode, relative freq

        pfb = self.sources[source_id]['pfb']

        pfb_samp_rate = self.target_size  #1000000
        pfb_center_freq = source_center_freq - (pfb_samp_rate / 2)

        num_channels = source_samp_rate / pfb_samp_rate

        offset = freq - source_center_freq
        chan = int(round(offset / float(pfb_samp_rate)))
        if chan < 0:
            chan = chan + num_channels

        pfb_offset = offset - (chan * (pfb_samp_rate))

        pfb_id = chan

        if pfb_offset < (-1 * (pfb_samp_rate / 2)) + (
                channel_rate / 2) or pfb_offset > (pfb_samp_rate /
                                                   2) - (channel_rate / 2):
            self.log.warning('warning: %s edge boundary' % freq)
        #We have all our parameters, lets see if we can re-use an idling channel
        self.access_lock.acquire()

        block = None

        for c in self.channels.keys():
            if self.channels[c].source_id == source_id and self.channels[
                    c].pfb_id == pfb_id and self.channels[c].in_use == False:
                block = self.channels[c]
                block_id = self.channels[c].block_id
                block.set_offset(pfb_offset)
                block.channel_close_time = 0
                #TODO: move UDP output
                break

        if block == None:
            for x in range(0, 3):
                port = random.randint(10000, 60000)
                try:
                    block = channel.channel(port, channel_rate,
                                            (pfb_samp_rate), pfb_offset)
                except RuntimeError as err:
                    self.log.error(
                        'Failed to build channel on port: %s attempt: %s' %
                        (port, x))
                    pass

            block.source_id = source_id
            block.pfb_id = pfb_id

            self.channels[port] = block
            block_id = '%s' % uuid.uuid4()
            block.block_id = block_id

            self.lock()
            self.connect((pfb, pfb_id), block)
            self.unlock()

        block.in_use = True

        self.access_lock.release()

        return block.block_id, port
Exemple #27
0
 def do_rss090_channel(self):
   from channel import channel
   self.dispatcher.defaultNamespaces.append("http://my.netscape.com/rdf/simple/0.9/")
   return channel(), noduplicates()
Exemple #28
0
 def do_rss090_channel(self):
   from channel import channel
   self.dispatcher.defaultNamespaces.append("http://my.netscape.com/rdf/simple/0.9/")
   return channel(), noduplicates()
Exemple #29
0
 def join_chan(self, chan):
     self.channels[chan.lower()] = channel.channel(self, chan)
     self.channels[chan.lower()].join()
Exemple #30
0
def main():

    #channel listing
    global list_of_motor
    list_of_motor = []
    list_of_motor.append(channel("servomoteur3", 18, 6, 33))
    list_of_motor.append(channel("servomoteur4", 19, 7, 32))
    list_of_motor.append(channel("stepper motor1", 22, 13, 34))
    list_of_motor.append(channel("stepper motor2", 23, 14, 35))
    #list_of_motor.append( channel( "channel4", 36, 4, 0) )

    global list_of_leds
    list_of_leds = []
    list_of_leds.append(channel("ledRouge", 0, 2, 64))
    list_of_leds.append(channel("ledRGBr", 1, 10, 65))
    list_of_leds.append(channel("ledRGBg", 2, 11, 66))
    list_of_leds.append(channel("ledRGBb", 3, 12, 67))
    #list_of_leds.append( channel( "ledSide2", 12, 34, 0))

    global list_of_videoFx
    list_of_videoFx = []
    list_of_videoFx.append(
        video_effect("sharpness", 5, "enhancement/sharpness"))
    list_of_videoFx.append(video_effect("Constrate", 4,
                                        "enhancement/contrast"))
    list_of_videoFx.append(
        video_effect("Saturation", 6, "enhancement/saturation"))
    list_of_videoFx.append(
        video_effect("Brightness", 7, "enhancement/brightness"))
    list_of_videoFx.append(video_effect("Filter +", 62, "filters/nextFilter"))
    list_of_videoFx.append(
        video_effect("Filter -", 61, "filters/previousFilter"))
    list_of_videoFx.append(
        video_effect("init Filter", 60, "filters/initFilter"))
    list_of_videoFx.append(video_effect("zoom", 20, "zoomCrop/topMargin"))
    list_of_videoFx.append(video_effect("zoom", 21, "zoomCrop/leftMargin"))
    list_of_videoFx.append(video_effect("zoom", 0, "zoomCrop/zoomLevel"))
    list_of_videoFx.append(video_effect("zoom", 59, "whiteBalance/wbNext"))
    list_of_videoFx.append(video_effect("zoom", 58, "whiteBalance/wbPrev"))

    global list_of_transport
    list_of_transport = []
    list_of_transport.append(transport_effect("release Stepper", 42, 21))
    list_of_transport.append(transport_effect("relay1", 32, 4))
    list_of_transport.append(transport_effect("release Stepper", 33, 5))
    #list_of_transport.append( transport_effect("hold Stepper", 41, 20))
    #list_of_transport.append( transport_effect("init stepper pos", 43, 22))

    global list_of_all
    list_of_all = dict()
    list_of_all['motor'] = list_of_motor
    list_of_all['led'] = list_of_leds
    list_of_all['videoFx'] = list_of_videoFx
    list_of_all['transport'] = list_of_transport

    #intern transport : record, play , stop , reset
    global is_recording
    is_recording = False
    global is_playing
    is_playing = False

    #Heating security : realase motor after inactivity
    global time_without_midi
    time_without_midi = 0

    # OSC connect
    global oscClient
    oscClient = OSCClient()
    oscClient.connect(("localhost", 12345))

    # Midi connect
    try:
        if sys.platform.startswith('darwin'):
            inport = mido.open_input('nanoKONTROL2 SLIDER/KNOB')
        elif sys.platform.startswith('linux') or sys.platform.startswith(
                'cygwin'):
            inport = mido.open_input('nanoKONTROL2 MIDI 1')
        else:
            inport = None
    except:
        print "Impossible to connect to Midi device"
        inport = None

    if (inport):
        inport.callback = receive_midi_msg

    #Serial connect
    try:
        global ser
        if sys.platform.startswith('darwin'):
            ser = serial.Serial('/dev/tty.usbmodem1a151', 115200)
            print "Serial connected"
        elif sys.platform.startswith('linux') or sys.platform.startswith(
                'cygwin'):
            try:
                ser = serial.Serial('/dev/ttyACM0', 115200)
                print "ACM0"
            except:
                ser = serial.Serial('/dev/ttyACM1', 115200)
                print "ACM1"

        else:
            ser = None
    except:
        print "Impossible to connect to Serial"
        ser = None

    while True:
        #Main update
        #Frequency update 20Hz
        time.sleep(0.05)

        for c in list_of_all['motor']:
            update_channel(c)
        for c in list_of_all['led']:
            update_channel(c)
        for c in list_of_all['videoFx']:
            update_videoFx(c)
        for c in list_of_all['transport']:
            update_transport(c)

        #Heating security, realese stepper after 5sec of inactivity
        time_without_midi = time_without_midi + 1
        if (time_without_midi > 100):
            #release stepper motor
            send_serial(100, 21)
            print "Surchauffe"
            time_without_midi = 0
Exemple #31
0
 def AddChannel(self, evt):
     pos = self.GetPositionTuple()
     pos = (pos[0]+800, pos[1]+0)
     self.channel = channel(parent=self, pos=pos)
     self.channel.Show(True)
     print "ADDING CHANNEL GUI ..."
import scipy.io as sio
import numpy as np
import matplotlib.pyplot as plt
import math
from channel import channel

import time

N = 10
num_train = 100000
num_test = 10000
trainseed = 7
testseed = 3

Xtrain, Ytrain, wtime = channel(N, num_train, seed=trainseed)
X, Y, swmmsetime = channel(N, num_test, seed=testseed)

sio.savemat('data/Train_data_%d_%d.mat' %(N, num_train), {'Xtrain': Xtrain, 'Ytrain': Ytrain})
print("Train data Saved")
sio.savemat('data/Test_data_%d_%d.mat' %(N, num_test), {'X': X, 'Y': Y, 'swmmsetime': swmmsetime})
print("Test data Saved")
def test(d_max, threshold, detection_time):
    end_time = 10**7
    packet_size = 100
    STA_list = []
    amount = 500
    CWmax = 1024
    for times in range(10):
        sys.stdout = open("log_file_Thr=" + str(threshold) + ".txt", 'w')
        timer = system_timer.SystemTimer(end_time)
        folder_name = "./Parameter_test/Thr=" + str(threshold) + "_T=" + str(
            detection_time / 10**3)
        if not os.path.isdir(folder_name):
            os.makedirs(folder_name)
        file = open(
            folder_name + "/d_max=" + str(d_max) + "_round=" + str(times) +
            ".txt", 'w')
        statistics_collection.collector.set_output_file(file)
        system_channel = channel.channel()
        AP, STA_list = initialization.init(amount, d_max, timer, False, False,
                                           CWmax, system_channel, threshold,
                                           detection_time)
        AP.block_list = initialization.AID_assignment(STA_list)
        system_channel.register_devices(STA_list + [AP])
        AP.channel = system_channel
        AP.max_data_size = packet_size
        statistics_collection.collector.end_time = end_time
        ################# start the simulation ##################
        while timer.events:
            current_events = timer.get_next_events()
            for each_event in current_events:
                if each_event.type != "backoff":
                    print("The event type is " + each_event.type + " at " +
                          str(timer.current_time))
                if each_event.time > timer.end_time:
                    break
                each_event.execute(STA_list + [AP], timer, system_channel)
                if each_event.type != "backoff":
                    counter = []
                    for each in STA_list:  # how many STAs stay awake
                        if each.status != "Sleep":
                            counter.append(each.AID)
                    print("There are " + str(counter.__len__()) +
                          " STAs stays awake at " + str(timer.current_time))
                    counter = []
                    backoff_timer = []
                    for each in STA_list:
                        if not (each.backoff_status == "Off" or not each.queue
                                or each.status != "Listen"):
                            counter.append(each.AID)
                            backoff_timer.append(each.backoff_timer)
                    print("There are " + str(counter.__len__()) +
                          " STAs are competing for the channel at " +
                          str(timer.current_time) + "\n")
                    # print("The backoff timers are "+str(backoff_timer)+"\n ")
            if (statistics_collection.collector.number_of_packet ==
                    statistics_collection.collector.successful_transmissions.
                    __len__()):
                if not [
                        x
                        for x in timer.events if x.type == "Polling round end"
                ]:  # stop the simulation
                    statistics_collection.collector.end_time = timer.current_time
                    timer.events = []
        if system_channel.packet_list:  # renew the channel busy time
            statistics_collection.collector.channel_busy_time += (
                timer.end_time -
                statistics_collection.collector.last_time_idle)
        statistics_collection.collector.print_statistics_of_delays()
        statistics_collection.collector.print_polling_info()
        statistics_collection.collector.print_other_statistics(
            end_time, packet_size)

        statistics_collection.collector.clear()
        file.close()
        os.system('cls' if os.name == 'nt' else 'clear')
Exemple #34
0
from channel import channel

c2 = channel(9)
c2.getfeeds()
print c2.getfeeds_field()
print c2.getlastEntry()



Exemple #35
0
 def getquery(self):
     ch = channel()
     self.query = ch.getquery(self.name)
Exemple #36
0
def test(RTS_enable, suspend_enable, reserved_data_size, d_max):
    PRAWs_duration = 5.3 * 1000
    BI = 500 * 1000
    #STA_number=20
    CWmin = 16
    CWmax = 16 * (2**6)  # 1024
    #packet_arrival_rate=1.0/150000 #in us
    end_time = 10**7 * 2
    data_size = reserved_data_size  #in bytes, this parameter is also need to be changed in packets.py
    STA_list = []
    radius = 1000
    amount = 500  # the total number of stations, it is used to read the corresponding files
    # d_max=1900

    for times in range(20):
        print("system end time=" + str(end_time))
        ############## initialization ###########
        timer = system_timer.SystemTimer(end_time)
        # file=open("./results/d_max="+str(d_max)+"_amount="+str(amount)+"/CWmax="+str(CWmax)+\
        # 	"_suspend="+str(suspend_enable)+"_round="+str(times)+"_new.txt","w")
        folder_name = "./results/d_max=" + str(d_max) + "_amount=" + str(
            amount)
        if not os.path.isdir(folder_name):
            os.makedirs(folder_name)
        file = open(
            folder_name + "/data_size=" + str(data_size) + "_round=" +
            str(times) + ".txt", "w")
        # file=open("./results/CWmax/CWmax="+str(CWmax)+\
        #  	"_suspend="+str(suspend_enable)+"_round="+str(times)+".txt","w")
        # file=open("./results/d_max="+str(d_max)+"_amount="+str(amount)+"/CWmax=unlimited"+"_suspend="+str(suspend_enable)+"_round="+str(times)+".txt","w")
        statistics_collection.collector.set_output_file(file)
        system_channel = channel.channel()
        system_AP, STA_list = initialization.init(amount,
                                                  d_max,
                                                  timer,
                                                  RTS_enable,
                                                  suspend_enable,
                                                  CWmax,
                                                  system_channel,
                                                  data_size=data_size)
        system_AP.block_list = initialization.AID_assignment(STA_list)
        system_channel.register_devices(STA_list + [system_AP])
        system_AP.channel = system_channel
        system_AP.max_data_size = reserved_data_size
        statistics_collection.collector.end_time = end_time

        ############# excute the simualtion ####################
        while timer.events:  #simulation starts
            current_events = timer.get_next_events()
            for each_event in current_events:
                if each_event.type != "backoff":
                    print("The event type is " + each_event.type + " at " +
                          str(timer.current_time))
                if each_event.time > timer.end_time:  # end the pragram
                    break
                each_event.execute(STA_list + [system_AP], timer,
                                   system_channel)  #### !!!!!
                if each_event.type != "backoff":
                    counter = []
                    for each in STA_list:  # how many STAs stay awake
                        if each.status != "Sleep":
                            counter.append(each.AID)
                    print("There are " + str(counter.__len__()) +
                          " STAs stays awake at " + str(timer.current_time))
                    counter = []
                    backoff_timer = []
                    for each in STA_list:
                        if not (each.backoff_status == "Off" or not each.queue
                                or each.status != "Listen"):
                            counter.append(each.AID)
                            backoff_timer.append(each.backoff_timer)
                    print("There are " + str(counter.__len__()) +
                          " STAs are competing for the channel at " +
                          str(timer.current_time))
                    print("The backoff timers are " + str(backoff_timer) +
                          "\n ")
            if statistics_collection.collector.number_of_packet == statistics_collection.collector.successful_transmissions.__len__(
            ):  # stop the simulation
                if not [
                        x
                        for x in timer.events if x.type == "Polling round end"
                ]:
                    statistics_collection.collector.end_time = timer.current_time
                    timer.events = []
        # for each in STA_list:
        # 	if each.has_pending_packet():
        # 		statistics_collection.collector.register_backoff_times(each.number_of_attempts,each.number_of_backoffs)
        if system_channel.packet_list:  # renew the channel busy time
            statistics_collection.collector.channel_busy_time += timer.end_time - statistics_collection.collector.last_time_idle

        statistics_collection.collector.print_statistics_of_delays()
        statistics_collection.collector.print_polling_info()
        statistics_collection.collector.print_other_statistics(
            end_time, data_size)

        statistics_collection.collector.clear()
        os.system('cls' if os.name == 'nt' else 'clear')
        file.close()