コード例 #1
0
ファイル: oscilloscope.py プロジェクト: Akanoa/CAI2014
    def __init__(self, parent=None, width=800, height=800):
        """ initialisation

        parent : une application
        width,height : dimension de l'oscilloscpe
        """
        Frame.__init__(self)
        self.master.title("Oscilloscope")
        # Modele
        self.time = 0
        self.signal = None
        # Vues
        self.menuBar         = MenuBar(parent=self)
        self.screen          = Screen(parent=self)
        self.frame = Frame(master=self)
        # Controleurs
        self.time_control = TimeBase(parent=self)
        self.signal_controlX = Generator(parent=self, name="X", color="red")
        self.signal_controlY = Generator(parent=self, name="Y", color="blue")
        # Affichage Vues, Controleurs
        self.menuBar.pack()
        self.screen.pack()

        self.signal_controlX.pack(side="left")
        self.signal_controlY.pack(side="left")
        self.time_control.pack()

        self.configure(width=width, height=height)
コード例 #2
0
ファイル: oscilloscope.py プロジェクト: Akanoa/CAI2014
    def __init__(self, parent=None, width=800, height=800):
        """
        Proprietes :
          -  un ecran (classe Screen)
          -  vibrations harmoniques (classe Vibration)
          -  base de temps (classe TimeBase)
        Methodes :
          -  get_time(self) : demander le temps de la base de temps
          -  update_time(self, time) : calcul de vibration si mise  a jour base de temps
          -  draw_curve(self, name, curve) : demander affichage d'une courbe
        """
        Frame.__init__(self)
        self.time = 0
        self.master.title("Oscilloscope")
        self.screen = Screen(parent=self)
        self.time_base = TimeBase(parent=self)
        self.vib_X = Vibration(parent=self, color="blue")

        self.curveX = None

        self.menuBar = MenuBar(self)

        self.menuBar.pack()
        self.screen.pack()
        self.vib_X.pack()
        self.time_base.pack()

        self.configure(width=width, height=height)
コード例 #3
0
ファイル: oscilloscope.py プロジェクト: Akanoa/CAI2014
    def __init__(self, parent=None, width=800, height=800):
        """ initialisation

        parent : une application
        width,height : dimension de l'oscilloscpe
        """
        Frame.__init__(self)
        self.master.title("Oscilloscope")
        # Modelethreading.Thread(None, affiche, None, (200,), {'nom':'thread a'}) 
        self.time = 0
        self.signal = None
        # # Vues
        # self.menuBar         = MenuBar(parent=self)
        # self.screen          = Screen(parent=self)
        # self.frame = Frame(master=self)
        # # Controleurs
        # self.time_control = TimeBase(parent=self)
        # self.signal_controlX = Generator(parent=self, name="X", color="red")
        # self.signal_controlY = Generator(parent=self, name="Y", color="blue")
        # # Affichage Vues, Controleurs
        # self.menuBar.pack()
        # self.screen.pack()

        # self.signal_controlX.pack(side="left")
        # self.signal_controlY.pack(side="left")
        # self.time_control.pack()

        # Vues
        self.menuBar          = MenuBar(parent=self)
        self.screenT          = Screen(parent=self)
        self.screenXY         = Screen(parent=self)
        # Controleurs
        self.signal_controlX = Generator(parent=self, name="X", color="red")
        self.signal_controlY = Generator(parent=self, name="Y", color="blue")
        self.signal_controlXY = Generator(parent=self, name="XY", color="blue")
        self.time_control = TimeBase(parent=self)
        self.varX  = IntVar()
        self.varY  = IntVar()
        self.varXY = IntVar()
        self.showX = Checkbutton(parent, text="X", variable=self.varX, command=lambda: self.update_show("X"))
        self.showY = Checkbutton(parent, text="Y", variable=self.varY, command=lambda: self.update_show("Y"))
        self.showXY = Checkbutton(parent, text="XY", variable=self.varXY, command=lambda: self.update_show("XY"))
        self.varX.set(1)
        self.varY.set(1)
        self.varXY.set(1)

        # Affichage Vues, Controleurs
        self.menuBar.grid(column=0, row=0)
        self.screenT.grid(column=0,row=1)
        self.screenXY.grid(column=1,row=1)
        self.signal_controlX.grid(column=0, row=2)
        self.signal_controlY.grid(column=0, row=3)
        self.time_control.grid(column=0, row=4)

        self.showX.grid(column=1, row=2)
        self.showY.grid(column=1, row=3)
        self.showXY.grid(column=1, row=4)

        self.configure(width=width, height=height)
コード例 #4
0
    def __init__(self, parent=None, width=800, height=800):
        """ 
        Initialisation

        parent : une application
        width,height : dimension de l'oscilloscpe
        """
        Frame.__init__(self)
        self.master.title("Oscilloscope - Diquélou - Toscer")

        # doit-on afficher la courbe de lissajoux
        self.drawXY = IntVar()
        
        # Modele
        self.time = 0
        # gestion des signaux X et Y
        self.signal_X   = None
        self.signal_Y   = None
        self.signal_XY = None
        # Vues
        self.view = Screen(parent=self)
        self.lissajoux = Screen(parent= self)
        # Controleurs
        self.control_time = TimeBase(parent=self)
        self.control_X = Generator(self,'X')
        self.control_Y = Generator(self, 'Y')



        # menu
        menuBar = MenuBar(self)
        menuBar.pack(fill="x");

        # Affichage Vues, Controleurs
        self.view.pack(fill="both")

        self.control_time.pack(side="left", fill="y")
     
        self.control_X.pack(side="left",fill="y")

        self.lissajoux.pack(fill="both", side="left", expand=1)

        self.control_Y.pack(side="right", fill="both")

        self.configure(width=width, height=height)
        self.master.protocol("WM_DELETE_WINDOW", self.quitter)
コード例 #5
0
ファイル: beat.py プロジェクト: gdkar/beat-off
class Beat:

	KEY_TAP=pygame.K_SPACE
	KEY_PHASE=pygame.K_RETURN
	KEY_RESET=pygame.K_ESCAPE

	EFFECT_HISTORY_LENGTH=2

	KEYBOARD={
		pygame.K_q:(0,0),
		pygame.K_w:(1,0),
		pygame.K_e:(2,0),
		pygame.K_r:(3,0),
		pygame.K_t:(4,0),
		pygame.K_y:(5,0),
		pygame.K_u:(6,0),
		pygame.K_i:(7,0),
		pygame.K_a:(0,1),
		pygame.K_s:(1,1),
		pygame.K_d:(2,1),
		pygame.K_f:(3,1),
		pygame.K_g:(4,1),
		pygame.K_h:(5,1),
		pygame.K_j:(6,1),
		pygame.K_k:(7,1),
		pygame.K_z:(0,2),
		pygame.K_x:(1,2),
		pygame.K_c:(2,2),
		pygame.K_v:(3,2),
		pygame.K_b:(4,2),
		pygame.K_n:(5,2),
		pygame.K_m:(6,2),
		pygame.K_COMMA:(7,2),
	}

	FUNCTION_KEYS={
		pygame.K_F1:1,
		pygame.K_F2:2,
		pygame.K_F3:3,
		pygame.K_F4:4,
		pygame.K_F5:5,
		pygame.K_F6:6,
		pygame.K_F7:7,
		pygame.K_F8:8,
		pygame.K_F9:9,
		pygame.K_F10:10,
		pygame.K_F11:11,
		pygame.K_F12:12,
	}

	PATTERN_KEYS={
		pygame.K_1:1,
		pygame.K_2:2,
		pygame.K_3:3,
		pygame.K_4:4,
		pygame.K_5:5,
		pygame.K_6:6,
		pygame.K_7:7,
		pygame.K_8:8,
		pygame.K_9:9,
		pygame.K_0:0,
	}

	KB_REMAP={
		pygame.K_RIGHTBRACKET:(0,1),
		pygame.K_QUOTE:(1,1),
		pygame.K_SLASH:(2,1),
		pygame.K_LEFTBRACKET:(0,-1),
		pygame.K_SEMICOLON:(1,-1),
		pygame.K_PERIOD:(2,-1),
	}

	COLORS=[
		(255,255,255), # white
		(255,0,0), # red
		(255,20,0), # orange
		(255,80,0), # yellow
		(50,100,0), # green
		(0,30,80), # blue
		(255,0,50), # purple
		(0,0,0), # black
	]

	EFFECT_NAMES=[
		'on',
		'strobe',
		'sweep',
		'rev sweep',
		'fast sweep',
		'fast rev sweep',
		'pulse',
		'rev pulse',
		'fast pulse',
		'fast rev pulse',
		'fade in',
		'fade out',
		'fast fade in',
		'fast fade out',
		'rainbow!',
	]

	def __init__(self):
		pygame.init()
		self.size=1024,480
		self.screen=pygame.display.set_mode(self.size)
		self.bg=0,0,0
		self.fg=255,255,255
		self.audio_color=0,0,255

		self.first_click=0
		self.last_click=0
		self.clicks=0
		self.last_tick=0

		self.effects={}
		self.function=1
		self.shift=False
		self.forever=False
		self.forever_patterns={}
		self.forever_fn={}
		self.last_stop=0
		self.recording=False
		self.recorded={}
		self.coarse_grain=1
		self.fine_grain=4
		self.saved_patterns={}
		self.rec_pat=None
		self.kb_map=[0,1,2]
		self.last_effect=collections.deque()

		self.r=Recorder()
		self.tb=TimeBase()
		self.tb.register_tickfn(self.tick)
		if len(sys.argv)>=2 and sys.argv[1]=='fake':
			b=[FakeSingleBespeckleDevice('/dev/ttyUSB0',115200)]
		else:
			b = []
			for i in range(10):
				try:
					b.append(SingleBespeckleDevice('/dev/ttyUSB%d' % i, 3000000))
					if len(b) >= 4:
						break
				except:
					pass

		self.oa=OutputAdapter(b,self.tb)
		self.oa.add_reset()

		self.seq=Sequencer(self.tb,self.oa)

		self.oa.start()
		self.r.start()
		self.tb.start()
		self.seq.start()

		while True:
			quit=False
			for event in pygame.event.get():
				if event.type==pygame.QUIT: quit=True
				if event.type==pygame.KEYDOWN:
					if event.key==self.KEY_TAP:
						self.tap()
					elif event.key==self.KEY_PHASE:
						self.phase()
					elif event.key==pygame.K_UP:
						self.tempo_adjust(1.)
					elif event.key==pygame.K_DOWN:
						self.tempo_adjust(-1.)
					elif event.key in self.KEYBOARD:
						self.effect(self.KEYBOARD[event.key])
					elif event.key==pygame.K_TAB:
						self.start_recording()
					elif event.key in self.PATTERN_KEYS:
						k=self.PATTERN_KEYS[event.key]
						if self.rec_pat is not None:
							self.save_pattern(k)
						else:
							p=self.pattern_map(k)
							if self.forever:
								if k in self.forever_patterns:
									self.remove_pattern(self.forever_patterns[k])
									self.forever_patterns.pop(k)
								elif p is not None:
									self.forever_patterns[k]=self.add_pattern(p,self.shift,self.forever)
							elif p is not None:
								self.add_pattern(p,self.shift,self.forever)
					elif event.key in self.FUNCTION_KEYS:
						k=self.FUNCTION_KEYS[event.key]
						p=self.function_map(k)
						if self.forever:
							if k in self.forever_fn:
								self.remove_pattern(self.forever_fn[k])
								self.forever_fn.pop(k)
							elif p is not None:
								self.forever_fn[k]=self.add_pattern(p,self.shift,self.forever)
						elif p is not None:
							self.add_pattern(p,self.shift,self.forever)
					elif event.key in self.KB_REMAP:
						self.kb_remap(*self.KB_REMAP[event.key])
					elif event.key==pygame.K_LSHIFT:
						self.shift=True
					elif event.key==pygame.K_LCTRL:
						self.forever=True
					elif event.key==self.KEY_RESET:
						self.oa.add_reset()
				elif event.type==pygame.KEYUP:
					if event.key in self.KEYBOARD:
						self.effect_release(self.KEYBOARD[event.key])
					elif event.key==pygame.K_LSHIFT:
						self.shift=False
					elif event.key==pygame.K_LCTRL:
						self.forever=False
					elif event.key==pygame.K_TAB:
						self.stop_recording()

			if quit:
				break

			font = pygame.font.Font(None, 36)
			text = font.render("TEMPO:"+str(self.tb.get_tempo())+" BPM", 1, self.fg)
			if self.recording:
				msg='recording'
			elif self.rec_pat is not None:
				msg='press a key to store'
			else:
				msg='not recording'
			text2 = font.render(msg,1,self.fg)

			audio=graphics.audio_widget(self.r,self.tb)
			pattern_timeline=graphics.pattern_timeline_widget(self.tb,self.seq,float(self.r.CHUNK)/self.r.RATE)

			self.screen.fill(self.bg)
			self.screen.blit(text, (0,0))
			self.screen.blit(text2, (0,30))
			self.screen.blit(audio, (0,60))
			self.screen.blit(pattern_timeline, (audio.get_width(),60))

			kb=[font.render(self.EFFECT_NAMES[self.kb_map[row]],1,self.fg) for row in range(3)]
			self.screen.blit(kb[0], (0,200))
			self.screen.blit(kb[1], (0,230))
			self.screen.blit(kb[2], (0,260))

			pygame.display.flip()
			time.sleep(0)

		self.seq.stop()
		self.r.stop()
		self.tb.stop()
		self.oa.stop()
		self.seq.join()
		self.r.join()
		self.tb.join()
		self.oa.join()

	def tick(self,num):
		self.r.set_beatline()
		self.last_tick=time.time()
		self.oa.add_tick()

	def tempo_adjust(self,amt):
		tempo=round(self.tb.get_tempo(),0)
		tempo+=amt
		self.tb.set_tempo(tempo)

	def tap(self):
		t=time.time()
		if t-self.last_click>2:
			self.first_click=t
			self.clicks=0
		else:
			self.clicks+=1
			self.tb.sync_period((t-self.first_click)/self.clicks)
		self.last_click=t

	def phase(self):
		t=time.time()
		self.tb.sync_phase(t)


	def kb_remap(self,remap_row,increment):
		self.kb_map[remap_row]=(self.kb_map[remap_row]+increment)%len(self.EFFECT_NAMES)

	def effect_map(self,(c,r)):
		if c>=len(self.COLORS):
			return None
		en=self.EFFECT_NAMES[self.kb_map[r]]
		opacity=0xFF
		if self.shift:
			opacity/=2

		color=self.COLORS[c]+(opacity,)
		if en=='on':
			return Effect(0x10,color,render=lambda *x:graphics.full_color(graphics.strip2screen(color),*x))
		if en=='strobe':
			return Effect(0x40,color+(0x00,0x10),False,render=lambda *x:graphics.strobe(graphics.strip2screen(color),*x))
		if en=='sweep':
			return Effect(0x41,color+(0x02,0x00),render=lambda *x:graphics.full_color(graphics.strip2screen(color),*x))
		if en=='rev sweep':
			return Effect(0x41,color+(0x82,0x00),render=lambda *x:graphics.full_color(graphics.strip2screen(color),*x))
		if en=='pulse':
			return Effect(0x42,color+(0x04,0x00),False,render=lambda *x:graphics.strobe(graphics.strip2screen(color),*x))
		if en=='rev pulse':
			return Effect(0x42,color+(0x84,0x00),False,render=lambda *x:graphics.strobe(graphics.strip2screen(color),*x))
		if en=='fast sweep':
			return Effect(0x41,color+(0x01,0x00),render=lambda *x:graphics.full_color(graphics.strip2screen(color),*x))
		if en=='fast rev sweep':
			return Effect(0x41,color+(0x81,0x00),render=lambda *x:graphics.full_color(graphics.strip2screen(color),*x))
		if en=='fast pulse':
			return Effect(0x42,color+(0x02,0x00),False,render=lambda *x:graphics.strobe(graphics.strip2screen(color),*x))
		if en=='fast rev pulse':
			return Effect(0x42,color+(0x082,0x00),False,render=lambda *x:graphics.strobe(graphics.strip2screen(color),*x))
		if en=='fade in':
			return Effect(0x43,color+(0x02,0x00),render=lambda *x:graphics.full_color(graphics.strip2screen(color),*x))
		if en=='fade out':
			return Effect(0x43,color+(0x82,0x00),render=lambda *x:graphics.full_color(graphics.strip2screen(color),*x))
		if en=='fast fade in':
			return Effect(0x43,color+(0x01,0x00),render=lambda *x:graphics.full_color(graphics.strip2screen(color),*x))
		if en=='fast fade out':
			return Effect(0x43,color+(0x81,0x00),render=lambda *x:graphics.full_color(graphics.strip2screen(color),*x))
		if en=='rainbow!':
			return Effect(0x03,(0x00, 0x04, 0x04),render=lambda *x:graphics.full_color(graphics.strip2screen(color),*x))
		return None
コード例 #6
0
ファイル: beat.py プロジェクト: gdkar/beat-off
	def __init__(self):
		pygame.init()
		self.size=1024,480
		self.screen=pygame.display.set_mode(self.size)
		self.bg=0,0,0
		self.fg=255,255,255
		self.audio_color=0,0,255

		self.first_click=0
		self.last_click=0
		self.clicks=0
		self.last_tick=0

		self.effects={}
		self.function=1
		self.shift=False
		self.forever=False
		self.forever_patterns={}
		self.forever_fn={}
		self.last_stop=0
		self.recording=False
		self.recorded={}
		self.coarse_grain=1
		self.fine_grain=4
		self.saved_patterns={}
		self.rec_pat=None
		self.kb_map=[0,1,2]
		self.last_effect=collections.deque()

		self.r=Recorder()
		self.tb=TimeBase()
		self.tb.register_tickfn(self.tick)
		if len(sys.argv)>=2 and sys.argv[1]=='fake':
			b=[FakeSingleBespeckleDevice('/dev/ttyUSB0',115200)]
		else:
			b = []
			for i in range(10):
				try:
					b.append(SingleBespeckleDevice('/dev/ttyUSB%d' % i, 3000000))
					if len(b) >= 4:
						break
				except:
					pass

		self.oa=OutputAdapter(b,self.tb)
		self.oa.add_reset()

		self.seq=Sequencer(self.tb,self.oa)

		self.oa.start()
		self.r.start()
		self.tb.start()
		self.seq.start()

		while True:
			quit=False
			for event in pygame.event.get():
				if event.type==pygame.QUIT: quit=True
				if event.type==pygame.KEYDOWN:
					if event.key==self.KEY_TAP:
						self.tap()
					elif event.key==self.KEY_PHASE:
						self.phase()
					elif event.key==pygame.K_UP:
						self.tempo_adjust(1.)
					elif event.key==pygame.K_DOWN:
						self.tempo_adjust(-1.)
					elif event.key in self.KEYBOARD:
						self.effect(self.KEYBOARD[event.key])
					elif event.key==pygame.K_TAB:
						self.start_recording()
					elif event.key in self.PATTERN_KEYS:
						k=self.PATTERN_KEYS[event.key]
						if self.rec_pat is not None:
							self.save_pattern(k)
						else:
							p=self.pattern_map(k)
							if self.forever:
								if k in self.forever_patterns:
									self.remove_pattern(self.forever_patterns[k])
									self.forever_patterns.pop(k)
								elif p is not None:
									self.forever_patterns[k]=self.add_pattern(p,self.shift,self.forever)
							elif p is not None:
								self.add_pattern(p,self.shift,self.forever)
					elif event.key in self.FUNCTION_KEYS:
						k=self.FUNCTION_KEYS[event.key]
						p=self.function_map(k)
						if self.forever:
							if k in self.forever_fn:
								self.remove_pattern(self.forever_fn[k])
								self.forever_fn.pop(k)
							elif p is not None:
								self.forever_fn[k]=self.add_pattern(p,self.shift,self.forever)
						elif p is not None:
							self.add_pattern(p,self.shift,self.forever)
					elif event.key in self.KB_REMAP:
						self.kb_remap(*self.KB_REMAP[event.key])
					elif event.key==pygame.K_LSHIFT:
						self.shift=True
					elif event.key==pygame.K_LCTRL:
						self.forever=True
					elif event.key==self.KEY_RESET:
						self.oa.add_reset()
				elif event.type==pygame.KEYUP:
					if event.key in self.KEYBOARD:
						self.effect_release(self.KEYBOARD[event.key])
					elif event.key==pygame.K_LSHIFT:
						self.shift=False
					elif event.key==pygame.K_LCTRL:
						self.forever=False
					elif event.key==pygame.K_TAB:
						self.stop_recording()

			if quit:
				break

			font = pygame.font.Font(None, 36)
			text = font.render("TEMPO:"+str(self.tb.get_tempo())+" BPM", 1, self.fg)
			if self.recording:
				msg='recording'
			elif self.rec_pat is not None:
				msg='press a key to store'
			else:
				msg='not recording'
			text2 = font.render(msg,1,self.fg)

			audio=graphics.audio_widget(self.r,self.tb)
			pattern_timeline=graphics.pattern_timeline_widget(self.tb,self.seq,float(self.r.CHUNK)/self.r.RATE)

			self.screen.fill(self.bg)
			self.screen.blit(text, (0,0))
			self.screen.blit(text2, (0,30))
			self.screen.blit(audio, (0,60))
			self.screen.blit(pattern_timeline, (audio.get_width(),60))

			kb=[font.render(self.EFFECT_NAMES[self.kb_map[row]],1,self.fg) for row in range(3)]
			self.screen.blit(kb[0], (0,200))
			self.screen.blit(kb[1], (0,230))
			self.screen.blit(kb[2], (0,260))

			pygame.display.flip()
			time.sleep(0)

		self.seq.stop()
		self.r.stop()
		self.tb.stop()
		self.oa.stop()
		self.seq.join()
		self.r.join()
		self.tb.join()
		self.oa.join()
コード例 #7
0
ファイル: oscilloscope.py プロジェクト: Akanoa/CAI2014
class Oscilloscope(Frame):
    def __init__(self, parent=None, width=800, height=800):
        """
        Proprietes :
          -  un ecran (classe Screen)
          -  vibrations harmoniques (classe Vibration)
          -  base de temps (classe TimeBase)
        Methodes :
          -  get_time(self) : demander le temps de la base de temps
          -  update_time(self, time) : calcul de vibration si mise  a jour base de temps
          -  draw_curve(self, name, curve) : demander affichage d'une courbe
        """
        Frame.__init__(self)
        self.time = 0
        self.master.title("Oscilloscope")
        self.screen = Screen(parent=self)
        self.time_base = TimeBase(parent=self)
        self.vib_X = Vibration(parent=self, color="blue")

        self.curveX = None

        self.menuBar = MenuBar(self)

        self.menuBar.pack()
        self.screen.pack()
        self.vib_X.pack()
        self.time_base.pack()

        self.configure(width=width, height=height)

    def get_time(self):
        """
        Retour : valeur courante de la base de temps
        """
        return self.time_base.get_time()

    def update_time(self, time):
        """
        Si modification base de temps : calcul vibration
        """
        if self.time != time:
            self.time = time
            self.curveX = self.vib_X.compute(a=self.vib_X.scale_A.get(), f=self.vib_X.scale_F.get(), p=self.vib_X.scale_P.get(), timeBase=self.get_time())
            self.draw_curve("X", self.curveX)

    def draw_curve(self, name="X", curve=None):
        """
        demande d'affichage de courbe
        """
        self.screen.draw_curve(name, curve)

    #########
    #event

    def exit(self):
        """
        Quitte le programme en demandant si l'on veut sauvegarder son programme 
        """
        
        self.quit()

    def save(self):
        """
        Sauvegarde la courbe dans un fichier
        """
        data = cPickle.dump(self.curveX)
        print "sauvegarde du fichier"
        print data
コード例 #8
0
ファイル: oscilloscope.py プロジェクト: Akanoa/CAI2014
class Oscilloscope(Frame):
    """ Oscilloscope 

    time : valeur de la base de temps
    signaux : liste de couples, (temps,elongation) ou (elongation X, elongation Y)  de signaux
    screen : ecran de visualisation de signaux
    time_control : controle de la base de temps
    signal_control : controle d'un signal
    """
    def __init__(self, parent=None, width=800, height=800):
        """ initialisation

        parent : une application
        width,height : dimension de l'oscilloscpe
        """
        Frame.__init__(self)
        self.master.title("Oscilloscope")
        # Modele
        self.time = 0
        self.signal = None
        # Vues
        self.menuBar         = MenuBar(parent=self)
        self.screen          = Screen(parent=self)
        self.frame = Frame(master=self)
        # Controleurs
        self.time_control = TimeBase(parent=self)
        self.signal_controlX = Generator(parent=self, name="X", color="red")
        self.signal_controlY = Generator(parent=self, name="Y", color="blue")
        # Affichage Vues, Controleurs
        self.menuBar.pack()
        self.screen.pack()

        self.signal_controlX.pack(side="left")
        self.signal_controlY.pack(side="left")
        self.time_control.pack()

        self.configure(width=width, height=height)

    def get_time(self):
        """valeur courante de la base de temps."""
        return self.time_control.get_time()

    def update_time(self, time):
        """demande de calcul de signal si modification de la base de temps"""
        if self.time != time:
            self.time = time
            self.signal_controlX.update_signal(None)
            self.signal_controlY.update_signal(None)

    def set_signal(self, name="X", signal=None):
        """ demande d'affichage de signal

        name : nom de la courbe (X,Y, X-Y)
        signal : liste des couples (temps,elongation) ou (elongation X, elongation Y)
        """
        print("Base de Temps :", self.get_time())
        msdiv = self.get_time()
        if signal :
            signal = signal[0:(len(signal)/msdiv) + 1]
            signal = map(lambda (x, y): (x*msdiv, y), signal)
            self.screen.plot_signal(name, signal)
        return signal
コード例 #9
0
ファイル: oscilloscope.py プロジェクト: Akanoa/CAI2014
class Oscilloscope(Frame):
    """ Oscilloscope 

    time : valeur de la base de temps
    signaux : liste de couples, (temps,elongation) ou (elongation X, elongation Y)  de signaux
    screen : ecran de visualisation de signaux
    time_control : controle de la base de temps
    signal_control : controle d'un signal
    """
    def __init__(self, parent=None, width=800, height=800):
        """ initialisation

        parent : une application
        width,height : dimension de l'oscilloscpe
        """
        Frame.__init__(self)
        self.master.title("Oscilloscope")
        # Modelethreading.Thread(None, affiche, None, (200,), {'nom':'thread a'}) 
        self.time = 0
        self.signal = None
        # # Vues
        # self.menuBar         = MenuBar(parent=self)
        # self.screen          = Screen(parent=self)
        # self.frame = Frame(master=self)
        # # Controleurs
        # self.time_control = TimeBase(parent=self)
        # self.signal_controlX = Generator(parent=self, name="X", color="red")
        # self.signal_controlY = Generator(parent=self, name="Y", color="blue")
        # # Affichage Vues, Controleurs
        # self.menuBar.pack()
        # self.screen.pack()

        # self.signal_controlX.pack(side="left")
        # self.signal_controlY.pack(side="left")
        # self.time_control.pack()

        # Vues
        self.menuBar          = MenuBar(parent=self)
        self.screenT          = Screen(parent=self)
        self.screenXY         = Screen(parent=self)
        # Controleurs
        self.signal_controlX = Generator(parent=self, name="X", color="red")
        self.signal_controlY = Generator(parent=self, name="Y", color="blue")
        self.signal_controlXY = Generator(parent=self, name="XY", color="blue")
        self.time_control = TimeBase(parent=self)
        self.varX  = IntVar()
        self.varY  = IntVar()
        self.varXY = IntVar()
        self.showX = Checkbutton(parent, text="X", variable=self.varX, command=lambda: self.update_show("X"))
        self.showY = Checkbutton(parent, text="Y", variable=self.varY, command=lambda: self.update_show("Y"))
        self.showXY = Checkbutton(parent, text="XY", variable=self.varXY, command=lambda: self.update_show("XY"))
        self.varX.set(1)
        self.varY.set(1)
        self.varXY.set(1)

        # Affichage Vues, Controleurs
        self.menuBar.grid(column=0, row=0)
        self.screenT.grid(column=0,row=1)
        self.screenXY.grid(column=1,row=1)
        self.signal_controlX.grid(column=0, row=2)
        self.signal_controlY.grid(column=0, row=3)
        self.time_control.grid(column=0, row=4)

        self.showX.grid(column=1, row=2)
        self.showY.grid(column=1, row=3)
        self.showXY.grid(column=1, row=4)

        self.configure(width=width, height=height)

    def get_time(self):
        """valeur courante de la base de temps."""
        return self.time_control.get_time()

    def update_time(self, time):
        """demande de calcul de signal si modification de la base de temps"""
        if self.time != time:
            self.time = time
            self.signal_controlX.update_signal(None)
            self.signal_controlY.update_signal(None)

    def set_signal(self, name="X", signal=None , color =None):
        """ demande d'affichage de signal

        name : nom de la courbe (X,Y, X-Y)
        signal : liste des couples (temps,elongation) ou (elongation X, elongation Y)
        """
        #print("Base de Temps :", self.get_time())
        msdiv = self.get_time()
        if signal :
            signal = signal[0:(len(signal)/msdiv) + 1]
            signal = map(lambda (x, y): (x*msdiv, y), signal)

            #Search if the signal need to be shown
            self.screenT.change_signal(name, signal,color)

            listCurveScreenT = self.screenT.listCurve

            if len(listCurveScreenT) > 1:
                listCurveX = listCurveScreenT[0]
                listCurveY = listCurveScreenT[1]

                curveXY= []
                for i in range(len(listCurveX)-1):
                    #create a new curve using the elongation of X & Y curves
                    curveXY.append((listCurveX[1][i][1]+0.05,listCurveY[1][i][1]))
                self.screenXY.change_signal("XY", curveXY, "green")
        return signal

    def update_show(self, name= None):
        """
        Function permettant de changer l'état d'une courbe ( affichée ou non) en fonction des checkbox
        """
        #print "EtatX", self.varX.get(), " EtatY" , self.varY.get(), " EtatY" , self.varXY.get()
        #print name

        if name == "X":
            self.screenT.show_curve(name, self.varX.get())
        elif name =="Y":
            self.screenT.show_curve(name, self.varY.get())
        elif name =="XY":
            self.screenXY.show_curve(name, self.varXY.get())
        #self.signal_controlX.update_signal(None)
        #self.signal_controlY.update_signal(None)

    def exit(self):
        """
        Prend en charge l'appui sur la croix pour quitter l'application, va stopper les threads
        """
        if tkMessageBox.askokcancel("Quitter l'application?", "Etes vous sur de vouloir quitter l'application oscilloscope?"):
            self.screenT.stop_draw()
            self.screenXY.stop_draw()
            self.master.quit()
コード例 #10
0
class Oscilloscope(Frame):
    """ 
    Modele d'Oscilloscope 

    time : valeur de la base de temps
    signal : liste de couples, (temps,elongation) ou (elongation X, elongation Y)  de signaux
    view : visualisation de signaux
    control_X : controle d'un signal
    control_time : controle de la base de temps
    """
    def __init__(self, parent=None, width=800, height=800):
        """ 
        Initialisation

        parent : une application
        width,height : dimension de l'oscilloscpe
        """
        Frame.__init__(self)
        self.master.title("Oscilloscope - Diquélou - Toscer")

        # doit-on afficher la courbe de lissajoux
        self.drawXY = IntVar()
        
        # Modele
        self.time = 0
        # gestion des signaux X et Y
        self.signal_X   = None
        self.signal_Y   = None
        self.signal_XY = None
        # Vues
        self.view = Screen(parent=self)
        self.lissajoux = Screen(parent= self)
        # Controleurs
        self.control_time = TimeBase(parent=self)
        self.control_X = Generator(self,'X')
        self.control_Y = Generator(self, 'Y')



        # menu
        menuBar = MenuBar(self)
        menuBar.pack(fill="x");

        # Affichage Vues, Controleurs
        self.view.pack(fill="both")

        self.control_time.pack(side="left", fill="y")
     
        self.control_X.pack(side="left",fill="y")

        self.lissajoux.pack(fill="both", side="left", expand=1)

        self.control_Y.pack(side="right", fill="both")

        self.configure(width=width, height=height)
        self.master.protocol("WM_DELETE_WINDOW", self.quitter)

        
    def get_time(self):
        """
        recuperer la valeur courante de la base de temps
        """
        return self.control_time.get_time()

    def update_time(self, time):
        """
        calcul de signal si modification de la base de temps

        time : nouvelle valeur de la base de temps
        """
        if self.time != time:
            self.time = time
            self.control_X.update_signal(None)
            self.control_Y.update_signal(None)
            

    def plot_all(self):
        """
        affiche tous les signaux
        """
        self.update_view('X',self.control_X.signal)
        self.update_view('Y',self.control_Y.signal)
        self.update_view('XY',self.control_X.signal)

    def update_view(self, name="X", signal=None):
        """ demande d'affichage de signal

        name : nom de la courbe (X,Y, X-Y)
        signal : liste des couples (temps,elongation) ou (elongation X, elongation Y)
        """
        print("Base de Temps :", self.get_time())
        msdiv = self.get_time()
        if signal :
            if name!='XY':
                signal = signal[0:(len(signal)/msdiv) + 1]
                signal = map(lambda (x, y): (x*msdiv, y), signal)
                
                self.view.plot_signal(name, signal)

            else:
                self.signal_XY = []
                for i in range(0, len(self.control_X.signal)):
                    self.signal_XY.append((self.control_X.signal[i][1],self.control_Y.signal[i][1]))
                self.lissajoux.plot_signal('XY',self.signal_XY)
        return signal


    
    def about(self):
        """
        Affiche les infos des créateurs
        """
        tkMessageBox.showinfo('Super oscilloscope',
                                 'v0.1.5\n\n\tYoann Diquélou\n\tLeïla Toscer\n\n# Copyright (C) 2015 by ENIB-CAI')

    def save(self):
        """
        Sauvegarde la courbe
        sauvegarde au format temps|amplitude|frequence|phase
        """
        print "Oscilloscope.save()"
        saveTxt = {}
        saveTxt["timebase"] = self.time
        saveTxt["graphs"] = []
        saveTxt["graphs"].append( self.getGraphInfos(self.control_X))
        saveTxt["graphs"].append( self.getGraphInfos(self.control_Y))
        filename = tkFileDialog.asksaveasfilename(title="Sauvegarder un graphe", filetypes=[('oscillographe file','.osc'),('all files', '.*')])
        print json.dumps(saveTxt, indent=4)
        if filename:
            file = open(filename,'w')
            file.write(json.dumps(saveTxt, indent=4))
            #file.write(str(self.time)+'|'+str(self.control_X.drawVar.get())+'|'+str(self.control_Y.drawVar.get())+'\n'+str(self.control_X.scale_A.get())+'|'+str(self.control_X.scale_F.get())+'|'+str(self.control_X.scale_P.get())+'|\n'+str(self.control_Y.scale_A.get())+'|'+str(self.control_Y.scale_F.get())+'|'+str(self.control_Y.scale_P.get())+'|\n')
            # fermeture du fichier
            file.close()

    def load(self):
        """
        Charger la courbe
        """
        print "Oscilloscope.load()"
        file = tkFileDialog.askopenfile(title="Ouvrir un graphe", filetypes=[('oscillographe file','.osc'),('all files', '.*')])
        if file:
            #data = file.readline().rstrip('\r\n')
            # vérification que le texte est en accord avec le format
            #            regex = re.compile('^[0-9]{1,2}\|[0-9]{1,2}\|[0-9]{1,2}\|[0-9]{1,2}$')
            # regex = re.compile('^([0-9]{1,2}\|){4}$')
            # if(regex.match(data)):
            #     print "Format ok, loading\n"
            #     a = re.split('\|+', data, flags = re.IGNORECASE)
            #     self.control_time.scale_time.set(int(a[0]))
            #     self.control_X.scale_A.set(int(a[1]))
            #     self.control_X.scale_F.set(int(a[2]))
            #     self.control_X.scale_P.set(int(a[3]))
            # else:
            #     print "Fichier incorrect"
            #     tkMessageBox.showerror('ERREUR',
            # 'Entrez un fichier valide, merci.')
            format = json.load(file)
            self.control_time.scale_time.set( format["timebase"])
            for i in range(0 ,len(format["graphs"])):
                eval('self.control_'+format["graphs"][i]["name"]+'.scale_A.set('+str(format["graphs"][i]["amp"])+')')
                eval('self.control_'+format["graphs"][i]["name"]+'.scale_F.set('+str(format["graphs"][i]["freq"])+')')
                eval('self.control_'+format["graphs"][i]["name"]+'.scale_P.set('+str(format["graphs"][i]["phi"])+')')
                if format["graphs"][i]["active"]==1:
                    eval('self.control_'+format["graphs"][i]["name"]+'.draw.select()')
                else:
                    eval('self.control_'+format["graphs"][i]["name"]+'.draw.deselect()')



                # if format["graphs"][i]["name"] == 'X':
                #     self.control_X.scale_A.set(format["graphs"][i]["amp"])
                #     self.control_X.scale_F.set(format["graphs"][i]["freq"])
                #     self.control_X.scale_P.set(format["graphs"][i]["phi"])
                #     if format["graphs"][i]["active"]==1:
                        
                #         self.control_X.draw.select()
                #     else:
                #         self.control_X.draw.deselect()
                # else:
                #     self.control_Y.scale_A.set(format["graphs"][i]["amp"])
                #     self.control_Y.scale_F.set(format["graphs"][i]["freq"])
                #     self.control_Y.scale_P.set(format["graphs"][i]["phi"])
                #     if format["graphs"][i]["active"]==1:
                #         self.control_Y.draw.select()
                #     else:
                #         self.control_Y.draw.deselect()

            file.close()


    def getGraphInfos(self, graph):
        graphique = {}
        graphique["name"] = graph.name
        graphique["active"] = graph.drawVar.get()
        graphique["amp"] = graph.scale_A.get()
        graphique["freq"] = graph.scale_F.get()
        graphique["phi"] = graph.scale_P.get()
        return graphique
            
    def quitter(self):
        """
        Affiche une boite de dialogue pour que l'utilisateur confirme son souhait de quitter
        """
        if tkMessageBox.askyesno('Quitter',
                                 'voulez-vous quitter?'):
            print "Oscilloscope.quitter()"
            self.quit()