Example #1
0
    def __init__(self, *args, **kwargs):
        Switch.__init__(self, *args, **kwargs)

        if type(self.number) == type(''):
            self.number = eval(self.number)
        
        self.house = housemap[self.house.capitalize()]
        self.number = devicemap[self.number]

        self.port = int(self.port)

        # start in off state, must be a way of determining device State ..
        self._power = 'Off'

        try:
            self._port = serial.Serial(self.port,
                                       baudrate = 4800,
                                       bytesize = serial.EIGHTBITS,
                                       parity = serial.PARITY_NONE, 
                                       stopbits = serial.STOPBITS_ONE,
                                       timeout = 1,
                                       xonxoff = 0,
                                       rtscts = 0)
        except serial.SerialException:
            self._port = None
    def parse_sel_switches(self, sel_switches):
        for each_id, switch in sel_switches.iteritems():
            # prepare the switch id
            switch_id = "s" + str(each_id)

            sw = self.get_node_object(switch_id)
            # Check to see if a switch with this id already exists in the graph,
            # if so grab it, otherwise create it
            if not sw:
                sw = Switch(switch_id, self)
                self.graph.add_node(switch_id, node_type="switch", sw=sw)
                self.switch_ids.append(switch_id)
            # Parse out the information about all the ports in the switch
            switch_ports = {}
            for port in switch["ports"]:
                switch_ports[port["portId"]] = Port(sw, port_json=port)

            sw.ports = switch_ports

            # Parse group table if one is available
            if "groups" in sel_switches[each_id]:
                sw.group_table = GroupTable(sw,
                                            sel_switches[each_id]["groups"])

            # Parse all the flow tables and sort them by table_id in the list
            switch_flow_tables = []
            for table_id in sel_switches[each_id]["flow_tables"]:
                switch_flow_tables.append(
                    FlowTable(sw, table_id,
                              sel_switches[each_id]["flow_tables"][table_id]))

            sw.flow_tables = sorted(switch_flow_tables,
                                    key=lambda flow_table: flow_table.table_id)
Example #3
0
def index():
    status_class = Status()
    switch_class = Switch()
    timer_class = Timer()

    # herokuå“ć‹ć‚‰paramsć®å—ć‘å–ć‚Š
    params = request.json
    kadenId = params['kadenId']
    manipulateId = params['manipulateId']
    timerDatetime = params['timerDatetime']

    #ć‚¹ćƒ†ćƒ¼ć‚æć‚¹ē®”ē†å‡¦ē†
    if int(manipulateId) == 0:
        result = status_class.checkStatus(kadenId)
        result = {
            "result": result
        }

    #ONOFF処ē†
    elif int(manipulateId) in [1, 2]:
        onOffData = params
        result = switch_class.Switching(onOffData) #kadenID manipulateId悒ęø”恙
        result = {
            "result": result
        }

    #ć‚æć‚¤ćƒžćƒ¼å‡¦ē†
    elif int(manipulateId) in [3, 4]:
        timer_class = Timer()      
        result = timer_class.timerSetting(params) #kadenId manipulateId,timerDatetime悒ęø”恙
        result = {
            "result": result
        }

    return json.dumps(result, ensure_ascii=False)
Example #4
0
def main():
    global relay_pin

    client = MQTTClient(CLIENT_ID, SERVER)
    client.set_callback(new_msg)

    try:
        client.connect()
    except OSError:
        print("MQTT Broker seems down")
        print("Resetting after 20 seconds")
        time.sleep(20)
        machine.reset()

    client.subscribe(COMMAND_TOPIC)

    # Publish as available once connected
    client.publish(AVAILABILITY_TOPIC, "online", retain=True)

    switch_pin = machine.Pin(5, machine.Pin.IN, machine.Pin.PULL_UP)
    reed_switch = Switch(switch_pin)

    # Initialize state of garage door after booting up
    if switch_pin.value():
        client.publish(STATE_TOPIC, "open", retain=True)
    else:
        client.publish(STATE_TOPIC, "closed", retain=True)

    relay_pin = machine.Pin(4, machine.Pin.OUT, 0)

    try:
        while True:

            reed_switch_new_value = False

            # Disable interrupts for a short time to read shared variable
            irq_state = machine.disable_irq()
            if reed_switch.new_value_available:
                reed_switch_value = reed_switch.value
                reed_switch_new_value = True
                reed_switch.new_value_available = False
            machine.enable_irq(irq_state)

            # If the reed switch had a new value, publish the new state
            if reed_switch_new_value:
                if reed_switch_value:
                    client.publish(STATE_TOPIC, "open")
                else:
                    client.publish(STATE_TOPIC, "closed")

            # Process any MQTT messages
            if client.check_msg():
                client.wait_msg()

            time.sleep_ms(500)

    finally:
        client.publish(AVAILABILITY_TOPIC, "offline", retain=False)
        client.disconnect()
        machine.reset()
Example #5
0
	def _handler_switch_enter(self, ev):
		"""
		Handler for event.EventSwitchEnter
		Add a node to the topology.
		"""
		switch = Switch(ev.switch)
		# Check switch capabilities
		self.switches[ev.switch.dp.id] = switch
		# HARDCODED
		for p in switch.switch.ports:
			if self._check_if_ap_port(p):
				ap_conf = self._get_ap_conf(switch, p)
				switch.is_ap = True
				switch.ap_conf = ap_conf
				self.accesspoints[ev.switch.dp.id] = switch
			elif self._check_if_gw_port(p):
				gw_conf = self._get_gw_conf(switch, p)
				switch.is_gw = True
				switch.gw_conf = gw_conf
				self.gateways[ev.switch.dp.id] = switch
							
		self._initialise_switch_of_tables(switch)

		ev_tu = EventSwitchEnter(switch)
		self.send_event_to_observers(ev_tu)

		ev_tu = EventTopologyUpdate(self.switches)
		self.send_event_to_observers(ev_tu)
		self.logger.info("Switch <" + str(hex(switch.switch.dp.id)) + "> connected")
Example #6
0
def readInitialization(file):
    fid = open(file, "r")
    data = fid.read()
    dataSplit = data.split()
    for i in [0, 2, 4]:
        with Switch(dataSplit[i]) as case:
            if case('Station:'):
                Station = dataSplit[i + 1]
                with Switch(Station) as station:
                    if station('Asian'):
                        delayTime = 0
                    if station('American'):
                        delayTime = 1
                    if station('Persian'):
                        delayTime = 2
                    if station('Italian'):
                        delayTime = 3
                    if station('Latin'):
                        delayTime = 4
#print "Station: ", Station
            if case('ipaddr:'):
                ipaddr = dataSplit[i + 1]
#print "ipaddr: ", ipaddr
            if case('port:'):
                port = int(dataSplit[i + 1])

#print "port: ", port

    return [Station, ipaddr, port, delayTime]
Example #7
0
  def _handle_ConnectionUp (self, event):

      sw = self.switches.get(event.dpid)
      sw_str = dpidToStr(event.dpid)
      log.info("Saw switch com up: %s", sw_str)
      name_str = self.t.id_gen(dpid = event.dpid).name_str()

      if name_str not in self.t.switches():
          log.warn("Ignoring unknown switch %s" % sw_str)
          return

      if sw is None:
          log.info("Added fresh switch %s" % sw_str)
          sw = Switch()
          self.switches[event.dpid] = sw
          sw.connect(event.connection)

      else:
          log.info("Odd - already saw switch %s come up" % sw_str)
          sw.connect(event.connection)
      sw.connection.send(of.ofp_set_config(miss_send_len = MISS_SEND_LEN))
        
      if len(self.switches) == len(self.t.switches()):
          log.info("Woo! All switches up")
          self.all_switches_up = True

          self._save_paths()
          # log.info("self.routeTable : %s" % self.routeTable)
          self._install_paths()
          log.info("Woo! All paths ok")
Example #8
0
 def test_get_switch(self):
     """get by id first the use the name for testing get by name"""
     pw_db = Ponicwatch_db("sqlite3")
     switch1 = Switch(pw_db, id=1)
     self.assertEqual(switch1["switch_id"], 1)
     print("[{}] has the id: {}".format(switch1, switch1["switch_id"]))
     name = switch1["name"]
     switch1 = Switch(pw_db, name=name)
     self.assertEqual(switch1["switch_id"], 1)
Example #9
0
    def __init__(self, args, config, logger):

        api_call = Connector(config, logger)
        sw_api_call = ConnSwitch(config, logger)
        ap_api_call = AccessPoint(config, logger)

        sw = Switch()
        sw.ipv4_address = args.address
        self.upgrade_code(api_call, sw_api_call, ap_api_call, sw, logger)
Example #10
0
    def parse_ryu_switches(self):

        ryu_switches = None

        with open(self.network_configuration.conf_path + "ryu_switches.json",
                  "r") as in_file:
            ryu_switches = json.loads(in_file.read())

        #  Go through each node and grab the ryu_switches and the corresponding hosts associated with the switch
        for dpid in ryu_switches:

            #  prepare a switch id
            switch_id = "s" + str(dpid)

            # Check to see if a switch with this id already exists in the graph,
            # if so grab it, otherwise create it
            sw = self.get_node_object(switch_id)
            if not sw:
                sw = Switch(switch_id, self)
                self.graph.add_node(switch_id, node_type="switch", sw=sw)
                self.switch_ids.append(switch_id)

            # Parse out the information about all the ports in the switch
            switch_ports = {}
            for port in ryu_switches[dpid]["ports"]:
                if port["port_no"] == 4294967294:
                    continue

                if port["port_no"] == "LOCAL":
                    continue

                switch_ports[int(port["port_no"])] = Port(sw, port_json=port)

            if (not ryu_switches[dpid]["ports"]):
                #import pdb; pdb.set_trace()
                ovs_sw = self.network_configuration.mininet_obj.get(switch_id)
                for intf in ovs_sw.intfList():
                    if intf.name != 'lo':
                        new_port_obj = Port(sw, None, intf)
                        switch_ports[new_port_obj.port_number] = new_port_obj

            sw.ports = switch_ports

            # Parse group table if one is available
            if "groups" in ryu_switches[dpid]:
                sw.group_table = GroupTable(sw, ryu_switches[dpid]["groups"])

            # Parse all the flow tables and sort them by table_id in the list
            switch_flow_tables = []
            for table_id in ryu_switches[dpid]["flow_tables"]:
                switch_flow_tables.append(
                    FlowTable(sw, table_id,
                              ryu_switches[dpid]["flow_tables"][table_id]))
                sw.flow_tables = sorted(
                    switch_flow_tables,
                    key=lambda flow_table: flow_table.table_id)
Example #11
0
 def post(self):
     session = Session()
     try:
         switch = Switch()
         switch.pin = int(self.get_argument("pin"))
         switch.description = self.get_argument("description")
         session.add(switch)
         session.commit()
     except Exception as e:
         #log.exception(e)
         session.rollback()
         raise tornado.web.HTTPError(500)
Example #12
0
    def ReInitUI(self):
        if self.layoutData is None:
            return

        if 'layoutName' in self.layoutData:
            self.SetTitle(self.layoutData['layoutName'])

        if "gridOn" in self.layoutData.keys():
            if 1 == self.layoutData['gridOn']:
                self.gridOn = True

        if "fastClockAddress" in self.layoutData.keys():
            self.fcAddress = int(str(self.layoutData['fastClockAddress']), 0)

        for text in self.layoutData['text']:
            newCell = TextCell()
            newCell.setText(text['value'])
            x = int(text['x'])
            y = int(text['y'])
            newCell.setXY(x, y)
            if text['type'] == 'blockname':
                newCell.setColor('#ccffff')
            self.cells.append(newCell)

        for signalconfig in self.layoutData['signals']:
            newSignal = Signal(signalconfig, self.txPacket)
            self.signals.append(newSignal)
            self.cells = self.cells + newSignal.getCells()
            self.clickables[newSignal.getClickXY()] = newSignal.onLeftClick

        for switchconfig in self.layoutData['switches']:
            newSwitch = Switch(switchconfig, self.txPacket)
            self.switches.append(newSwitch)
            self.cells = self.cells + newSwitch.getCells()
            self.clickables[newSwitch.getClickXY()] = newSwitch.onLeftClick

        for blockconfig in self.layoutData['blocks']:
            newBlock = Block(blockconfig, self.txPacket, self.cellXY)
            self.blocks.append(newBlock)
            self.cells = self.cells + newBlock.getCells()

        for cell in self.cells:
            # Build a cell finder
            self.cellXY[(cell.cell_x, cell.cell_y)] = cell

        for cpconfig in self.layoutData['controlPoints']:
            if cpconfig['type'] == 'cp3':
                newCP = ControlPoint_CP3(cpconfig, self.txPacket,
                                         self.getRailroadObject)
            else:
                newCP = ControlPoint(cpconfig, self.txPacket,
                                     self.getRailroadObject)
            self.controlpoints.append(newCP)
Example #13
0
def test(duration=0
         ):  # Runs oscillator, counts interrupts, responds to switches
    if duration:
        print("Test interrupt on pin X8 for {:3d} seconds".format(duration))
    objSched = Sched()  # Requires jumper between pins X7 and X8
    objSched.add_thread(oscillator(1))  # 1Hz
    objSched.add_thread(irqtest_thread())
    Switch(objSched, 'X5', open_func=x5print,
           open_func_args=("Red", ))  # X5 triggers on open
    Switch(objSched, 'X6', x6print, ("Yellow", ))  # X6 triggers on close
    if duration:
        objSched.add_thread(stop(duration, objSched))
    objSched.run()
 def __init__(self,
              host_ip,
              hostname,
              ip_def_gateway,
              vlan_first,
              vlan_end,
              transit_vlan="none",
              transit_vlan_end="none",
              ip_snmp_server="192.168.0.1",
              timezone="5"):
     Switch.__init__(self, host_ip, hostname, ip_def_gateway, vlan_first,
                     vlan_end, transit_vlan, transit_vlan_end,
                     ip_snmp_server, timezone)
Example #15
0
    def __init__(self, filepath, **kwargs):
        super(Homepage, self).__init__(**kwargs)

        self.filepath = filepath
        self.filename = filepath.replace('.', '/').split('/')[-2]

        Window.clearcolor = (0.2, 0.2, 0.2, 1)
        self.color_switch = Switch()
        self.canvas.add(self.color_switch)

        # LEFT IMAGE #
        im = Image.open(filepath).convert("RGBA")
        self.image = im.copy()
        width, height = self.image.size
        self.w_h_ratio = width / height
        self.image_rect = Rectangle(texture=CoreImage(self.filepath).texture)
        self.canvas.add(self.image_rect)

        # CENTER PIXELATED IMAGE & SLIDER #
        self.pixeate_image = im.copy()
        self.pixelate_rect = Rectangle()
        self.canvas.add(self.pixelate_rect)
        self.value = None
        self.pixel_slider = Slider(
            1, ((Window.width - self.image_rect.size[0]) // 2,
                (Window.height - self.image_rect.size[1]) // 2),
            self.pixelate_rect.size)

        self.generate_pressed = False
        self.generate_button = Rectangle(
            texture=CoreImage('./buttons/generate_button.png').texture)
        self.canvas.add(self.generate_button)

        # RIGHT DOMINO IMAGE #
        self.domino_image = Image.new(mode='RGBA',
                                      size=(width, height),
                                      color=(235, 74, 90, 150))
        data = BytesIO()
        self.domino_image.save(data, format='png')
        data.seek(0)
        self.domino_rect = Rectangle(
            texture=CoreImage(BytesIO(data.read()), ext='png').texture)
        self.canvas.add(self.domino_rect)

        self.label = Label()
        self.add_widget(self.label)

        self.imgSmall = None

        self.on_update()
        self.on_layout((Window.width, Window.height))
Example #16
0
def main():  # Programa principal
    # Routers
    RINT = Router('RINT', secret.ENABLE_PASSWORD, secret.CONSOLE_PASSWORD)
    RoExt = Router('RoExt', secret.ENABLE_PASSWORD, secret.CONSOLE_PASSWORD)
    RBor1 = Router('RBor1', secret.ENABLE_PASSWORD, secret.CONSOLE_PASSWORD)
    RBor2 = Router('RBor2', secret.ENABLE_PASSWORD, secret.CONSOLE_PASSWORD)

    #Switches
    SW1 = Switch('SW1', secret.ENABLE_PASSWORD, secret.CONSOLE_PASSWORD)
    SW2 = Switch('SW2', secret.ENABLE_PASSWORD, secret.CONSOLE_PASSWORD)
    SW3 = Switch('SW3', secret.ENABLE_PASSWORD, secret.CONSOLE_PASSWORD)
    SwExt = Switch('SwExt', secret.ENABLE_PASSWORD, secret.CONSOLE_PASSWORD)

    print(SW1.interfaces)
Example #17
0
class BrushCNC():
    def __init__(self):
        self._stepper_x = StepperMotor(defines.STEPPER_X_1,
                                       defines.STEPPER_X_2,
                                       defines.STEPPER_X_3,
                                       defines.STEPPER_X_4)
        self._stepper_y_left = StepperMotor(defines.STEPPER_Y_LEFT_1,
                                            defines.STEPPER_Y_LEFT_2,
                                            defines.STEPPER_Y_LEFT_3,
                                            defines.STEPPER_Y_LEFT_4)
        self._stepper_y_right = StepperMotor(defines.STEPPER_Y_RIGHT_1,
                                             defines.STEPPER_Y_RIGHT_2,
                                             defines.STEPPER_Y_RIGHT_3,
                                             defines.STEPPER_Y_RIGHT_4)
        self._stepper_z = StepperMotor(defines.STEPPER_Z_1,
                                       defines.STEPPER_Z_2,
                                       defines.STEPPER_Z_3,
                                       defines.STEPPER_Z_4)
        self._switch_reset_x = Switch(defines.SWITCH_RESET_X)
        self._switch_reset_y = Switch(defines.SWITCH_RESET_Y)
        self._switch_reset_z = Switch(defines.SWITCH_RESET_Z)

    def zeroing(self):
        """
        Uses the limit switches for each of the motors to bring them all back to a zeroed position
        """
        x_zeroed, y_zeroed, z_zeroed = False, False, False
        self._stepper_x.set_stepper(defines.STEPPER_X_MAX_HZ / 2,
                                    -defines.BOARD_X_LENGTH)
        self._stepper_y_left.set_stepper(defines.STEPPER_Y_MAX_HZ / 2,
                                         -defines.BOARD_Y_LENGTH)
        self._stepper_y_right.set_stepper(defines.STEPPER_Y_MAX_HZ / 2,
                                          -defines.BOARD_Y_LENGTH)
        self._stepper_z.set_stepper(defines.STEPPER_Z_MAX_HZ / 2,
                                    -defines.BOARD_Z_LENGTH)

        while x_zeroed is False or y_zeroed is False or z_zeroed is False:
            if x_zeroed is False and self._switch_reset_x.get_state() is True:
                self._stepper_x.set_stepper(0, 0)
                x_zeroed = True

            if y_zeroed is False and self._switch_reset_y.get_state() is True:
                self._stepper_y_left.set_stepper(0, 0)
                self._stepper_y_right.set_stepper(0, 0)
                y_zeroed = True

            if z_zeroed is False and self._switch_reset_z.get_state() is True:
                self._stepper_z.set_stepper(0, 0)
                z_zeroed = True
def invoke_command_on(input):
    for case in Switch(get_command_from_input(input)):
        if case(QUIT):
            quit()
            break
        if case(PERF):
            break
        if case(QUIT_WITHOUT_SAVE):
            break
        if case(KICK):
            break
        if case(HELP):
            break
        if case(BAN):
            print(
                "This will execute a kick ban. It will then be broadcast to the entire server."
            )
            break
        if case(STATUS):
            print(
                "This will cause the console to print out a partial list of connected clients along with their ping, ip"
            )
            break
        if case(TIME):
            time()
            break
        if case(COMMANDS):
            commands()
            break
        if case():  # default, could also just omit condition or 'if True'
            print(
                "Command not found. For information on the commands, type commands"
            )
Example #19
0
def main():
    pi = pigpio.pi()
    srv = Servo(pi)
    swi = Switch(pi, srv)
    door = Door(pi)

    try:
        while True:
            logger.debug("waiting id card")
            # ć“ć“ć§ć‚«ćƒ¼ćƒ‰čŖ­ćæč¾¼ćæ
            if database.confirm("恓恓恫ē•Ŗ号"), "恓恓恫IDm"):
                srv.open_lock()
                slack.send_slack("恓恓恫ćŖć¾ćˆ")
                time.sleep(10)
                while door.door_status() == door.OPEN:
                    time.sleep(0.5)
                srv.close_lock()
            else:
                led.red_led_on()
                print("Can't confirm.")
                time.sleep(3)
                led.red_led_off()
    except:
        pi.stop()
        r.close()
        main()
Example #20
0
    def create_switches(self):
        '''
        Create switches with definition in the config file
        '''

        switches = []
        for name in self.config.sections():
            if name != "COMMON":
                sid = name

                other_options = dict(self.config.items(sid, vars))

                if self.config.has_option(name, "active"):
                    del other_options["active"]
                    if not self.config[name].getboolean("active"):
                        continue

                if not self.config.has_option(name, "timeout"):
                    raise Exception("switch doesn't have timeout set")

                del other_options["timeout"]
                timeout = int(self.config[name]["timeout"])

                to_file = True
                if self.config.has_option(name, "to_file"):
                    del other_options["to_file"]
                    to_file = self.config[name].getboolean("to_file")

                sw = Switch(sid, timeout, to_file, **other_options)
                switches.append(sw)

                if len(switches) > self.num_switches:
                    break

        return switches
 def menupresidente(self):
     layout_presidente = [
         [sg.Text("Menu Presidente")],
         [
             sg.ReadButton("Cadastrar Presidente"),
             sg.ReadButton("Listar Presidentes")
         ],
         [
             sg.ReadButton("Excluir Presidente"),
             sg.ReadButton("Editar Presidente")
         ],
     ]
     window = sg.Window("Gerenciar presidente",
                        default_button_element_size=(15, 1),
                        auto_size_buttons=False,
                        grab_anywhere=False).Layout(layout_presidente)
     botao, valor = window.Read()
     with Switch(valor) as case:
         if case('Criar'):
             self.cadastrar_presidente()
         if case('Editar'):
             self.cadastrar_presidente()
         if case('Excluir'):
             self.cadastrar_presidente()
         if case('Listar'):
             self.cadastrar_presidente()
    def cadastrar_presidente(self):
        layout_criar = [[sg.Text("Cadastrar aluno")],
                        [
                            sg.Text('Nome', size=(15, 1)),
                            sg.InputText('', key='nome', size=(15, 1))
                        ],
                        [
                            sg.Text('Matricula', size=(15, 1)),
                            sg.InputText('', key='matricula', size=(15, 1))
                        ],
                        [
                            sg.Text('CPF', size=(15, 1)),
                            sg.InputText('', key='cpf', size=(15, 1))
                        ],
                        [
                            sg.Text('Senha', size=(15, 1)),
                            sg.InputText('', key='senha', size=(15, 1))
                        ],
                        [sg.ReadButton("Cadastrar"),
                         sg.ReadButton("Voltar")]]
        window = sg.Window("Gerenciar Aluno").Layout(layout_criar)
        event, valor = window.Read()
        with Switch(valor) as case:
            if case('Cadastrar'):
                nome = valor['nome']
                matricula = valor['matricula']
                cpf = valor['cpf']
                senha = valor['senha']
                self.__ctrlPresidente.inclui_presidente(
                    self.__ctrlPresidente, nome, matricula, cpf, senha)

            if case('Voltar'):
                TelaPresidente.menupresidente(self)
Example #23
0
    def __init__(self, env, period):
        super(STFQ_tb, self).__init__(env, period)

        self.sched_alg = "STFQ"
        self.sched_tree_shape = {0: []}
        self.switch = Switch(self.env, self.period, self.sw_ready_out_pipe, self.sw_pkt_in_pipe, self.sw_pkt_out_pipe, self.start_dequeue_pipe, self.sched_tree_shape, self.sched_alg)

        # start dequeueing immediately
        self.start_dequeue_pipe.put(1)

        # create flows
        rates = [10, 13, 20, 25]
        num_flows = len(rates)
        base_sport = 0
        self.generators = []
        self.pkt_gen_pipes = []
        for i in range(num_flows):
            pipe = simpy.Store(env)
            rate = rates[i] # Gbps
            pkt = Ether()/IP()/TCP(sport=base_sport+i)/('\x00'*10)
            meta = StdMetadata(len(pkt), 0b00000001, 0b00000100, [0], 0, sched_meta=STFQMeta())
            pkt_gen = PktGenerator(env, period, pipe, rate, pkt, meta, cycle_limit=5000)
            self.generators.append(pkt_gen)
            self.pkt_gen_pipes.append(pipe)

        self.egress_link_rate = 10 # Gbps

        self.arbiter = Arbiter(env, period, self.pkt_gen_pipes, self.sw_pkt_in_pipe)
        self.receiver = PktReceiver(env, period, self.sw_pkt_out_pipe, self.sw_ready_out_pipe, self.egress_link_rate)

        self.env.process(self.wait_complete()) 
    def entrar(self):
        login_principal = [[sg.Text("Controle de Acesso ao CASIN")],
                           [
                               sg.Text('Matricula'),
                               sg.InputText(size=(15, 1),
                                            do_not_clear=True,
                                            justification='left',
                                            key='matricula')
                           ],
                           [
                               sg.Text('Matricula'),
                               sg.InputText(size=(15, 1),
                                            do_not_clear=True,
                                            justification='left',
                                            key='senha')
                           ], [sg.ReadButton('Entrar'),
                               sg.ReadButton('Sair')]]
        login = sg.Window("Controle de Acesso",
                          default_button_element_size=(5, 2),
                          auto_size_buttons=False,
                          grab_anywhere=False).Layout(login_principal)
        event, valor = login.Read()
        with Switch(valor) as case:
            if case('Entrar'):
                matricula = valor['matricula']
                senha = valor['senha']
                CtrlPrincipal.login(self.__ctrl_principal, matricula, senha)

            if case('Sair'):
                CtrlPrincipal.finalizar(self.__ctrl_principal)
Example #25
0
    def arithmetic_phase(self, operation, node):
        """
        Arithmetic phase

        """
        for case in Switch(operation):
            if case('AND'):
                self.output[:, node] = np.bitwise_and(self.input1[:, node], self.input2[:, node])
                break
            if case('OR'):
                self.output[:, node] = np.bitwise_or(self.input1[:, node], self.input2[:, node])
                break
            if case('XOR'):
                self.output[:, node] = np.bitwise_xor(self.input1[:, node], self.input2[:, node])
                break
            if case('NOR'):
                self.output[:, node] = np.bitwise_nor(self.input1[:, node])  # Single operand instruction
                break
            if case('ADD'):
                self.output[:, node] = np.add(self.input1[:, node], self.input2[:, node])
                break
            if case('SUB'):
                self.output[:, node] = np.subtract(self.input1[:, node], self.input2[:, node])
                break
            if case('MULT'):
                self.output[:, node] = np.multiply(self.input1[:, node], self.input2[:, node])
                break
            if case():  # Default
                print("Error! Undefined instruction ", operation)
                exit()
Example #26
0
def postProcessing(sPhraseSpec, node_dict):
  #verifica punct in caso di interrogative
    questionMarksList = list(filter(lambda elem:
                                    elem.get_dependency() == 'punct' and elem.get_original_token() == '?', node_dict.values()))
    if (len(questionMarksList) > 0):
        sPhraseSpec.setFeature(Feature.INTERROGATIVE_TYPE,
                               InterrogativeType.YES_NO)
        print(str(len(questionMarksList)))
  #POST PROCESSING IN CASO IN CUI IL SOGGETTO NON SIA STATO ESPLICITATO
    if sPhraseSpec.getSubject() == None:
      #sPhraseSpec.setFeature(LexicalFeature.EXPLETIVE_SUBJECT, True)
      verbalPhrase = sPhraseSpec.getVerbPhrase()
      allFeatures = verbalPhrase.getAllFeatures()
      with Switch(str(verbalPhrase.getFeature(Feature.PERSON))) as case:
        if case('FIRST'):
           sPhraseSpec.setSubject('I') if str(verbalPhrase.getFeature(
               Feature.NUMBER)) == 'SINGULAR' else sPhraseSpec.setSubject('we')
        if case('SECOND'):
          str(verbalPhrase.getFeature(LexicalFeature.GENDER))
        if case('THIRD'):
            if str(verbalPhrase.getFeature(Feature.NUMBER)) != 'SINGULAR':
              sPhraseSpec.setSubject('they')
            else:  # TODO verificare genere
              if verbalPhrase.getFeature(LexicalFeature.GENDER)==None:
               sPhraseSpec.setSubject('it')
              else:
               sPhraseSpec.setSubject('he')
    return sPhraseSpec
    def switch_feature_handler(self, event):
        dpid = event.msg.datapath_id
        try:
            switch = self.dpid_to_switch[dpid]
        except KeyError:
            self.dpid_to_switch[dpid] = Switch(event.msg.datapath)
            switch = self.dpid_to_switch[dpid]

        for port_no, port in event.msg.ports.iteritems():
            if port_no not in switch.ports:
                p = Port(port=port, dp=event.msg.datapath)
                switch.ports[port_no] = p

            p = switch.ports[port_no]

            if port_no == ofproto_v1_0.OFPP_LOCAL:
                switch.name = port.name.rstrip('\x00')
            else:
                # port.curr is a number of 32 bits, only used 12 bits in ovs
                # represents current features of the port.
                # LOCAL port doesn't have a cost value
                curr = port.curr & 0x7f  # get last 7 bits
                p.cost = 64 / curr
                print 'cost:', p.cost

        switch.update_from_config(self.switch_cfg)
        self.routing_algo.topology_last_update = time.time()
Example #28
0
def getLastTotal(Station):
    conn = sqlite3.connect(
        "/var/www/html/PeopleTracker-C4C/HTML/mainDatabase.db")
    curs = conn.cursor()
    with Switch(Station) as case:
        if case('Asian'):
            curs.execute("SELECT * FROM Asian")
            data = curs.fetchall()
        if case('American'):
            curs.execute("SELECT * FROM American")
            data = curs.fetchall()
        if case('Persian'):
            curs.execute("SELECT * FROM Persian")
            data = curs.fetchall()
        if case('Italian'):
            curs.execute("SELECT * FROM Italian"),
            data = curs.fetchall()
        if case('Latin'):
            curs.execute("SELECT * FROM Latin")
            data = curs.fetchall()

    print "about to get data"
    L = len(data)
    print "length: ", L
    Total = data[L - 1]
    print "Station: ", Station
    print "Total,: ", Total[2]
    return Total[2]
Example #29
0
    def menu_aluno(self):
        layout_aluno = [[sg.Text("Menu Aluno")],
                        [
                            sg.ReadButton("Criar", key='Criar'),
                            sg.ReadButton("Listar", key='Listar')
                        ],
                        [
                            sg.ReadButton("Editar", key='Editar'),
                            sg.ReadButton("Excluir", key='Excluir')
                        ],
                        [
                            sg.Text("    "),
                            sg.ReadButton("Voltar", key='Voltar')
                        ]]
        window = sg.Window("Gerenciar Aluno").Layout(layout_aluno)
        event, valor = window.Read()
        with Switch(valor) as case:
            if case('Criar'):
                self.cadastrar_aluno()

            if case('Editar'):
                self.cadastrar_aluno()
            if case('Excluir'):
                self.cadastrar_aluno()
            if case('Listar'):
                self.cadastrar_aluno()
Example #30
0
    def __init__(self, post: RedditPostContents, post_type: str) -> None:
        self.type = post_type
        with Switch(self.type) as case:
            if case("post"):
                self.credit_string = "Post by:"
            if case("meme"):
                self.credit_string = "Meme by:"
        super().__init__(
            colour=discord.Color.orange(),
            title=post.title,
            image=post.image,
            source=post.subreddit,
            author=post.author,
            author_icon=post.author_avatar,
            link=post.link,
            footer_author_url=post.author_avatar,
            footer_string=
            f"Posted on: {post.subreddit}\n{self.credit_string} {post.author}",
        )

        self.object_embed_session.insert_field_at(
            20,
            name="Link to post",
            value=f"[Go to post]({self.link})",
            inline=True,
        )
Example #31
0
def create(name:str, url : str, farbe1:str, farbe2: str):
  if farbe1.lowcase() == farbe2.lowcase():
   print("err")
  with Switch(farbe1) as case:
    if case.match(r'rot|Rot'):
      farbe1 = 255,0,0
    if case.match(r'grĆ¼n|GrĆ¼n'):
      farbe1 = 124,252,0
Example #32
0
def main():
    my_switch = Switch(buzzer_button)
    while True:

        my_switch_new_value = False
        # Disable interrupts for a short time to read shared variable
        irq_state = machine.disable_irq()
        if my_switch.new_value_available:
            my_switch_value = my_switch.value
            my_switch_new_value = True
            my_switch.new_value_available = False
        machine.enable_irq(irq_state)

        # If my switch had a new value, print the new state
        if my_switch_new_value:
            if not my_switch_value:
                request_photo()
Example #33
0
def generateThreeLayer(k):
	# initialize essential parameters 
	num_ports_per_switch = k	# number of ports per switch
	num_pod = k					# number of pods
	num_servers = int(k/2)			# number of hosts under a ToR switch 
	num_tor = int(k/2)				# number of ToR switches in a pod 
	num_agg = int(k/2)				# number of aggregation switches in a pod 
	num_core = int((k**2)/4)			# number of core switches 
	total_servers = int((k**3)/4)	# number of total servers 

	# initialize component generation 
	num_racks = num_pod * num_tor
	list_of_racks = []
	cpu_cores = 16
	for i in range(num_racks):
		rack = Rack(str(i))
		for j in range(num_servers):
			server = Server(i*(num_servers)+j,"server"+str(i)+"-"+str(j), cpu_cores)
			rack.accumulate(server)
		list_of_racks.append(rack)

	list_of_tors = []
	for i in range(num_tor * num_pod):
		tor = Switch("ToR"+str(i), "ToR", k)
		list_of_tors.append(tor)

	list_of_agg= []
	for i in range(num_agg * num_pod):
		agg = Switch("Agg"+ str(i), "Agg", k)
		list_of_agg.append(agg)

	list_of_core = []
	for i in range(num_core):
		core = Switch("Core"+str(i), "Core", k)
		list_of_core.append(core)

	list_of_links = []
	num_links = int(3 * (k**3) / 4)
	capacity = 1024 	# Mbits
	delay = 1			# ms
	for i in range(num_links):
		link = Link("link"+str(i), capacity, delay)
		list_of_links.append(link)

	return list_of_racks, list_of_tors, list_of_agg, list_of_core, list_of_links
Example #34
0
    def __init__(self, *args, **kwargs):
        Switch.__init__(self, *args, **kwargs)

        self._power = False

        try:
            self._port = serial.Serial(
                self.port,
                baudrate=19200,
                bytesize=serial.EIGHTBITS,
                parity=serial.PARITY_NONE,
                stopbits=serial.STOPBITS_ONE,
                timeout=0.1,
                xonxoff=0,
                rtscts=0,
            )
        except serial.SerialException:
            self._port = None
Example #35
0
 def drawGpuSwitch(self, MainWindow):
     MainWindow.GpuSwitch = Switch(thumb_radius=8,
                                   track_radius=10,
                                   show_text=False)
     MainWindow.horizontalLayout.addWidget(MainWindow.GpuSwitch)
     MainWindow.GpuSwitch.setEnabled(torch.cuda.is_available())
     MainWindow.use_cuda = False
     MainWindow.GpuSwitch.setToolTip("<h4>CUDA installed: {}</h4>".format(
         torch.cuda.is_available()))
Example #36
0
  def _handle_ConnectionUp (self, event):

      sw = self.switches.get(event.dpid)
      sw_str = dpidToStr(event.dpid)
      log.info("Saw switch com up: %s", sw_str)
      name_str = self.t.id_gen(dpid = event.dpid).name_str()

      if name_str not in self.t.switches():
          log.warn("Ignoring unknown switch %s" % sw_str)
          return

      if sw is None:
          log.info("Added fresh switch %s" % sw_str)
          sw = Switch()
          self.switches[event.dpid] = sw
          sw.connect(event.connection)

      else:
          log.info("Odd - already saw switch %s come up" % sw_str)
          sw.connect(event.connection)
      sw.connection.send(of.ofp_set_config(miss_send_len = MISS_SEND_LEN))
        
      if len(self.switches) == len(self.t.switches()):
          log.info("Woo! All switches up")
          self.all_switches_up = True

          self._save_paths()

          # log.info("self.routeTable : %s" % self.routeTable)

          # self._install_paths()

          log.info("Woo! All paths ok")

          # suppose here we have a traffic matrix
          # find the routing policies for this traffic matrix
          #for i in range(10):
          #    num_matrix = i
          #    self.test(num_matrix)
          self.input_traffic()
Example #37
0
    def __init__(self,pin_step=0,delay=0.1,pin_direction=0,pin_ms1=0,pin_ms2=0,pin_ms3=0,\
    			 pin_sleep=0,pin_enable=0,pin_reset=0,name="Stepper",pin_left_end=0,pin_right_end=0):
        self.pin_step = pin_step
        self.delay = delay / 2
        self.abs_position=self.read_abs_position()
        self.pin_direction = pin_direction
        self.direction=True
        self.pin_microstep_1 = pin_ms1
        self.pin_microstep_2 = pin_ms2
        self.pin_microstep_3 = pin_ms3
        self.pin_sleep = pin_sleep
        self.pin_enable = pin_enable
        self.pin_reset = pin_reset
        self.name = name
        self.pin_left_end = pin_left_end
        self.pin_right_end = pin_right_end
        self.left_switch = Switch(pin_left_end)
        self.right_switch = Switch(pin_right_end)
        self.left_limit=0
        self.right_limit=100
	
        gpio.setmode(gpio.BCM)
        gpio.setwarnings(False)

        if self.pin_step > 0:
            gpio.setup(self.pin_step, gpio.OUT)
        if self.pin_direction > 0:
            gpio.setup(self.pin_direction, gpio.OUT)
            gpio.output(self.pin_direction, True)
        if self.pin_microstep_1 > 0:
            gpio.setup(self.pin_microstep_1, gpio.OUT)
            gpio.output(self.pin_microstep_1, False)
        if self.pin_microstep_2 > 0:
            gpio.setup(self.pin_microstep_2, gpio.OUT)
            gpio.output(self.pin_microstep_2, False)
        if self.pin_microstep_3 > 0:
            gpio.setup(self.pin_microstep_3, gpio.OUT)
            gpio.output(self.pin_microstep_3, False)
        if self.pin_sleep > 0:
            gpio.setup(self.pin_sleep, gpio.OUT)
            gpio.output(self.pin_sleep,True)
        if self.pin_enable > 0:
            gpio.setup(self.pin_enable, gpio.OUT)
            gpio.output(self.pin_enable,False)
        if self.pin_reset > 0:
            gpio.setup(self.pin_reset, gpio.OUT)
            gpio.output(self.pin_reset,True)
        self.sleep()
class TestSwitch:

    # 恓恮ć‚Æćƒ©ć‚¹ć®ćƒ†ć‚¹ćƒˆć‚±ćƒ¼ć‚¹ć‚’å®Ÿč”Œć™ć‚‹å‰ć«ļ¼‘åŗ¦ć ć‘å®Ÿč”Œć™ć‚‹
    @classmethod
    def setup_class(clazz):
        # å„½ććŖ恓ćØ悒恙悋
        pass
    
    # 恓恮ć‚Æćƒ©ć‚¹ć®ćƒ†ć‚¹ćƒˆć‚±ćƒ¼ć‚¹ć‚’ć™ć¹ć¦å®Ÿč”Œć—ćŸå¾Œć«ļ¼‘åŗ¦ć ć‘å®Ÿč”Œć™ć‚‹
    @classmethod
    def teardown_class(clazz):
        # å„½ććŖ恓ćØ悒恙悋
        pass
    
    # 恓恮ć‚Æćƒ©ć‚¹ć®å„ćƒ†ć‚¹ćƒˆć‚±ćƒ¼ć‚¹ć‚’å®Ÿč”Œć™ć‚‹å‰ć«å®Ÿč”Œć™ć‚‹
    def setup(self):
        self.sw = Switch('sw001')
        assert self.sw.name == 'sw001'
        
    # 恓恮ć‚Æćƒ©ć‚¹ć®å„ćƒ†ć‚¹ćƒˆć‚±ćƒ¼ć‚¹ć‚’å®Ÿč”Œć—ćŸå¾Œć«å®Ÿč”Œć™ć‚‹
    def teardown(self):
        # å„½ććŖ恓ćØ悒恙悋
        pass
    
    def test_add_ports(self):
        self.sw.add_ports(['01'])
        assert self.sw.ports == ['01'] 
        self.sw.add_ports(['02', '03'])
        assert self.sw.ports == ['01', '02', '03'] 

    def test_add_rules(self):
        self.rules = []
        self.rules.append( {'in_ports' : [1]} )
        self.rules.append( {'in_ports' : [2, 3]} )
        self.rules[0]['out_ports'] = [1]
        self.rules[1]['out_ports'] = [2, 3]
        self.sw.add_rules(self.rules)
        
        assert self.sw.rules == self.rules 
Example #39
0
class Actuator(Daemon):

    SLEEP_TIME = 180            # controllo standard 180 sec, 3 minuti
    DEF_LOG_LEVEL = INFO

    TEMP_THRESHOLD = 0.5        # Grado soglia di innesco cambiamento stato
    TEMP_MAXTHRESHOLD = 1.0     # Soglia massima variazione sleep per rating
    TIME_THRESHOLD = 7200       # 2 ore

    SENS_DATA_THR = 1800        # soglia di validitĆ  dati sensori.

    def run(self):

        self.db = self._get_db_connection(
            smac_utils.read_db_config()
        )
        # inizializzo lo swich passando il log attuale
        self.sw = Switch(self.log)

        # inizializzo lo switcher inviandogli la configurazione del pi
        self.log.info('Invio configurazione allo switcher')
        # Lo switcher non configurato ignora ogni comando. Tuttavia
        # nel caso fosse giĆ  configurato ignorerebbe il set_gipio_pin
        self.sw.reload()
        while not self.sw.set_gpio_pin(self._get_gpio_pin()):
            self.log.error('Impossible configurare lo switcher')
            sleep(30)

        delay_check = 0

        self.db.set_notification(Database.EVT_ALTER_RELE_PIN)
        self.db.set_notification(Database.EVT_ALTER_PROGRAM)

        while True:

            # inizio transazione
            self.db.begin_transaction()

            # Ottengo pid e temperatura di rifemento
            (pid, trif) = self._get_current_schedule()

            # commit e chiudo transazione
            self.db.commit()
            self.db.end_transaction()

            # se pid -1 significa sistema spento imposto una temperatura
            # fittizia (-100) per costringere il sistema a spegnersi
            trif = Decimal(-100) if pid == -1 else trif
            sensordata = self._get_sensor_data()

            if not sensordata:
                self.log.error('Impossibile ottenere stato dei sensori')
                delay_check = self.SLEEP_TIME * 2
                self.sw.off()

            elif not self._is_actual_data(sensordata['lastup'],
                                          self.TIME_THRESHOLD):
                self.log.error(
                    'Dati sensore non aggiornati (%s)', sensordata['lastup'])
                delay_check = self.SLEEP_TIME
                self.sw.off()

            else:
                self.log.debug(
                    'Ultimo aggiornamento dati %s', sensordata['lastup'])
                rating = self._get_temp_rating(
                    sensordata['temp'], sensordata['tavg'], sensordata['tfor']
                )

                # Imposto lo stato del sistema in base ai parametri rilevati
                delay_check = self._set_system_state(
                    trif, sensordata['temp'], rating
                )

            # attendo eventi sul db fino a delay_check
            if self.db.wait_notification(delay_check):
                self._check_db_events()

    def _get_db_connection(self, dbd):
        return Database(dbd['host'], dbd['user'], dbd['pass'], dbd['schema'])

    def _check_db_events(self):

        self.log.debug('Verifico notifiche da Database')

        # notify.pid, notify.channel, notify.payload
        notify = self.db.get_notification()

        while notify:

            self.log.info(
                'Ricevuta notifica pid %s, canale %s, contenuto: %s',
                notify.pid, notify.channel, notify.payload
            )

            if notify.channel == Database.EVT_ALTER_PROGRAM:
                # risvegliato dal cambio programma
                # ignoro tutto, perchĆØ in ogni caso rileggo
                pass
            elif notify.channel == Database.EVT_ALTER_RELE_PIN:
                # invio nuove impostazioni allo switcher
                while True:

                    if self.sw.reload():
                        sleep(0.5)      # sync con switcher
                        if self.sw.set_gpio_pin(notify.payload):
                            break
                    sleep(10)

            notify = self.db.get_notification()

    def _get_gpio_pin(self):

        pin = None
        while pin is None:

            try:
                str_pin = self.db.get_setting(Database.DB_SET_PIN_RELE, None)
                self.log.debug('Valore Database %s', str_pin)
                pin = int(str_pin)
                self.log.info('Uso Pin GPIO %s', pin)

            except Exception as e:
                    self.log.error('Errore lettura pin GPIO RelĆØ', repr(e))
                    raise
        return pin

    def _get_current_schedule(self):

        # La stored function programmazioni() restituisce la programmazione
        # del programma corrente quando richiamata senza parametri
        schedule = self.db.query(
            "SELECT id_programma, t_rif_val FROM programmazioni()"
            " WHERE current_time > ora ORDER BY ora DESC LIMIT 1")
        self.log.debug('Lettura programmazione attuale: %s', schedule)
        return schedule[0] if schedule else []

    def _is_actual_data(self, capture_time, thr):

        delta = datetime.datetime.now() - capture_time

        delta_sec = abs(delta.total_seconds())

        return False if delta_sec > thr else True

    def _get_sensor_data(self):

        rawdata = self.db.query(
            "SELECT * FROM dati_sensore"
            "((SELECT sensore_rif FROM dati_programma()))"
        )
        self.log.debug('Lettura dati sensore di riferimento: %s', (rawdata))
        sdata = {}

        if rawdata:
            d = rawdata.pop()
            sdata = {
                'id':     d[0],  'name':    d[2],  'temp':   d[3],
                'tmin':   d[4],  'tavg':    d[5],  'tmax':   d[6],
                'tfor':   d[7],  'humd':    d[8],  'hmin':   d[9],
                'havg':   d[10], 'hmax':    d[11], 'hfor':   d[12],
                'lastup': d[13], 'lastfor': d[14]
            }

        return sdata

    # Rating indice di stabilitĆ  della temperatura
    # 2 in salita, 1 probabile salita, 0.5 salita incerta
    # -2 in discesa, -1 probabile discesa, -0.5 discesa incerta
    def _get_temp_rating(self, treal, tavg, tfor):

        t_min = min(treal, tavg, tfor)
        t_max = max(treal, tavg, tfor)

        if t_min == treal:
            rating = 2.0 if tfor == t_max else 1.5
        elif t_min == tavg:
            rating = 1.0 if tfor == t_max else -1.0
        elif t_min == tfor:
            rating = -1.5 if tavg == t_max else -2.0

        self.log.debug(
            'Rating: %s - TĀ° mis: %s - TĀ° media: %s - TĀ° prevista %s',
            rating, treal, tavg, tfor)
        return rating

    def _set_system_state(self, reference, temperature, rating):

        next_check = self.SLEEP_TIME
        deltat = abs(reference - temperature)
        stato_attuale = self.sw.state()
        nuovo_stato = stato_attuale

        self.log.debug('Stato Sistema: %s' % (stato_attuale))

        # Commuto il sistema in on/off se si supera la soglia minima
        if deltat >= self.TEMP_THRESHOLD:

            nuovo_stato = (
                Switch.ST_ON if reference > temperature else Switch.ST_OFF
            )

            self.log.debug(
                'Rilevazione: T Ril %.2f, T Rif %.2f - SUPERATA Soglia %s',
                temperature, reference, self.TEMP_THRESHOLD
            )

        else:

            self.log.debug(
                'Rilevazione: T Ril %.2f, T Rif %.2f - ENTRO Soglia %s',
                temperature, reference, self.TEMP_THRESHOLD
            )

            # Nel caso lo stato attuale sia sconosciuto forzo il sistema
            # ad avere uno stato consistente
            if stato_attuale == Switch.ST_UNKNOW:
                nuovo_stato = (
                    Switch.ST_ON if reference > temperature else Switch.ST_OFF
                )
                self.log.warning('Stato sconosciuto: Forzo Commutazione')

        res = True

        # Inserisco stato caldaia a database
        self.db.query(
            'INSERT INTO storico_commutazioni(stato) VALUES(%s)',
            [None if nuovo_stato is Switch.ST_UNKNOW
             else nuovo_stato == Switch.ST_ON]
        )

        if nuovo_stato != stato_attuale:

            self.log.info(
                'Commutazione: DA %s - A %s',
                stato_attuale, nuovo_stato)

            res = (self.sw.on() if nuovo_stato == Switch.ST_ON
                   else self.sw.off())

            if not res:

                next_check = self.SLEEP_TIME // 3
                self.log.error(
                    'Impossibile commutare il sistema in %s'
                    ' Prossmo controllo tra %s secondi',
                    nuovo_stato, next_check
                )
        else:
            self.log.debug(
                'Sistema in stato %s - Nessuna commutazione', nuovo_stato)

        if res and deltat <= self.TEMP_MAXTHRESHOLD:

            if nuovo_stato == Switch.ST_ON:
                next_check = (
                    (self.SLEEP_TIME // rating) if rating > 0
                    else (self.SLEEP_TIME * abs(rating))
                )
            else:
                next_check = (
                    (self.SLEEP_TIME * rating) if rating > 0
                    else (self.SLEEP_TIME // abs(rating)))

            self.log.debug(
                "T Ril %.2f entro soglia massima %s. Fisso prossimo controllo "
                "tra %s sec in base IST (indice stabilitĆ  temperatura) %s",
                temperature, self.TEMP_MAXTHRESHOLD, next_check, rating)

        return next_check
import move_base_msgs.msg

bs0 = RobotPatrolArea0("robot_2/move_base/switch0","robot_2_partrol0_node")
bs1 = RobotPatrolArea1("robot_2/move_base/switch1","robot_2_partrol1_node")
bs2 = RobotPatrolArea2("robot_2/move_base/switch2","robot_2_partrol2_node")
bs0.start()
bs1.start()
bs2.start()

mb0 = MotivationalBehavior('r2_mb0',2,0,'robot2_switch0_patrol/activate')#nodename,robotid,behaviorid
mb0.set_fast(10)
mb0.enable_random_inc()
mb0.set_sensory_feedback(1)
mb0.set_sensor('robot_2/patrol_sensory_feedback')
mb0.start()
s0 = Switch('robot2_switch0_patrol','robot_2/move_base/switch0/goal',move_base_msgs.msg.MoveBaseActionGoal,'robot_2/move_base/goal','/robot_2/move_base/result', move_base_msgs.msg.MoveBaseActionResult, '/robot_2/move_base/switch0/result')#nodename,subtopic,type,pubtopic
s0.add_action('robot_2/move_base/switch0','robot_2/move_base')
s0.start()

mb1 = MotivationalBehavior('r2_mb1',2,1,'robot2_switch1_patrol/activate')#nodename,robotid,behaviorid
mb1.set_fast(10)
mb1.enable_random_inc()
mb1.set_sensory_feedback(1)
mb1.set_sensor('robot_2/patrol_sensory_feedback')
mb1.start()
s1 = Switch('robot2_switch1_patrol','robot_2/move_base/switch1/goal',move_base_msgs.msg.MoveBaseActionGoal,'robot_2/move_base/goal','/robot_2/move_base/result', move_base_msgs.msg.MoveBaseActionResult, '/robot_2/move_base/switch1/result')#nodename,subtopic,type,pubtopic
s1.add_action('robot_2/move_base/switch1','robot_2/move_base')
s1.start()

mb2 = MotivationalBehavior('r2_mb2',2,2,'robot2_switch2_patrol/activate')#nodename,robotid,behaviorid
mb2.set_fast(20)
Example #41
0
        format='%(asctime)s %(levelname)s %(message)s',
        datefmt='%m/%d/%Y %H:%M:%S'
)

if conf_warn != "":
    logging.warning(conf_warn)
    # exit(1)


def get_switch_config():
    for section in config.sections():
        if section.find("switch_") != -1:
            switch_conf = {}
            for item in ["switch_type", "ip", "name", "stack_member", "user", "pass"]:
                switch_conf[item] = config.get(section, item)
            return switch_conf


if __name__ == "__main__":
    print "Test"
    dict_sw = get_switch_config()
    sw = Switch(
            stype=dict_sw['switch_type'],
            sm=dict_sw['stack_member'],
            ip=dict_sw['ip'],
            host=dict_sw['name'],
            user=dict_sw['user'],
            passwd=dict_sw['pass']
    )
    sw.info()
 def setup(self):
     self.sw = Switch('sw001')
     assert self.sw.name == 'sw001'
Example #43
0
 def __init__(self, house, xml):
     Switch.__init__(self, house, xml)
Example #44
0
	def __init__(self, name, addr):
		Switch.__init__(self, name, addr)
Example #45
0
 def __init__(self,parent,mapping):
     self.parent = parent
     Switch.__init__(self,mapping)
Example #46
0
	def makeSwitch(self, name, x, y):
		switch = Switch(name, self.squareHeight, self.squareWidth)
#		switch.model.setColor(0, 0, 0)
		x,y = self.gridToPos((x,y))
		switch.setPos(x,y)
		return switch
Example #47
0
File: api.py Project: rlane/pybsn
 def remove_switch_by_dpid(self, dpid):
     return Switch.remove_switch_by_dpid(self.client, dpid)
Example #48
0
File: api.py Project: rlane/pybsn
 def get_switch_by_dpid(self, dpid):
     return Switch.get_switch_by_dpid(self.client, dpid)
Example #49
0
File: api.py Project: rlane/pybsn
 def remove_switch_by_name(self, name):
     return Switch.remove_switch_by_name(self.client, name)
Example #50
0
File: api.py Project: rlane/pybsn
 def get_switch_by_name(self, name):
     return Switch.get_switch_by_name(self.client, name)
Example #51
0
File: api.py Project: rlane/pybsn
 def get_switches(self):
     return Switch.get_switches(self.client)
Example #52
0
    def run(self):

        self.db = self._get_db_connection(
            smac_utils.read_db_config()
        )
        # inizializzo lo swich passando il log attuale
        self.sw = Switch(self.log)

        # inizializzo lo switcher inviandogli la configurazione del pi
        self.log.info('Invio configurazione allo switcher')
        # Lo switcher non configurato ignora ogni comando. Tuttavia
        # nel caso fosse giĆ  configurato ignorerebbe il set_gipio_pin
        self.sw.reload()
        while not self.sw.set_gpio_pin(self._get_gpio_pin()):
            self.log.error('Impossible configurare lo switcher')
            sleep(30)

        delay_check = 0

        self.db.set_notification(Database.EVT_ALTER_RELE_PIN)
        self.db.set_notification(Database.EVT_ALTER_PROGRAM)

        while True:

            # inizio transazione
            self.db.begin_transaction()

            # Ottengo pid e temperatura di rifemento
            (pid, trif) = self._get_current_schedule()

            # commit e chiudo transazione
            self.db.commit()
            self.db.end_transaction()

            # se pid -1 significa sistema spento imposto una temperatura
            # fittizia (-100) per costringere il sistema a spegnersi
            trif = Decimal(-100) if pid == -1 else trif
            sensordata = self._get_sensor_data()

            if not sensordata:
                self.log.error('Impossibile ottenere stato dei sensori')
                delay_check = self.SLEEP_TIME * 2
                self.sw.off()

            elif not self._is_actual_data(sensordata['lastup'],
                                          self.TIME_THRESHOLD):
                self.log.error(
                    'Dati sensore non aggiornati (%s)', sensordata['lastup'])
                delay_check = self.SLEEP_TIME
                self.sw.off()

            else:
                self.log.debug(
                    'Ultimo aggiornamento dati %s', sensordata['lastup'])
                rating = self._get_temp_rating(
                    sensordata['temp'], sensordata['tavg'], sensordata['tfor']
                )

                # Imposto lo stato del sistema in base ai parametri rilevati
                delay_check = self._set_system_state(
                    trif, sensordata['temp'], rating
                )

            # attendo eventi sul db fino a delay_check
            if self.db.wait_notification(delay_check):
                self._check_db_events()
Example #53
0
File: api.py Project: rlane/pybsn
 def add_switch(self, **kwargs):
     return Switch.add_switch(self.client, **kwargs)
Example #54
0
class easydriver(object):
    def __init__(self,pin_step=0,delay=0.1,pin_direction=0,pin_ms1=0,pin_ms2=0,pin_ms3=0,\
    			 pin_sleep=0,pin_enable=0,pin_reset=0,name="Stepper",pin_left_end=0,pin_right_end=0):
        self.pin_step = pin_step
        self.delay = delay / 2
        self.abs_position=self.read_abs_position()
        self.pin_direction = pin_direction
        self.direction=True
        self.pin_microstep_1 = pin_ms1
        self.pin_microstep_2 = pin_ms2
        self.pin_microstep_3 = pin_ms3
        self.pin_sleep = pin_sleep
        self.pin_enable = pin_enable
        self.pin_reset = pin_reset
        self.name = name
        self.pin_left_end = pin_left_end
        self.pin_right_end = pin_right_end
        self.left_switch = Switch(pin_left_end)
        self.right_switch = Switch(pin_right_end)
        self.left_limit=0
        self.right_limit=100
	
        gpio.setmode(gpio.BCM)
        gpio.setwarnings(False)

        if self.pin_step > 0:
            gpio.setup(self.pin_step, gpio.OUT)
        if self.pin_direction > 0:
            gpio.setup(self.pin_direction, gpio.OUT)
            gpio.output(self.pin_direction, True)
        if self.pin_microstep_1 > 0:
            gpio.setup(self.pin_microstep_1, gpio.OUT)
            gpio.output(self.pin_microstep_1, False)
        if self.pin_microstep_2 > 0:
            gpio.setup(self.pin_microstep_2, gpio.OUT)
            gpio.output(self.pin_microstep_2, False)
        if self.pin_microstep_3 > 0:
            gpio.setup(self.pin_microstep_3, gpio.OUT)
            gpio.output(self.pin_microstep_3, False)
        if self.pin_sleep > 0:
            gpio.setup(self.pin_sleep, gpio.OUT)
            gpio.output(self.pin_sleep,True)
        if self.pin_enable > 0:
            gpio.setup(self.pin_enable, gpio.OUT)
            gpio.output(self.pin_enable,False)
        if self.pin_reset > 0:
            gpio.setup(self.pin_reset, gpio.OUT)
            gpio.output(self.pin_reset,True)
        self.sleep()

    def step(self):
    	if self.left_limit<self.abs_position and self.direction or self.abs_position<self.right_limit and not self.direction:
	    	self.wake()
	        gpio.output(self.pin_step,True)
	        time.sleep(self.delay)
	        gpio.output(self.pin_step,False)
	        time.sleep(self.delay)
	        if not self.direction:
	        	self.add_to_abs_position(1)
	        else:
	        	self.add_to_abs_position(-1)
     	print(self.abs_position)
        	
    def set_direction(self,direction):
    	self.direction=direction
        gpio.output(self.pin_direction,self.direction)

    def set_full_step(self):
        gpio.output(self.pin_microstep_1,False)
        gpio.output(self.pin_microstep_2,False)
        gpio.output(self.pin_microstep_3,False)
        
    def set_half_step(self):
        gpio.output(self.pin_microstep_1,True)
        gpio.output(self.pin_microstep_2,False)
        gpio.output(self.pin_microstep_3,False)
        
    def set_quarter_step(self):
        gpio.output(self.pin_microstep_1,False)
        gpio.output(self.pin_microstep_2,True)
        gpio.output(self.pin_microstep_3,False)
        
    def set_eighth_step(self):
        gpio.output(self.pin_microstep_1,True)
        gpio.output(self.pin_microstep_2,True)
        gpio.output(self.pin_microstep_3,False)

    def set_sixteenth_step(self):
        gpio.output(self.pin_microstep_1,True)
        gpio.output(self.pin_microstep_2,True)
        gpio.output(self.pin_microstep_3,True)
        
    def add_to_abs_position(self,delta):
    	self.abs_position+=delta
    	self.write_abs_position(str(self.abs_position))
    	
    def set_abs_position_zero(self):
    	self.abs_position=0
    	self.write_abs_position(self.abs_position)
    	
    def sleep(self):
        gpio.output(self.pin_sleep,False)

    def wake(self):
        gpio.output(self.pin_sleep,True)
    
    def disable(self):
        gpio.output(self.pin_enable,True)

    def enable(self):
        gpio.output(self.pin_enable,False)

    def reset(self):
        gpio.output(self.pin_reset,False)
        time.sleep(1)
        gpio.output(self.pin_reset,True)

    def set_delay(self, delay):
        self.delay = delay / 2
        
    def read_abs_position(self):
    	file=open('abs_pos.txt','r')
    	self.abs_position=eval(file.readline())
    	file.close()
    	return self.abs_position
        
    def write_abs_position(self, abs_pos):
    	file=open('abs_pos.txt','w')
    	file.write(str(abs_pos))
    	file.close()
    	self.abs_position=int(abs_pos)
        
    def left_switch_status(self):
		return self.left_switch.switch_status()
		
    def find_left_end_stop(self):
    	self.set_direction(False)
    	while not (self.left_switch_status()):
			self.step()
    	self.set_abs_position_zero()
	
    def finish(self):
    	if self.pin_sleep!=0:
    		self.sleep()
        gpio.cleanup()