def test_FlowManager(self): network = { "openflow:1": Switch("openflow:1"), "openflow:3": Switch("openflow:3") } fm = flow_manager.FlowManager(network=network, solution=None, controller_address=TEST_SERVER) fm.network["openflow:1"].add_flow("0", Flow("0")) fm.network["openflow:1"].remove_flow("0", "0")
def main(self, debug): print('### RotaryEncoderListener demo') self.rel = RotaryEncoderListener(self.pin_re, self.cb_re, debug=debug) self.sw = Switch(self.pin_sw, debug=debug) self.sl = SwitchListener([self.sw], self.cb_sw, debug=debug) self.start_sec = time.time() self.loop_flag = True while self.loop_flag: time.sleep(1) self.sl.stop() self.rel.stop() print('') print('### RotaryKey demo') self.rek = RotaryKey(self.pin_re, self.pin_sw, self.cb_rk, debug=debug) self.loop_flag = True while self.loop_flag: time.sleep(1) self.rek.stop() print('') print('### Finished')
def addSwitch(): SwitchQueue = Queue() name = input("Enter the name of the Switch in Single small Letter") switch = Switch(SwitchQueue, "Active", name) toSwitchConnectionObjects = switch.toHostPipe() NETWORK_Connection_Register[1].append( (name, switch, toSwitchConnectionObjects))
def __init__(self, pin, valq, loop_interval, debug=False): ''' @param pin [pin1, pin2] @param valq value queue @param loop_interval sec @param debug debug flag ''' self.logger = init_logger(__class__.__name__, debug) self.logger.debug('pin:%s', pin) if len(pin) != 2: return None self.pin = pin self.valq = valq self.loop_interval = loop_interval self.switch = [] for p in self.pin: sw = Switch(p, timeout_sec=[], debug=debug) self.switch.append(sw) self.stat = [-1, -1] self.sl = SwitchListener(self.switch, self.cb, self.loop_interval, debug=debug)
def run_latency(warmup_time_s, upstream_ip, upstream_port, duration_s, ssl): switch = Switch(DPID("00:00:00:00:00:00:00:01"), warmup_time_s, upstream_ip, upstream_port, 1, False, ssl) switch.start() time.sleep(duration_s) print("stop!") switch.stop() FileWriter().write_results_to_file(switch.get_results())
def __init__(self, pin_led, pin_sw, debug=False): print('pin_led:%d' % pin_led) print('pin_sw :%d' % pin_sw) self.pin_led = pin_led self.pin_sw = pin_sw self.long_press = [ { 'timeout': 0.7, 'blink': { 'on': 1, 'off': 0 } }, # multi click { 'timeout': 1, 'blink': { 'on': 0.2, 'off': 0.04 } }, # blink1 { 'timeout': 3, 'blink': { 'on': 0.1, 'off': 0.04 } }, # blink2 { 'timeout': 5, 'blink': { 'on': 0.02, 'off': 0.04 } }, # blink3 { 'timeout': 7, 'blink': { 'on': 0, 'off': 0 } } ] # end self.timeout_sec = [] for i in range(len(self.long_press)): self.timeout_sec.append(self.long_press[i]['timeout']) self.sw = Switch(self.pin_sw, self.timeout_sec, debug=debug) self.sl = SwitchListener([self.sw], self.sw_callback, debug=debug) self.led = Led(self.pin_led) self.active = True
def __addElements(self, top): self.__topLevel = top self.__topLevelWindow = top.getTopLevel() self.__topLevelWindow.protocol('WM_DELETE_WINDOW', self.__closeWindow) from Switch import Switch self.__banks = [] for num in range(3, 9): testbank = Switch(self.__loader, self.__topLevel, self.__topLevelWindow, num, self.__banks) self.__banks.append(testbank)
def __init__(self): GPIO.setup(pin_dir, GPIO.OUT) GPIO.setup(pin_step, GPIO.OUT) print("pins set up") self.inches = 0 self.switch = Switch() self.start = time.time() self.lc = lcm.LCM()
def criar_ambiente_sw(): sw = Switch(24, '192.168.2.1', '255.255.255.0', '22:22:11:22') sinet.initialize(sw) sinet.connect(client_1) sinet.connect(client_2) sinet.connect(client_3) sinet.run(Message(client_1.address, client_3.address, u'Pacote ICMP')) sinet.run(Message(client_1.address, client_3.address, u'Pacote ICMP')) sinet.run(Message(client_1.address, client_2.address, u'Pacote ICMP')) sinet.run(Message(client_1.address, client_2.address, u'Pacote ICMP')) sinet.run(Message(client_2.address, client_3.address, u'Pacote ICMP')) sinet.run(Message(client_3.address, client_2.address, u'Pacote ICMP'))
def main(self): totalSwitches = int(input("How many switches you want?")) self.switches = [] for i in range(totalSwitches): totalPorts = int( input("Enter total number of ports for switch " + str(i) + ":")) self.switches.append(Switch(i, totalPorts)) print("Now time for connection configuration") for i in range(totalSwitches): print("Ports configuration for switch ", i) for j in range(self.switches[i].ports): a = int(input("Enter other switch ID:")) b = int(input("Enter other switch's port ID:")) self.switches[i].portsConf[j] = ["", a, b] for i in range(self.switches[0].ports): self.switches[0].portsConf[i][0] = "dp" #for first time root ports setting oppPorts = self.getOppositePorts("dp", self.switches[0]) listKeys = list(oppPorts.keys()) #keys of oppPorts dict self.rootSelectionFromRoot(oppPorts, listKeys) #get list of switches jin ke root port set ni hoi basic rp setting k bad nonRootList = self.getNonRootSwitches() #set nonRoot switche's port to rp one by one if nonRootList: portsDist = {} for i in range(len(nonRootList)): portsDist = {} currentSwitch = self.switches[nonRootList[i]] for j in range(currentSwitch.ports): currentPort = currentSwitch.portsConf[j] portsDist[j] = self.setRPOfNonROOT(currentSwitch, currentPort, dist=0) #work for dp print("thanks")
def __init__(self,id,ip,binaad,binaid): self.id = id self.ip = ip self.binaid = binaid self.binaad = binaad SnmpProtocol2 = SnmpProtocol() switches = [] stmt = SnmpProtocol2.execute(ip, '1.3.6.1.2.1.4.22.1.1', '"INTEGER: 28"') eachline = stmt.splitlines () for i in eachline: a = (i.split ('.')) if (a[14].split (' ')[0] != '1'): ip =a[11] + "." + a[12] + "." + a[13] + "." + a[14].split (' ')[0] switch = Switch(ip) switches.append(switch) self.switches = switches
def __init__(self, pin_re, pin_sw, cb_func, chl=CH_LIST, debug=False): self.logger = init_logger(__class__.__name__, debug) self.logger.debug('pin_re:%s', pin_re) self.logger.debug('pin_sw:%d', pin_sw) self.logger.debug('chl :%s', chl) self.pin_re = pin_re self.pin_sw = pin_sw self.cb_func = cb_func self.chl = chl self.chl_len = len(self.chl) self.chl_i = 0 self.cur_ch = self.CH_LIST[self.chl_i] self.out_ch = '' self.rl = RotaryEncoderListener(self.pin_re, self.cb_re, debug=debug) self.sw = Switch(self.pin_sw, debug=debug) self.sl = SwitchListener([self.sw], self.cb_sw, debug=debug)
def __init__(self, encoder_left: Encoder, encoder_right: Encoder, imu: IMU): ### Switch On/Off self.switch_OnOff = Switch() ### Encoders self.encoder_left = encoder_left self.encoder_right = encoder_right ### IMU self.imu = imu ### PID self.PID_stab = PID(self.P_stab, self.I_stab, self.D_stab) self.PID_position = PID(self.P_position, self.I_position, self.D_position) ### Motors self.Motors = Motors()
if __name__ == "__main__": db = Database('127.0.0.1', 'root', '', 'ilab') print "Sit back and relax will take some time..." print "(DO NOT CTRL+C)" strfile = '%ssw_details.log' % defn.log_dir cli_cmd = 'rm %s' % (strfile) subprocess.call(cli_cmd, shell=True) fout = file(strfile, 'a') logging.basicConfig(filename=strfile, format='%(asctime)s: %(levelname)s : %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.DEBUG) switches = db.select('switches_test',None,'*') for switch in switches sw = Switch(switch_name = str(switch['switch_name']), \ console_ip = str(switch['console_ip']), \ mgmt_ip = str(switch['mgmt_ip']), \ act_port = str(switch['active_port']), \ stnd_port = str(switch['standby_port']), \ switch_pwd = str(switch['switch_pwd']), \ console_pwd = 'nbv123', \ log = strfile, \ kick = str(switch['kickstart']), \ sys = str(switch['system'])) switch_details(db,sw,fout) print "Collected all the Current Details"
log.quiet = options.quiet options.rate = if_else(options.verbose, options.rate, max(options.rate, 0.1)) options.version = VERSION options.max_update_time = 60 options.device = tokenize(options.device, 'device', []) options.cutoff_temp = tokenize(options.cutoff_temp, 'cutoff_temp', [95], float) options.cutoff_interval = tokenize(options.cutoff_interval, 'cutoff_interval', [0.01], float) switch = None try: switch = Switch(options) if not options.no_ocl: import OpenCLMiner for miner in OpenCLMiner.initialize(options): switch.add_miner(miner) if not options.no_bfl: import BFLMiner for miner in BFLMiner.initialize(options): switch.add_miner(miner) if not switch.servers: print '\nAt least one server is required\n' elif not switch.miners: print '\nNothing to mine on, exiting\n'
TCP_PORT = 5091 SUCCESS_MSG = 'Data transfer succesful' def createSocket(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((SERVER_IP, TCP_PORT)) s.listen(1) return s def acceptConnection(socket): connection, address = socket.accept() print 'Server accessed by:', address[0] + " on port " + str(address[1]) return connection socket = createSocket() switch = Switch(17) while True: print('Waiting for connection...') connection = acceptConnection(socket) data = connection.recv(1024) print "Receieved Data:", data if data == "ON": switch.flipSwitchOn() switch.getState() elif data == "OFF": switch.flipSwitchOff() switch.getState() else:
def __init__(self): self._lamp = Light() self._switchUp = FlipUpCommand(self._lamp) self._switchDown = FlipDownCommand(self._lamp) self._switch = Switch(self._switchUp, self._switchDown)
from StepperMotor import Grua from Electroiman import Magnet from Encoder import Encoder from Estado import Estado from Switch import Switch from Robot import Robot from multiprocessing import Process from time import sleep, time from pdb import set_trace import pigpio import serial #Componentes del Robot suicheD = Switch(9, 10) #Suiche izquierdo suicheI = Switch(24, 25) #Suiche Derecho motores = Motors(26, 20) # Pines GPIO20 y GPIO26 grua = Grua(19, 16, 18, 17) magnet = Magnet(23, 22) robot = Robot() arduino = Arduino() def foundLevel(state): """Funcion que indica cuanto debe subir la grua dependiendo de su estado. ARGUMENTOS: state: Estado del robot. """
#!/usr/bin/env python import sys import yaml import Command from Task import Task from Switch import Switch from Variables import Variables from Result import Result with open(sys.argv[2]) as f: yml = yaml.load(f, Loader=yaml.SafeLoader) with open('/Users/hirano.shigetoshi/fzfyml_list.txt', 'a') as f: f.write(sys.argv[2] + '\n') variables = Variables(sys.argv) switch = Switch(yml.get('switch_task', {}), variables) base_task = Task(yml['base_task'], variables, switch.get_expect()) task = base_task if sys.argv[1] == 'run': while True: r = Command.execute(task.get_cmd()) result = Result(r, task.get_transform()) if result.is_empty(): break if switch.has(result.key): variables.set_pre_result(result) task = task.create_switch_task(switch.get_switch_dict(result.key)) else: task.output(result) break
pyhg_action = Restore() elif options.action == 'conflicts': from Shelf import Conflicts Conflicts(options) elif options.action == 'push': from Push import Push Push(options) elif options.action == 'mergeheads': from MergeHeads import MergeHeads MergeHeads(options) elif options.action == 'diff': from Diff import Diff Diff(options) elif options.action == 'switch': from Switch import Switch pyhg_action = Switch() if pyhg_action: if not pyhg_action.execute(options): print(pyhg_action.message, file=sys.stderr) result = 1 else: if not pyhg_action.cleanup(options): print(pyhg_action.message, file=sys.stderr) result = 1 if os.name != 'nt': # reset the console colors to defaults print(Colors['Reset']) sys.exit(result)
class StartMaker(): ip = IP() host = [] enlacePP = [] enlacePP = [] switch = [] router = [] nic_host = [] nic_switch = [] nic_router = [] # All Class Objects store in arrays[n] started 0 to n-1 # Start Hosts 0~11 for n in range(0,12): host.append(Host()) # Start Enlace 0~21 for n in range(0,22): enlacePP.append(EnlacePP()) # Start Switchs 0~2 for n in range(0,3): switch.append(Switch()) switch[0].setNome('switch_0') switch[1].setNome('Switch_1') switch[2].setNome('Switch_2') # Start Routers 0~2 for n in range(0,3): router.append(Router()) router[0].setNome('Router_0') router[1].setNome('Router_1') router[2].setNome('Router_2') # Start Hosts-NICs ( 12th ) # NIC receved MAC, Enlace and Host # Network 201.10.0.0 nic_host.append(NIC('01:0A:00:FF:0A:01',enlacePP[0],host[0])) nic_host.append(NIC('02:0A:00:FF:0A:02',enlacePP[1],host[1])) nic_host.append(NIC('03:0A:00:FF:0A:03',enlacePP[2],host[2])) nic_host.append(NIC('04:0A:00:FF:0A:04',enlacePP[3],host[3])) # Network 200.171.0.0 nic_host.append(NIC('05:0B:00:EE:0B:05',enlacePP[5],host[4])) nic_host.append(NIC('06:0B:00:EE:0B:06',enlacePP[6],host[5])) nic_host.append(NIC('07:0B:00:EE:0B:07',enlacePP[7],host[6])) nic_host.append(NIC('08:0B:00:EE:0B:08',enlacePP[8],host[7])) # Network 192.168.0.0 nic_host.append(NIC('09:0C:00:CC:0C:09',enlacePP[10],host[8])) nic_host.append(NIC('0A:0C:00:CC:0C:0A',enlacePP[11],host[9])) nic_host.append(NIC('0B:0C:00:CC:0C:0B',enlacePP[12],host[10])) nic_host.append(NIC('0C:0C:00:CC:0C:0C',enlacePP[13],host[11])) # Start Switchs-NICs ( 15th ) # Nic receved MAC, Enlace and Switch # Switch 0 nic_switch.append(NIC('040A7119SW01',enlacePP[0],switch[0])) nic_switch.append(NIC('040A7119SW02',enlacePP[1],switch[0])) nic_switch.append(NIC('040A7119SW03',enlacePP[2],switch[0])) nic_switch.append(NIC('040A7119SW04',enlacePP[3],switch[0])) # Dedicated Router 0 - Network 201.10.0.0 nic_switch.append(NIC('040A7119SW05',enlacePP[4],switch[0]))# Local Network 201.10.0.0 # Switch 1 nic_switch.append(NIC('040A7119SW06',enlacePP[5],switch[1])) nic_switch.append(NIC('040A7119SW07',enlacePP[6],switch[1])) nic_switch.append(NIC('040A7119SW08',enlacePP[7],switch[1])) nic_switch.append(NIC('040A7119SW09',enlacePP[8],switch[1])) # Dedicated Router 1 - Network 200.171.0.0 nic_switch.append(NIC('0040A7119SW10',enlacePP[9],switch[1]))# Local Network 200.171.0.0 # Switch 2 nic_switch.append(NIC('040A7119SW11',enlacePP[10],switch[2])) nic_switch.append(NIC('040A7119SW12',enlacePP[11],switch[2])) nic_switch.append(NIC('040A7119SW13',enlacePP[12],switch[2])) nic_switch.append(NIC('040A7119SW14',enlacePP[13],switch[2])) # Dedicated Router 2 - 192.168.0.0 nic_switch.append(NIC('040A7119SW15',enlacePP[14],switch[2]))# Local Network 192.168.0.0 # Start Routers-NICs ( 12th ) # Router 0 Networks 10.0.0.0 and 201.10.0.0 nic_router.append(NIC('040A7119SR01',enlacePP[4],router[0])) # Network 201.10.0.0 - Local nic_router.append(NIC('040A7119SR02',enlacePP[15],router[0])) # Network 10.0.0.0 nic_router.append(NIC('040A7119SR03',enlacePP[16],router[0])) # unused nic_router.append(NIC('040A7119SR04',enlacePP[17],router[0])) # unused # Router 1 Networks 10.0.0.0, 11.0.0.0 and 200.171.0.0 nic_router.append(NIC('040A7119SR05',enlacePP[15],router[1])) # Network 10.0.0.0 - 201.10.0.0 nic_router.append(NIC('040A7119SR06',enlacePP[18],router[1])) # Network 11.0.0.0 - 192.168.0.0 nic_router.append(NIC('040A7119SR07',enlacePP[9],router[1])) # Network 200.171.0.0 - Local nic_router.append(NIC('040A7119SR08',enlacePP[19],router[1])) # Internet # Router 2 Networks 11.0.0.0 and 192.168.0.0 nic_router.append(NIC('040A7119SR09',enlacePP[18],router[2])) # Network 11.0.0.0 nic_router.append(NIC('040A7119SR10',enlacePP[14],router[2])) # Network 192.168.0.0 - Local nic_router.append(NIC('040A7119SR11',enlacePP[20],router[2])) # unused nic_router.append(NIC('040A7119SR12',enlacePP[21],router[2])) # unused # Set Routers IP router[0].setIP('201.10.0.1') router[1].setIP('200.171.0.1') router[2].setIP('192.168.0.1') # Adding Routes #router.setRota(Rota('<destination>','<route>','<mask>', '<metric>', '<MAC>')) # Router 0 to Router 1 Network A router[0].setRota(Rota('201.10.0.0','201.10.0.1','255.255.0.0', '0', '040A7119SR01')) # Network 201.10.0.0 - Local router[0].setRota(Rota('200.171.0.0','200.171.0.1','255.255.0.0', '0', '040A7119SR02')) router[0].setRota(Rota('192.168.0.0','192.168.0.1','255.255.0.0', '0', '040A7119SR02')) router[0].setRota(Rota('10.0.0.0','10.0.0.1','255.0.0.0', '0', '040A7119SR02')) router[0].setRotaDefault(Rota('10.0.0.0','10.0.0.1','255.0.0.0', '0', '040A7119SR02')) # Router 1 Network 01, 02 and 04 router[1].setRota(Rota('200.171.0.0','200.171.0.1','255.255.0.0', '0', '040A7119SR07')) # Network 200.171.0.0 - Local router[1].setRota(Rota('201.10.0.0','201.10.0.1','255.255.0.0', '0', '040A7119SR05')) # Network 10.0.0.0 - 201.10.0.0 router[1].setRota(Rota('10.0.0.0','10.0.0.1','255.0.0.0', '0', '040A7119SR05')) # Network 10.0.0.0 - R05 router[1].setRota(Rota('192.168.0.0','192.168.0.1','255.255.0.0', '0', '040A7119SR06')) # Network 11.0.0.0 - 192.168.0.0 router[1].setRota(Rota('11.0.0.0','11.0.0.1','255.0.0.0', '0', '040A7119SR06')) # Network 11.0.0.0 - R06 router[1].setRotaDefault(Rota('0.0.0.0','0.0.0.0','0.0.0.0', '0', 'INTERNET')) # Router 2 Network 02 and 05 router[2].setRota(Rota('192.168.0.0','192.168.0.1','255.255.0.0', '0', '040A7119SR10')) # Network 192.168.0.0 - Local router[2].setRota(Rota('11.0.0.0','11.0.0.1','255.0.0.0', '0', '040A7119SR09')) router[2].setRota(Rota('200.171.0.0','200.171.0.1','255.255.0.0', '0', '040A7119SR09')) router[2].setRota(Rota('201.10.0.0','201.10.0.1','255.255.0.0', '0', '040A7119SR09')) router[2].setRotaDefault(Rota('11.0.0.0','11.0.0.1','255.0.0.0', '0', '040A7119SR09')) # HOSTs reset IPs# for n in range(0,12): host[n].setIP('ip-not-found') host[n].setMascara('255.255.0.0') host[n].setLigado(False) nic_host[n].setLigado(False) nic_host[n].setTDados(False) host[n].resetPing() # SWITCHs reset# switch[0].setLigado(False) for n in range(0,5): nic_switch[n].setLigado(False) nic_switch[n].setTDados(False) switch[1].setLigado(False) for n in range(5,10): nic_switch[n].setLigado(False) nic_switch[n].setTDados(False) switch[2].setLigado(False) for n in range(10,15): nic_switch[n].setLigado(False) nic_switch[n].setTDados(False) # ROUTERs # router[0].setLigado(False) for n in range(0,4): nic_router[n].setLigado(False) nic_router[n].setTDados(False) router[1].setLigado(False) for n in range(4,8): nic_router[n].setLigado(False) nic_router[n].setTDados(False) router[2].setLigado(False) for n in range(8,12): nic_router[n].setLigado(False) nic_router[n].setTDados(False)
from Switch import Switch switch = Switch() switch.main()
def initialiseLists(self): db = sqlite3.connect("./test2.sql") gpio = db.execute(""" SELECT * FROM Gpio """) for row in gpio: gpioType = row[2] pinNumber = row[0] gpioNumber = row[1] label = row[3] if gpioType == 'out': # create a switch switch = Switch(pinNumber, gpioNumber, label, self) #self.gpioList.append(switch) self.gpioLabelMapping[label] = gpioNumber self.gpioMap[gpioNumber] = switch elif gpioType == 'in': # create a contact contact = Contact(pinNumber, gpioNumber, label, self) #self.gpioList.append(contact) self.gpioLabelMapping[label] = gpioNumber self.gpioMap[gpioNumber] = contact elif gpioType == 'PWM': # create a pwm pwm = PWM(pinNumber, gpioNumber, label, self) #self.gpioList.append(pwm) self.gpioLabelMapping[label] = gpioNumber self.gpioMap[gpioNumber] = pwm # else: # print("Skipped pin for now") for gpio in self.gpioMap.values(): if gpio.threadBehavior != None: gpio.threadBehavior.start() table = db.execute(""" SELECT * FROM Alias""") self.gpioAliasMapping = {} for row in table: alias = row[1] gpio = row[2] self.gpioAliasMapping[alias] = gpio self.gpioAliasMapping = { **self.gpioLabelMapping, **self.gpioAliasMapping } print("---------------") print("GPIO Map:") print("---------------") print(self.gpioMap) print("---------------") print("Alias Map:") print("---------------") print(self.gpioAliasMapping) db = sqlite3.connect("./test2.sql") rules = db.execute(""" SELECT * FROM Rules """) for row in rules: ruleGpioTrigger = row[1] ruleGpioNewValue = row[2] ruleTriggeredScript = row[3] if ruleGpioTrigger not in self.ruleTableSwitchType: self.ruleTableSwitchType[ruleGpioTrigger] = [] self.ruleTableSwitchType[ruleGpioTrigger].append( [ruleGpioNewValue, ruleTriggeredScript]) cronJobs = db.execute(""" SELECT * FROM CronJobs """) for row in cronJobs: ruleCronStatement = row[1] ruleTriggeredScript = row[2] if ruleCronStatement not in self.ruleTableCronType: self.ruleTableCronType[ruleCronStatement] = [] self.ruleTableCronType[ruleCronStatement].append( ruleTriggeredScript)
def selectNextActionTyping(self, playerCurrentPokemon, allPlayerPokemon): numRemainingAlivePokemon = 0 remainingAliveIndexList = [] for pokemonNum in range(Constants.NUM_POKEMON_PER_PLAYER): if self.pokemons[pokemonNum] != self.currentPokemon: if self.pokemons[pokemonNum].isAlive(): numRemainingAlivePokemon += 1 remainingAliveIndexList.append(pokemonNum) costList = np.zeros(1 + numRemainingAlivePokemon) oppMultiplierList = np.array([ getMultiplier(playerCurrentPokemon.getMove1().getName(), playerCurrentPokemon, self.currentPokemon), getMultiplier(playerCurrentPokemon.getMove2().getName(), playerCurrentPokemon, self.currentPokemon), getMultiplier(playerCurrentPokemon.getMove3().getName(), playerCurrentPokemon, self.currentPokemon), getMultiplier(playerCurrentPokemon.getMove4().getName(), playerCurrentPokemon, self.currentPokemon) ]) maxOppMultiplier = np.max(oppMultiplierList) # Calculate what is the max damage the AI can do aiMultiplierList = np.array([ getMultiplier(self.currentPokemon.getMove1().getName(), self.currentPokemon, playerCurrentPokemon), getMultiplier(self.currentPokemon.getMove2().getName(), self.currentPokemon, playerCurrentPokemon), getMultiplier(self.currentPokemon.getMove3().getName(), self.currentPokemon, playerCurrentPokemon), getMultiplier(self.currentPokemon.getMove4().getName(), self.currentPokemon, playerCurrentPokemon) ]) maxAIMultiplier = np.max(aiMultiplierList) # compute cost edgeCost = 0 diff = maxAIMultiplier - maxOppMultiplier if diff >= 1.0: edgeCost = 1.0 elif (0 >= diff and diff < 1.0): edgeCost = 2.0 else: edgeCost = 4.0 # compute heuristic minHeuristicCurr = 0 for aiPoke in self.pokemons: if not (aiPoke.isAlive()): continue heuristic = 0 for oppPoke in allPlayerPokemon: if not (oppPoke.isAlive()): continue # Calculate what is the max damage the AI can do damageGiveList = np.array([ calculateDamage(self.currentPokemon.getMove1().getName(), self.currentPokemon, oppPoke), calculateDamage(self.currentPokemon.getMove2().getName(), self.currentPokemon, oppPoke), calculateDamage(self.currentPokemon.getMove3().getName(), self.currentPokemon, oppPoke), calculateDamage(self.currentPokemon.getMove4().getName(), self.currentPokemon, oppPoke) ]) maxDamageDealt = np.max(damageGiveList) # to incentivize staying in, skip current pokemon if you can kill it if oppPoke.getBattleHP() - maxDamageDealt <= 0: continue oppMultiplierList = np.array([ getMultiplier(oppPoke.getMove1().getName(), oppPoke, aiPoke), getMultiplier(oppPoke.getMove2().getName(), oppPoke, aiPoke), getMultiplier(oppPoke.getMove3().getName(), oppPoke, aiPoke), getMultiplier(oppPoke.getMove4().getName(), oppPoke, aiPoke) ]) maxOppMultiplier = np.max(oppMultiplierList) aiMultiplierList = np.array([ getMultiplier(aiPoke.getMove1().getName(), aiPoke, oppPoke), getMultiplier(aiPoke.getMove2().getName(), aiPoke, oppPoke), getMultiplier(aiPoke.getMove3().getName(), aiPoke, oppPoke), getMultiplier(aiPoke.getMove4().getName(), aiPoke, oppPoke) ]) maxAIMultiplier = np.max(aiMultiplierList) diff = maxAIMultiplier - maxOppMultiplier if diff >= 1.0: heuristic += 1.0 elif (0 >= diff and diff < 1.0): heuristic += 2.0 else: heuristic += 4.0 minHeuristicCurr = min(minHeuristicCurr, heuristic) costList[0] = edgeCost + minHeuristicCurr minHeuristicRest = 0 for aiPoke in self.pokemons: if not (aiPoke.isAlive()): continue heuristic = 0 for oppPoke in allPlayerPokemon: if not (oppPoke.isAlive()): continue oppMultiplierList = np.array([ getMultiplier(oppPoke.getMove1().getName(), oppPoke, aiPoke), getMultiplier(oppPoke.getMove2().getName(), oppPoke, aiPoke), getMultiplier(oppPoke.getMove3().getName(), oppPoke, aiPoke), getMultiplier(oppPoke.getMove4().getName(), oppPoke, aiPoke) ]) maxOppMultiplier = np.max(oppMultiplierList) aiMultiplierList = np.array([ getMultiplier(aiPoke.getMove1().getName(), aiPoke, oppPoke), getMultiplier(aiPoke.getMove2().getName(), aiPoke, oppPoke), getMultiplier(aiPoke.getMove3().getName(), aiPoke, oppPoke), getMultiplier(aiPoke.getMove4().getName(), aiPoke, oppPoke) ]) maxAIMultiplier = np.max(aiMultiplierList) diff = maxAIMultiplier - maxOppMultiplier if diff >= 1.0: heuristic += 1.0 elif (0 >= diff and diff < 1.0): heuristic += 2.0 else: heuristic += 4.0 minHeuristicRest = min(minHeuristicRest, heuristic) # repeat for switching indexInCostList = 1 for i in remainingAliveIndexList: aiPoke = self.pokemons[i] oppMultiplierList = np.array([ getMultiplier(playerCurrentPokemon.getMove1().getName(), playerCurrentPokemon, aiPoke), getMultiplier(playerCurrentPokemon.getMove2().getName(), playerCurrentPokemon, aiPoke), getMultiplier(playerCurrentPokemon.getMove3().getName(), playerCurrentPokemon, aiPoke), getMultiplier(playerCurrentPokemon.getMove4().getName(), playerCurrentPokemon, aiPoke) ]) maxOppMultiplier = np.max(oppMultiplierList) # Calculate what is the max damage the AI can do aiMultiplierList = np.array([ getMultiplier(aiPoke.getMove1().getName(), aiPoke, playerCurrentPokemon), getMultiplier(aiPoke.getMove2().getName(), aiPoke, playerCurrentPokemon), getMultiplier(aiPoke.getMove3().getName(), aiPoke, playerCurrentPokemon), getMultiplier(aiPoke.getMove4().getName(), aiPoke, playerCurrentPokemon) ]) maxAIMultiplier = np.max(aiMultiplierList) edgeCost = 0 diff = maxAIMultiplier - maxOppMultiplier if diff >= 1.0: edgeCost = 1.0 elif (0 >= diff and diff < 1.0): edgeCost = 2.0 else: edgeCost = 4.0 costList[indexInCostList] = edgeCost + minHeuristicRest indexInCostList += 1 # Select the min cost edge minEdgeIndex = np.argmin(costList) if minEdgeIndex == 0: # If the best action is one of the current pokemon moves moveOptions = [ self.currentPokemon.getMove1(), self.currentPokemon.getMove2(), self.currentPokemon.getMove3(), self.currentPokemon.getMove4() ] damageGiveList = np.array([ calculateDamage(self.currentPokemon.getMove1().getName(), self.currentPokemon, playerCurrentPokemon), calculateDamage(self.currentPokemon.getMove2().getName(), self.currentPokemon, playerCurrentPokemon), calculateDamage(self.currentPokemon.getMove3().getName(), self.currentPokemon, playerCurrentPokemon), calculateDamage(self.currentPokemon.getMove4().getName(), self.currentPokemon, playerCurrentPokemon) ]) bestMoveIndex = np.argmax(damageGiveList) return moveOptions[bestMoveIndex] else: # If the best action is switching offset = minEdgeIndex - 1 pokemonToSwitchIndex = remainingAliveIndexList[offset] self.currentPokemon = self.pokemons[pokemonToSwitchIndex] return Switch(pokemonToSwitchIndex)
def selectNextAction(self, playerCurrentPokemon): # Want to select the edge that has min cost # Cost(action) = max damage could receive in current round + -(max damage could give in current round) # Total out edge = 4(moves of current pokemon) + numPokemonAlive(switches to the rest alive pokemon) numRemainingAlivePokemon = 0 remainingAliveIndexList = [] for pokemonNum in range(Constants.NUM_POKEMON_PER_PLAYER): if self.pokemons[pokemonNum] != self.currentPokemon: if self.pokemons[pokemonNum].isAlive(): numRemainingAlivePokemon += 1 remainingAliveIndexList.append(pokemonNum) costList = np.zeros(4 + numRemainingAlivePokemon) # Calculate what is the max damage AI could receive damageReceivedList = np.array([ calculateDamage(playerCurrentPokemon.getMove1().getName(), playerCurrentPokemon, self.currentPokemon), calculateDamage(playerCurrentPokemon.getMove2().getName(), playerCurrentPokemon, self.currentPokemon), calculateDamage(playerCurrentPokemon.getMove3().getName(), playerCurrentPokemon, self.currentPokemon), calculateDamage(playerCurrentPokemon.getMove4().getName(), playerCurrentPokemon, self.currentPokemon) ]) maxDamageReceived = np.max(damageReceivedList) maxDamageReceived = np.ones(4) * maxDamageReceived # Calculate what is the max damage the AI can do damageGiveList = np.array([ calculateDamage(self.currentPokemon.getMove1().getName(), self.currentPokemon, playerCurrentPokemon), calculateDamage(self.currentPokemon.getMove2().getName(), self.currentPokemon, playerCurrentPokemon), calculateDamage(self.currentPokemon.getMove3().getName(), self.currentPokemon, playerCurrentPokemon), calculateDamage(self.currentPokemon.getMove4().getName(), self.currentPokemon, playerCurrentPokemon) ]) costList[:4] = maxDamageReceived - damageGiveList # (4,) damageReceivedSwitchList = np.zeros(numRemainingAlivePokemon) indexInCostList = 4 for index in remainingAliveIndexList: pokemonToSwitch = self.pokemons[index] damageReceivedList = np.array([ calculateDamage(playerCurrentPokemon.getMove1().getName(), playerCurrentPokemon, pokemonToSwitch), calculateDamage(playerCurrentPokemon.getMove2().getName(), playerCurrentPokemon, pokemonToSwitch), calculateDamage(playerCurrentPokemon.getMove3().getName(), playerCurrentPokemon, pokemonToSwitch), calculateDamage(playerCurrentPokemon.getMove4().getName(), playerCurrentPokemon, pokemonToSwitch) ]) maxDamageReceived = np.max(damageReceivedList) costList[indexInCostList] = maxDamageReceived indexInCostList += 1 # Select the min cost edge minEdgeIndex = np.argmin(costList) if minEdgeIndex <= 3: # If the best action is one of the current pokemon moves moveOptions = [ self.currentPokemon.getMove1(), self.currentPokemon.getMove2(), self.currentPokemon.getMove3(), self.currentPokemon.getMove4() ] return moveOptions[minEdgeIndex] else: # If the best action is switching offset = minEdgeIndex - 4 pokemonToSwitchIndex = remainingAliveIndexList[offset] self.currentPokemon = self.pokemons[pokemonToSwitchIndex] return Switch(pokemonToSwitchIndex)
#!/usr/bin/env python3 ''' This program tests whether the switch is working by continuously checking the state, and printing a message when it detects a switch change ''' from Switch import Switch s = Switch() while True: if s.is_changed_state(): print("switch pressed")
def selectNextActionOffensive(self, playerCurrentPokemon, allPlayerPokemon): # Want to select the edge that has min cost # Cost(action) = max damage could receive in current round + -(max damage could give in current round) # Total out edge = 4(moves of current pokemon) + numPokemonAlive(switches to the rest alive pokemon) numRemainingAlivePokemon = 0 remainingAliveIndexList = [] for pokemonNum in range(Constants.NUM_POKEMON_PER_PLAYER): if self.pokemons[pokemonNum] != self.currentPokemon: if self.pokemons[pokemonNum].isAlive(): numRemainingAlivePokemon += 1 remainingAliveIndexList.append(pokemonNum) costList = np.zeros(1 + numRemainingAlivePokemon) opponentsHPLeft = 0 for pokemonNum in range(Constants.NUM_POKEMON_PER_PLAYER): if allPlayerPokemon[pokemonNum].isAlive(): opponentsHPLeft += allPlayerPokemon[pokemonNum].getBattleHP() # Calculate what is the max damage the AI can do damageGiveList = np.array([ calculateDamage(self.currentPokemon.getMove1().getName(), self.currentPokemon, playerCurrentPokemon), calculateDamage(self.currentPokemon.getMove2().getName(), self.currentPokemon, playerCurrentPokemon), calculateDamage(self.currentPokemon.getMove3().getName(), self.currentPokemon, playerCurrentPokemon), calculateDamage(self.currentPokemon.getMove4().getName(), self.currentPokemon, playerCurrentPokemon) ]) for i in range(0, len(damageGiveList)): damageGiveList[i] = min(damageGiveList[i], playerCurrentPokemon.getBattleHP()) bestMoveIndex = np.argmax(damageGiveList) g = playerCurrentPokemon.getBattleHP() - np.max(damageGiveList) heuristic = opponentsHPLeft costList[0] = g + heuristic damageReceivedSwitchList = np.zeros(numRemainingAlivePokemon) indexInCostList = 1 for index in remainingAliveIndexList: pokemonToSwitch = self.pokemons[index] damageGivenList = np.array([ calculateDamage(pokemonToSwitch.getMove1().getName(), pokemonToSwitch, playerCurrentPokemon), calculateDamage(pokemonToSwitch.getMove2().getName(), pokemonToSwitch, playerCurrentPokemon), calculateDamage(pokemonToSwitch.getMove3().getName(), pokemonToSwitch, playerCurrentPokemon), calculateDamage(pokemonToSwitch.getMove4().getName(), pokemonToSwitch, playerCurrentPokemon) ]) for i in range(0, len(damageGivenList)): damageGivenList[i] = min(damageGivenList[i], playerCurrentPokemon.getBattleHP()) g = playerCurrentPokemon.getBattleHP() - np.max(damageGivenList) heuristic = opponentsHPLeft costList[indexInCostList] = g + heuristic indexInCostList += 1 # Select the min cost edge minEdgeIndex = np.argmin(costList) if minEdgeIndex == 0: # If the best action is one of the current pokemon moves moveOptions = [ self.currentPokemon.getMove1(), self.currentPokemon.getMove2(), self.currentPokemon.getMove3(), self.currentPokemon.getMove4() ] return moveOptions[bestMoveIndex] else: # If the best action is switching offset = minEdgeIndex - 1 pokemonToSwitchIndex = remainingAliveIndexList[offset] self.currentPokemon = self.pokemons[pokemonToSwitchIndex] return Switch(pokemonToSwitchIndex)
host = input("Host: ") username = input("Login: "******"host": host, "username": username, "password": password, "secret": password, "device_type": "ubiquiti_edge", } net_connect = Netmiko(**edge1) switch = Switch(interpreter.getDeviceName(net_connect.find_prompt())) switch.addVlanList(net_connect.send_command("show vlan")) switch.addPortToPorts(net_connect.send_command("show vlan port all")) while True: mainMenu.printMenu() choice = input("Choose: ") if choice == "1": for vlan in switch.getVlans(): print(vlan.getDescription() + " " + vlan.getNumber()) elif choice == "2": for port in switch.getPorts(): print(port.getPortNr() + " " + port.getPortVlan()) elif choice == "3": switch = Switch(interpreter.getDeviceName(net_connect.find_prompt())) switch.addVlanList(net_connect.send_command("show vlan"))
def selectNextActionDefensive(self, playerCurrentPokemon, allPlayerPokemon): # Want to select the edge that has min cost # Cost(action) = max damage could receive in current round + -(max damage could give in current round) # Total out edge = 4(moves of current pokemon) + numPokemonAlive(switches to the rest alive pokemon) numRemainingAlivePokemon = 0 remainingAliveIndexList = [] for pokemonNum in range(Constants.NUM_POKEMON_PER_PLAYER): if self.pokemons[pokemonNum] != self.currentPokemon: if self.pokemons[pokemonNum].isAlive(): numRemainingAlivePokemon += 1 remainingAliveIndexList.append(pokemonNum) costList = np.zeros(1 + numRemainingAlivePokemon) currTotalHP = 0 for pokemonNum in range(Constants.NUM_POKEMON_PER_PLAYER): if self.pokemons[pokemonNum].isAlive(): currTotalHP += self.pokemons[pokemonNum].getBattleHP() # Calculate what is the max damage AI could receive damageReceivedList = np.array([ calculateDamage(playerCurrentPokemon.getMove1().getName(), playerCurrentPokemon, self.currentPokemon), calculateDamage(playerCurrentPokemon.getMove2().getName(), playerCurrentPokemon, self.currentPokemon), calculateDamage(playerCurrentPokemon.getMove3().getName(), playerCurrentPokemon, self.currentPokemon), calculateDamage(playerCurrentPokemon.getMove4().getName(), playerCurrentPokemon, self.currentPokemon) ]) for i in range(0, len(damageReceivedList)): damageReceivedList[i] = min(damageReceivedList[i], self.currentPokemon.getBattleHP()) maxDamageReceived = np.max(damageReceivedList) g = maxDamageReceived maxHeuristicCurr = 0 # compute heuristic for aiPoke in self.pokemons: if not (aiPoke.isAlive()): continue maxDamageTaken = 0 for oppPoke in allPlayerPokemon: if not (oppPoke.isAlive()): continue # Calculate what is the max damage the AI can do damageGiveList = np.array([ calculateDamage(self.currentPokemon.getMove1().getName(), self.currentPokemon, oppPoke), calculateDamage(self.currentPokemon.getMove2().getName(), self.currentPokemon, oppPoke), calculateDamage(self.currentPokemon.getMove3().getName(), self.currentPokemon, oppPoke), calculateDamage(self.currentPokemon.getMove4().getName(), self.currentPokemon, oppPoke) ]) maxDamageDealt = np.max(damageGiveList) # to incentivize staying in, skip current pokemon if you can kill it if oppPoke.getBattleHP() - maxDamageDealt <= 0: continue # Calculate what is the max damage AI could receive damageReceivedList = np.array([ calculateDamage(oppPoke.getMove1().getName(), oppPoke, aiPoke), calculateDamage(oppPoke.getMove2().getName(), oppPoke, aiPoke), calculateDamage(oppPoke.getMove3().getName(), oppPoke, aiPoke), calculateDamage(oppPoke.getMove4().getName(), oppPoke, aiPoke) ]) for i in range(0, len(damageReceivedList)): damageReceivedList[i] = min(damageReceivedList[i], aiPoke.getBattleHP()) maxDamageTaken = max(maxDamageTaken, np.max(damageReceivedList)) maxHeuristicCurr += maxDamageTaken costList[0] = g + maxHeuristicCurr maxHeuristicRest = 0 # compute heuristic for aiPoke in self.pokemons: if not (aiPoke.isAlive()): continue maxDamageTaken = 0 for oppPoke in allPlayerPokemon: if not (oppPoke.isAlive()): continue # Calculate what is the max damage AI could receive damageReceivedList = np.array([ calculateDamage(oppPoke.getMove1().getName(), oppPoke, aiPoke), calculateDamage(oppPoke.getMove2().getName(), oppPoke, aiPoke), calculateDamage(oppPoke.getMove3().getName(), oppPoke, aiPoke), calculateDamage(oppPoke.getMove4().getName(), oppPoke, aiPoke) ]) for i in range(0, len(damageReceivedList)): damageReceivedList[i] = min(damageReceivedList[i], aiPoke.getBattleHP()) maxDamageTaken = max(maxDamageTaken, np.max(damageReceivedList)) maxHeuristicRest += maxDamageTaken damageReceivedSwitchList = np.zeros(numRemainingAlivePokemon) indexInCostList = 1 for index in remainingAliveIndexList: pokemonToSwitch = self.pokemons[index] damageReceivedList = np.array([ calculateDamage(playerCurrentPokemon.getMove1().getName(), playerCurrentPokemon, pokemonToSwitch), calculateDamage(playerCurrentPokemon.getMove2().getName(), playerCurrentPokemon, pokemonToSwitch), calculateDamage(playerCurrentPokemon.getMove3().getName(), playerCurrentPokemon, pokemonToSwitch), calculateDamage(playerCurrentPokemon.getMove4().getName(), playerCurrentPokemon, pokemonToSwitch) ]) for i in range(0, len(damageReceivedList)): damageReceivedList[i] = min(damageReceivedList[i], pokemonToSwitch.getBattleHP()) maxDamageReceived = np.max(damageReceivedList) g = maxDamageReceived heuristic = maxHeuristicRest costList[indexInCostList] = g + heuristic indexInCostList += 1 # Select the min cost edge minEdgeIndex = np.argmin(costList) if minEdgeIndex == 0: # If the best action is one of the current pokemon moves # Calculate what is the max damage the AI can do damageGiveList = np.array([ calculateDamage(self.currentPokemon.getMove1().getName(), self.currentPokemon, playerCurrentPokemon), calculateDamage(self.currentPokemon.getMove2().getName(), self.currentPokemon, playerCurrentPokemon), calculateDamage(self.currentPokemon.getMove3().getName(), self.currentPokemon, playerCurrentPokemon), calculateDamage(self.currentPokemon.getMove4().getName(), self.currentPokemon, playerCurrentPokemon) ]) moveOptions = [ self.currentPokemon.getMove1(), self.currentPokemon.getMove2(), self.currentPokemon.getMove3(), self.currentPokemon.getMove4() ] return moveOptions[np.argmax(damageGiveList)] else: # If the best action is switching offset = minEdgeIndex - 1 pokemonToSwitchIndex = remainingAliveIndexList[offset] self.currentPokemon = self.pokemons[pokemonToSwitchIndex] return Switch(pokemonToSwitchIndex)
def OnMenuConnect(self, event): if (self.switch == None): self.switch = Switch(self.config, self.fielddef, self.package) self.switch.online() self.dataFrame.setSwitch(self.switch) self.switch.setTransactionThread(self.dataFrame)