async def handleconnection(reader, writer): receivedrequest = await readhttpheaders(reader) log(receivedrequest) if "POST" in receivedrequest: # this is causing the str and binary comparison warning await recpostsave(receivedrequest, reader, "POSTUPLOAD.txt") await servemessage(writer, "done") await writer.aclose() #await reader.aclose() # this gets a keyerror convertsavepostfile("POSTUPLOAD.txt") return rpath = receivedrequest.get("GET") bcallaclose = True if "WebSocketKey" in receivedrequest: bcallaclose = await servewebsocket(rpath, reader, writer, receivedrequest["WebSocketKey"], wswritesensorloop) elif rpath is None: pass elif rpath == "": await servefilelist(writer) else: await servestaticfile(writer, rpath) if bcallaclose: await writer.aclose()
async def wswritesensorloop(rpath, writer, wscondition): rpath = rpath.split(",") delayms = int(rpath[1]) hexbuff = bytearray(16) #if rpath[0] == "bme280": try: while wscondition[1]: while len(wscondition) > 2: incoming = wscondition.pop(2) log("[WS%d incoming] %s" % (wscondition[0], incoming)) await writer.awrite(make_hybi07_header(16)) ustruct.pack_into(">II", hexbuff, 8, hook_ms5611[1], hook_ms5611[2]) for i in range(8): b = hexbuff[i + 8] hexbuff[i * 2] = (b >> 4) + (48 if b < 160 else 55 ) #ord('0')=48; ord('A')=65 b &= 15 hexbuff[i * 2 + 1] = b + (48 if b < 10 else 55) await writer.awrite(hexbuff) await uasyncio.sleep_ms(delayms) except OSError as e: elog(e) wscondition[1] = 1 log("[WS%d wpleave]" % wscondition[0])
async def wsread(reader, wsid): while True: rex = await reader.readexactly(1) if len(rex) != 0: break log("[WS%d readexactly]" % wsid, [rex]) opcode = (rex)[0] & 0x0F # 8 means close if opcode == 8: log("[WS%d close]" % wsid) return None v = (await reader.readexactly(1))[0] masked = (v & 0x80) length = v & 0x7F if length == 0x7E: length = ustruct.unpack(">H", await reader.readexactly(2))[0] if length == 0x7F: length = ustruct.unpack(">Q", await reader.readexactly(8))[0] if masked: masked = await reader.readexactly(4) else: masked = b"\x00\x00\x00\x00" v = await reader.readexactly(length) v = bytes(k ^ masked[i % 4] for i, k in enumerate(v)) return v
async def ams5611(): log("Entering ams5611") bdat = open("b%d_%d.dat" % (powid, time.ticks_ms() // 1000), "wb") nbdat = 0 try: dc = GetMS5611calibrations(i2c) readout = bytearray(3) while hook_ms5611[0]: await ams5611read(dc, readout, i2c, uasyncio) t = time.ticks_ms() hook_ms5611[2] = MS5611convert(dc) if bdat: nextpt(t, hook_ms5611[2] - 100000, bdat) nbdat += 1 if nbdat > 10000: bdat.close() bdat = None if hook_ms5611[3]: # dump out to logfile here (if open) hook_ms5611[3].write( ustruct.pack("<II", hook_ms5611[1], hook_ms5611[2])) if (hook_ms5611[1] >> 13) != (t >> 13): # 8 seconds hook_ms5611[3].flush() hook_ms5611[1] = t greenpin.duty((t % 500) if hook_ms5611[3] or (((t // 500) % 3) == 0) else 0) except Exception as e: elog(e) hook_ms5611[0] = -1 log("Leaving ams5611")
def update(self, table, key, value, where=""): qstr = "UPDATE {0} SET {1}='{2}'".format(table, key, value) if where: qstr += " WHERE {0}".format(where) try: self.execute(qstr) self.db.commit() return self.cur.lastrowid except Exception, e: log(LOG_INFO, "{0}: database.Sqlite3Database.update: Exception occurred when updating {1}: {2}".format(self.session, table, e))
async def recpostsave(receivedrequest, reader, fname): rpath = receivedrequest["POST"] fsize = int(receivedrequest["Content-Length"]) log("recpostsave", str(fsize)) fout = open(fname, "wb") while fsize > 0: fb = await reader.read(min(fsize, 20)) fout.write(fb) fsize -= len(fb) fout.close()
def update_d(self, table, d, where=""): set_str = ", ".join(["{0}='{1}'".format(x, y) for x, y in d.iteritems()]) qstr = "UPDATE {0} SET {1}".format(table, set_str) if where: qstr += " WHERE {0}".format(where) try: self.execute(qstr) self.db.commit() return self.cur.lastrowid except Exception, e: log(LOG_INFO, "{0}: database.Sqlite3Database.update_d: Exception occurred when updating {1}: {2}".format(self.session, table, e))
def grow(self, size): # size is in MB # make sure that 20% over current usage is preallocated fh = util.createUnlinkedTmpFile(self._path) usage = self._getFileSystemUsage() while self._allocated < 1.2 * usage: util.growFile(fh, size) self._allocated += size log('growing %s to %sMB' % (self._path, self._allocated)) fh.close()
def clear_speedtest(): if os.path.isfile(SPEEDTEST_LOCK_FILE): try: os.unlink(SPEEDTEST_LOCK_FILE) except: syslog.log("Unable to remove speed test lock file.") if os.path.isfile(SPEEDTEST_RESULTS_FILE): try: os.unlink(SPEEDTEST_RESULTS_FILE) except IOError: syslog.log("Unable to remove speed test results file.")
def start(self): """ Every 5min try to allocate more space. """ # Wait a couple of minutes before starting allocation to let the # machine finish booting. log('sleeping 120s before growing filesystems') time.sleep(120) while True: for fs in self._fs: fs.grow(self._size) log('sleeping 300s') time.sleep(300)
def bme280init(i2c): k = i2c.readfrom_mem(0x77, 0xD0, 1) if k != b'\x60': log("bme280 chip not found") return False i2c.writeto_mem(0x77, 0xF2, b'\x01') # switch on humidity (over)sampling=1 i2c.writeto_mem( 0x77, 0xF4, b'\x27' ) # switch on temp and pressure (over)sampling=1, mode=normal(continuous readings) i2c.writeto_mem(0x77, 0xF5, b'\x00') # 0.5ms standby, no filtering, no-SPI return True
def __init__(self, config_path): log(syslog.LOG_INFO, "starting service...") self._prepare() self.config = Config(config_path) self.xorg_server = XorgServer(self.config) system_bus = dbus.SystemBus() self.name = dbus.service.BusName("org.bumblepyy", system_bus) dbus.service.Object.__init__(self, system_bus, '/BumblePyy')
def __init__(self, config): self.args = ":%s -config %s -sharevts -nolisten tcp -noreset -configdir /dev/null %s" % ( config.x_display, config.x_config, config.system.x_args ) self._thread = None self._proc = None self._library_path = config.system.library_path log(syslog.LOG_INFO, "X.Org server ready")
def create_call(self, src, dst, cid, context, xid="None"): try: self.ami.originate( "SIP/1{0}@outbound".format(src), dst, context, '1', '', cid, True, xid ) except Exception, e: log(LOG_ERR, "Exception occurred in create_call: {0}".format(e))
def send(self, src, dst, msg): msg = msg.replace("<br />", "\r\n") msg = re.sub("<.*?>", "", msg) success = self.sendsms(src, dst, msg) if not success: raise SMSSendFailed( "sms: Failed to send message from {0} to {1}".format(src, dst)) else: log(LOG_INFO, "SMS Send success: SRC: {0}, DST: {1} -> {2}".format(src, dst, success)) return success
async def createLogFile(): ti = 0 while hook_ms5611: ti = (ti + 1 if touchpin.read() < 1100 else 0) if ti > 3: log("making datfile") hook_ms5611[3] = open( "%d_%d.dat" % (powid, time.ticks_ms() // 1000), "wb") for i in range(12 * 10): # 10 minutes await uasyncio.sleep_ms(5 * 1000) # 5 second chunks if touchpin.read() < 1100: break # break early hook_ms5611[3].close() hook_ms5611[3] = None await uasyncio.sleep_ms(5 * 1000) # pause before activating again await uasyncio.sleep_ms(50)
async def wsreadprintloop(reader, wscondition): while wscondition[1]: try: res = await wsread(reader, wscondition[0]) except OSError as e: print("[WS%d wsreadexception] %s" % (wscondition[0], str(e))) res = None if res is None: wscondition[1] = 0 # closed condition break log("[WS%d]" % wscondition[0], res) # pass any important messages through into this sequence! # (not seen as a signal, but picked up next time that task wakes up) wscondition.append(res) log("[WS%d rlleave]" % wscondition[0])
def stop(self): if self._thread != None and self._thread.isAlive(): log(syslog.LOG_DEBUG, "Trying to stop X.Org...") self._proc.send_signal(signal.SIGTERM) self._thread.join(timeout=3) if self._thread.isAlive(): log(syslog.LOG_WARNING, "X.Org couldn't be stopped, killing") self._proc.kill() self._thread.join(timeout=5) if self._thread.isAlive(): log(syslog.LOG_ERR, "X.Org couldn't be killed") return False else: log(syslog.LOG_WARNING, "X.Org killed") else: log(syslog.LOG_DEBUG, "X.Org stopped") return True
def select(self, table, keys="*", where="", fetchall = False, as_dict = False, order_by=""): if keys == "*": keys = ", ".join([x[1] for x in self.execute("PRAGMA table_info({0})".format(table)).fetchall()]) else: keys = ", ".join(keys) qstr = "SELECT {0} FROM {1}".format(keys, table) if where: qstr += " WHERE {0}".format(where) if order_by: qstr += " ORDER BY {0}".format(order_by) try: res = self.execute(qstr) if not as_dict: if fetchall: return res.fetchall() return res.fetchone() else: keys = keys.split(", ") if fetchall: d = [] for row in res.fetchall(): temp = {} if not row: continue t = zip(keys, row) [temp.__setitem__(x, y) for x, y in t] d.append(temp) else: d = {} row = res.fetchone() if not row: return {} row = zip(keys, row) [d.__setitem__(x, y) for x, y in row] return d except Exception, e: log(LOG_INFO, "{0}: database.Sqlite3Database.select: Exception occurred when selecting {1} from {2}: {3}".format(self.session, keys, table, e))
async def handleconnection(reader, writer): receivedrequest = await readhttpheaders(reader) if "POST" in receivedrequest: await recpostsave(receivedrequest, reader, "POSTUPLOAD.txt") await servemessage(writer, "done") await writer.aclose() convertsavepostfile("POSTUPLOAD.txt") return rpath = receivedrequest.get("GET") log(receivedrequest) bcallaclose = True if rpath == "": await servefilelist(writer) elif rpath: await servestaticfile(writer, rpath) if bcallaclose: await writer.aclose()
def run(self, name, password): if doomrl.user(): return 'You are already logged in!' if not name or not password: return 'You must specify both a username and a password.' # Check password try: with open(doomrl.homepath('passwd', user=name)) as f: passwd = f.read() if passwd == password: log('%s successfully logged in.' % name) doomrl.login(name) return except IOError as e: pass log('Failed login attempt as %s' % name) doomrl.login() return 'Login failed.'
def connect(self, path): if not os.path.exists(path): log(LOG_INFO, "{0}: database.Sqlite3Database.connect: {1} doesn't exist. Creating it".format(self.session, path)) db = sql.connect(path) cur = db.cursor() create = [ ( "CREATE TABLE users(" "rowID INTEGER PRIMARY KEY AUTOINCREMENT, " "username VARCHAR, " "phonenumber VARCHAR UNIQUE, " "extension VARCHAR, " "secret VARCHAR" ")" ), ( "CREATE TABLE entry(" "rowID INTEGER PRIMARY KEY AUTOINCREMENT, " "game INTEGER, " "phonenumber VARCHAR, " "result VARCHAR, " "UNIQUE(game, phonenumber) ON CONFLICT ABORT" ")" ) ] try: for stmt in create: log(LOG_INFO, "{0}: database.Sqlite3Database: Executing statement: {1}".format(self.session, stmt)) cur.execute(stmt) db.commit() except Exception, e: log(LOG_INFO, "{0}: database.Sqlite3Database: Failed to create tables: {1}".format(self.session, e))
async def servestaticfile(w, lpath, fsize=0): try: if fsize == 0: try: fsize = os.stat(lpath)[6] except OSError: pass if fsize == 0: log("File '%s' not found"%(lpath)) await w.awrite(b"HTTP/1.0 404 Not found\r\n\r\n") await w.awrite(b"File '%s' not found" % lpath.encode()) return await w.awrite(b"HTTP/1.0 200 OK\r\n") lfext = lpath[lpath.rfind(".")+1:] await w.awrite(b"Content-Type: %s\r\n" % contenttypes.get(lfext, "text/plain; charset=utf-8")) if lfext == "js" and fsize > 20000: await w.awrite(b"Cache-Control: max-age=31536000\r\n") await w.awrite(b"Content-Length: %d\r\n" % fsize) await w.awrite(b"\r\n") #fsize = os.stat(lpath)[6] fin = open(lpath, "rb") t0 = time.ticks_ms() bs = bytearray(60) Dn = 0 for i in range(int((fsize-1)/len(bs))): fin.readinto(bs) await w.awrite(bs) Dn += len(bs) nbs = fin.readinto(bs) Dn += nbs await w.awrite(bs, sz=nbs) td = time.ticks_ms() - t0 log("File '%s' (%d bytes) served in %dms"%(lpath, fsize, td)) except OSError as e: elog(e)
def run(self, name): if not doomrl.user(): return 'You must log in first.' if not name: return self.list_running_games() # We can be a bit looser about names here, but for simplicity's sake we # just reuse the name validation code we use for player names. if not doomrl.name_valid(name): return 'Invalid save name.' # Check that they aren't already playing *right now*. self.recfile = doomrl.homepath('ttyrec') if exists(self.recfile): return 'You are already playing in another window! Quit that game first.' (scores, mortem) = self.setup(name) try: self.run_doomrl() except OSError as e: # This almost certainly means that the user disconnected in mid-game. # Don't try to output any error messages, they'll just throw again because # our tty is gone. if self.child and (self.child.poll() is None): self.child.kill() self.child = None # Call _exit rather than using sys.exit so we don't try to run finalizers. os._exit(1) except Exception as e: import traceback log('Error running DoomRL: ' + traceback.format_exc()) traceback.print_exc() sys.exit(1) finally: self.shutdown(name, scores, mortem)
def run(self, name): if not doomrl.user(): return 'You must log in first.' if not name: return self.list_running_games() # We can be a bit looser about names here, but for simplicity's sake we # just reuse the name validation code we use for player names. if not doomrl.name_valid(name): return 'Invalid save name.' # Check that they aren't already playing *right now*. self.recfile = doomrl.homepath('ttyrec') if exists(self.recfile): return 'You are already playing in another window! Quit that game first.' (scores,mortem) = self.setup(name) try: self.run_doomrl() except OSError as e: # This almost certainly means that the user disconnected in mid-game. # Don't try to output any error messages, they'll just throw again because # our tty is gone. if self.child and (self.child.poll() is None): self.child.kill() self.child = None # Call _exit rather than using sys.exit so we don't try to run finalizers. os._exit(1) except Exception as e: import traceback log('Error running DoomRL: ' + traceback.format_exc()) traceback.print_exc() sys.exit(1) finally: self.shutdown(name, scores, mortem)
def convertsavepostfile(pname): lgen = flinesplitgen(pname, 80) linebreakhash = uhashlib.sha1(next(lgen)).digest() # get the headers for l in lgen: if l == b'\r\n': break k, v = bytes(l).split(b":") if k == b'Content-Disposition': for s in v.split(b";"): se = s.strip().split(b"=", 1) if len(se) == 2: if se[0] == b"filename": filename = se[1].strip(b'"').decode() log("convpostfile", filename) fout = open(filename, "wb") prelinebreak = b"" # used to handle the linebreak before the breakline for l in lgen: linehash = uhashlib.sha1(l).digest() if linehash == linebreakhash: if not prelinebreak: print("where the prelinebreak?") break if prelinebreak: fout.write(prelinebreak) prelinebreak = b"" if len(l) == 2: prelinebreak = bytes(l) if prelinebreak != b"\r\n": prelinebreak = b"" if not prelinebreak: fout.write(l) fout.close() os.remove(pname)
def run_doomrl(self): if exists(doomrl.datapath('ttysound', 'libSDL_mixer-1.2.so.0')): cmd = ['./doomrl'] env = { **os.environ, "LD_LIBRARY_PATH": doomrl.datapath('ttysound'), "SDL_AUDIODRIVER": 'disk', 'SDL_DISKAUDIOFILE': '/dev/null', } else: cmd = ['./doomrl', '-nosound'] env = os.environ (rpipe, wpipe) = os.pipe() self.child = subprocess.Popen(cmd, stdout=wpipe, env=env, cwd=doomrl.homepath()) os.close(wpipe) # DoomRL needs the terminal in raw mode, but since it's running inside ttyrec # it can't control that setting. tty.setraw(1) with TTYRec(self.recfile) as rec: # This will return when DoomRL closes the fd. # It will also automatically reset the TTY on leaving the 'with' block. rec.ttyrec(in_fd=rpipe) try: self.child.wait() except Exception as e: import traceback log('Error while DoomRL was running: ' + traceback.format_exc()) self.child.kill() raise e self.child = None
def start(self): if self.running(): return True log(syslog.LOG_INFO, "Starting X.Org server...") self._thread = threading.Thread(target=self._run) self._thread.start() time.sleep(1) if self._thread.isAlive(): log(syslog.LOG_INFO, "X.Org server started") else: log(syslog.LOG_ERR, "X.Org server cannot be started") return self._thread.isAlive()
def _run(self): self._proc = Popen("X "+self.args, shell=True, stderr=subprocess.PIPE, env={ "LD_LIBRARY_PATH": self._library_path }) for line in self._proc.stderr: log(syslog.LOG_DEBUG, "[xorg] %s" % (line.strip(),)) self._proc.stderr.close() self._proc.kill() status = self._proc.wait() if status == 0: log(syslog.LOG_INFO, "X.Org was successfully stopped") else: log(syslog.LOG_WARNING, "X.Org ended with status %d" % (status,)) self._proc = None
def run(self, name, password): # Check name validity if not doomrl.name_valid(name): return 'Invalid name.' # Check that password was specified if not password: return 'No password specified.' # Try to create user directory and die if we can't try: os.mkdir(doomrl.homepath(user=name)) except OSError as e: return 'That name is unavailable.' # Fill in user directory log('Creating a new account: %s' % name) print('Creating user account.') try: doomrl.login(name) self.install(password) except Exception as e: doomrl.login() log('Error creating account %s: %s' % (name, e)) print('Error creating user directory.') print('Report this to the server administrator.') if doomrl.debug(): raise e try: shutil.rmtree(doomrl.homepath(user=name)) except OSError as e: log('Error cleaning up account %s: %s' % (name, e)) print('Error cleaning up the half-created user directory! This username is unavailable until the admin fixes things.') return 'Unable to create user.' return
def requestCaption(session, uuid, path, method="PREMIUM"): reference = uuid callback = CALLBACK apikey = KEY try: duration = getAudioDuration(path) except: duration = 10 log(LOG_INFO, "{0}: mycaption.requestCaption: Sending {1} for MyCaption transcription".format( session, path)) fmt = getFormat(path) if not fmt: raise Exception("Unable to determine file format") log(LOG_INFO, "{0}: mycaption.requestCaption: File format: {1}".format(session, fmt)) if method == 'ASR': api = MYCAPTION_ASR_API else: api = MYCAPTION_PREMIUM_API url = genURL(apikey, duration, reference, fmt, callback, url=api) if not url: raise Exception("Unable to generate URL") data = open(path, 'rb').read() size = len(data) if size <= 100: log(LOG_INFO, "{0}: mycaption.requestCaption: File size indicates empty file!".format( session)) return False log(LOG_INFO, "{0}: mycaption.requestCaption: Read in {1} bytes of audio data".format( session, size)) headers = {'content-type': 'application/octet-stream'} log(LOG_INFO, "{0}: mycaption.requestCaption: Sending request to MyCaption".format( session)) res = requests.post(url=url, data=data, headers=headers) log(LOG_INFO, "{0}: mycaption.requestCaption: Got a response! {1}".format(session, res.content)) try: response = json.loads(res.content) except: response = {} if 'status' in response and response['status'] == '200': for key, value in response.iteritems(): log(LOG_INFO, "{0}: mycaption.requestCaption: {1} - {2}".format(session, key, value)) return True else: log(LOG_INFO, "{0}: mycaption.requestCaption: Transmission failed.".format( session)) return False
def execute(self, qstr): log(LOG_INFO, "database.Sqlite3Database.execute: EXECUTING: {0}".format(qstr)) return self.cur.execute(qstr)
def speedtest_worker(sio): def run_thread(t, timeout_seconds): timeout_time = time.time() + timeout_seconds t.start() while t.isAlive() and time.time() < timeout_time: time.sleep(0.25) if t.isAlive(): timed_out = True else: timed_out = False return timed_out ABORT_SPEEDTEST = False servers = [] s = Speedtest() try: sio.emit('speedtest', '{ "progress": "getservers" }', broadcast=False) except IOError: pass # get a speedtest server t = threading.Thread(target=s.get_servers, args=(servers, )) thread_timed_out = run_thread(t, SPEEDTEST_GETSERVERS_TIMEOUT) if thread_timed_out: try: sio.emit('speedtest', '{ "error": "Timeout while getting server list."}', broadcast=False) ABORT_SPEEDTEST = True except: pass if not ABORT_SPEEDTEST: t = threading.Thread(target=s.get_best_server) thread_timed_out = run_thread(t, SPEEDTEST_GETSERVERS_TIMEOUT) if thread_timed_out: try: sio.emit('speedtest', '{"error" : "Timeout while getting best server."}', broadcast=False) ABORT_SPEEDTEST = True except: pass if not ABORT_SPEEDTEST: try: sio.emit('speedtest', '{ "progress": "download" }', broadcast=False) except IOError: pass t = threading.Thread(target=s.download) thread_timed_out = run_thread(t, SPEEDTEST_DOWNLOAD_TIMEOUT) if thread_timed_out: try: sio.emit('speedtest', '{"error" : "Timeout while testing download speed."}', broadcast=False) ABORT_SPEEDTEST = True except: pass if not ABORT_SPEEDTEST: try: sio.emit('speedtest', '{ "progress": "upload" }', broadcast=False) except IOError: pass t = threading.Thread(target=s.upload) thread_timed_out = run_thread(t, SPEEDTEST_UPLOAD_TIMEOUT) if thread_timed_out: try: sio.emit('speedtest', '{"error" : "Timeout while testing upload speed."}', broadcast=False) ABORT_SPEEDTEST = True except: pass if not ABORT_SPEEDTEST: output = s.results.dict() speedtestResults = {} speedtestResults['results'] = output try: sio.emit('speedtest', json.dumps(speedtestResults), broadcast=True) except IOError: pass try: # save results to a file outfile = open(SPEEDTEST_RESULTS_FILE, 'w') json.dump(output, outfile) except IOError: syslog.log("Unable to create / write to speed test results file.") try: # remove lock file os.unlink(SPEEDTEST_LOCK_FILE) except IOError: syslog.log("Unable to remove speed test lock file")
from webserve_funcs import convertsavepostfile from websocket_funcs import make_hybi07_header from websocket_funcs import servewebsocket from ms5611 import GetMS5611calibrations, MS5611convert, ams5611read from ds3231 import rtctojsepoch, jsepochtoisodate import machine, array i2c = machine.I2C(scl=machine.Pin(5), sda=machine.Pin(4)) greenpin = machine.PWM(machine.Pin(13), freq=1024, duty=40) touchpin = machine.TouchPad(machine.Pin(33)) jsepochoffset = rtctojsepoch(i2c, busywaitsec=True) - time.ticks_ms() log(jsepochtoisodate(jsepochoffset)) # enable the wifi only if entry is held down on startup ipnumber = "" for i in range(10): if touchpin.read() > 1100: break greenpin.duty(500 if ((i % 2) == 0) else 0) time.sleep_ms(200) touchpin.read() else: # this should be deferred or made on-off for i in range(20): greenpin.duty(500 if ((i % 2) == 0) else 0) time.sleep_ms(50)
def rush_hero_logic(self, things, t): enemy_team = settings.ENEMY_TEAMS[self.team] enemies = [ thing for thing in things.values() if thing.team == enemy_team ] enemy_ancient = [e for e in enemies if e.name == 'ancient'][0] enemy_tower = [e for e in enemies if e.name == 'tower'] if enemy_tower: enemy_tower = enemy_tower[0] enemy_hero = [e for e in enemies if e.__class__.__name__ == "Hero"] if enemy_hero: enemy_hero = enemy_hero[0] closest_enemy = closest(self, enemies) closest_enemy_distance = distance(self, closest_enemy) friends = [ thing for thing in things.values() if thing.team == self.team and thing != self ] friendly_ancient = [e for e in friends if e.name == 'ancient'][0] back_friends = sort_by_distance(self, friends)[2:] closest_friend = closest(self, friends) closest_friend_distance = distance(self, closest_friend) # I'm offside if there are not at least 2 friendlies in front of me offside = closest(enemy_ancient, back_friends + [self]) == self # There are enemy units behind me enemy_offside = closest(friendly_ancient, enemies + [self]) != self # log("offside: "+ str(offside)) # log("friend: %s, enemy: %s" % (str(closest_friend), str(closest_enemy))) # if I can stun the other hero, that's highest priority if closest_enemy and closest_enemy == enemy_hero\ and closest_enemy_distance <= settings.STUN_DISTANCE and self.can('stun', t): # try to stun him log('stun !!!') return 'stun', closest_enemy.position # move to get conver if I'm low on energy or there's an enemy behind me if (offside and self.life < 200): # or enemy_offside: moves = sort_by_distance(friendly_ancient, valid_positions(self, things)) return 'move', moves[0] if self.life < (self.max_life - settings.HEAL_BASE_HEALING[1]) and self.can('heal', t)\ and (closest_friend and closest_friend_distance <= settings.HEAL_DISTANCE): log("heal") return 'heal', self.position else: if closest_enemy: # there is an enemy # if closest_enemy_distance <= settings.FIREBALL_DISTANCE and self.can('fireball', t) and closest_enemy_distance > settings.FIREBALL_RADIUS and closest_friend_distance > (settings.FIREBALL_DISTANCE + settings.FIREBALL_RADIUS): if self.can('fireball', t) and closest_enemy_distance < settings.FIREBALL_DISTANCE +settings.FIREBALL_RADIUS\ and closest_enemy_distance > settings.FIREBALL_RADIUS\ and distance(closest_friend, closest_enemy) > settings.FIREBALL_RADIUS: # else try to fireball him, but only if I'm not in range log("fireball !!!") return 'fireball', closest_enemy.position elif closest_enemy_distance <= settings.HERO_ATTACK_DISTANCE: # else try to attack him log("attack") return 'attack', closest_enemy.position else: if enemy_tower: if distance(self, enemy_tower) < 5: log("halt") return moves = sort_by_distance(enemy_ancient, valid_positions(self, things)) return 'move', moves[0]
def run(self): log(syslog.LOG_INFO, "running") self.mainloop.run()
def shutdown(self, sig, frame): log(syslog.LOG_INFO, "shutdown requested") self.remove_from_connection() self.mainloop.quit() self.xorg_server.stop() syslog.closelog()
def disable(self): if not self.xorg_server.stop(): log(syslog.LOG_ERR, "X.Org server cannot be stopped") return False return True
si = network.WLAN(network.STA_IF) macaddress = "".join("{:02x}".format(x) for x in si.config("mac")) si.active(True) # wificodes are lines in form "name:password:"******":")[:2] for k in open("wificodes.txt", "rb")) print("Scanning wifis:", ", ".join(s.decode() for s in knownwifis)) # X[3]=RSSI (received signal strength) wifiname = max((sc for sc in si.scan() if sc[0] in knownwifis), key=lambda X: X[3], default=[None])[0] if wifiname is not None: log("Strongest wifi", wifiname.decode()) si.connect(wifiname, knownwifis[wifiname]) del knownwifis while not si.isconnected(): pass ipnumber = si.ifconfig()[0] else: log("No recognized wifi") si = network.WLAN(network.AP_IF) # create access-point interface si.active(True) # activate the interface log("Creating access point ESP_{}".format(macaddress[-6:])) ipnumber = si.ifconfig()[0]
def rush_hero_logic(self, things, t): enemy_team = settings.ENEMY_TEAMS[self.team] enemies = [thing for thing in things.values() if thing.team == enemy_team] enemy_ancient = [e for e in enemies if e.name == 'ancient'][0] enemy_tower = [e for e in enemies if e.name == 'tower'] if enemy_tower: enemy_tower = enemy_tower[0] enemy_hero = [e for e in enemies if e.__class__.__name__ == "Hero"] if enemy_hero: enemy_hero = enemy_hero[0] closest_enemy = closest(self, enemies) closest_enemy_distance = distance(self, closest_enemy) friends = [thing for thing in things.values() if thing.team == self.team and thing != self] friendly_ancient = [e for e in friends if e.name == 'ancient'][0] back_friends = sort_by_distance(self, friends)[2:] closest_friend = closest(self, friends) closest_friend_distance = distance(self, closest_friend) # I'm offside if there are not at least 2 friendlies in front of me offside = closest(enemy_ancient, back_friends + [self]) == self # There are enemy units behind me enemy_offside = closest(friendly_ancient, enemies + [self]) != self # log("offside: "+ str(offside)) # log("friend: %s, enemy: %s" % (str(closest_friend), str(closest_enemy))) # if I can stun the other hero, that's highest priority if closest_enemy and closest_enemy == enemy_hero\ and closest_enemy_distance <= settings.STUN_DISTANCE and self.can('stun', t): # try to stun him log('stun !!!') return 'stun', closest_enemy.position # move to get conver if I'm low on energy or there's an enemy behind me if (offside and self.life < 200):# or enemy_offside: moves = sort_by_distance(friendly_ancient, valid_positions(self, things)) return 'move', moves[0] if self.life < (self.max_life - settings.HEAL_BASE_HEALING[1]) and self.can('heal', t)\ and (closest_friend and closest_friend_distance <= settings.HEAL_DISTANCE): log("heal") return 'heal', self.position else: if closest_enemy: # there is an enemy # if closest_enemy_distance <= settings.FIREBALL_DISTANCE and self.can('fireball', t) and closest_enemy_distance > settings.FIREBALL_RADIUS and closest_friend_distance > (settings.FIREBALL_DISTANCE + settings.FIREBALL_RADIUS): if self.can('fireball', t) and closest_enemy_distance < settings.FIREBALL_DISTANCE +settings.FIREBALL_RADIUS\ and closest_enemy_distance > settings.FIREBALL_RADIUS\ and distance(closest_friend, closest_enemy) > settings.FIREBALL_RADIUS: # else try to fireball him, but only if I'm not in range log("fireball !!!") return 'fireball', closest_enemy.position elif closest_enemy_distance <= settings.HERO_ATTACK_DISTANCE: # else try to attack him log("attack") return 'attack', closest_enemy.position else: if enemy_tower: if distance(self,enemy_tower) < 5: log("halt") return moves = sort_by_distance(enemy_ancient, valid_positions(self, things)) return 'move', moves[0]