def __init__(self): super(TestWindow, self).__init__() self.__bus = Bus() print self.__bus.get_name() self.__bus.connect("disconnected", gtk.main_quit) context_path = self.__bus.create_input_context("Test") print context_path self.__context = InputContext(self.__bus, context_path) self.__context.set_capabilities(9) self.__context.connect("commit-text", self.__commit_text_cb) self.__context.connect("update-preedit-text", self.__update_preedit_text_cb) self.__context.connect("show-preedit-text", self.__show_preedit_text_cb) self.__context.connect("update-auxiliary-text", self.__update_auxiliary_text_cb) self.__context.connect("update-lookup-table", self.__update_lookup_table_cb) self.set_events(gtk.gdk.KEY_PRESS_MASK | gtk.gdk.KEY_RELEASE_MASK | gtk.gdk.FOCUS_CHANGE_MASK) self.connect("key-press-event", self.__key_press_event_cb) self.connect("key-release-event", self.__key_release_event_cb) self.connect("delete-event", gtk.main_quit) self.connect("focus-in-event", lambda *args: self.__context.focus_in()) self.connect("focus-out-event", lambda *args: self.__context.focus_out()) self.show_all()
def query_stop(router_name, stop_id): stoptype = request.args.get('stoptype', '0') bus = Bus() res = bus.query_stop(router_name, stoptype, stop_id) return jsonify(res)
def __init__(self, debug): """ Initialize the data members of the component. """ self.debug_info = debug if self.debug_info is True: print("[CPU] initializing...") self.bus = Bus(debug) self.register_table = { # General purpose registers "rax": 0, "rbx": 0, "rcx": 0, "rdx": 0, "r8": 0, "r9": 0, # Special purposee registers "pc": 0, "rsp": 0, "rbp": 0, "rip": 0, "rflags": 0, } # Performance/timing variables self.current_instr_size = 0 self.current_instr_cycles = 0 self.cpi = 0 ########################### if self.debug_info is True: print("[CPU] finished initializing...")
def query_router(router_name): direction = request.args.get('direction', '0') router_name = router_name.encode('utf-8') bus = Bus() routers = bus.query_router(router_name, direction) return jsonify(routers)
def query_router_details(router_name): direction = request.args.get('direction', '0') bus = Bus() router_details = bus.query_router_details(router_name, direction) return jsonify(router_details)
def get_stops(stop_type, number): if stop_type not in ['up', 'down']: return jsonify(Response(error=1, msg='stop type error').dumps()) bus = Bus(number=number, stop_type={'up': 0, 'down': 1}[stop_type]) bus.get_stations() stops = bus.get_stops() return jsonify(Response(error=0, msg='', data=stops).dumps())
def query_stop(router_name, stop_id): direction = request.args.get('direction', '0') bus = Bus() res = bus.query_stop(router_name, direction, stop_id) return jsonify(res)
def __init__(self, memory_size, virtual_memory_size, debug): self.debug_info = debug if self.debug_info is True: print("[Memory] initializing...") ### Initialization code ### self.virtual_memory = [None] * virtual_memory_size self.memory = [None] * memory_size self.page_table_register = None self.bus = Bus(debug) self.memory_size = memory_size self.number_of_pages_loaded = 0 self.memory_used = 0 ### Virtual Memory ### # Assuming size of memory is self.stack_address_used = 0x8000 # decrease as memory is used, stack # grows up self.const_stack_start = 0x8000 self.heap_address_used = 0 # increase as memory is used self.const_heap_start = 0x4000 self.bss_address_used = 0 # increase as memory is used self.const_bss_start = 0x2000 self.text_address_used = 0 # increase as memory is used self.const_text_start = 0x1000 ########################### if self.debug_info is True: print("[Memory] finished initializing...")
def test_bus_apply(): bus = Bus(4) bus.line = [0, 1, 0, 1] bus.apply([1, None, None, 0]) assert bus.line == [1, 1, 0, 0]
def _set_bus_list(self, passenger): bus_list = [] for line in self._get_csv_list(): bus = Bus() bus.bus_builder(line, passenger) bus_list.append(bus) self._bus_list = bus_list
def new_bus(bus: Bus): print(bus) bus.on_close().subscribe( on_next=lambda x: print(f"CLOSE BUS {x}"), on_error=lambda e: logging.exception(e) )
def query_router_details(router_name): stoptype = request.args.get('stoptype', '0') bus = Bus() router_details = bus.query_router_details(router_name, stoptype) return jsonify(router_details)
def __init__(self): super().__init__() nes = Nes() nes.load('roms/mario.nes') # configure ppu self._ppu_bus = Bus() self._ppu_pattern = PatternTable() self._ppu_pattern.load(nes.chr) self._ppu_name = NameTable() self._ppu_palette = PaletteTable() self._ppu_bus.connect(self._ppu_pattern) self._ppu_bus.connect(self._ppu_name) self._ppu_bus.connect(self._ppu_palette) self._ppu = Ppu(self._ppu_bus) # configure cpu self._cpu_ram = Ram() self._pgr = PGRRom() self._pgr.load(nes.pgr) self._papu_ram = PAuExp() self._cpu_bus = Bus() self._cpu_bus.connect(self._pgr) self._cpu_bus.connect(self._cpu_ram) self._cpu_bus.connect(self._papu_ram) self._cpu_bus.connect(self._ppu.get_register()) self._cpu = Cpu6502(self._cpu_bus) self._cpu.reset() self._ppu.set_request_nmi(self._cpu.request_nmi) self._addr_map, self._code = self._cpu.decode(0x8000, 0xFF00) self._font = pygame.font.SysFont('inconsolatan', 24) self._cpu_running = False self._cpu_time_last = 0
def __init__(self, cache_size, block_size, debug): """ Initialize the cache component. """ self.debug_info = debug if self.debug_info is True: print("[Cache] initializing...") ### Initialization code ### self.cache_size = cache_size self.block_size = block_size self.num_of_blocks_used = 0 self.max_number_of_blocks = int(self.cache_size / self.block_size) self.cache = [Block()] * int(self.cache_size / self.block_size) self.bus = Bus(self.debug_info) ########################### #### Performance Stats #### self.hits = 0 self.misses = 0 self.replacements = 0 ########################### if self.debug_info is True: print("[Cache] finished initializing...") print("[Cache] Max number of blocks '", self.max_number_of_blocks, "'...")
class TestWindow(gtk.Window): def __init__(self): super(TestWindow, self).__init__() self.__bus = Bus() print self.__bus.get_name() self.__bus.connect("disconnected", gtk.main_quit) context_path = self.__bus.create_input_context("Test") print context_path self.__context = InputContext(self.__bus, context_path) self.__context.set_capabilities(9) self.__context.connect("commit-text", self.__commit_text_cb) self.__context.connect("update-preedit-text", self.__update_preedit_text_cb) self.__context.connect("show-preedit-text", self.__show_preedit_text_cb) self.__context.connect("update-auxiliary-text", self.__update_auxiliary_text_cb) self.__context.connect("update-lookup-table", self.__update_lookup_table_cb) self.set_events(gtk.gdk.KEY_PRESS_MASK | gtk.gdk.KEY_RELEASE_MASK | gtk.gdk.FOCUS_CHANGE_MASK) self.connect("key-press-event", self.__key_press_event_cb) self.connect("key-release-event", self.__key_release_event_cb) self.connect("delete-event", gtk.main_quit) self.connect("focus-in-event", lambda *args: self.__context.focus_in()) self.connect("focus-out-event", lambda *args: self.__context.focus_out()) self.show_all() def __commit_text_cb(self, context, text): print "commit-text:", text.text def __update_preedit_text_cb(self, context, text, cursor_pos, visible): print "preedit-text:", text.text, cursor_pos, visible def __show_preedit_text_cb(self, context): print "show-preedit-text" def __hide_preedit_text_cb(self, context): print "hide-preedit-text" def __update_auxiliary_text_cb(self, context, text, visible): print "auxiliary-text:", text.text, visible def __update_lookup_table_cb(self, context, table, visible): print "update-lookup-table:", visible def __key_press_event_cb(self, widget, event): self.__context.process_key_event(event.keyval, event.state) def __key_release_event_cb(self, widget, event): self.__context.process_key_event( event.keyval, event.state | modifier.RELEASE_MASK)
def process_threaded(self, in_bus: Bus, out_bus: Bus, delay: float, kill_thread: Event): while not kill_thread.is_set(): sensor_vals = in_bus.read() if sensor_vals is not None: control_val = self.process(sensor_vals) out_bus.write(control_val) sleep(delay)
def distribute_initial_buses(self): m = 2 n = self._stop_num // m for bs in range(n - 1): enter_link_no = (bs + 1) * m bus = Bus(self._total_bus, self._stop_num) bus.is_counted = False self._total_bus += 1 self._link_list[enter_link_no].enter_bus(bus, 0) self._total_bus_list.append(bus)
class Peer(object): def __init__(self, share_path, host=None, port=None): self.host, self.port = (host or ALL), (port or PORT) self.db = dal.DB("sqlite://") self.db.define_table("config", dal.Field("key", key=True), dal.Field("value")) if "peerid" not in self.db.config: self.db.config["peerid"] = hex(random.getrandbits(48))[2:14] self.db.define_table( "peers", dal.Field("peerid"), dal.Field( "address", serialize=lambda x: "%s:%i" % x, convert=lambda x: tuple(f(a) for f, a in zip((str, int), x.rsplit(":", 1))), ), dal.Field("ignore", default=False), ) self.db.define_table("resources", dal.Field("path", key=True), dal.Field("age", int), dal.Field("real_path")) if os.path.isdir(share_path) and share_path[-1] != "/": share_path += "/" for path in find(os.path.abspath(share_path)): short_path = path[len(share_path) :] print path, short_path self.db.resources.insert(path=short_path, age=mod_time(os.stat(path)), real_path=path) self.bus = Bus() self.bus.connect(MessageType.HeardFromPeer, self.introduce) self.bus.connect(MessageType.Request, self.notify) self.bus.connect(MessageType.RemoteUpdate, self.remote_update) self.public = Broadcaster(self.bus, self.db.config["peerid"], (self.host, self.port)) self.private = Whisperer(self.bus, (self.host, self.port)) def start(self): self.bus.start() self.public.start() self.private.start() def announce(self): self.broadcaster.send("Hello?") def remote_update(self, message): if self.filter(message.path): self.private.retrieve(message.address, message.path) def introduce(self, message): print message self.db.peers.insert(**message) def notify(self, message): print message self.public.send(self.db.resources[message.path].age) def stop(self): self.private.stop() self.public.stop() self.bus.stop()
def __init__(self, port, baud=1000000, show_packets=False): Bus.__init__(self, show_packets) self.serial_port = serial.Serial(port=port, baudrate=baud, timeout=0.1, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, xonxoff=False, rtscts=False, dsrdtr=False)
def __init__(self, port, baud=1000000, show=SHOW_NONE): Bus.__init__(self, show) self.serial_port = serial.Serial(port=port, baudrate=baud, timeout=0.1, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, xonxoff=False, rtscts=False, dsrdtr=False)
def get_hardware_config(): """ Read some sort of easy to do configuration for how the hardware is setup. Return an array that holds MCP23017 class instances. """ # instantiate the bus from the class file. The class file has the # hw configuration specific to this installation. busses=Bus() #return chip1 return busses.get_bus_devices() # only return bus1, dev0
def get_hardware_config(): """ Read some sort of easy to do configuration for how the hardware is setup. Return an array that holds MCP23017 class instances. """ # instantiate the bus from the class file. The class file has the # hw configuration specific to this installation. busses = Bus() #return chip1 return busses.get_bus_devices() # only return bus1, dev0
def __init__(self): self.clk = None self.bus = Bus(CPU.REG_WIDTH) self.memory_register = WideRegister(4) self.memory = Memory() self.register_a = WideRegister(CPU.REG_WIDTH) self.register_a_three_state = WideThreeState(CPU.REG_WIDTH) self.register_b = WideRegister(CPU.REG_WIDTH) self.register_b_three_state = WideThreeState(CPU.REG_WIDTH) self.alu = Alu(CPU.REG_WIDTH) self.out_register = WideRegister(CPU.REG_WIDTH) self.display = NumDisplay(CPU.REG_WIDTH)
class TestWindow(gtk.Window): def __init__(self): super(TestWindow,self).__init__() self.__bus = Bus() print self.__bus.get_name() self.__bus.connect("disconnected", gtk.main_quit) context_path = self.__bus.create_input_context("Test") print context_path self.__context = InputContext(self.__bus, context_path) self.__context.set_capabilities (9) self.__context.connect("commit-text", self.__commit_text_cb) self.__context.connect("update-preedit-text", self.__update_preedit_text_cb) self.__context.connect("show-preedit-text", self.__show_preedit_text_cb) self.__context.connect("update-auxiliary-text", self.__update_auxiliary_text_cb) self.__context.connect("update-lookup-table", self.__update_lookup_table_cb) self.set_events(gtk.gdk.KEY_PRESS_MASK | gtk.gdk.KEY_RELEASE_MASK | gtk.gdk.FOCUS_CHANGE_MASK) self.connect("key-press-event", self.__key_press_event_cb) self.connect("key-release-event", self.__key_release_event_cb) self.connect("delete-event", gtk.main_quit) self.connect("focus-in-event", lambda *args: self.__context.focus_in()) self.connect("focus-out-event", lambda *args: self.__context.focus_out()) self.show_all() def __commit_text_cb(self, context, text): print "commit-text:", text.text def __update_preedit_text_cb(self, context, text, cursor_pos, visible): print "preedit-text:", text.text, cursor_pos, visible def __show_preedit_text_cb(self, context): print "show-preedit-text" def __hide_preedit_text_cb(self, context): print "hide-preedit-text" def __update_auxiliary_text_cb(self, context, text, visible): print "auxiliary-text:", text.text, visible def __update_lookup_table_cb(self, context, table, visible): print "update-lookup-table:", visible def __key_press_event_cb(self, widget, event): self.__context.process_key_event(event.keyval, event.state) def __key_release_event_cb(self, widget, event): self.__context.process_key_event(event.keyval, event.state | modifier.RELEASE_MASK)
def poll(): os.system('setterm -cursor off') interface = Bus() device = interface.identify() time.sleep(0.02) while device['system'] == WB_DOWN: device = interface.identify() time.sleep(1) if device['system'] == WB_AUTH: interface.wavebird_init(device['id']) try: while 1: device = interface.identify() time.sleep(0.02) status = interface.status(device['system']) for field, values in BUTTON[device['system']].items(): for value in values: if value.mask != 0xFF: print("{}{}{} ".format(value.color if getattr(status, field) & value.mask else DGRAY, value.name, END), end='') else: print("{}{}:{:+03X}{} ".format(value.color, value.name, getattr(status, field), END), end='') if 'slot' in device: print("slot:{}".format(device['slot']), end='') print("\r", end='') time.sleep(0.02) except KeyboardInterrupt: pass os.system('setterm -cursor on') print("")
def __init__(self) -> None: ''' Check for dat file, serializes all dag file DAG objects, sets dags set class attribute ''' signal.signal(signal.SIGINT, lambda x, y: sys.exit(0)) self.db = {} self.dags = pqueue.PriorityQueue() self.tsq = Queue() self.lock = mt.Lock() self.store_dags() self.bus = Bus(self.lock, self.tsq, self.db, self.dags) self.bus.start() self.printdb() self.seat_sections()
def main(): list = [ Vehicle(100, 200000, 4), Bus(90, 350000, 45), Vehicle(200, 300000, 8), Bus(100, 300000, 40), Vehicle(150, 250000, 2), Bus(95, 400000, 35), ] for x in list: if not isinstance(x, Bus): continue print(f"{ x }\nFare: { fare(x) } $", end="\n\n")
def start(self): last(self.cfg) if self.cfg.channel not in self.channels: self.channels.append(self.cfg.channel) self.stopped.clear() self.connected.clear() self.joined.clear() self.sock = None self.doconnect(self.cfg.server, self.cfg.nick, int(self.cfg.port)) self.connected.wait() Handler.start(self) Output.start(self) Bus.add(self) if not self.keeprunning: launch(self.keep) self.wait()
def update_buses(self): """ Polls the API and creates and adds Bus objects to the current bus list. Puts the buses in the current list to the previous bus list. Then sorts the current list by Bus ID. """ self.__prev = self.__buses self.__buses = [] raw_bus_list = api.get_buses() # raw_bus_list = api.get_buses_on_route(633) for raw_bus in raw_bus_list: id = raw_bus['id'] name = raw_bus['name'] route = raw_bus['route'] location = (raw_bus['lat'], raw_bus['lon']) heading = raw_bus['heading'] speed = -1 last_stop = raw_bus['lastStop'] last_update = raw_bus['lastUpdate'] b = Bus(id, name=name, route=route, location=location, heading=heading, speed=speed, last_stop=last_stop, last_update=last_update) self.__buses.append(b) self.__buses.sort(key=lambda x: x.get_id()) self.calculate_speeds()
def main(): """ Main Routine """ print("\n[.] Initializing parameters/settings for simulator...") print("[.] Values in brackets represent reccommended/tested values.") print("[.] Using untested values may result in unstable behavior.\n") # Ask for parameters user_debug = input("[?] Enable debugging information [No]: ") debug = (user_debug == "Yes") memory_size = input("[?] Size of main memory (bytes) [100]: ") virtual_memory_size = input("[?] Size of virtual memory (bytes) [8000]: ") cache_size = input("[?] Size of cache (bytes)[40]: ") block_size = input("[?] Size of cache blocks (bytes)[4]: ") page_size = input("[?] Size of disk pages (bytes)[32]: ") table_size = input("[?] Number of TLB table entries (bytes)[10]: ") # Initialize components with bus and debug flag bus = Bus(debug) cpu = CPU(debug) cache = Cache(int(cache_size), int(block_size), debug) tlb = TLB(int(table_size), debug) memory = Memory(int(memory_size), int(virtual_memory_size), debug) disk = Disk(int(page_size), debug) # Initialize GUI menu = GUI(bus, cpu, cache, tlb, memory, disk, debug) menu.menu_loop()
def main(args): readConfig(vars(args)) if args.debug: level = logging.DEBUG else: level = logging.INFO logstream = sys.stderr try: if args.logMain: logstream = open(args.logMain, 'w') except: pass logging.basicConfig(level=level, stream=logstream) logging.debug(args) ser = rs485.RS485(args.port, args.baudrate, timeout=0.2, writeTimeout=0.2) bus = Bus(ser) script = None try: if args.script: script = open(args.script) except Exception as e: logging.warning("Unable to open script file (%s)" % str(e)) master = Master(bus, script) master.loop() return 0
def _startBuses(self): for _ in range(2): self._queuesOut.append(queue.Queue()) self._buses.append( Bus("P" + str(0), self._chipNumber, self._queuesIn, self._queuesOut[0], self._lock, self._mainwin, self._guiQueues[1:3], self._gameMode)) self._buses.append( Bus("P" + str(1), self._chipNumber, self._queuesIn, self._queuesOut[1], self._lock, self._mainwin, self._guiQueues[3:5], self._gameMode)) self._buses[0].start() self._buses[1].start()
def __init__(self): super(TestWindow,self).__init__() self.__bus = Bus() print self.__bus.get_name() self.__bus.connect("disconnected", gtk.main_quit) context_path = self.__bus.create_input_context("Test") print context_path self.__context = InputContext(self.__bus, context_path) self.__context.set_capabilities (9) self.__context.connect("commit-text", self.__commit_text_cb) self.__context.connect("update-preedit-text", self.__update_preedit_text_cb) self.__context.connect("show-preedit-text", self.__show_preedit_text_cb) self.__context.connect("update-auxiliary-text", self.__update_auxiliary_text_cb) self.__context.connect("update-lookup-table", self.__update_lookup_table_cb) self.__context.connect("enabled", self.__enabled_cb) self.__context.connect("disabled", self.__disabled_cb) self.set_events(gtk.gdk.KEY_PRESS_MASK | gtk.gdk.KEY_RELEASE_MASK | gtk.gdk.FOCUS_CHANGE_MASK) self.connect("key-press-event", self.__key_press_event_cb) self.connect("key-release-event", self.__key_release_event_cb) self.connect("delete-event", gtk.main_quit) self.connect("focus-in-event", lambda *args: self.__context.focus_in()) self.connect("focus-out-event", lambda *args: self.__context.focus_out()) self.show_all()
def test_bus_arrived_and_everybody_got_on_the_bus(self): lane = Lane() stop = BusStop(lane, 30, 10) line = BusLine([stop], 0, 500) bus = Bus(line, 10, 10) control.bus_stop(bus, stop) self.assertEquals(bus.people_carried, 20) self.assertEquals(stop.people, 0)
def test_bus_arrived_at_stop_at_full_capacity(self): lane = Lane() stop = BusStop(lane, 30, 10) line = BusLine([stop], 0, 500) bus = Bus(line, 10, 100) control.bus_stop(bus, stop) self.assertEquals(bus.people_carried, 100) self.assertEquals(stop.people, 10)
def test_bus_arrived_and_people_were_left_at_stop(self): lane = Lane() stop = BusStop(lane, 30, 10) line = BusLine([stop], 0, 500) bus = Bus(line, 10, 93) control.bus_stop(bus, stop) self.assertEquals(bus.people_carried, 100) self.assertEquals(stop.people, 3)
class TestPanel(PanelBase): def __init__(self): self.__bus = Bus() self.__bus.connect("disconnected", gtk.main_quit) super(TestPanel, self).__init__(self.__bus) self.__bus.request_name(IBUS_SERVICE_PANEL, 0) def focus_in(self, ic): print "focus-in:", ic context = InputContext(self.__bus, ic) info = context.get_factory_info() print "factory:", info.name def focus_out(self, ic): print "focus-out:", ic def update_auxiliary_text(self, text, visible): print "update-auxiliary-text:", text.text def update_lookup_table(self, table, visible): print "update-lookup-table", table
def changeShape(self,index): print "changeShape" tempoffset=self.offset self.settings.shape=self.nameid[index][1] self.bus=Bus(self.settings.shape,self.offset,self.backsb.value(),self.forwardsb.value()) self.busname=self.nameid[index][0] self.showMessage("Monitoring "+self.busname+".\n Alert near "+self.bus.offsetToName(self.bus.busoffset)) self.update() self.stopcb.clear() for n in self.bus.waypointlist: self.stopcb.addItem(n[0]) stopnamelist=[x[0] for x in self.bus.waypointlist] self.stopcb.setCurrentIndex(stopnamelist.index(self.bus.offsetToName(tempoffset)))
def bus_data(self, route, sort=False): """Get list of timeframes of bus objects.""" # Initialize variables bus_files = self._available_bus_files(route, sort=sort) read_json = self._read_json bus_data = [] for bus_file in bus_files: bus_json = read_json(bus_file) if bus_json is not None: recv_time = self._date_from_file(bus_file) buses = map(lambda x: Bus.from_json(x), bus_json["bus"]) timeframe = TimeFrame(recv_time, data=buses) bus_data.append(timeframe) return bus_data
def __init__(self, useLogger = False): self.id = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] self.pose = [512, 512, 512, 512, 512, 512, 512, 512, 512, 512, 512, 512] self.nextPose = [512, 512, 512, 512, 512, 512, 512, 512, 512, 512, 512, 512] self.speed = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] self.interpolating = False self.playing = False self.servoCount = 12 self.lastFrame = pyb.millis() self.port = UART_Port(1, 1000000) self.bus = Bus(self.port, show=Bus.SHOW_PACKETS) # Bus.SHOW_NONE # Bus.SHOW_COMMANDS # Bus.SHOW_PACKETS if useLogger: self.logger = Logger('sync_log.txt') else: self.logger = None
def __init__(self, username, username_password=None, realname=None, init_channels=None): self._conn = None self._write_conn = None self._read_conn = None self.username = username self.username_password = username_password if not realname: self.realname = username else: self.realname = realname self.bus = Bus() self.plugins = Loader(self.bus) self.plugins.load_plugins() self.joined = False if init_channels is None: self._init_channels = [] else: self._init_channels = init_channels
# pylint: disable=I0011,C0103 from event import Event from bus import Bus from listener import WeatherBot # 1- Register listeners on the bus bot_name = 'pyro' zipcode = 94040 bus = Bus() bus.register(WeatherBot(bot_name), Event.Types.message_created_event) # 2- Let's create some events on the bus and see if our listeners pick them up for i in range(4): if i % 2 == 0: print "throwing message_created_event" bus.notify(Event(Event.Types.message_created_event, {"room_id":1, "data": "{} weather {}".format(bot_name, zipcode), "user_id": 123})) else: print "throwing user_joins_room" bus.notify(Event(Event.Types.user_joins_room, {}))
def __init__(self): self.__bus = Bus() self.__bus.connect("disconnected", gtk.main_quit) super(TestPanel, self).__init__(self.__bus) self.__bus.request_name(IBUS_SERVICE_PANEL, 0)
def __init__(self): self.bus=None self.count=0 super(Window, self).__init__() #need to catch timeout exceptions etc... self.settings = QtCore.QSettings('busSettings.ini', QtCore.QSettings.IniFormat) self.settings.setFallbacksEnabled(False) # File only, no fallback to registry or or. # Initial window size/pos last saved if available #self.resize(400, 300) #self.setGeometry(200, 200,500*self.bus.xfactor,500) self.resize(self.settings.value('size', QtCore.QSize(350, 500))) self.move(self.settings.value('pos', QtCore.QPoint(200, 200))) self.offset=int(self.settings.value('offset',89)) self.busname=(self.settings.value('bus',None)) self.setWindowTitle(u"busLocator map") self.show() #-------------------basic menu item------------------ self.settingAction = QtGui.QAction(u"setting", self, triggered=self.showSettingWindow) self.minimizeAction = QtGui.QAction(u"hide", self, triggered=self.hide) self.restoreAction = QtGui.QAction(u"show", self, triggered=self.showNormal) self.quitAction = QtGui.QAction(u"exit", self, triggered=self.quitApplication) #add menu self.trayIconMenu = QtGui.QMenu(self) self.trayIconMenu.addAction(self.restoreAction) self.trayIconMenu.addAction(self.minimizeAction) self.trayIconMenu.addAction(self.settingAction) self.trayIconMenu.addAction(self.quitAction) #self.trayIconMenu.clear() #self.trayIconMenu.addAction(self.quitAction) self.trayIcon = QtGui.QSystemTrayIcon(self) self.trayIcon.setContextMenu(self.trayIconMenu) #-------------------basic menu end------------------ #-------------------icon------------------ self.icon=QtGui.QIcon(":/images/bus.ico") self.trayIcon.setIcon(self.icon) #tooltip do not work on both ubuntu and win #self.trayIcon.setToolTip("tooltip") self.trayIcon.show() self.trayIcon.activated.connect( self.iconActivated) self.nameid=Bus.getRouteIDs() #self.nameid=Bus.getActiveRoute() self.names=[x[0] for x in self.nameid] self.nametoid=dict(self.nameid) #print self.busname #print self.nameid self.backsb=QtGui.QSpinBox() self.backsb.setRange(0,25) self.backsb.valueChanged[int].connect(self.backChange) self.backsb.setValue(int(self.settings.value('backward',10))) self.forwardsb=QtGui.QSpinBox() self.forwardsb.setRange(0,25) self.forwardsb.valueChanged[int].connect(self.forwardChange) self.forwardsb.setValue(int(self.settings.value('forward',10))) self.sbGroup=QtGui.QWidget() self.sblayout=QtGui.QHBoxLayout() self.sblayout.setSpacing(0) self.sblayout.addWidget(QtGui.QLabel("backward:")) self.sblayout.addWidget(self.backsb) self.sblayout.addWidget(QtGui.QLabel("forward:")) self.sblayout.addWidget(self.forwardsb) self.sbGroup.setLayout(self.sblayout) self.settingwindow=QtGui.QWidget() cb=QtGui.QComboBox() self.stopcb=QtGui.QComboBox() self.stopcb.currentIndexChanged.connect(self.changeOffset) for n in self.names: cb.addItem(n) cb.currentIndexChanged.connect(self.changeShape) if self.busname in self.nametoid: ind=self.names.index(self.busname) cb.setCurrentIndex(ind) self.changeShape(ind) toprow=QtGui.QGroupBox("Please select route") toplayout=QtGui.QFormLayout() toplayout.addRow(QtGui.QLabel("Route:"),cb) toprow.setLayout(toplayout) botrow=QtGui.QGroupBox("Route detail:") botlayout=QtGui.QFormLayout() botlayout.addRow(QtGui.QLabel("Stop to be alert:"),self.stopcb) botlayout.addRow(QtGui.QLabel("Fine adjustment:"),self.sbGroup) #botlayout.addRow([QtGui.QLabel("backward:"),self.backsb,QtGui.QLabel("forward:"),self.forwardsb]) botrow.setLayout(botlayout) slayout=QtGui.QVBoxLayout() slayout.addWidget(toprow) slayout.addWidget(botrow) self.settingwindow.setLayout(slayout) self.settingwindow.setWindowTitle(u"busLocator Setting") self.settingwindow.resize(self.settings.value('setsize', QtCore.QSize(288,134))) self.settingwindow.move(self.settings.value('setpos', QtCore.QPoint(566, 202))) if self.busname not in self.nametoid: self.settingwindow.show() self.settingwindow.setFocus() cb.setCurrentIndex(0) self.changeShape(0) else: #self.bus=Bus(self.nametoid[self.busname],self.offset,self.backsb.value(),self.forwardsb.value()) #self.showMessage("Monitoring "+self.busname+".\n Alert near "+self.bus.offsetToName(self.bus.busoffset)) #if self.busname in self.nametoid: stopnamelist=[x[0] for x in self.bus.waypointlist] self.stopcb.setCurrentIndex(stopnamelist.index(self.bus.offsetToName(self.bus.busoffset))) if len(self.bus.shape)!=0: self.bus.locateBus() self.mouse=None self.timer=QtCore.QTimer() self.timer.timeout.connect(self.doWork) self.timer.start(8000)
from event import Event from bus import Bus from listener import WeatherBot # 1- Register listeners on the bus bus = Bus() bus.register(WeatherBot(), Event.Types.message_created_event) # 2- Let's create some events on the bus and see if our listeners pick them up for i in range(4): if i % 2 == 0: print "throwing message_created_event" bus.notify(Event(Event.Types.message_created_event, {"room_id":1, "data": "pyro weather 94301", "user_id": 123})) else: print "throwing user_joins_room" bus.notify(Event(Event.Types.user_joins_room, {}))
class Window(QtGui.QWidget): def drawBus(self,nx,ny,angle,qp): ang=angle/180.*math.pi angd=15 line=8 headx=+math.sin(ang)*line+nx heady=-math.cos(ang)*line+ny tailx=-math.sin(ang)*line+nx taily=+math.cos(ang)*line+ny wing1x=-math.sin(ang+angd+math.pi)*line+headx wing1y=+math.cos(ang+angd+math.pi)*line+heady wing2x=-math.sin(ang-angd+math.pi)*line+headx wing2y=+math.cos(ang-angd+math.pi)*line+heady qp.drawLine(headx,heady,tailx,taily) qp.drawLine(headx,heady,wing1x,wing1y) qp.drawLine(headx,heady,wing2x,wing2y) def backChange(self,setvalue): if self.bus!=None: self.bus.backward=setvalue self.update() def forwardChange(self,setvalue): if self.bus!=None: self.bus.forward=setvalue self.update() def showSettingWindow(self): self.settingwindow.show() def quitApplication(self): self.closeSaving() QtGui.qApp.quit() def closeSaving(self): self.settings.setValue('size', self.size()) self.settings.setValue('pos', self.pos()) self.settings.setValue('setsize', self.settingwindow.size()) self.settings.setValue('setpos', self.settingwindow.pos()) if self.bus!=None: self.settings.setValue('bus', self.busname) self.settings.setValue('offset', self.bus.busoffset) self.settings.setValue('backward', self.bus.backward) self.settings.setValue('forward', self.bus.forward) def closeEvent(self, e): self.closeSaving() e.accept() def changeOffset(self,index): self.bus.busoffset=self.bus.waypointlist[index][1] self.offset=self.bus.busoffset #self.showMessage("Monitoring "+self.busname+".\n Alert near "+self.bus.offsetToName(self.bus.busoffset)) self.update() def changeShape(self,index): print "changeShape" tempoffset=self.offset self.settings.shape=self.nameid[index][1] self.bus=Bus(self.settings.shape,self.offset,self.backsb.value(),self.forwardsb.value()) self.busname=self.nameid[index][0] self.showMessage("Monitoring "+self.busname+".\n Alert near "+self.bus.offsetToName(self.bus.busoffset)) self.update() self.stopcb.clear() for n in self.bus.waypointlist: self.stopcb.addItem(n[0]) stopnamelist=[x[0] for x in self.bus.waypointlist] self.stopcb.setCurrentIndex(stopnamelist.index(self.bus.offsetToName(tempoffset))) def __init__(self): self.bus=None self.count=0 super(Window, self).__init__() #need to catch timeout exceptions etc... self.settings = QtCore.QSettings('busSettings.ini', QtCore.QSettings.IniFormat) self.settings.setFallbacksEnabled(False) # File only, no fallback to registry or or. # Initial window size/pos last saved if available #self.resize(400, 300) #self.setGeometry(200, 200,500*self.bus.xfactor,500) self.resize(self.settings.value('size', QtCore.QSize(350, 500))) self.move(self.settings.value('pos', QtCore.QPoint(200, 200))) self.offset=int(self.settings.value('offset',89)) self.busname=(self.settings.value('bus',None)) self.setWindowTitle(u"busLocator map") self.show() #-------------------basic menu item------------------ self.settingAction = QtGui.QAction(u"setting", self, triggered=self.showSettingWindow) self.minimizeAction = QtGui.QAction(u"hide", self, triggered=self.hide) self.restoreAction = QtGui.QAction(u"show", self, triggered=self.showNormal) self.quitAction = QtGui.QAction(u"exit", self, triggered=self.quitApplication) #add menu self.trayIconMenu = QtGui.QMenu(self) self.trayIconMenu.addAction(self.restoreAction) self.trayIconMenu.addAction(self.minimizeAction) self.trayIconMenu.addAction(self.settingAction) self.trayIconMenu.addAction(self.quitAction) #self.trayIconMenu.clear() #self.trayIconMenu.addAction(self.quitAction) self.trayIcon = QtGui.QSystemTrayIcon(self) self.trayIcon.setContextMenu(self.trayIconMenu) #-------------------basic menu end------------------ #-------------------icon------------------ self.icon=QtGui.QIcon(":/images/bus.ico") self.trayIcon.setIcon(self.icon) #tooltip do not work on both ubuntu and win #self.trayIcon.setToolTip("tooltip") self.trayIcon.show() self.trayIcon.activated.connect( self.iconActivated) self.nameid=Bus.getRouteIDs() #self.nameid=Bus.getActiveRoute() self.names=[x[0] for x in self.nameid] self.nametoid=dict(self.nameid) #print self.busname #print self.nameid self.backsb=QtGui.QSpinBox() self.backsb.setRange(0,25) self.backsb.valueChanged[int].connect(self.backChange) self.backsb.setValue(int(self.settings.value('backward',10))) self.forwardsb=QtGui.QSpinBox() self.forwardsb.setRange(0,25) self.forwardsb.valueChanged[int].connect(self.forwardChange) self.forwardsb.setValue(int(self.settings.value('forward',10))) self.sbGroup=QtGui.QWidget() self.sblayout=QtGui.QHBoxLayout() self.sblayout.setSpacing(0) self.sblayout.addWidget(QtGui.QLabel("backward:")) self.sblayout.addWidget(self.backsb) self.sblayout.addWidget(QtGui.QLabel("forward:")) self.sblayout.addWidget(self.forwardsb) self.sbGroup.setLayout(self.sblayout) self.settingwindow=QtGui.QWidget() cb=QtGui.QComboBox() self.stopcb=QtGui.QComboBox() self.stopcb.currentIndexChanged.connect(self.changeOffset) for n in self.names: cb.addItem(n) cb.currentIndexChanged.connect(self.changeShape) if self.busname in self.nametoid: ind=self.names.index(self.busname) cb.setCurrentIndex(ind) self.changeShape(ind) toprow=QtGui.QGroupBox("Please select route") toplayout=QtGui.QFormLayout() toplayout.addRow(QtGui.QLabel("Route:"),cb) toprow.setLayout(toplayout) botrow=QtGui.QGroupBox("Route detail:") botlayout=QtGui.QFormLayout() botlayout.addRow(QtGui.QLabel("Stop to be alert:"),self.stopcb) botlayout.addRow(QtGui.QLabel("Fine adjustment:"),self.sbGroup) #botlayout.addRow([QtGui.QLabel("backward:"),self.backsb,QtGui.QLabel("forward:"),self.forwardsb]) botrow.setLayout(botlayout) slayout=QtGui.QVBoxLayout() slayout.addWidget(toprow) slayout.addWidget(botrow) self.settingwindow.setLayout(slayout) self.settingwindow.setWindowTitle(u"busLocator Setting") self.settingwindow.resize(self.settings.value('setsize', QtCore.QSize(288,134))) self.settingwindow.move(self.settings.value('setpos', QtCore.QPoint(566, 202))) if self.busname not in self.nametoid: self.settingwindow.show() self.settingwindow.setFocus() cb.setCurrentIndex(0) self.changeShape(0) else: #self.bus=Bus(self.nametoid[self.busname],self.offset,self.backsb.value(),self.forwardsb.value()) #self.showMessage("Monitoring "+self.busname+".\n Alert near "+self.bus.offsetToName(self.bus.busoffset)) #if self.busname in self.nametoid: stopnamelist=[x[0] for x in self.bus.waypointlist] self.stopcb.setCurrentIndex(stopnamelist.index(self.bus.offsetToName(self.bus.busoffset))) if len(self.bus.shape)!=0: self.bus.locateBus() self.mouse=None self.timer=QtCore.QTimer() self.timer.timeout.connect(self.doWork) self.timer.start(8000) def showMessage(self,message): icon = QtGui.QSystemTrayIcon.MessageIcon() #icon=QtGui.QSystemTrayIcon.Information self.trayIcon.showMessage( u'bus coming',message, icon,2000) def mousePressEvent(self, event): self.mouse=event.pos() self.update() def paintEvent(self,event): qp=QtGui.QPainter() qp.begin(self) self.drawDetails(event,qp) qp.end() def drawDetails(self,event,qp): if len(self.bus.shape)==0: return size=self.size() w=size.width() h=size.height() wid=min(h,w/self.bus.xfactor) margine=int(wid*0.05) if self.mouse!=None: t=self.mouse.toTuple() qp.setPen(QtGui.QColor(168,34,3)) qp.setFont(QtGui.QFont('Decorative', 10)) qp.drawText(event.rect(), QtCore.Qt.AlignTop, "Offset: %s. Stop: %s"% (str(self.bus.scalemapLoopupWaypoint(margine,wid,t)),self.bus.scalemapLoopupStopName(margine,wid,t))) monitorl=self.bus.busoffset-self.bus.backward if monitorl<0: monitorl+=len(self.bus.route) monitorr=self.bus.busoffset+self.bus.forward if monitorr>len(self.bus.route): monitorr-=len(self.bus.route) pen = QtGui.QPen(QtCore.Qt.black, 2, QtCore.Qt.SolidLine) qp.setPen(pen) for i in range(len(self.bus.route)-1): if i>=monitorl and i<monitorr: continue if (i>=monitorl or i<monitorr ) and monitorl>monitorr: continue cordi=self.bus.route[i] nx,ny=self.bus.scalemap(margine,wid,cordi) cordi2=self.bus.route[i+1] nx2,ny2=self.bus.scalemap(margine,wid,cordi2) qp.drawLine(nx,ny,nx2,ny2) #print nx,ny,nx2,ny2 pen = QtGui.QPen(QtCore.Qt.green, 2, QtCore.Qt.SolidLine) qp.setPen(pen) if monitorl<monitorr: for i in range(monitorl,monitorr): cordi=self.bus.route[i] nx,ny=self.bus.scalemap(margine,wid,cordi) cordi2=self.bus.route[i+1] nx2,ny2=self.bus.scalemap(margine,wid,cordi2) qp.drawLine(nx,ny,nx2,ny2) else: for i in range(0,monitorr): cordi=self.bus.route[i] nx,ny=self.bus.scalemap(margine,wid,cordi) cordi2=self.bus.route[i+1] nx2,ny2=self.bus.scalemap(margine,wid,cordi2) qp.drawLine(nx,ny,nx2,ny2) for i in range(monitorl,len(self.bus.route)-1): cordi=self.bus.route[i] nx,ny=self.bus.scalemap(margine,wid,cordi) cordi2=self.bus.route[i+1] nx2,ny2=self.bus.scalemap(margine,wid,cordi2) qp.drawLine(nx,ny,nx2,ny2) #print nx,ny,nx2,ny2 #dotpen = QtGui.QPen(QtCore.Qt.magenta, 5, QtCore.Qt.SolidLine) #qp.setPen(dotpen) #for cordi in self.bus.ol: # nx,ny=self.bus.scalemap(margine,wid,self.bus.route[cordi]) # qp.drawPoint(nx,ny) dotpen = QtGui.QPen(QtCore.Qt.blue, 6, QtCore.Qt.SolidLine) qp.setPen(dotpen) for cordi in self.bus.co: nx,ny=self.bus.scalemap(margine,wid,cordi) qp.drawPoint(nx,ny) dotpen = QtGui.QPen(QtCore.Qt.red, 4, QtCore.Qt.SolidLine) qp.setPen(dotpen) for cordi in self.bus.buses: #print nx,ny nx,ny=self.bus.scalemap(margine,wid,cordi[:2]) self.drawBus(nx,ny,cordi[2],qp) #qp.drawPoint(nx,ny) def doWork(self): if len(self.bus.shape)==0: return self.count+=1 info,wayp=self.bus.locateBus() numbus=len(wayp) self.menu=[] self.trayIconMenu.clear() for i in range(numbus): menuitem= QtGui.QAction(info[i]+":"+str(wayp[i]), self) self.trayIconMenu.addAction(menuitem) if -self.bus.backward<wayp[i] and wayp[i]<self.bus.forward: self.showMessage(str(wayp)) self.trayIconMenu.addAction(self.restoreAction) self.trayIconMenu.addAction(self.minimizeAction) self.trayIconMenu.addAction(self.settingAction) self.trayIconMenu.addAction(self.quitAction) self.update() if self.count>3600/8: self.quitApplication() def iconActivated(self, reason): if reason in (QtGui.QSystemTrayIcon.Trigger, QtGui.QSystemTrayIcon.DoubleClick): if self.isHidden(): self.showNormal() else: self.hide()
class BioloidController: def __init__(self, useLogger = False): self.id = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] self.pose = [512, 512, 512, 512, 512, 512, 512, 512, 512, 512, 512, 512] self.nextPose = [512, 512, 512, 512, 512, 512, 512, 512, 512, 512, 512, 512] self.speed = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] self.interpolating = False self.playing = False self.servoCount = 12 self.lastFrame = pyb.millis() self.port = UART_Port(1, 1000000) self.bus = Bus(self.port, show=Bus.SHOW_PACKETS) # Bus.SHOW_NONE # Bus.SHOW_COMMANDS # Bus.SHOW_PACKETS if useLogger: self.logger = Logger('sync_log.txt') else: self.logger = None # Load a pose into nextPose def loadPose(self, poseArray): for i in range(self.servoCount): self.nextPose[i] = (poseArray[i]) # << BIOLOID_SHIFT) #print ('loadPose[', self.id[i], '] = ', self.nextPose[i]) def isLogging(self): return self.logger is not None # read the current robot's pose def readPose(self): for i in range(self.servoCount): self.pose[i] = (self.readTwoByteRegister(self.id[i], AX_GOAL_POSITION)) # << BIOLOID_SHIFT) #print ('readPose[', self.id[i], '] = ', self.pose[i]) pyb.delay(25) def writePose(self): values = [] logging = self.isLogging() if logging: logValues = [] for i in range(self.servoCount): poseValue = int(self.pose[i]) values.append(struct.pack('<H', poseValue)) if logging: logValues.append(poseValue) self.bus.sync_write(self.id, AX_GOAL_POSITION, values) if logging: self.logger.log(logValues) def slowMoveServoTo(self, deviceId, targetPosition, speed = SLOW_SERVO_MOVE_SPEED, scanFunction = None): oldSpeed = self.readTwoByteRegister(deviceId, AX_MOVING_SPEED) currentPosition = self.readTwoByteRegister(deviceId, AX_PRESENT_POSITION) self.writeTwoByteRegister(deviceId, AX_MOVING_SPEED, speed) self.writeTwoByteRegister(deviceId, AX_GOAL_POSITION, targetPosition) done = False scanCount = 0 lastPosition = 0 startTime = pyb.millis() while abs(currentPosition - targetPosition) > 5: currentPosition = self.readTwoByteRegister(deviceId, AX_PRESENT_POSITION) if scanFunction is not None: if currentPosition != lastPosition: scanCount += 1 lastPosition = currentPosition scanFunction(currentPosition, scanCount) pyb.delay(1) self.writeTwoByteRegister(deviceId, AX_MOVING_SPEED, oldSpeed) if scanFunction is not None: scanFunction(targetPosition, scanCount + 1) print("Elapsed Time: %d" % (pyb.millis() - startTime)) def rampServoTo(self, deviceId, targetPosition): currentPosition = self.readTwoByteRegister(deviceId, AX_PRESENT_POSITION) # present position if targetPosition > currentPosition: stepDelta = 1 stepAccel = 2 comparison = lambda: targetPosition > (currentPosition + stepDelta) else: stepDelta = -1 stepAccel = -2 comparison = lambda: currentPosition > (targetPosition - stepDelta) while comparison(): movePosition = currentPosition + stepDelta stepDelta += stepAccel self.setPosition(deviceId, movePosition) currentPosition = self.readTwoByteRegister(deviceId, AX_PRESENT_POSITION) # present position pyb.delay(25) self.setPosition(deviceId, targetPosition) def setPosition(self, deviceId, position): self.writeTwoByteRegister(deviceId, AX_GOAL_POSITION, position) def writeData(self, deviceId, controlTableIndex, byteData): try: result = self.bus.write(deviceId, controlTableIndex, byteData) except BusError as ex: if ex.get_error_code() == ErrorCode.CHECKSUM: print ("CHECKSUM Error - retrying...") return self.bus.write(deviceId, controlTableIndex, byteData) raise return result def writeTwoByteRegister(self, deviceId, controlTableIndex, value): return self.writeData(deviceId, controlTableIndex, struct.pack('<H', value)) def writeOneByteRegister(self, deviceId, controlTableIndex, value): return self.writeData(deviceId, controlTableIndex, struct.pack('B', value)) def readTwoByteRegister(self, deviceId, controlTableIndex): values = self.readData(deviceId, controlTableIndex, 2) return struct.unpack('<H', values)[0] def readOneByteRegister(self, deviceId, controlTableIndex): values = self.readData(deviceId, controlTableIndex, 1) return struct.unpack('B', values)[0] def readData(self, deviceId, controlTableIndex, count): try: result = self.bus.read(deviceId, controlTableIndex, count) except BusError as ex: if ex.get_error_code() == ErrorCode.CHECKSUM: print ("CHECKSUM Error - retrying...") return self.bus.read(deviceId, controlTableIndex, count) raise return result def interpolateSetup(self, time): frames = (time / BIOLOID_FRAME_LENGTH) + 1 self.lastFrame = pyb.millis() for i in range(self.servoCount): if self.nextPose[i] > self.pose[i]: self.speed[i] = (self.nextPose[i] - self.pose[i]) / frames + 1 else: self.speed[i] = (self.pose[i] - self.nextPose[i]) / frames + 1 self.interpolating = True def interpolateStep(self): if not self.interpolating: return complete = self.servoCount while (pyb.millis() - self.lastFrame < BIOLOID_FRAME_LENGTH): pass self.lastFrame = pyb.millis() for i in range(self.servoCount): diff = self.nextPose[i] - self.pose[i] if diff == 0: complete -= 1 else: if diff > 0: if diff < self.speed[i]: self.pose[i] = self.nextPose[i] complete -= 1 else: self.pose[i] += self.speed[i] else: if (-diff) < self.speed[i]: self.pose[i] = self.nextPose[i] complete -= 1 else: self.pose[i] -= self.speed[i] if complete <= 0: self.interpolating = False self.writePose()
class Botter(object): def __init__(self, username, username_password=None, realname=None, init_channels=None): self._conn = None self._write_conn = None self._read_conn = None self.username = username self.username_password = username_password if not realname: self.realname = username else: self.realname = realname self.bus = Bus() self.plugins = Loader(self.bus) self.plugins.load_plugins() self.joined = False if init_channels is None: self._init_channels = [] else: self._init_channels = init_channels def connect(self, server, port): LOG.info('Connect to %s:%s' % (server, port)) self._con_opts = (server, port) self._conn = socket.create_connection((server, port)) self._conn.send("""PASS {uniquepass}\r\n NICK {username}\r\n USER {username} testbot testbot :{realname}\r\n""".format(uniquepass=uuid.uuid1().hex, username=self.username, realname=self.realname)) self._write_conn = self._conn.dup() self._read_conn = self._conn.dup() def pong(self, msg): answer = msg.strip().split(':')[1] self._write_conn.send('PONG %s\r\n' % answer) def _parse_message(self, buf): LOG.info('Start message parsing') messages = [] for msg in buf.split('\r\n'): msg = msg.strip() if not msg: continue LOG.info('Parse: %s' % msg) if msg.startswith('PING'): self.pong(msg) continue if 'ERROR :Closing Link:' in msg: self.connect(self._con_opts[0], self._con_opts[1]) return [] msg_opts = msg.split() user_opts = msg_opts[0][1:].split('!') if len(user_opts) > 1: sender, user_ident = user_opts[0], user_opts[1] else: sender, user_ident = user_opts[0], None receiver = msg_opts[2] msg_type = msg_opts[1] message = ' '.join(msg_opts[3:])[1:] if msg_type == 'NOTICE' and receiver == 'AUTH' and message.startswith('*** You connected'): for chan in self._init_channels: self.join_channel(chan) if msg_type == 'NOTICE' and sender == 'NickServ' and 'NickServ IDENTIFY' in message: self.authorize() continue messages.append({'sender': sender, 'receiver': receiver, 'msg_type': msg_type, 'message': message, 'user_ident': user_ident}) return messages def authorize(self): LOG.info('Authorize in nickserv') if self.username_password: self.bus.send_out_message({'receiver':'NickServ', 'message': 'identify %s' % self.username_password}) def send_message(self, message): if isinstance(message, list): for m in message: LOG.info('Send "%s" to "%s"' % (m['message'], m['receiver'])) self._write_conn.send('PRIVMSG %s :%s\r\n' % (m['receiver'], m['message'])) else: LOG.info('Send "%s" to "%s"' % (message['message'], message['receiver'])) self._write_conn.send('PRIVMSG %s :%s\r\n' % (message['receiver'], message['message'])) def join_channel(self, channel): LOG.info('Join to channel %s' % channel) self.joined = True if not channel.startswith('#'): channel = '#' + channel if len(channel.split(':')) > 1: channel, password = channel.split(':') self._write_conn.send('JOIN %s %s\r\n' % (channel, password)) else: self._write_conn.send('JOIN %s\r\n' % channel) def work(self): """Start Loader check bus to input messages""" receive = gevent.spawn(self._start_recv) sender = gevent.spawn(self._start_send) while not self.joined: gevent.sleep(1) self.plugins.work() gevent.joinall([ receive, sender ]) def _start_recv(self): buf = '' while True: try: msg = self._read_conn.recv(512) except socket.error, e: LOG.error('Can\'t send message: %s' % e) if 'Broken pipe' in e: LOG.info('Reconnect to server') self.connect(self._con_opts[0], self._con_opts[1]) buf += msg if len(msg) < 512 and msg.endswith('\r\n'): messages = self._parse_message(buf) buf = '' if messages: self.bus.send_in_message(messages) gevent.sleep(0.1)
logger = logging.getLogger("simple_example") logger.setLevel(logging.DEBUG) # Create console handler and set level to debug console_logger = logging.StreamHandler() console_logger.setLevel(logging.DEBUG) # Create formatter formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") # Add formatter to console_logger console_logger.setFormatter(formatter) # Add console_logger to logger logger.addHandler(console_logger) app.logger.addHandler(logger) # Create an event bus bus = Bus() sparklebot_name = 'Pyro' sparklebot = SparkleBot(name=sparklebot_name, bus=bus) # Register our new bot with the bus as a listener for # any Event.Types.message_created_event that are emitted bus.register(sparklebot, Event.Types.message_created_event) # ====== END Server Start-up ====== # ====== Routes Definitions ======
# pylint: disable=I0011,C0103 from event import Event from bus import Bus from listener import SparkleBot import os import re import urllib import urllib2 from weather_api import WeatherAPI # 1- Register listeners on the bus bot_name = 'Pyro' zipcode = 94040 bus = Bus() bus.register(SparkleBot(bot_name, bus=bus, user_id=8), Event.Types.message_created_event) # 2- Let's create some events on the bus and see if our listeners pick them up num = 4 for i in range(num): if i % num == 0: print "throwing message_created_event - weather" bus.notify(Event(Event.Types.message_created_event, {"room_id":1, "data": "{} weather {}".format(bot_name, zipcode), "user_id": 2, "user_name": "Anony Mouse"})) elif i % num == 1: print "throwing message_created_event - help" bus.notify(Event(Event.Types.message_created_event, {"room_id":1, "data": "{} help".format(bot_name), "user_id": 2, "user_name": "Anony Mouse"})) elif i % num == 2: print "throwing message_created_event - story" bus.notify(Event(Event.Types.message_created_event, {"room_id":1, "data": "{} story".format(bot_name), "user_id": 2, "user_name": "Anony Mouse"})) else: print "throwing user_joins_room_event" bus.notify(Event(Event.Types.user_joins_room_event, {}))
#!/usr/bin/env python # # Write the memory pak's 32k SRAM from a binary file specified on the command line. # # --Micah Dowty <*****@*****.**> # from bus import Bus import sys b = Bus() if b.probe() != "memory": sys.exit(1) f = open(sys.argv[1], "rb") addr = 0x0000 while addr < 0x8000: sys.stdout.write("\r0x%04X (%.02f%%)" % (addr, addr * 100.0 / 0x8000)) b.write(addr, f.read(32)) addr += 32 sys.stdout.write("\n") ### The End ###