Ejemplo n.º 1
0
 def _init_shm(self, retro_run_id):
     if self.system != 'Snes':
         self.shm = None
         return
     ##### Set up the shared memory segment ##################################################
     # currently only supports Snes
     # Set the identifier that the SNES C code may use to create a shared memory segment
     if retro_run_id is None:
         self.retro_run_id = random.randint(1, 1 << 30)
     else:
         self.retro_run_id = retro_run_id
     os.environ['RETRO_RUN_ID'] = f"{self.retro_run_id}"
     self.shm_key = self.retro_run_id
     shm_size = VISITED_BUFFER_SIZE * WORD_SIZE  # enough to hold 2^15 16-bit words
     try:
         self.shm = ipc.SharedMemory(self.shm_key,
                                     flags=ipc.IPC_CREX,
                                     mode=0o666,
                                     size=shm_size)
     except Exception as e:  # FIXME tighten this except up
         shm = ipc.SharedMemory(self.shm_key, 0, 0)
         ipc.remove_shared_memory(shm.id)
         self.shm = ipc.SharedMemory(self.shm_key,
                                     flags=ipc.IPC_CREX,
                                     mode=0o666,
                                     size=shm_size)
     return
Ejemplo n.º 2
0
 def Disconnect(self):
     try:
         self._shm.detach()
         sysv_ipc.remove_shared_memory(self._shm.id)
     except:
         pass
     finally:
         self.SetConnectionState(False)
    def test_remove_shared_memory(self):
        """Exercise remove_shared_memory()"""
        mem = sysv_ipc.SharedMemory(None, sysv_ipc.IPC_CREX)

        sysv_ipc.remove_shared_memory(mem.id)

        with self.assertRaises(sysv_ipc.ExistentialError):
            sysv_ipc.SharedMemory(mem.key)
Ejemplo n.º 4
0
    def __del__(self):


        # Remove shared memory only if the owner/creator
        #
        if self._is_creator:
            # Debating function vs SharedMemory method; I've
            # seen it done both ways
            if self._memory and self._memory.id:
                sysv_ipc.remove_shared_memory(self._memory.id)
            #self._memory.remove()
        # Otherwise, just detach from the shared memory segment
        #
        elif self._memory:
            self._memory.detach() 
Ejemplo n.º 5
0
    def Process(self):
        # I seed the shared memory with a random value which is the current time.
        what_i_wrote = time.asctime()
        s = what_i_wrote

        #utils.write_to_memory(self.Memory, what_i_wrote)

        utils.say("iteration %d" % self.Cntr)
        self.Cntr += 1

        if not self.Params["LIVE_DANGEROUSLY"]:
            # Releasing the semaphore...
            utils.say("releasing the semaphore")
            self.Semaphore.release()
            utils.say("acquiring the semaphore...")
            self.Semaphore.acquire()

        self.DispatchMsg(utils.read_from_memory(self.Memory))

        if self.State == "IDLE":
            pass
        elif self.State == "INCR":
            pass
        elif self.State == "DECR":
            pass
        elif self.State == "QUIT":
            if not self.Params["LIVE_DANGEROUSLY"]:
                utils.say(
                    "Final release of the semaphore followed by a 5 second pause"
                )
                self.Semaphore.release()
                time.sleep(5)
                # ...before beginning to wait until it is free again.
                utils.say("Final acquisition of the semaphore")
                self.Semaphore.acquire()

            utils.say("Destroying semaphore and shared memory")
            # It'd be more natural to call memory.remove() and semaphore.remove() here,
            # but I'll use the module-level functions instead to demonstrate their use.
            sysv_ipc.remove_shared_memory(self.Memory.id)
            sysv_ipc.remove_semaphore(self.Semaphore.id)
        else:
            sysv_ipc.remove_shared_memory(self.Memory.id)
            sysv_ipc.remove_semaphore(self.Semaphore.id)
Ejemplo n.º 6
0
 def __del__(self):
     if self.shm is not None:
         ipc.remove_shared_memory(self.shm.id)
Ejemplo n.º 7
0
    # What I read must be the md5 of what I wrote or something's gone wrong.
    what_i_wrote = what_i_wrote.encode()

    try:
        assert(s == hashlib.md5(what_i_wrote).hexdigest())
    except AssertionError:
        raise AssertionError("Shared memory corruption after %d iterations." % i)

    # MD5 the reply and write back to Mrs. Conclusion.
    s = s.encode()
    what_i_wrote = hashlib.md5(s).hexdigest()
    utils.write_to_memory(memory, what_i_wrote)


# Announce for one last time that the semaphore is free again so that
# Mrs. Conclusion can exit.
if not params["LIVE_DANGEROUSLY"]:
    utils.say("Final release of the semaphore followed by a 5 second pause")
    semaphore.release()
    time.sleep(5)
    # ...before beginning to wait until it is free again.
    utils.say("Final acquisition of the semaphore")
    semaphore.acquire()

utils.say("Destroying semaphore and shared memory")
# It'd be more natural to call memory.remove() and semaphore.remove() here,
# but I'll use the module-level functions instead to demonstrate their use.
sysv_ipc.remove_shared_memory(memory.id)
sysv_ipc.remove_semaphore(semaphore.id)
Ejemplo n.º 8
0
        what_i_wrote = what_i_wrote.encode()

    try:
        assert(s == hashlib.md5(what_i_wrote).hexdigest())
    except AssertionError:
        flex_utils.raise_error(AssertionError, 
                        "Shared memory corruption after %d iterations." % i)

    # MD5 the reply and write back to Mrs. Conclusion.
    if PY_MAJOR_VERSION > 2:
        s = s.encode()
    what_i_wrote = hashlib.md5(s).hexdigest()
    utils.write_to_memory(memory, what_i_wrote)


# Announce for one last time that the semaphore is free again so that 
# Mrs. Conclusion can exit.
if not params["LIVE_DANGEROUSLY"]:
    utils.say("Final release of the semaphore followed by a 5 second pause")
    semaphore.release()
    time.sleep(5)
    # ...before beginning to wait until it is free again.
    utils.say("Final acquisition of the semaphore")
    semaphore.acquire()

utils.say("Destroying semaphore and shared memory")
# It'd be more natural to call memory.remove() and semaphore.remove() here, 
# but I'll use the module-level functions instead to demonstrate their use.
sysv_ipc.remove_shared_memory(memory.id)
sysv_ipc.remove_semaphore(semaphore.id)
Ejemplo n.º 9
0
 def Cleanup(self):
     sysv_ipc.remove_shared_memory(self.Memory.id)
     sysv_ipc.remove_semaphore(self.Semaphore.id)
def main():
#	instacia das variaveis globais
	global counter
	global shutdown
	global fanPort
	global minFanUpTime
	global refreshRate
	global maxTemp
	global minTemp
	global channel_id
	global write_key
	global tskrefresh
	global lastUpdate
	global channel
	global isRelay
	global onValue
	global offValue
	global useSocCmd
	
#	Carrega as configura??es	
	(fanPort,minFanUpTime,refreshRate,maxTemp,minTemp,channel_id,write_key,tskrefresh,isRelay,useSocCmd) = configs.loadConfig()
	
	if(isRelay):
		onValue = 0
		offValue = 1
	else:
		onValue = 1
		offValue = 0
	
	if(channel_id != -1):
		channel = thingspeak.Channel(id=channel_id,write_key=write_key)
	
	parser = optparse.OptionParser()
	
	parser.add_option("-v", "--version", action="store_true", dest="version",
                  help="Show the software version.", default = False)
				  
	parser.add_option("-c", "--config", action="store_true", dest="config",
                  help="Generates a default config file. WARNING: this can overwrite existing settings file.", default = False)
	
	parser.add_option("--reloadConf", action="store_true", dest="reload",
                  help="Reloads the config file to apply changes.", default = False)
	
	group = optparse.OptionGroup(parser, "Controll Options")
	
	group.add_option("-f", "--force", type="string", nargs = 1, dest="force",
                  help="force the fan to be always ON/OFF", default = "null")
	
	group.add_option("-r", "--restore", action="store_true", dest="restore",
                  help="restore the fan to auto mode", default = False)
	
	parser.add_option_group(group)
	
	group = optparse.OptionGroup(parser, "Status Options")
	  
	group.add_option("-a", "--appear", action="store_true", dest="appear",
                  help="force run even if a process is already running", default=False)
	
	group.add_option("-s", "--status", action="store_true", dest="fanstatus",
                  help="show if the fan is ON/OFF", default=False)
				  
	group.add_option("-t", "--temp", action="store_true", dest="temp",
                  help="shows the current temperature", default=False)
	
	parser.add_option_group(group)
	
	group = optparse.OptionGroup(parser, "Installation Options")
				  
	group.add_option("--install", action="store_true", dest="install",
                  help="makes 'fan' command available to bash command line", default=False)
	
	group.add_option("--uninstall", action="store_true", dest="uninstall",
                  help="uninstall 'fan' command from bash command line", default=False)
				  
	group.add_option("--autoinit", type="string", nargs = 1, dest="autoinit",
                  help="sets the auto init true/false, if true the process will start at boot up", default = "null")
				  
	parser.add_option_group(group)
	
	group = optparse.OptionGroup(parser, "Dangerous Options","Use this options with caution.")
				  
	group.add_option("--clear", action="store_true", dest="clear",
                  help="free shared memory, this may cause some stability issues, try using '--restore' after using this option.", default = False)
				  
	parser.add_option_group(group)
				  
	(options, args) = parser.parse_args()
	
#	para o processo caso o computador comece a desligar
	signal.signal(signal.SIGTERM, stop)
	
	if(options.reload):
		
		try:
			configReload = sysv_ipc.SharedMemory(19021999) #procura a memoria compartilhada
			utils.write_to_memory(configReload,"reload")
			print("The configuration was reloaded.")

		except:
			print("Fail to reload the configuration.")
				
		sys.exit()
		
	elif(options.config):
		try:
			configs.createConfig()
			print('Config file created.')
		
		except:
			print('Fail to create the config file.')
			
		sys.exit()
		
	elif(options.version):
		print("Fan version: %s" % (version))
		sys.exit()
		
	elif(options.clear):
		try:
			setGPIO()
			fanForce = sysv_ipc.SharedMemory(22061995)
			sysv_ipc.remove_shared_memory(fanForce.id)
			print("Memory Cleared.")
		except:
			print("There was no memory to clear.")
		

		GPIO.cleanup(fanPort)
		print("GPIO Cleared.")
			
		sys.exit()
	
	elif(options.install):		
		try:
			installFan()
			print("'fan' was installed to the command line.")
		except:
			print("Fail to install 'fan' to the command line.")
		
		sys.exit()
		
	elif(options.uninstall):		
		try:
			os.remove("/usr/local/bin/fan")
			print("'fan' was removed from command line.")
		except:
			print("Fail to remove 'fan' from command line.")
		
		sys.exit()
		
	elif(options.autoinit == "true"):
		try:
			installAutoInit()
			print("Autoinit set to True, restart your system apply changes.")
		except:
			print("Fail to set Autoinit to True.")
		
		sys.exit()

	elif(options.autoinit == "false"):
		try:
			uninstallAutoInit()
			print("Autoinit set to False")
		except:
			print("Fail to set Autoinit to False.")
		
		sys.exit()
			
	elif(options.autoinit != "null"):
		print("Invalid parameter.")
		print("")
		print("Usage: --autoinit [true/false]")
		sys.exit()
		
#	se receber o comando -a forca abrir uma instancia nova		
	elif (options.appear):
		setGPIO()
#		desliga a fan
		GPIO.output(fanPort,offValue)
	
	elif(options.force == "on"):
		try:
			fanForce = sysv_ipc.SharedMemory(22061995) #procura a memoria compartilhada
			utils.write_to_memory(fanForce,"on")
			setGPIO()
			GPIO.output(fanPort,onValue)
			print("The Fan was forced to be on.")
		except:
			print("Fail forcing fan to be on.")
		
		sys.exit()
		
	elif(options.force == "off"):
		try:
			fanForce = sysv_ipc.SharedMemory(22061995) #procura a memoria compartilhada
			utils.write_to_memory(fanForce,"off")
			setGPIO()
			GPIO.output(fanPort,offValue)
			print("The Fan was forced to be off. WARNING: The fan will not auto turn on anymore.")
		except:
			print("Fail forcing fan to be off.")
		
		sys.exit()
	
	elif(options.force != "null"):
		print("Invalid parameter.")
		print("")
		print("Usage: --force [on/off]")
		sys.exit()
	
	elif(options.restore):

		try:
			fanForce = sysv_ipc.SharedMemory(22061995) #procura a memoria compartilhada
			utils.write_to_memory(fanForce,"default")
			print("The Fan was restored to auto-mode.")

		except:
			print("The Fan was restored to auto-mode.")
		
		sys.exit()
		
	elif(options.fanstatus):
		setGPIO()
		if(GPIO.input(fanPort) == offValue):
			print("The fan is inactive.")
		else:
			print("The fan is active.")
		sys.exit()
	
	elif(options.temp):
		print ("Temperature: %0.2f 'C" % (getTemp()))
		sys.exit()
		
	else:
		parser.error("fan requires an argument.")
		quit()
	
	try:
		fanForce = sysv_ipc.SharedMemory(22061995,sysv_ipc.IPC_CREX) #cria memoria compartilhada
		configReload = sysv_ipc.SharedMemory(19021999,sysv_ipc.IPC_CREX) #cria memoria compartilhada
	except:
		fanForce = sysv_ipc.SharedMemory(22061995) #cria memoria compartilhada
		configReload = sysv_ipc.SharedMemory(19021999) #cria memoria compartilhada
		
	utils.write_to_memory(fanForce,"default")
	utils.write_to_memory(configReload,"default")
	
	try:
		while (shutdown == False):
#			descobre se a fan esta ligada			
			status = GPIO.input(fanPort)
#			se receber um comando de force via console para de rodar
			if(utils.read_from_memory(fanForce) == "default"):
#				se a temperatura for maior ou igual a maxTemp graus liga a fan
				if (getTemp() >= maxTemp):
					if(status == offValue):
#						liga a fan
						GPIO.output(fanPort,onValue)
#						envia o status para o thingspeak
						
						k=0
						
#						aguarda o tempo minimo de execucao da fan
						while(k < minFanUpTime and shutdown == False):	
#							se receber um comando de controle de fan sai da espera
							if(utils.read_from_memory(fanForce) == "default"):
#								envia o status para o thingspeak
								updateThingspeak()
								
								if(utils.read_from_memory(configReload) == "reload"):
									reloadConfigs()
									utils.write_to_memory(configReload,"default")
									
								time.sleep(1)
								k+=1
							else:
								break
						
						counter=0
					else:
						updateThingspeak()
						
						if(utils.read_from_memory(configReload) == "reload"):
									reloadConfigs()
									utils.write_to_memory(configReload,"default")
								
						time.sleep(refreshRate)#apos o tempo minimo ele aguarda o tempo de refresh hate definido
						counter=0
						
#				se estiver no limite da transicao aguarda 2x o refresh rate para desligar a fan, assim evitando liga e desliga de fan			
				elif (counter < 2):
					counter += 1
					time.sleep(refreshRate)
				
				elif (minTemp < getTemp()):
					counter = 0
					updateThingspeak()
					
					if(utils.read_from_memory(configReload) == "reload"):
									reloadConfigs()
									utils.write_to_memory(configReload,"default")
				
				else:
					if(status == onValue):
						GPIO.output(fanPort,offValue)
						
					updateThingspeak()
					if(utils.read_from_memory(configReload) == "reload"):
									reloadConfigs()
									utils.write_to_memory(configReload,"default")
									
					time.sleep(refreshRate)
			else:
				updateThingspeak()
				if(utils.read_from_memory(configReload) == "reload"):
									reloadConfigs()
									utils.write_to_memory(configReload,"default")
				time.sleep(refreshRate)
				
	except KeyboardInterrupt:
		pass
	
	finally:
		GPIO.cleanup(fanPort)
		sysv_ipc.remove_shared_memory(fanForce.id)
		sysv_ipc.remove_shared_memory(configReload.id)
Ejemplo n.º 11
0
 def __del__(self):
     try:
         self._shm.detach()
         sysv_ipc.remove_shared_memory(self._shm.id)
     except:
         pass