def __init__(self, controlhandler): self.controlhandler = controlhandler GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) self.currentInstr = None self.ledState = 1 self.ledDriver = libDriver.LedDriver() self.pitch_click = libSwitch.Switch(22) # Pitch Encoder Click GPIO self.speed_click = libSwitch.Switch(26) # Speed Encoder Click GPIO # Set up Rotary Encoders self.encoder_pitch = libEnc.Encoder.Worker(17, 27) self.encoder_pitch.start() # Start Interrupt in a separate thread. self.encoder_speed = libEnc.Encoder.Worker(6, 13) self.encoder_speed.start() # Start Interrupt in a separate thread. self.pitch_delay = 0 self.speed_delay = 0 self.pitch_inc_dir = 0 self.speed_inc_dir = 0 self.encoder_delay_time = 500 self.now = int(round(time.time() * 1000)) self.pitch_blink_anim_flag = False self.pitch_blink_timer = self.now # Below are just the Blue on all RGB LEDs # Deltas for Encoders self.delta_p = 0 self.delta_s = 0 # Real Control Values (later share this with ControlHandler class self.speed_amount = self.controlhandler.getStaticVal("speed") self.alt_speed_amount = 23 # input level self.pitch_amount = self.controlhandler.getStaticVal("pitch") self.mode = "normal" user_dir = "/home/alarm/instr/" factory_dir = "/home/alarm/QB_Nebulae_V2/Code/instr/" pd_dir = "/home/alarm/pd/" self.factoryinstr_fhandle = filehandler.FileHandler( factory_dir, ".instr") self.userinstr_fhandle = filehandler.FileHandler(user_dir, ".instr") self.puredata_fhandle = filehandler.FileHandler(pd_dir, ".pd") cur_bank = self.controlhandler.getInstrSelBank() self.bank_shift_counter = 0 if cur_bank == "factory": cnt = self.factoryinstr_fhandle.numFiles() elif cur_bank == "user": cnt = self.userinstr_fhandle.numFiles() elif cur_bank == "puredata": cnt = self.puredata_fhandle.numFiles() self.controlhandler.setInstrSelNumFiles(cnt) self.reload_flag = False # Flag to reload the whole program. self.alt_file_bright = 0.0 self.alt_file_cnt = 0.0 self.blink_counter = 0 self.prev_blink = False self.blink = False self.time_pressed_pitch = self.now self.ignore_next_pitch_click = False self.ignore_next_speed_click = False self.clearAllLEDs() self.restoreDefaultsFlag = False
def main(): config = configparser.ConfigParser() config.read('config.ini') pin = int(config['DEFAULT']['ultrasonic_sensor_pin']) sonar = GroveUltrasonicRanger(pin) red = redis.Redis() sw = switch.Switch(int(config['DEFAULT']['switch3_pin'])) print('Detecting distance...') i = 0 state = 1 while True: dist = sonar.get_distance() if state == 1: if dist < lower_th: state = 2 red.mset({'presence': 1}) sw.set_state(1) i = 0 else: if dist > upper_th: i = i + 1 if i > wait_time: state = 1 red.mset({'presence': 0}) sw.set_state(0) time.sleep(1)
def main(): def print_list(l): [print(str(x) + ' ', end='') for x in l] print() # Take from the user the input and output interfaces of the switch and the network input_interfaces = [int(x) for x in input('Insert a list of input interfaces (ex. 1 2 3):\t').split()] output_interfaces = [int(x) for x in input('Insert a list of output interfaces (ex. 1 2 3):\t').split()] ip_address1 = ip_address(input('Insert the first ip address of the network (ex. 192.168.0.1):\t')) ip_address2 = ip_address(input('Insert the last ip address of the network (ex. 192.168.0.10):\t')) ip_addresses = [ip_address(ip) for ip in range(int(ip_address1), int(ip_address2))] print(col.GREEN + '\nSetting up the switch, the controller and the input interface simulator...' + col.ENDC) print(col.GREEN + 'Input interfaces: ' + col.ENDC, end='') print_list(input_interfaces) print(col.GREEN + 'Output interfaces: ' + col.ENDC, end='') print_list(output_interfaces) print(col.GREEN + 'Network: ' + col.ENDC, end='') print_list(ip_addresses) print() # Create the generator of the packets pg = input_interface_simulator.InputInterfaceSimulator(input_interfaces, ip_addresses) # Create the switch and the controller c = control.Controller(ip_addresses) s = switch.Switch(output_interfaces, pg.gen(), c, True) # TODO pass gen() or gen? s.main_loop() return 0
def lunch(conf): api = falcon.API() sw = switch.Switch() api.add_route("/alert/v1.0/switch", sw) return api
def test_setup_round__deals_cards(): """setup_round deals correct number of cards""" s = switch.Switch() s.players = [MockPlayer([]), MockPlayer([])] s.setup_round() assert all(len(p.hand) == 7 for p in s.players) assert len(s.discards) == 1 assert len(s.stock) == 52 - len(s.players) * 7 - 1
def test_setup_round__resets_flags(): """setup_round sets all flags to initial value""" s = switch.Switch() s.players = [MockPlayer([]), MockPlayer([])] s.setup_round() assert s.skip is False assert s.draw2 is False assert s.draw4 is False assert s.direction == 1
def loop(): global status # global msgque # setup() while True: client.subscribe("wzf01") if msgque == 1: return Value = ADC.read(0) print 'Value:', Value if Value > 248 and status == 1: print 'on' Switch.Switch(0) status = 0 if Value < 242 and status == 0: print 'off' Switch.Switch(1) status = 1 time.sleep(1)
def __init__(self): self.switch = switch.Switch() while not self.con: print("NO CONN DROPPER") time.sleep(2) try: self.motor = grove_i2c_motor_driver.motor_driver(address=0x0f) self.motor.MotorSpeedSetAB(100, 100) except IOError: continue self.con = True self.motor.MotorSpeedSetAB(0, 0) self.bus = smbus.SMBus(1)
def mock_setup_round(hands, stock, discards, skip=False, draw2=False, draw4=False, direction=1): def str_to_cards(spec): return [Card(sv[:1], sv[1:]) for sv in spec.split()] s = switch.Switch() s.players = [MockPlayer(str_to_cards(hand)) for hand in hands] s.discards = str_to_cards(discards) s.stock = str_to_cards(stock) s.skip = skip s.draw2 = draw2 s.draw4 = draw4 s.direction = direction return s
def prettify_key(key: str): with switch.Switch(key.lower()) as case: if case("pve"): return "PvE" if case("pvp"): return "PvP" if case("wvw"): return "WvW" if case("fractals"): return "Fractals" if case("special"): return "Festival" if case.default: return False
def __init__(self, topo, soft_labels=None, regions=None): self.topo = topo self.switch_num = len(topo) self.switches = [] for label in range(self.switch_num): self.switches.append(switch.Switch(label)) self.soft_labels = soft_labels if soft_labels is None: self.soft_labels = [] for label in self.soft_labels: self.switches[label].set_sw_type(setting.TYPE_SOFTWARE) self.controller = controller.Controller(topo, soft_labels, regions) self.traffic = traffic.Traffic()
def mock_setup_round(hands, stock, discards, skip=False, draw2=False, draw4=False, direction=1): """Setup a mock round of the switch game. Starts a round of switch game by handing out cards to each of the mock players's hands, creating a stock pile and a discard pile. It also assigns all the game effects from switch.py module to new values which are used in this test file. Parameters: hands -- cards in each of the player's hand stock -- cards in the stock pile discards -- cards in the discard pile Keyword arguments: skip -- game effect when the next person in line is skipped draw2 -- game effect when the next person draws 2 cards draw4 -- game effect when the next person draws 4 cards direction -- the direction of the game Returns: A new mock round of the switch game. """ def str_to_cards(spec): return [Card(sv[:1], sv[1:]) for sv in spec.split()] s = switch.Switch() s.players = [MockPlayer(str_to_cards(hand)) for hand in hands] s.discards = str_to_cards(discards) s.stock = str_to_cards(stock) s.skip = skip s.draw2 = draw2 s.draw4 = draw4 s.direction = direction return s
def main(): def print_list(l): [print(str(x) + ' ', end='') for x in l] print() # Define the input and output interfaces of the switch and the network input_interfaces = [1, 2, 3] output_interfaces = [4, 5, 6, 7] ip_address1 = ip_address('192.168.0.1') ip_address2 = ip_address('192.168.0.5') ip_addresses = [ ip_address(ip) for ip in range(int(ip_address1), int(ip_address2)) ] print( col.GREEN + '\nSetting up the switch, the controller and the input interface simulator...' + col.ENDC) print(col.GREEN + 'Input interfaces: ' + col.ENDC, end='') print_list(input_interfaces) print(col.GREEN + 'Output interfaces: ' + col.ENDC, end='') print_list(output_interfaces) print(col.GREEN + 'Network: ' + col.ENDC, end='') print_list(ip_addresses) print() # Create the generator of the packets pg = input_interface_simulator.InputInterfaceSimulator( input_interfaces, ip_addresses) # Create the switch and the controller c = control.Controller(ip_addresses) s = switch.Switch(output_interfaces, pg.gen(), c, False) s.main_loop() return 0
def __init__(self, name, button_gate_mode, gate_pin, button_pin, sr, mode="latching", edge="falling", maximum=1, longtouch_cb=None, inc_order=0, init_val=0): self.b_state = 0 self.g_state = 0 self.gate_pin = gate_pin self.button_pin = button_pin self.sr = sr self.prev_state = int(init_val) self.state = int(init_val) self.led_state = int(init_val) self.edge = edge self.mode = mode self.gate_pulse_time = time.time() * 1000.0 self.button_pulse_time = time.time() * 1000.0 self.led_pulse_time = time.time() * 1000.0 self.maximum = maximum # check for out of range selection at init time. if self.state > self.maximum: self.state = 0 self.time_held = 0 self.button_pressed = False self.long_press_time = 300 self.output_period = 10 # output to csound pulse in ms self.led_period = 40 # output to csound pulse in ms #self.long_press_time = 63 self.ignore_next_btrig = False self.name = name self.longtouch_cb = longtouch_cb self.inc_order = inc_order self.ignore_button = False self.ignore_gate = False self.trig_source = "button" ## hacky way for making sure LED stays low ## when file is >0 at bootup if name == "file": self.led_state = 0 if button_gate_mode is BUTTON_GATE_GPIO: # Setup both inputs as self.gate_src = "GPIO" self.button_src = "GPIO" self.gate_switch = libSwitch.Switch(gate_pin) self.button_switch = libSwitch.Switch(button_pin) elif button_gate_mode is BUTTON_SR_GATE_GPIO: # Setup button as SR input, and gate as GPIO (most common) self.gate_src = "GPIO" self.button_src = "SR" self.gate_switch = libSwitch.Switch(gate_pin) self.button_switch = self.sr elif button_gate_mode is BUTTON_GPIO_GATE_SR: # Setup Button as GPIO and Gate as SR (doesn't happen) self.gate_src = "SR" self.button_src = "GPIO" self.gate_switch = self.sr self.button_switch = libSwitch.Switch(button_pin) elif button_gate_mode is BUTTON_GATE_SR: # Setup both inputs as SR (source only I believe) self.gate_src = "SR" self.button_src = "SR" self.gate_switch = self.sr self.button_switch = self.sr elif button_gate_mode is BUTTON_GPIO_GATE_NONE: self.gate_switch = None self.gate_src = "NONE" self.button_src = "GPIO" self.button_switch = libSwitch.Switch(button_pin) elif button_gate_mode is BUTTON_SR_GATE_NONE: self.gate_switch = None self.gate_src = "NONE" self.button_src = "SR" self.button_switch = self.sr
import rotary_encoder import switch import app import OLD_mympd # http://stackoverflow.com/questions/7505988/importing-from-a-relative-path-in-python app = current_app._get_current_object() A_PIN = 7 B_PIN = 1 SW_PIN = 3 with app.app_context(): mpd_player = OLD_mympd.PersistentMPDClient() encoder = rotary_encoder.RotaryEncoder.Worker(A_PIN, B_PIN) encoder.start() switch = switch.Switch(SW_PIN) last_state = None while True: delta = encoder.get_delta() if delta != 0: print ("rotate %d" % delta) mpd_player.play_media() sw_state = switch.get_state() if sw_state != last_state: print ("switch %d" % sw_state) last_state = sw_state mpd_player.stop()
import camera import speaker import motor import LEDMatrix import piezo import messure import RPi.GPIO as GPIO if __name__ == '__main__': piz = piezo.Piezo(16) print("Piezo init") pointer = servo.Servo(17) print("Servo init") sw = switch.Switch(18) print("Switch init") cam = camera.camera() time.sleep(0.1) print("Camera init") speak = speaker.speaker("OhYeah.mp3") print("Speaker init") mot = motor.motor() print("Motor init") matrix = LEDMatrix.LEDMatrix() print("LEDMatrix init") mes = messure.messure() print("messure init") #start piezo in parallel time.sleep(0.1) pizWait = Value('d', 0.4)
import pin import input import ttl_7408 import connection import switch p = pin.Pin() sw1 = switch.Switch(p, 'sw1') u1 = ttl_7408.TTL_7408(p, 'u1') # w1 = connection.Connection(p, 'w1', sw1, 'sw1_out', 'u1_a1') sw1.set_state(1) print(p.pin) print(p.pin['sw1_out']) u1.set_input(a1=0) u1.update() print(p.pin['u1_y1']) # print(pin.Pin()['sw1_out']) # u1.set_input(a1=1, b1=1) # u1.update() # print(u1_y1) # print(globals())
def main(): game = switch.Switch() game.run_game()
"200000 " + PATH + "qsort_input_200000.bin " + PATH + "qsort_gold_200000.bin", "matmul_400": PATH + "matmul_input_400.bin" + " " + PATH + "matmul_gold_400.bin 400", "matmul_checksum": PATH + "matmul_input_400.bin" + " " + PATH + "matmul_gold_400.bin 400 matmul_crc_400.bin", "lavamd_checksum": "5 " + PATH + "input_distance_1_5 " + PATH + "input_charges_1_5 " + PATH + "output_gold_1_5", "matmul_600": PATH + "matmul_input_600.bin" + " " + PATH + "matmul_gold_600.bin 600" } subnet = ".".join(board_ip.split(".")[:3]) + ".1" power_switch = switch.Switch(switch_type, switch_port, switch_ip, sleep_time) #creates a power switch object a = get_self_ip_address() sock = socket.socket( socket.AF_INET, socket.SOCK_DGRAM) # the UDP socket which receives the messages sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind((get_self_ip_address(), pc_port)) sock.settimeout(SOCKET_TIMEOUT) openLog() try: main() except KeyboardInterrupt as err: print(err)
from flask import Flask, render_template, url_for import redis from flask_restful import Resource, Api import switch import configparser app = Flask(__name__) api = Api(app) red = redis.Redis() # read config file config = configparser.ConfigParser() config.read('config.ini') switches = [] switches.append(switch.Switch(int(config['DEFAULT']['switch1_pin']))) switches.append(switch.Switch(int(config['DEFAULT']['switch2_pin']))) class Temperature(Resource): def get(self): return {'temperature': red.get('temperature')} class SwitchOnOff(Resource): def put(self, sw_id): sw_id = int(sw_id) if switches[sw_id].get_state() == 0: switches[sw_id].set_state(1) else: switches[sw_id].set_state(0)
if __name__ == '__main__': try: client = mqtt.Client("wzf01") #create new instance client.on_message = on_message #attach function to callback client.connect(broker_address) #connect to broker client.loop_start() #start the loop setup() while True: if msgque == 1: get_Rdis_status() msgque = 0 if Rdis_status == 'AUTO': print 'Switch: AUTO' loop() if Rdis_status == 'ON': print 'Switch: ON' Switch.Switch(0) status = 0 if Rdis_status == 'OFF': print 'Switch: OFF' Switch.Switch(1) status = 1 client.subscribe("wzf01") time.sleep(5) pass except KeyboardInterrupt: Switch.Switch_destroy() GPIO.cleanup() # pass
def setup(): GPIO.setmode(GPIO.BCM) ADC.setup(0x48) Switch.Switch(0)
# S1 ---- S2 # / | \ | # H1 H2 H3 H4 # import topology, switch, host, port topo = topology.Topology() s1 = switch.Switch("s1") topo.addSwitch(s1) s2 = switch.Switch("s2") topo.addSwitch(s2) s3 = switch.Switch("s3") topo.addSwitch(s3) #s3.chassi=100 s4 = switch.Switch("s4") topo.addSwitch(s4) h1 = host.Host('h1') h1.addPort(port.Port('AA:AA:AA:CC:CC:CC')) h1.addPort(port.Port('AA:AA:AA:AC:CC:CC')) h2 = host.Host('h2') h2.addPort(port.Port('AA:AA:AA:CC:CC:CD')) h3 = host.Host('h3') h3.addPort(port.Port('AA:AA:AA:CC:CC:CE'))
elapsed_time = 0 # pseudo time max_devices = 0 results_file = open(path, 'w') results_file.write('Время проведения теста: {time}'.format( time=str(datetime.datetime.now())).split('.')[0]) results_file.write('\n') for i in range(len(number_of_devices)): try: elapsed_time = 0 max_devices = number_of_devices[i] devices = [device.Device() for i in range(number_of_devices[i])] Switch = switch.Switch(devices) constants.DEVICE_COUNTER = 0 constants.DEVICES_NUMBER = number_of_devices[i] test_string = 'ТЕСТ # {n}, абонентов: {number_of_devices}'.format( n=i + 1, number_of_devices=constants.DEVICES_NUMBER) results_file.write(test_string) print(test_string) results_file.write('\n') obtain_responses(devices, Switch) begin = '*********************[Начало цикла обмена]***************\n' print(begin) results_file.write(begin) elapsed_time += len( devices) * 1 * 10**-5 # time to obtain data from N devices elapsed_time += 2 * 10**-4 # switch receives data elapsed_time += 5 * 10**-4 # switch processes data
print 'led process created: ' + str(led_process) def kill_bootled(): cmd = "sudo pkill -1 -f /home/alarm/QB_Nebulae_V2/Code/nebulae/bootleds.py" os.system(cmd) led_process = None if len(sys.argv) > 1: arg = sys.argv[1] else: arg = None collector = calibration_collector.CalibrationCollector() pitch_click = switch.Switch(22) # Pitch Encoder Click GPIO pitch_click.update() if pitch_click.state() == True or arg == 'force': launch_bootled() #time.sleep(2) print 'Calibration commencing' collector.collect() # Clear out settings and factory reset if neb_globals.remount_fs is True: os.system("sh /home/alarm/QB_Nebulae_V2/Code/scripts/mountfs.sh rw") cmd = "rm /home/alarm/QB_Nebulae_V2/Code/config/bootinstr.txt" os.system(cmd) cmd = "rm /home/alarm/QB_Nebulae_V2/Code/config/nebsettings.txt" os.system(cmd) cmd = "rm /home/alarm/QB_Nebulae_V2/Code/config/buffer_cnt.txt" os.system(cmd)
# S1 ---- S2 # / | \ | # H1 H2 H3 H4 # import topology, switch, host, port topo = topology.Topology() s1 = switch.Switch("s1") topo.addSwitch(s1) s2 = switch.Switch("s2") topo.addSwitch(s2) s3 = switch.Switch("s3") topo.addSwitch(s3) #s3.chassi=100 s4 = switch.Switch("s4") topo.addSwitch(s4) s5 = switch.Switch("s5") topo.addSwitch(s5) s6 = switch.Switch("s6") topo.addSwitch(s6) h1 = host.Host('h1') h1.addPort(port.Port('AA:AA:AA:CC:CC:CC'))
# S1 ---- S2 # / | \ | # H1 H2 H3 H4 # import topology, switch, host, port topo = topology.Topology() central=switch.Switch("central") topo.addSwitch(central) for z in range(10): s1 = switch.Switch("s1") topo.addSwitch(s1) central.addConnection(z,s1,101,topology._100M) s2 = switch.Switch("s2") topo.addSwitch(s2) central.addConnection(100 + z,s2,101,topology._100M) for i in range(100): h=host.Host("h"+str(i)) h.addPort(port.Port('AA:AA:AA:CC:CC:CF')) s1.addConnection(i,h,h.ports[0],topology._100M) for i in range(100): h=host.Host("h"+str(i)) h.addPort(port.Port('AA:AA:AA:CC:CC:CF')) s2.addConnection(i,h,h.ports[0],topology._100M)
import pin import ttl_7408 import ttl_7432 import input import switch import connection as w from time import sleep u1 = ttl_7408.TTL_7408('u1') u2 = ttl_7432.TTL_7432('u2') in1 = input.Input('in1') in2 = input.Input('in2') in3 = input.Input('in3') in4 = input.Input('in4') sw1 = switch.Switch('sw1') w1 = w.Connection('in1out', 'sw1a1') w2 = w.Connection('in2out', 'u1b1') w3 = w.Connection('sw1y1', 'u1a1') w4 = w.Connection('in3out', 'u2a1') w5 = w.Connection('in4out', 'u2b1') # print(pin.pin) in1.set('out', 1) in2.set('out', 1) in3.set('out', 1) in4.set('out', 0) sw1.set_state(True) # print(pin.pin) # u1.set('a1', 1)
bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=20) # initialize the test again #sem_ip_state = 0 # open log filename_inj = 'logs/log_' + datetime.now().strftime( "%d-%m-%Y_%H-%M-%S") + '.txt' filemode_inj = 'a' log_outf = open(filename_inj, filemode_inj) serial_port = sys.argv[1] # serial port to read data from s = switch.Switch(sys.argv[2], 4) port = int(sys.argv[3]) serial_baud = 115200 # baud rate for serial port #configure FPGA write_logs("[INFO] starting radiation experiment...") write_logs("[INFO] configuring device...") reset() ######################## #serial port parameters ######################## serial_interface = serial.Serial(port=serial_port,
from flask_restful import reqparse, abort, Api, Resource, inputs app = Flask(__name__) api = Api(app) parser = reqparse.RequestParser() parser.add_argument(SwitchRequest.waterPump) parser.add_argument(SwitchRequest.lights) lightPinNumber = 23 pumpPinNumber = 24 currentTime = time.time() lightsPin = None # lightsPin = gpiozero.DigitalOutputDevice(lightPinNumber) lightSwitch = switch.Switch(lightsPin, currentTime) pumpPin = None # pumpPin = gpiozero.DigitalOutputDevice(pumpPinNumber) pumpSwitch = switch.Switch(pumpPin, currentTime) def getSecondsFromMinutes(minutes): return minutes * 60 def getSwitchData(): data = {} data[SwitchRequest.waterPump] = pumpSwitch.isOn data[SwitchRequest.lights] = lightSwitch.isOn return data