def get_sunset(self): r = requests.get('https://www.timeanddate.com/sun/@5493452') soup = BeautifulSoup(r.text, 'html.parser') tab = soup.find('table', {'class': 'table'}) self.sunset_time = tab.findAll('tr')[-1].findAll( 'td')[0].text.split()[0] s.iprint(f'Sunset is at {self.sunset_time}', 1)
def run(self): for song in self.songs: s.iprint( "[{:12.0f}] Playing {} at volume {:.3f}" "".format(time.time(), song.name, self.volume), 1) # p = Process(self.try_bluetooth()) # p.start() dt = self.play_song(song) # p.join() if dt < 60 * 60: self.volume = ( self.volume_init + (self.volume_final - self.volume_init) * dt / 60 / 60) else: self.volume = self.volume_final if not self.played_weather: try: self.play_weather() self.played_weather = True except Exception as e: print(e) self.played_weather = True if dt >= 3 * 3600: return 0
def main(): report = Weather() report.convert_units() response = report.send_daily('beancc_weather.key', '#general') if response["ok"]: pass else: s.iprint(response["error"], 1)
def send(self): key_file = self.here / 'beancc_xkcd.key' key = key_file.open('r').readline().strip('\n') # print(key) sc = slack.WebClient(token=key) response = sc.chat_postMessage(channel='#general', text=self.alt_text, attachments=[{ 'title': 'xkcd', 'image_url': 'http://' + self.img_url }]) if response['ok']: s.iprint('xkcd successfully sent to Slack', 1) self.images_file.open('a').write(f'{self.img_url}\n') else: s.iprint(response['error'], 1)
def main(): if len(sys.argv) == 3: # print(sys.argv) path, site, chnnl = sys.argv else: site = "APO" chnnl = 'Beans' if "--test" in sys.argv: test = True else: test = False weather = ClearSky(site, chnnl, test) try: weather.get_sunset() except Exception as e: s.iprint(e, 1) weather.sunset_time = '' weather.compose() weather.send()
def __init__(self, flacs, wavs, mp3s, screensaver=False, cec=False, lights=False): self.flacs = flacs self.wavs = wavs self.mp3s = mp3s self.screensaver = screensaver self.cec = cec self.lights = lights self.start = time.time() s.iprint("[{:12.0f}] Alarm started".format(self.start), 0) sub.call('amixer set PCM -- 85%', shell=True) if self.cec: tv_on = sub.call('echo "on 0" | cec-client -s -d 1 -p 3', shell=True) s.iprint(f"[{time.time():12.0f}] TV turn on exit code: {tv_on}", 1) time.sleep(20) tv_source = sub.call('echo "as 0" | cec-client -s -d 1 -p 3', shell=True) s.iprint( f"[{time.time():12.0f}] TV switch source exit code" f" {tv_source}", 1) # Set volume to 16 # sub.call('echo "voldown 0" | cec-client -s -d 1 -p 1', shell=True) # sub.call('echo "volup 16" | cec-client -s -d 1 -p 1', shell=True) self.songs = np.array( list(self.wavs) + list(self.mp3s) + list(self.flacs)) np.random.shuffle(self.songs) s.iprint( "[{:12.0f}] There are {} songs" "".format(time.time(), len(self.songs)), 1) self.played_weather = False self.volume_init = 0.04 self.volume_final = 0.095 self.volume = self.volume_init if self.screensaver: sub.call('xscreensaver-command -activate', shell=True) if self.lights: self.lights = fairy_lights.Lights(17) self.lights.on()
def fetch(self): # Get a new comic try: r = requests.get('https://www.xkcd.com') except requests.exceptions.ConnectionError: s.iprint('Cannot connect to xkcd.com, skipping', 1) exit() soup = BeautifulSoup(r.text, 'html.parser') image = soup.find(id='comic').find_all()[0] self.alt_text = str(image).split('title=')[1].strip('">\n</img>') self.alt_text = self.alt_text.replace('"', '"') self.img_url = str(image).split('src=')[-1].split()[0][3:-1] self.here = Path(__file__).parent.absolute() # Check to see if I already got the comic self.images_file = self.here / 'shown_xkcd_comics.txt' images_list = self.images_file.open('r').readlines() # print(images_list) if f'{self.img_url}\n' not in images_list: self.is_new = True else: self.is_new = False s.iprint('XKCD is not new', 1)
def compose(self): if sum(self.good_times) > 0: self.post_line += ("These are the times with good conditions at" " {}:\n``` Date: Time: Score:\n".format( self.location_name)) for da, ti, qu in zip(self.weather['Day'][self.good_times], self.weather['Time'][self.good_times], self.weather['Rating'][self.good_times]): self.post_line += "{: >8}: {: >6.0f} {: >8.0f}\n".format( da, ti, qu) self.post_line += "```\n" else: self.post_line += ( "There are no good times for observing in the " "next few days at {}. Good weather means seeing " "is a 3/5, transparency is a 3/5, cloud cover " "is below 30%, humidity is below 60%, winds are " "below 20mph, and the temperature is " "reasonable. Perfect weather has a score of " "40.\n".format(self.location_name)) self.post_line += f'Sunset is at {self.sunset_time}\n' self.post_line += self.location s.iprint(self.post_line, 1) log.write(self.post_line + "\n")
def send(self): """This function sends post_line to the selected chnnl""" s.iprint("Sending to {}".format(self.channel), 1) # print(self.oauth_token) sc = slack.WebClient(token=self.oauth_token) if not self.test: response = sc.chat_postMessage(channel=self.channel, text=self.post_line) if response["ok"]: log.write("Successfully sent to {}\n\n".format(self.channel)) s.iprint("Successfully sent to {}".format(self.channel), 1) else: log.write(response["error"] + "\n\n") s.iprint(response["error"], 1)
#!/usr/bin/env python3 import subprocess as sub import numpy as np import starcoder42 as s s.iprint('Skipping song', 1) sub.call('ps auxf > procs.txt', shell=True) with open("procs.txt", "r") as proc_fil: lines = np.array(proc_fil.readlines()) is_song = np.array(["play" in proc for proc in lines]) to_kill = lines[is_song] for proc in to_kill: # print(proc) pid = proc.split()[1] # print(pid) sub.call(['kill', pid]) sub.call(['rm', 'procs.txt'])
def __init__(self, location, channel, test): self.location_name = location self.location = location_names[location] self.channel = channel_names[channel] self.sunset_time = '' self.post_line = '' self.test = test # print(home / 'bean_clear_skies.key') try: self.oauth_token = (home / 'beancc_clearskies.key').open('r').readline() except Exception as e: print(e) if self.oauth_token is None: raise s.GatlinError('No oauth token found') # Download from website using requests) # print(self.location) np.random.choice header = { "user-agent": np.random.choice([ "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101" " Firefox/89.0", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36" " (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64) AppleWebKit/605.1.15" " (KHTML, like Gecko) Version/14.0 Safari/605.1.15 Midori/6" ]), "referer": "http://google.com" } r = requests.get(self.location, headers=header) # print(r) # print(r.content) # print(r.text) # The content of the image soup = BeautifulSoup(r.text, 'html.parser') if "Mod_Security" in str(soup): raise s.GatlinError("Request declined by CSC") subset = soup.find('map') # print(subset) log.write("Clear Skies successfully reached.\n") # Check to see how long useful values is # There may be anywhere between 44 and 65 items in each line # Some lines might be longer than others at APO # print(subset) self.n_times = [] self.includes_ecmwf = 'Cloud' in str(subset) self.includes_smoke = 'Smoke' in str(subset) loc = 0 for i, line in enumerate(subset): if i == 0: continue if line == '\n': continue # print(line) line = str(line) split_line = line.split(',') if int(split_line[1]) != loc: loc = int(split_line[1]) self.n_times.append(1) # print(loc) else: self.n_times[-1] += 1 # print(subset) # print() s.iprint("There are {} times in the record".format(self.n_times), 1) # TODO User BeautifulSoup to iterate instead of manually indexing self.useful_values = str(subset).split(">\n<")[1:] # print(self.useful_values) # print(self.useful_values[self.ntimes]) # Cloud Cover, percentage n_loops = 0 clouds = [] for line in self.useful_values[:self.n_times[n_loops]]: # print(line) val = line.split('title=')[-1].split(':')[-1] # print(val) if "Clear" in val: clouds.append(0) elif "Overcast" in val: clouds.append(100) elif "Too cloudy" in val: clouds.append(100) else: clouds.append(int(val.split("%")[0])) clouds = np.array(clouds) # print(clouds) n_loops += 1 # ECMWF Cloud ecmwf_clouds = [] for line in self.useful_values[sum(self.n_times[:n_loops] ):sum(self.n_times[:n_loops + 1])]: # print(line) val = line.split('title=')[-1].split('Cloud ')[-1].strip('%"/') # print(val) if 'Clear Sky' in str(val): ecmwf_clouds.append(0) elif 'Overcast' in str(val): ecmwf_clouds.append(100) else: ecmwf_clouds.append(int(val)) ecmwf_clouds = np.array(ecmwf_clouds) n_loops += 1 # Transparency # 1 is bad, 5 is good trans = [] # print('Transparency') for line in self.useful_values[sum(self.n_times[:n_loops] ):sum(self.n_times[:n_loops + 1])]: # print(line) # s.iprint(line.split(":"), 1) val = line.split(":")[2].split('"')[0].split(" (")[0][1:] # s.iprint(val, 1) if val == "Transparent": trans.append(5) elif val == "Above average": trans.append(4) elif val == "Average": trans.append(3) elif val == "Below Average": trans.append(2) elif val == 'Too cloudy to forecast' or val == 'Poor': trans.append(1) else: # s.iprint("printing else", 1) s.iprint(f"Unable to parse: {line}", 1) trans = np.array(trans) n_loops += 1 # Seeing # 1 is bad, 5 is good seens = [] # print('Seeing') for line in self.useful_values[sum(self.n_times[:n_loops] ):sum(self.n_times[:n_loops + 1])]: # print(line) val = line.split(':')[-1] if val == "Bad 1/5": seens.append(1) elif val == "Poor 2/5": seens.append(2) elif val == "Average 3/5": seens.append(3) elif val == "Good 4/5": seens.append(4) else: seens.append(5) seens = np.array(seens) # print(seens) n_loops += 1 # Only run with smoke if it finds the first value to contain smoke # if self.includes_smoke: # Smoke (which may not always be there) smokes = [] # print('Smoke') for line in self.useful_values[sum(self.n_times[:n_loops] ):sum(self.n_times[:n_loops + 1])]: # print(line) val = line.split(':')[-1] if 'No Smoke' in val: smokes.append(0) else: smokes.append(1) n_loops += 1 # Wind # Lower limit winds = [] # print('Wind') for line in self.useful_values[sum(self.n_times[:n_loops] ):sum(self.n_times[:n_loops + 1])]: # print(line) val = line.split(':')[-1] # print(val) if ">" in val: winds.append(45) elif 'Smoke' in val: winds.append(0) else: # print(val.split()) winds.append(int(val.split()[2])) winds = np.array(winds) n_loops += 1 # Humidity humids = [] # print('Humidity') for line in self.useful_values[sum(self.n_times[:n_loops] ):sum(self.n_times[:n_loops + 1])]: # print(line) val = line.split(':')[-1] # print(val) if ("<" not in val) and ('<' not in val): # print("ran") humids.append(int((val.split()[2]).strip('%"/'))) else: humids.append(10) humids = np.array(humids) n_loops += 1 # Temperatures temps = [] # print('Temps') for line in self.useful_values[sum(self.n_times[:n_loops] ):sum(self.n_times[:n_loops + 1])]: # print(line) val = line.split(':')[-1] # print(val) if "<" in val: temps.append(s.fahr2cel(-40)) elif ">" in val: temps.append(s.fahr2cel(113)) else: temp = int(val.split()[2].strip('F"/')) temps.append(s.fahr2cel(temp)) temps = np.array(temps) # print(temps) log.write("Values successfully unpacked\n") # Times times = [] for line in self.useful_values[sum(self.n_times[:n_loops] ):sum(self.n_times[:n_loops + 1])]: time = line.split('title="')[-1].split(':')[0] times.append(int(time)) # print(times) # Creates a list of the days using times days = [] date = 1 for i, time in enumerate(times): if date == 1 and time < 23: days.append("Today") elif time == 23: date += 1 days.append(days[-1]) elif date == 2 and time < 23: days.append("Tomorrow") elif time == 23: date += 1 days.append(" Today") elif date == 3 and time < 23: days.append("The Next") times = np.array(times) days = np.array(days) shortest = np.min([ len(days), len(times), len(clouds), len(trans), len(seens), len(temps), len(winds), len(humids) ]) if shortest == 0: raise s.GatlinError( f"One of the arrays is of length 0:" f" Days: {len(days)}, Times: {len(times)}," f" Clouds: {len(clouds)}," f" Transparency: {len(trans)}, Seeing: {len(seens)}," f" Temperature: {len(temps)}, Wind: {len(winds)}," f" Humidity: {len(humids)}") # print(len(days[:shortest])) # print(len(clouds[:shortest])) # if self.includes_ecmwf: # print(len(ecmwf_clouds[:shortest])) # print(len(trans[:shortest])) # print(len(seens[:shortest])) # print(len(winds[:shortest])) # print(len(humids[:shortest])) # print(len(times[:shortest])) # print(len(days[:shortest])) self.weather = astropy.table.Table([ days[:shortest], times[:shortest], clouds[:shortest], trans[:shortest], seens[:shortest], temps[:shortest], winds[:shortest], humids[:shortest], ], names=[ "Day", "Time", "CloudCover", "Transparency", "Seeing", "Temperature", "Wind", "Humidity" ]) bool_stats = ((self.weather['CloudCover'] <= 30) & (self.weather['Transparency'] >= 3) & (self.weather['Seeing'] >= 3) & (self.weather['Wind'] <= 25) & (self.weather['Humidity'] <= 80)) qualities = ((10 - self.weather['CloudCover'] / 10) + 2 * self.weather['Transparency'] + 2 * self.weather['Seeing'] + 5 * (self.weather['Wind'] < 25) + (5 - self.weather['Humidity'] / 20)) bool_temps = (-10 <= self.weather['Temperature'])\ & (self.weather['Temperature'] <= 25) bool_times = np.logical_or(20 <= times, times <= 6)[:shortest] self.good_times = bool_stats & bool_temps & bool_times self.weather.add_column(astropy.table.Column(qualities, name="Rating")) self.weather["Rating"].format = ".0f" self.weather.add_column( astropy.table.Column(self.good_times, name="IsGood")) log.write("Forecast:\n") log.write(str(self.weather))
import starcoder42 as s now = datetime.datetime.now() print("Get OW Rank started at {}".format(now)) pc = {'tank': 0, 'damage': 0, 'support': 0} try: data = requests.get("https://ow-api.com/v1/stats/pc/us/Starkiller42-11691/" "profile") # print(data.json()) # try: ranks = data.json()["ratings"] for rank in ranks: pc[rank['role']] = rank['level'] except Exception as e: s.iprint(e, 1) xbox = {'tank': 0, 'damage': 0, 'support': 0} try: data = requests.get("https://ow-api.com/v1/stats/xbl/Starkiller625/profile") # print(data.json()) # try: xranks = data.json()["ratings"] ranks = data.json()["ratings"] for rank in xranks: xbox[rank['role']] = rank['level'] except Exception as e: s.iprint(e, 1) rank_path = (Path(__file__).parent / "ow_rolelock_ranks.txt").absolute()
import datetime import slack import starcoder42 as s from pathlib import Path import subprocess as sub import sys now = datetime.datetime.now() print("IP Logger started at {}".format(now)) ip_path = (Path(__file__).parent / "ip_archive.txt").absolute() my_ip = sub.Popen('dig +short myip.opendns.com @resolver1.opendns.com', shell=True, stdout=sub.PIPE).stdout.read().decode('utf-8').strip('\n') message = "Your Raspberry Pi's IP Address is: {}".format(my_ip) s.iprint(message, 1) # Now that we have it, we'll save it if not ip_path.exists(): ip_path.touch() else: ip_archive = ip_path.open('r') lines = ip_archive.readlines() is_there = bool(sum([my_ip in line for line in lines])) ip_archive.close() has_argv = False try: sys.argv[1] sys.argv[2] has_argv = True
def main(): fct = CatFact() response = fct.send_daily() if response["ok"]: s.iprint('Cat fact sent to Beans', 1)
parts = proc.split() pid = parts[1] dt = parts[9] m, sec = dt.split(b':') dt = datetime.timedelta(minutes=int(m), seconds=int(sec)) if dt > datetime.timedelta(hours=23): sub.call(['kill', pid]) port = int(sys.argv[1]) threshhold = float(sys.argv[2]) fan = LED(port) try: cond = True while cond: # Run forever temp = str( sub.Popen(['/opt/vc/bin/vcgencmd', 'measure_temp'], stdout=sub.PIPE).stdout.read()) temp = float(temp.split("=")[1].split("'")[0]) if temp > threshhold: fan.on() else: fan.off() sleep(60) dt = datetime.datetime.now() - start cond = dt.seconds < 60 * 60 * 12 s.iprint((dt.seconds, temp), 1) except KeyboardInterrupt: GPIO.cleanup() sys.exit()