コード例 #1
0
ファイル: clock.py プロジェクト: greyzero/starcal
 def update(self):
     if self.running:
         timeout_add(time_rem(), self.update)
         if self.local:
             self.set_label(strftime(self.format))
         else:
             self.set_label(strftime(self.format, time.gmtime()))
コード例 #2
0
ファイル: armve_controller.py プロジェクト: bauna/vot.ar
    def registrar(self, tag, solo_impimir=False, crypto_tag=None):
        """Registra un voto.

        Argumentos:
            tag -- el voto a registrar serializado como tag.
            solo_impimir -- no guarda el tag, solo imprime.
        """
        ret = {"status": "OK"}
        marcar_ro = QUEMA

        if solo_impimir:
            tag_guardado = True
        else:
            if crypto_tag is None:
                crypto_tag = tag

            tag_guardado = self.guardar_tag(TAG_VOTO, crypto_tag, marcar_ro)

        if tag_guardado:
            def _inner():
                seleccion = Seleccion.desde_string(tag)
                self.imprimir_serializado("Seleccion", seleccion, True)
            timeout_add(10, _inner)
        else:
            ret['status'] = "TAG_NO_GUARDADO"

        return dumps(ret)
コード例 #3
0
ファイル: timeline.py プロジェクト: ubuntu-ir/starcal
	def updateMovingAnim(self, f1, t0, t1, v0, a1):
		t2 = now()
		f = self.movingF
		if f!=f1:
			return
		v1 = self.movingV
		if f==0 and v1==0:
			return
		timeout = movingKeyTimeoutFirst if t2-t0<movingKeyTimeoutFirst else movingKeyTimeout
		if f!=0 and t2 - self.movingLastPress >= timeout:## Stopping
			f = self.movingF = 0
		if v1 > 0:
			a2 = f - movingFrictionForce
		elif v1 < 0:
			a2 = f + movingFrictionForce
		else:
			a2 = f
		if a2 != a1:
			return self.updateMovingAnim(f, t2, t2, v1, a2)
		v2 = v0 + a2*(t2-t0)
		if v2 > movingMaxSpeed:
			v2 = movingMaxSpeed
		elif v2 < -movingMaxSpeed:
			v2 = -movingMaxSpeed
		if f==0 and v1*v2 <= 0:
			self.movingV = 0
			return
		timeout_add(movingUpdateTime, self.updateMovingAnim, f, t0, t2, v0, a2)
		self.movingV = v2
		self.timeStart += v2 * (t2-t1) * self.timeWidth/float(self.get_allocation().width)
		self.queue_draw()
コード例 #4
0
ファイル: armve_service.py プロジェクト: bauna/vot.ar
    def reset_device(self, number):
        """Resetea el dispositivo.

        Argumentos:
            number -- el numero de dispositivo a reiniciar.
        """
        logger.info("Reinicializando dispositivo %s", number)
        self.power_manager.set_leds(7, 1, 200, 1000)
        func = None
        if number == DEV_AGENT:
            func = self.initialize
        elif number == DEV_PWR:
            func = self._eventos_power
        elif number == DEV_PRINTER:

            def _inner():
                self._eventos_impresora()
                self._set_autofeed()
                self._set_print_quality()

            func = _inner
        elif number == DEV_RFID:
            func = self._eventos_rfid

        if func is not None:
            timeout_add(100, func)
コード例 #5
0
    def _consultar(self, datos_tag, serial, force=False):
        """Cuando se apolla una boleta con datos. Mostramos el contenido."""
        # si no estamos ya consultando un voto o no forzamos la muestra.
        if self.estado != E_CONSULTANDO or force:
            # si ese tag tiene datos
            if datos_tag is not None and len(datos_tag) > 0:
                def _fin():
                    """Se llama en el final de la consulta."""
                    if self.estado == E_CONSULTANDO:
                        sigue = False
                        # Si el papel esta insertado se expulsa, sin embargo
                        # si está apoyada el acta hacemos que siga consultando
                        # nuevamente
                        if self.rampa.tiene_papel:
                            self.rampa.expulsar_boleta()
                        else:
                            tag = self.sesion.lector.get_tag()
                            if tag is not None:
                                # ok, vamos de nuevo por que la persona esta
                                # todavia chequeando. lo forzamos para que
                                # renueve
                                sigue = True
                                self._consultar(tag['datos'], tag['serial'],
                                                True)
                        if not sigue:
                            # reseteo el estado del tag por si no me llega el
                            # evento.
                            self.rampa.datos_tag = None
                            self.pantalla_insercion()

                seleccion_tag = None
                try:
                    seleccion_tag = Seleccion.desde_tag(datos_tag,
                                                        self.sesion.mesa)
                    if seleccion_tag is not None \
                            and not len(seleccion_tag.candidatos_elegidos()):
                        # Si el tag no esta vacio pero no tiene candidatos.
                        seleccion_tag = None
                    elif seleccion_tag is not None and \
                            seleccion_tag.serial != bytes(serial, "utf8"):
                        seleccion_tag = None
                except Exception as e:
                    # Esto maneja la instancia de que alguien quiera meter
                    # un voto que no cumple con las condiciones requeridas.
                    self.logger.error("La boleta no contiene datos validos")
                    self.logger.exception(e)
                    self.rampa.expulsar_boleta()
                    _fin()

                # Si el tag es validos arrancamos la consulta del voto.
                if seleccion_tag is not None:
                    self.set_estado(E_CONSULTANDO)
                    self.controlador.consulta(seleccion_tag)
                    timeout_add(self.tiempo_verificacion, _fin)
            else:
                # si la boleta que se ingresó no es un voto la expulsamos.
                self.rampa.expulsar_boleta()
コード例 #6
0
ファイル: controlador.py プロジェクト: bauna/vot.ar
 def _inicializa_pantalla(self):
     """Inicializa la pantalla de previsualizacion de la apertura."""
     if self.sesion._tmp_apertura is not None:
         imagen_acta = self.sesion._tmp_apertura.a_imagen(svg=True,
                                                          de_muestra=True)
         imagen_data = quote(imagen_acta.encode("utf-8"))
         self.set_pantalla_confirmacion(imagen_data)
     else:
         timeout_add(100, self.modulo.salir)
コード例 #7
0
ファイル: button.py プロジェクト: ubuntu-ir/starcal
	def onPressRemain(self, func, counter):
		if counter == self.counter and now() - self.pressTm >= ui.timeout_repeat / 1000:
			func()
			timeout_add(
				ui.timeout_repeat,
				self.onPressRemain,
				self.doTrigger,
				self.counter,
			)
コード例 #8
0
ファイル: registrador.py プロジェクト: bauna/vot.ar
 def _imprimir_acta(self):
     """Efectivamente manda a imprimir el acta."""
     def _imprimir():
         self.sesion.logger.info("Imprimiendo acta de Apertura.")
         tipo_tag = self.sesion._tmp_apertura.__class__.__name__
         tag = self.sesion._tmp_apertura.a_tag()
         self.sesion.impresora.imprimir_serializado(tipo_tag,
                                                    b64encode(tag))
     timeout_add(100, _imprimir)
コード例 #9
0
ファイル: button.py プロジェクト: goodosuser/starcal
 def onPressRemain(self, func, counter):
     if counter == self.counter and now() - self.pressTm >= ui.timeout_repeat / 1000:
         func()
         timeout_add(
             ui.timeout_repeat,
             self.onPressRemain,
             self.doTrigger,
             self.counter,
         )
コード例 #10
0
ファイル: clock.py プロジェクト: greyzero/starcal
 def update(self):
     if self.running:
         timeout_add(time_rem(), self.update)
         if self.seconds:
             l = '%.2d:%.2d:%.2d'%tuple(localtime()[3:6])
         else:
             l = '%.2d:%.2d'%tuple(localtime()[3:5])
         if self.bold:
             l = '<b>%s</b>'%l
         self.set_label(l)
コード例 #11
0
ファイル: adjust_dtime.py プロジェクト: ilius/starcal
 def updateTimes(self):
     dt = now() % 1
     timeout_add(iceil(1000 * (1 - dt)), self.updateTimes)
     # print('updateTimes', dt)
     lt = localtime()
     self.label_cur.set_label(_("Current:") + " %.4d/%.2d/%.2d - %.2d:%.2d:%.2d" % lt[:6])
     if not self.editTime:
         self.timeInput.set_value(lt[3:6])
     if not self.editDate:
         self.dateInput.set_value(lt[:3])
     return False
コード例 #12
0
ファイル: button.py プロジェクト: ubuntu-ir/starcal
	def onPress(self, widget, event=None):
		self.pressTm = now()
		self.doTrigger()
		self.counter += 1
		timeout_add(
			ui.timeout_initial,
			self.onPressRemain,
			self.doTrigger,
			self.counter,
		)
		return True
コード例 #13
0
ファイル: rfid_controller.py プロジェクト: bauna/vot.ar
    def consultar_lector(self, funcion):
        logger.debug("Registrando callback lector %s", funcion)

        def _inner(tipo_tag, datos):
            funcion(tipo_tag, datos)

        lector = self._get_lector()
        if lector is not None:
            self.remover_consultar_lector()
            self._signal_tag = lector.connect_to_signal("tag_leido", _inner)
        else:
            timeout_add(1000, self._intentar_conectar, _inner)
コード例 #14
0
ファイル: registrador.py プロジェクト: bauna/vot.ar
 def _imprimir_acta(self, tipo_acta):
     """Imprime las actas."""
     def _imprimir():
         encoded_data = b64encode(self.sesion.recuento.a_tag(tipo_acta[1]))
         extra_data = self._get_extra_data(tipo_acta)
         try:
             self.sesion.impresora.imprimir_serializado(
                 "Recuento", encoded_data, extra_data=extra_data)
         except DBusException:
             # ignorando posible timeout de dbus para carga de buffer
             # el zen de python me pide que lo haga explicito :D
             pass
     timeout_add(100, _imprimir)
コード例 #15
0
ファイル: controlador.py プロジェクト: bauna/vot.ar
    def confirmar_seleccion(self, data):
        """Confirma la seleccion. Manda a imprimir."""
        def _inner():
            if self.modulo.rampa.tiene_papel:
                self.modulo._guardar_voto()
                self.reiniciar_seleccion()
            else:
                self.reiniciar_seleccion()
                self.modulo.pantalla_insercion()

        # Lo tiramos asincronico con un timeout por que si queda en el mismo
        # thread no actualiza la UI hasta que termina de cargar el buffer de
        # impresion, y si se extiende mucho puede tirar un segfault.
        timeout_add(50, _inner)
コード例 #16
0
ファイル: __init__.py プロジェクト: bauna/vot.ar
    def _fin_registro(self):
        """Se llama cuando se termina de registrar un voto."""
        self.logger.info("Se muestra la pantalla de mensaje final")
        self.estado = E_ESPERANDO
        self.set_pantalla(PANTALLA_MENSAJE_FINAL)
        self.rampa.tiene_papel = False

        def _retornar():
            """Retorna a la pantalla de insercion de voto."""
            self.logger.info("Se llamó a la funcion retornar")
            if self.estado not in (E_CONSULTANDO, E_VOTANDO, E_REGISTRANDO):
                self.pantalla_insercion()

        # Se muestra el mensaje de agradecimiento durante 6 segundos
        timeout_add(6000, _retornar)
コード例 #17
0
ファイル: registrador.py プロジェクト: bauna/vot.ar
    def _imprimir_acta(self, data_sensores):
        """Manda a imprimir el acta."""
        if not self._imprimiendo:
            self._imprimiendo = True
            self.sesion.impresora.remover_insertando_papel()
            self.sesion.impresora.remover_consultar_tarjeta()

            self.logger.info("Imprimiendo acta")
            if self.callback_imprimiendo is not None:
                self.logger.info("callback_imprimiendo")
                self.callback_imprimiendo(self.acta_actual, self._finalizado)
            # tiramos este timeout por que sino no actualiza el panel de estado
            timeout_add(200, self._impresion_real)
        else:
            self.logger.warning("Frenado intento de impresion concurrente")
コード例 #18
0
ファイル: timeline.py プロジェクト: ubuntu-ir/starcal
	def currentTimeUpdate(self, restart=False, draw=True):
		if restart:
			try:
				source_remove(self.timeUpdateSourceId)
			except AttributeError:
				pass
		try:
			pixelPerSec = self.pixelPerSec
		except AttributeError:
			pixelPerSec = 1
		seconds = iceil(0.4/pixelPerSec)
		tm = now()
		#print('time=%.2f'%(tm%100), 'pixelPerSec=%.1f'%pixelPerSec, 'seconds=%d'%seconds)
		miliSeconds = int(1000*(seconds + 0.01 - tm%1))
		miliSeconds = min(miliSeconds, 4294967295)
		# to avoid: OverflowError: %d not in range 0 to 4294967295
		self.timeUpdateSourceId = timeout_add(
			miliSeconds,
			self.currentTimeUpdate,
		)
		self.currentTime = int(tm)
		if draw and self.get_parent():
			if self.get_parent().get_visible() and \
			self.timeStart <= tm <= self.timeStart + self.timeWidth + 1:
				#print('%.2f'%(tm%100), 'currentTimeUpdate: DRAW')
				self.queue_draw()
コード例 #19
0
    def cambio_tag(self, tipo_tag, tag_dict):
        """ Callback de cambio de tag.

        Argumentos:
            tipo_tag -- el tipo de tag
            tag_dict -- los datos del tag
        """
        if tag_dict is not None:
            if tipo_tag == TAG_ADMIN:
                timeout_add(500, self.salir)
            elif tipo_tag == TAG_COLISION:
                self.expulsar_boleta()
                self.tag_colision()

        if tag_dict != self.datos_tag:
            self.datos_tag = tag_dict
            self.maestro()
コード例 #20
0
ファイル: rampa.py プロジェクト: bauna/vot.ar
    def cambio_tag(self, tipo_tag, tag_dict):
        """ Callback de cambio de tag.

        Argumentos:
            tipo_tag -- el tipo de tag
            tag_dict -- los datos del tag
        """
        if tag_dict is not None:
            if tipo_tag == TAG_ADMIN:
                timeout_add(500, self.salir)
            elif tipo_tag == TAG_COLISION:
                self.expulsar_boleta()
                self.tag_colision()

        if tag_dict != self.datos_tag:
            self.datos_tag = tag_dict
            self.maestro()
コード例 #21
0
ファイル: registrador.py プロジェクト: bauna/vot.ar
    def _registrar_voto(self, solo_impimir=False):
        """La funcion que explicitamente manda a registrar el voto."""
        logger = self.modulo.sesion.logger
        logger.info("Registrando voto.")
        fallo = False
        impresora = self.modulo.sesion.impresora

        def fin_de_la_impresion(estado=None):
            """Callback que se llama cuando se terminó de imprimir una BUE."""
            logger.info("Terminó de imprimir.")
            if not self._evento_ya_lanzado:
                logger.info("Rehookeando eventos.")
                self._evento_ya_lanzado = True
                impresora.remover_insertando_papel()
                rampa = self.modulo.rampa
                rampa.tiene_papel = False
                impresora.registrar_insertando_papel(rampa.cambio_sensor_2)
                if not fallo:
                    logger.info("Llamando al callback post impresión.")
                    self.callback()
            return False

        self._evento_ya_lanzado = False
        # hookeo el evento, pero tambien agrego un timeout para asegurarme de
        # que si por alguna razón no salta el evento de fin de impresión sigue
        # su curso y asume que la sesion de impresión terminó. El manejo del
        # error de esto se hace mas abajo y es syncronico, a diferencia de
        # esto que es asincronico.
        if impresora is not None:
            impresora.remover_insertando_papel()
            impresora.registrar_insertando_papel(fin_de_la_impresion)
            timeout_add(10000, fin_de_la_impresion)

            logger.info("Enviando comando de impresion.")
            self.seleccion.serial = \
                bytes(self.modulo.rampa.datos_tag['serial'], "utf8")
            respuesta = impresora.registrar(self.seleccion, solo_impimir)
            logger.info("Fin del registro.")
            if respuesta['status'] == "TAG_NO_GUARDADO":
                logger.error("Recibido el mensaje de tag no guardado.")
                fallo = True
                self.callback_error()
        else:
            fallo = True
            self.callback_error()
コード例 #22
0
    def _registrar_voto(self, solo_impimir=False):
        """La funcion que explicitamente manda a registrar el voto."""
        logger = self.modulo.sesion.logger
        logger.info("Registrando voto.")
        fallo = False
        impresora = self.modulo.sesion.impresora

        def fin_de_la_impresion(estado=None):
            """Callback que se llama cuando se terminó de imprimir una BUE."""
            logger.info("Terminó de imprimir.")
            if not self._evento_ya_lanzado:
                logger.info("Rehookeando eventos.")
                self._evento_ya_lanzado = True
                impresora.remover_insertando_papel()
                rampa = self.modulo.rampa
                rampa.tiene_papel = False
                impresora.registrar_insertando_papel(rampa.cambio_sensor_2)
                if not fallo:
                    logger.info("Llamando al callback post impresión.")
                    self.callback()
            return False

        self._evento_ya_lanzado = False
        # hookeo el evento, pero tambien agrego un timeout para asegurarme de
        # que si por alguna razón no salta el evento de fin de impresión sigue
        # su curso y asume que la sesion de impresión terminó. El manejo del
        # error de esto se hace mas abajo y es syncronico, a diferencia de
        # esto que es asincronico.
        if impresora is not None:
            impresora.remover_insertando_papel()
            impresora.registrar_insertando_papel(fin_de_la_impresion)
            timeout_add(10000, fin_de_la_impresion)

            logger.info("Enviando comando de impresion.")
            self.seleccion.serial = \
                bytes(self.modulo.rampa.datos_tag['serial'], "utf8")
            respuesta = impresora.registrar(self.seleccion, solo_impimir)
            logger.info("Fin del registro.")
            if respuesta['status'] == "TAG_NO_GUARDADO":
                logger.error("Recibido el mensaje de tag no guardado.")
                fallo = True
                self.callback_error()
        else:
            fallo = True
            self.callback_error()
コード例 #23
0
ファイル: rampa.py プロジェクト: bauna/vot.ar
    def cambio_tag(self, tipo_tag, tag_dict):
        """ Callback de cambio de tag.

        Argumentos:
            tipo_tag -- el tipo de tag
            tag_dict -- los datos del tag
        """
        if tag_dict is not None:
            if tag_dict['tipo'] == TAG_APERTURA:
                datos_tag = tag_dict['datos']
                self.modulo._configurar_mesa_apertura(datos_tag)
            elif tipo_tag == TAG_ADMIN:
                timeout_add(500, self.modulo.salir_a_modulo, MODULO_INICIO)
            elif tipo_tag == TAG_COLISION:
                self.expulsar_boleta()
                self.tag_colision()

        if tag_dict != self.datos_tag:
            self.datos_tag = tag_dict
            self.maestro()
コード例 #24
0
ファイル: armve_service.py プロジェクト: bauna/vot.ar
    def _service_init(self):
        """Inicializacion real del canal y corrida del service loop."""
        logger.info("corriendo el canal, inicializando el service loop")

        def _service_loop():
            """El loop del servicio. Se corre cada 100ms."""
            try:
                if self.buffer is not None and self.device is not None:
                    arm_data = self.device.read(True)
                    if arm_data is not None:
                        response, device_id, command_id, response_type = \
                            arm_data
                        self._process_arm_data(response, device_id, command_id,
                                               response_type)
                else:
                    self.connect_and_load()
            except (SerialException, TypeError):
                logger.error("problema de lectura del canal, desconectando")
                self._reset_connection()
            return True

        timeout_add(100, _service_loop)

        if self._usa_fan:
            timeout_add(10000, self.temp_manager)

        if self._usa_pir:
            timeout_add(10000, self.backlight_manager)
コード例 #25
0
ファイル: __init__.py プロジェクト: bauna/vot.ar
    def procesar_tag_apertura(self, tag_dict):
        """Procesa el tag que se apoya en el lector."""
        read_only = tag_dict.get("read_only")
        if tag_dict['datos'] == b'' and not read_only:
            if self.controlador.estado == E_INGRESO_ACTA and \
                    self.rampa.tiene_papel:
                self.apertura = None
                self.sesion.apertura = None

                con_datos = self.config("con_datos_personales")
                if con_datos:
                    self.cargar_datos()
                else:
                    self.crear_objeto([], None)

        elif tag_dict['tipo'] != TAG_APERTURA:
            self.controlador.set_mensaje(_("acta_contiene_informacion"))

            def _expulsar():
                self.controlador.set_mensaje(self.controlador.MSG_APERTURA)
                self.sesion.impresora.expulsar_boleta()
            timeout_add(1500, _expulsar)
コード例 #26
0
ファイル: rampa.py プロジェクト: bauna/vot.ar
    def maestro(self):
        """El maestro de ceremonias, el que dice que se hace y que no."""
        if self.datos_tag is not None:
            if self.datos_tag['tipo'] == TAG_VOTO:
                self.modulo._consultar(self.datos_tag['datos'],
                                       self.datos_tag['serial'])
            elif self.tiene_papel and self.datos_tag['tipo'] == TAG_VACIO:
                self.modulo.hay_tag_vacio()
            elif self.datos_tag['tipo'] in (TAG_APERTURA, TAG_RECUENTO):
                self.expulsar_boleta()
            elif self.modulo.estado != E_ESPERANDO:
                self.modulo.pantalla_insercion()
        elif self.tiene_papel:
            def _expulsar():
                self.datos_tag = self.sesion.lector.get_tag()
                if self.tiene_papel and self.datos_tag is None:
                    self.modulo.pantalla_insercion()
                    self.expulsar_boleta()
            timeout_add(300, _expulsar)

        elif self.modulo.estado not in (E_REGISTRANDO, E_CONSULTANDO,
                                        E_ESPERANDO):
            self.modulo.pantalla_insercion()
コード例 #27
0
ファイル: controlador.py プロジェクト: bauna/vot.ar
    def inicio_mantenimiento(self):
        """Corre el inicio de los datos del modulo de mantenimiento."""
        self.get_volume()
        self.get_brightness()
        self.get_rfid_antenna_level()
        self.get_build()
        self.get_fan_mode(True)
        self.get_fan_speed()
        self.get_temperature()
        self.get_power_source()
        self.get_pir_status()
        self.get_pir_mode(True)
        self.send_command("inicio_mantenimiento")

        self.timeout_bateria = timeout_add(10000, self.get_battery_status)
        self.send_command("inicio_intervals")
コード例 #28
0
ファイル: __init__.py プロジェクト: bauna/vot.ar
    def _configurar_mesa_apertura(self, datos_tag):
        """
        Configura la mesa con los datos que contiene el tag.
        """
        apertura = Apertura.desde_tag(datos_tag)

        def _salir():
            """Estamblece la apertura y la mesa en la sesion y sale al menu."""
            apertura.mesa = self.sesion.mesa
            self.sesion.apertura = apertura
            self.rampa.desregistrar_eventos()
            self.salir_a_menu()

        if apertura.mesa is not None:
            if apertura.mesa.numero == self.sesion.mesa.numero:
                self.sesion.impresora.expulsar_boleta()
                self.sesion.impresora.consultar_tarjeta(
                    lambda x: timeout_add(500, _salir))
            else:
                self.controlador.set_mensaje(_("acta_mesa_erronea"))
                self.rampa.expulsar_boleta()
コード例 #29
0
ファイル: clock.py プロジェクト: greyzero/starcal
 def update(self):
     if self.running:
         timeout_add(time_rem(), self.update)
         self.set_label(strftime(self.format))
コード例 #30
0
ファイル: __init__.py プロジェクト: ubuntu-ir/starcal
	def _arrow_press(self, plus):
		self.pressTm = now()
		self._remain = True
		timeout_add(ui.timeout_initial, self._arrow_remain, plus)
		self.entry_plus(plus)
コード例 #31
0
ファイル: __init__.py プロジェクト: ubuntu-ir/starcal
	def _arrow_remain(self, plus):
		if self.get_editable() and self._remain and now()-self.pressTm>=ui.timeout_repeat/1000.0:
			self.entry_plus(plus)
			timeout_add(ui.timeout_repeat, self._arrow_remain, plus)
コード例 #32
0
ファイル: __init__.py プロジェクト: bauna/vot.ar
 def reimprimir(self, *args):
     timeout_add(100, self.controlador.reimprimir)
コード例 #33
0
ファイル: registrador.py プロジェクト: bauna/vot.ar
 def _hide_and_try(status):
     rampa.remover_nuevo_papel()
     self.modulo.hide_dialogo()
     self.modulo.controlador.mostrar_imprimiendo()
     timeout_add(100, self.registrar)