def _login(self): user = self.user.value; passwd = self.passwd.value; if not network.isConnected(): network.connect() # plain silly, we need to remove this if network.isConnected(): ans = protocol.sendMessage(TYPE = protocol.LOGIN, USER = user, PASS = passwd) if ans == True: state.logged_in = True state.in_game_select = True return else: title = "Error" err_msg = "Invalid username or password" else: title, err_msg = network.getError() # If the login was incorrect prompt the user CustomDialog(title, err_msg).open()
def link(self, ssid, password): print("Link", ssid, password) self.indicator.blink(period=500) print("blink to disconnect") network.disconnect() print("disconnected to connect") network.connect(ssid, password) print("connected")
def __init__(self, name, ip, port): self.map_ = {} self.slice_heights = {} self.current_players = {} self.game = True self.error = None self._name = name # We cannot serve, we are connected to a server. # TODO: Maybe we can do this better...? self.serving = None try: self._sock = network.connect(ip, int(port)) except (ConnectionRefusedError, ValueError): self.error = 'Cannot connect to server' return self._sock.setblocking(True) self.finished_login = Event() self._listener_t = Thread(target=self._listener) self._listener_t.daemon = True self._listener_t.start() # Login self._send('login', [self._name]) # Server doesn't respond if not self.finished_login.wait(3): self.error = 'No response from server on login' log(self.error) self._sock.close() return # Server responds with error if self.error is not None: log('Error response from server on login:'******'tick'] self._dt = False self._last_tick = time() self._chunks_requested = set() self._send('get_players') self._send('get_time') self.redraw = False self.view_change = False
def main(): parser = argparse.ArgumentParser() parser.add_argument('--limit', default=9.6, type=float, help='number of seconds to run for') parser.add_argument('--share-freq', default=0.5, type=float, metavar='SF', help='how often in seconds to report best') parser.add_argument('--pop-size', default=1000, type=int, metavar='N', help='number of solutions kept in the population') parser.add_argument('--spawn-count', default=100, type=int, metavar='K', help='number of new solutions added each generation') parser.add_argument('--link', help='join this network to some other hostname:port') parser.add_argument('--port', '-p', type=int, default=8099, help='port to listen on') parser.add_argument('--debug', '-v', action='store_true', help='print verbose debugging output') group = parser.add_mutually_exclusive_group(required=True) group.add_argument('--filename', help='solve a puzzle from a local JSON filename') group.add_argument('--workers', type=int, help='create a network with a given number of workers') args = parser.parse_args() logging.basicConfig(level=logging.DEBUG if args.debug else logging.WARNING) if args.filename: puzzle = json.load(open(args.filename)) network.GlobalBest.reset(puzzle['id']) result = GrideaWorker(args).solve(puzzle) json.dump(result, open(args.filename + '.result', 'w')) print 'score={}, result written to {}.result'.format(len(result), args.filename) else: pool = multiprocessing.Pool(args.workers) jobs = pool.imap(run_child_process, [args] * args.workers) network.listen(args.port) if args.link: network.connect(args.link) reactor.run() for _ in jobs: pass # Empty job queue pool.terminate() pool.join()
def main(): parser = argparse.ArgumentParser() parser.add_argument('--key', help='key for challenge API server') parser.add_argument('--mode', default='local', choices=('local', 'trial', 'contest'), help='environment to report to challenge API') parser.add_argument('--limit', default=9.6, type=float, help='seconds to wait before reporting results') parser.add_argument('--hostname', default='localhost:8099', help='worker process cluster hostname:port connect to') parser.add_argument('--filename', default='example_puzzle.json', help='puzzle JSON file for --mode=local') parser.add_argument('--count', '-n', default=1, type=int, metavar='N', help='count of number of puzzles to solve') parser.add_argument('--debug', '-v', action='store_true', help='print verbose debugging output') args = parser.parse_args() logging.basicConfig(level=logging.DEBUG if args.debug else logging.WARNING) network.connect(args.hostname, on_connect=GrideaSubmitClient(args).start_next_puzzle) reactor.run()
def test_local_socket(self): import network try: a = network.connect("127.0.0.1:22") self.assertFalse(a == None) #Socket Creation Failed - Connection Refused except: self.assertTrue(False) #Socket creation failed - Exception Raised #close the socket - not part of the test try: a.close() except: pass
def recvMessage(self, world, lobby): if not network.isConnected(): network.connect() if not network.isConnected(): return "" message = network.mySelect() if message == "": return msg_type = message[0] if msg_type == MAP: self._handleMapRecv(message[1:], world) elif msg_type == START: state.in_game = True state.in_game_lobby = False elif msg_type == GAMES_LIST: self._handleGamesList(message[1:], lobby)
def main(): global dynamic, ableton dynamic = Dynamic() dynamic.setup().acquire() ableton = Ableton() print('Start!') while True: print('Session start') s = connect() sleep(.2) dynamic.acquire() handle(s) dynamic.release() ableton.release()
def login(fname, lname, anumber, alias, endpoint, label=None): if label==None: label=alias id = packet.ID() id.fname = fname id.lname = lname id.alias = alias id.anumber = anumber session = Session() session.id = id while session.socket == None: session.socket, session.registry = network.connect(endpoint) #While we're still waiting on a login reply, keep listening status = 0 while(session.login == False): network.send( session, packet.login_request(session.id, label) ) time.sleep(1) data = network.receive(session) if data==None: continue if(data["__type"] == "LoginReply:#Messages.ReplyMessages"): if(data["Success"]): log.info("Login succeeded") session.procinfo = data["ProcessInfo"] session.login = True else: log.error("Login failed") log.error("Error message was: "+ data["Note"]) return session else: log.warning("Unexpected packet received: " + str(data) ) return session
def check(bot, update, args): if len(args) != 1: update.message.reply_text("\u274c Usage: /check [common_name]") return common_name = args[0] client = db.clients.find_one({"cn": common_name}) if client is None: update.message.reply_text("\u274c This client does not exist") return if update.message.from_user.id != client["owner"] and update.message.from_user.id not in ADMINS: update.message.reply_text("\u274c You don't have privileges to check this client") return if client["ip"] is None: update.message.reply_text("\u274c Client is not connected") return message = "Client <b>{cn}</b> ({ip})\n\n".format(cn=common_name, ip=client["ip"]) ping_result = network.ping(client["ip"]) if ping_result: message += "\u2705 Ping OK\n" else: message += "\u274c Ping failed\n" for host, port in [(DUMMY_HOST, 80), (HOST, 1080)]: ip = network.resolve(host) connect_result = network.connect(ip, port, client["ip"]) if connect_result: message += "\u2705 Connect to {host} ({ip}) OK\n".format(host=host, ip=ip) else: message += "\u274c Connect to {host} ({ip}) failed\n".format(host=host, ip=ip) update.message.reply_html(message)
def worker(self, host, port, speed): socket = network.connect(host, port) rspeed = float(speed) data = '1234567890-=qwertyuiopsdfghjkl;zxcvbnm,QWERTYUIOPASDFGHJLZXCVBNM' for i in range(10): data += data delay = 0.75 / (rspeed / 512.0) print 'delay:', delay, 'chunk:', len(data) while self._working: back = time.time() socket.sendall(data) back = time.time() - back if (delay - back) > 0.0: time.sleep(delay - back) print 'stop writing...' try: socket.close() except: pass
from video import Recorder # 检查参数 if len(usys.argv) < 3: print("Usage: %s <ssid> <password>" % usys.argv[0]) usys.exit(1) # 定义网络事件回调函数 def network_evt_cb(eid): print('%s:%d' % ('eid', eid)) # 连接网络 network.init(network.WIFI) network.connect(usys.argv[1], usys.argv[2], network_evt_cb) network.close() # 等待网络连接 utime.sleep_ms(10000) print("start recorder with rtsp test") # 开启视频流功能 recorder = Recorder() recorder.open(0, recorder.H264) recorder.start() utime.sleep_ms(100000000) # 关闭视频流功能 recorder.stop() recorder.close()
def connect(self): print "Connecting to", self._host, self._port self._sock = network.connect(self._host, self._port) self._sock.setblocking(True) self._sock.settimeout(None) print " >>> Done"
"<head><h1 align='center'>Python for esp8266 - SciPy India 2015</h1></head>\r\n" "<body bgcolor='#ccff99'>\r\n" "<form align='center' action='' method='post'>\r\n" "<fieldset>\r\n" "<legend style='color:red'>Red LED Control</legend>\r\n" "<input type='radio' name='LED' value='ON'> ON\r\n" "<input type='radio' name='LED' value='OFF'> OFF<br>\r\n" "</fieldset>\r\n" "<input type='submit' value='Submit'>\r\n" "</form>\r\n" "</body>\r\n" ) else: s.send("HTTP/1.0 404 OK\r\n" "Server: Micropython for ESP8266\r\n" "Content-Type: text/html\r\n" "Connection: close\r\n" "\r\n" "<h1>:(</h1>") def onclientsent(s): s.close() network.connect(ssid, passwd) socket = esp.socket() socket.onconnect(onnewclient) gc.collect() socket.bind(("", 80)) socket.listen(5)
def join_game(self, a): ip = self.aipi.get_text() name = self.con_win_name.get_text() if ";" in name or name == "": self.errormsgwin = gtk.MessageDialog(message_format="Fehlerhafter Name") self.errormsgwin.show_all() return players = 0 plist = [] if self.join_one.get_active(): players += 1 plist.append(0) if self.join_two.get_active(): players += 2 plist.append(1) if self.join_three.get_active(): players += 4 plist.append(2) if self.join_four.get_active(): players += 8 plist.append(3) self.hide() result = network.connect(ip, name, players) # 1 : ip/port nicht richtig # 2 : verlangte spieler nicht frei # else if result == 1: ermsg = "Konnte keine Verbindung erstellen" elif result == 2: ermsg = "Diese Spieler sind nicht mehr verfuegbar" else: # print plist # passe menue an result an # start_window.hostbut.set_sensitive(False) start_window.but.set_sensitive(False) start_window.join.set_label("Leave Game") # umbenennen start_window.join.connect("clicked", start_window.leavegame) network.hosting = False # start_window.opt_but.set_sensitive(False)voruebergehend for i in range(4): typ = result[i][0] name = result[i][1] start_window.sel_but[i].set_sensitive(False) if typ == "h": # server start_window.sel_but[i].set_active(0) start_window.pl[i] = 1 elif typ == "n": # network start_window.sel_but[i].set_active(3) start_window.pl[i] = 4 elif typ == "b": # bot start_window.sel_but[i].set_active(2) start_window.pl[i] = 2 elif typ == "c": # closed start_window.sel_but[i].set_active(1) start_window.pl[i] = 0 start_window.names[i].set_sensitive(0) start_window.names[i].set_text(name) network.gamedetails.pna[0] = name network.gamedetails.pn[0] = name for i in plist: start_window.names[i].set_sensitive(1) print("clientmenu set") return self.errormsgwin = gtk.MessageDialog(message_format=ermsg) self.errormsgwin.show_all() return
# This script is run on boot import esp, network, re network.connect('iot', 'noodlebrain') def socket_recv(self, sock, data): if data == b'HTTP/1.0 200 OK\r\n': return state = 'header' for ii in data.split(b'\r\n'): if state == 'header': if ii == b'': state = 'body' continue hdr = re.search('^([A-Za-z0-9-]+): *(.*)$', ii) if hdr and hdr.group(1) == 'Date': self.mutex.release() sock.close() self.got_date(hdr.group(2)) return else: self.mutex.release() sock.close() def on_connect(self, sock): method = 'GET / HTTP/1.1\r\n' headers = {'Content-Type': 'application/json', 'Content-Length': 0} to_send = method + '\r\n'.join("%s: %s" % (field, value) for field, value in headers.items())
def create(username, image, cid=None): """通过 swarm leader 创建容器 调用 swarm manager api, 来创建容器, 限制容器内存, 磁盘, 网络, CPU 资源, 指定基础网络和 Nginx 网络(Console 专用), 利用 overlayfs 文件系统特性, 为其挂载 Ceph rbd 块存储, 实现容器中的数据持久化. :param str username: Fuvism user name :param str image: image name for container :param str or None cid: The container uuid """ user_path = "/storage/user_data/%s" % username # 创建容器参数 params = { "Tty": True, "Cmd": "bash", "Image": image, "OpenStdin": True, "AttachStdin": True, "HostConfig": { "Memory": 102400000, # 100M "MemorySwap": 512000000, # 512M # "MemoryReservation": 80000000, # 80M "NetworkMode": NETWORK_LEARN_NAME, # 限制 CPU 最高使用率为 20% "CpuPeriod": 50000, "CpuQuota": 10000, # "OomKillDisable": True, "Ulimits": [ { "Name": "nproc", "Hard": 512, "Soft": 400 }, { "Name": "nofile", "Hard": 1024, "Soft": 800 }, ], # 限制容器中最大进程数,可以有效防止 Fork 炸弹 # https://blog.docker.com/2016/02/docker-engine-1-10-security/ "PidsLimit": 512, "Binds": [ "/storage/.system:/storage/.system:ro", "%s/me:/storage/me:rw" % user_path, "%s/learn:/storage/learn:rw" % user_path, ] }, } kwargs = { "url": URL + "/containers/create", "headers": HEADERS, "data": json.dumps(params) } req = pack_requests("POST", **kwargs) status = req.status_code if status != 201: return (status, req.text, "") # 获取容器的详细信息 s_inspect, m_inspect, r_inspect = inspect.inspect(req.json()["Id"]) if s_inspect != 200: return (s_inspect, m_inspect, r_inspect) # 在容器未启动之前,限制磁盘空间 s, m, r = _limit_disk_quota(r_inspect, username, user_path, req.json()["Id"], cid) if s != 0: return (s, m, r) # 启动容器 kwargs = { "url": URL + "/containers/%s/start" % req.json()["Id"], "headers": HEADERS } r = pack_requests("POST", **kwargs) s = r.status_code if s != 204: return (s, r.text, "") # 连接容器到 nginx 网络中 s_net, m_net, r_net = network.connect(req.json()["Id"], NETWORK_NGINX_NAME) if s_net != 200: return (s_net, m_net, "") # 在容器启动后,限制容器下载速率 _limit_network_bandwidth(user_path, req.json()["Id"]) # 打入 ssh bash web 进程,开启 8000 域名访问 s_exec, m_exec, r_exec = console.console(username, req.json()["Id"]) if s_exec != 0: return (s_exec, m_exec, r_exec) return (0, "Container created successfully", { "console": r_exec, "cid": req.json()["Id"] })
def __init__(self, name, ip, port): self.map_ = {} self.slice_heights = {} self.current_players = {} self.mobs = {} self.items = {} self.game = True self.error = None self._name = name # We cannot serve, we are connected to a server. # TODO: Maybe we can do this better...? self.serving = None try: self._sock = network.connect(ip, int(port)) except (ConnectionRefusedError, ValueError): self.error = 'Cannot connect to server' return self._sock.setblocking(True) self.finished_login = Event() self._listener_t = Thread(target=self._listener) self._listener_t.daemon = True self._listener_t.start() # Login self._send('login', [self._name]) # Server doesn't respond if not self.finished_login.wait(3): self.error = 'No response from server on login' log(self.error) self._sock.close() return # Server responds with error if self.error is not None: log('Error response from server on login:'******'tick'] self._dt = False self._last_tick = time() self._chunks_requested = set() self._send('get_players') self._send('get_mobs') self._send('get_items') self._send('get_time') self.redraw = False self.view_change = False
def network_init(ap, password, dest_ip, dest_port): if esp.wifi_mode() != esp.STA_MODE: esp.wifi_mode(esp.STA_MODE) if network.status() != network.STAT_GOT_IP: network.connect(ap, password) return Socky(dest_ip, dest_port)
def connect(self): esp.sleep_type(esp.SLEEP_NONE) esp.wifi_mode(esp.STA_MODE) network.connect("MosEisleySpaceport", "supersonic")
def connect(self): self.socket = network.connect(self.ip, self.port)
for check in range( 0, 50 ): # Wait a maximum of 10 times (10 * 500ms = 5 seconds) for success if wlan_sta.isconnected(): break time.sleep_ms(100) if wlan_sta.isconnected(): break if wlan_sta.isconnected(): print("Connected to Wifi. IP: " + str(wlan_sta.ifconfig())) # start network #global network network = Blocky(config) if not network.connect(): # connect to server print('Failed to connect to broker. Enter config mode') status_led_blink_timer.deinit() status_led.fill((0, 0, 0)) status_led.write() gc.collect() import config_manager else: # run user code #import firmware status_led_blink_timer.deinit() status_led.fill((0, 0, 0)) status_led.write() gc.collect() print(gc.mem_free()) run_user_code() # no thread here , thread kill timer !
def run_child_process(args): network.connect('localhost:{}'.format(args.port), GrideaWorker(args)) reactor.run()
#!/usr/bin/env python from daemon import storage from network import connect,message_handler,presence_handler import xmpp jid=storage.config.get("jabber_id","*****@*****.**") password=storage.config.get("jabber_password","xxx") client=connect(jid,password) client.sendInitPresence() client.RegisterHandler('presence',presence_handler) client.RegisterHandler('message',message_handler) client.RegisterDefaultHandler(message_handler) roster=client.getRoster() f2fnode=xmpp.protocol.Node(tag="f2f",attrs={"url":"http://lemonde.fr","body":"a nice website"}) message=xmpp.Message(to="*****@*****.**",body="text-only version",typ="message",payload=[f2fnode]) #client.send(message)
/ /_/ /| |/ |/ / /|_/ /___/ ___/ /_/ / / /|_/ / \____/ |__/|__/_/ /_/ /_/ \___\_\/_/ /_/ """) test_box_ip_address = "" while len(test_box_ip_address.split('.')) != 4: test_box_ip_address = raw_input( "Enter the IP address of the test device : ") if len(test_box_ip_address.split('.')) != 4: print("Invalid IP Address") print("Test Box IP Address {}".format(test_box_ip_address)) try: network.connect(test_box_ip_address, network.connect_test_box) except Exception as e: print(type(e)) print(e.args) print(e) print("Couldn't Connect to Test Device") exit(1) network.connect_test_box.send("Remote Desktop Connected") received_data = network.connect_test_box.recv(2048) if (received_data == "Raspberry Pi Connected"): data_log_temp = open('temp_log.csv', 'w') temp_list = []
def connect(self): try: network.connect() except OSError: network.connect("badgenet", "VVQZp3NwRazmEu7Z")
def check_all(): EMOJI = {"ok": "\u2705", "fail": "\u274c", "down": "\ud83d\udc80"} INFO = { "ok": "is OK", "fail": "can't reach {host}".format(host=HOST), "down": "is down" } last_checks = list(db.checks.find({}, sort=[("ts", DESC)]).limit(2)) while len(last_checks) < 2: last_checks.append({"ip": "", "result": {}}) last_ip = last_checks[0]["ip"] ip = network.resolve(HOST) while ip == network.resolve("nsychev.ru") or ip == "": print("Bad resolving, retrying in 3 seconds", flush=True) sleep(3) ip = network.resolve(HOST) if ip != last_ip: notify("\ud83d\udd01 *{host}* has new IP address: *{ip}*".format( host=HOST, ip=ip)) result = {} for client in db.clients.find({}): client_ip, cn = client["ip"], client["cn"] if not client_ip: verdict = "down" elif network.connect(ip, 1080, client_ip): verdict = "ok" elif network.connect(network.resolve(DUMMY_HOST), 80, client_ip): verdict = "fail" else: verdict = "down" result[cn] = verdict old_results = [item["result"].get(cn, "down") for item in last_checks] old_status = status_merge(*old_results) status = status_merge(old_results[0], verdict) if status == "fail" and old_status == "ok": notify("\u274c Failed to connect via *{cn}* to *{host}* ({ip})". format(cn=cn, host=HOST, ip=ip)) elif status == "ok" and old_status == "fail": notify( "\u2705 Client *{cn}* restored connection to *{host}* ({ip})". format(cn=cn, host=HOST, ip=ip)) elif status != old_status: bot.send_message(chat_id=client["owner"], text="{emoji} Your client *{cn}* {state}".format( emoji=EMOJI[status], cn=cn, state=INFO[status]), parse_mode="Markdown") db.checks.insert_one({"ts": time(), "ip": ip, "result": result}) return result, ip
import network import mockups #browsers = operatingsystem.getBrowsers() browsers = ['chrome-mac', 'safari-mac'] for browseros in browsers: browser.openBrowser(browseros) browser.openURL("http://mockups.dev") mockups.testProjectLoaded() # Test Socket Auto-reconnect network.disconnect() App.focus(browseros) mockups.testLostConnection() network.connect() App.focus(browseros) mockups.testReconnected() # Test Reconnect Button network.disconnect() App.focus(browseros) mockups.testLostConnection() wait("Yourconnectl.png", 40) network.connect() App.focus(browseros) mockups.reconnect() mockups.testReconnected() # Test Name Change mockups.changeName("Todd")