def send_print_notification_pushbullet(_print, event_type=None): if not _print.printer.user.has_valid_pushbullet_token(): return pb = Pushbullet(_print.printer.user.pushbullet_access_token) title = 'The Spaghetti Detective - Print job notification' link = site.build_full_url('/') body = get_notification_body(_print, event_type=event_type) file_url = None try: file_url = _print.poster_url if not settings.SITE_IS_PUBLIC: pb.upload_file(requests.get(file_url).content, 'Snapshot.jpg') except: pass try: if file_url: pb.push_file(file_url=file_url, file_name="Snapshot.jpg", file_type="image/jpeg", body=body, title=title) else: pb.push_link(title, link, body) except (PushError, PushbulletError) as e: LOGGER.error(e)
def send_failure_alert_pushbullet(printer, is_warning, print_paused): if not printer.user.has_valid_pushbullet_token(): return pausing_msg = '' if print_paused: pausing_msg = 'Printer is paused.' elif printer.action_on_failure == Printer.PAUSE and is_warning: pausing_msg = 'Printer is NOT paused because The Detective is not very sure about it.' pb = Pushbullet(printer.user.pushbullet_access_token) title = 'The Spaghetti Detective - Your print {} on {} {}.'.format( printer.current_print.filename or '', printer.name, 'smells fishy' if is_warning else 'is probably failing') link = site.build_full_url('/') body = '{}\nGo check it at: {}'.format(pausing_msg, link) try: file_url = None try: file_url = printer.pic['img_url'] if not ipaddress.ip_address(urlparse(file_url).hostname).is_global: pb.upload_file(requests.get(file_url).content, 'Detected Failure.jpg') except: pass if file_url: pb.push_file(file_url=file_url, file_name="Detected Failure.jpg", file_type="image/jpeg", body=body, title=title) else: pb.push_link(title, link, body) except PushError as e: LOGGER.error(e) except PushbulletError as e: LOGGER.error(e)
def send_print_notification_pushbullet(_print): if not _print.printer.user.has_valid_pushbullet_token(): return pb = Pushbullet(_print.printer.user.pushbullet_access_token) title = 'The Spaghetti Detective - Print job notification' link = site.build_full_url('/') body = f"Your print job {_print.filename} {'has been canceled' if _print.is_canceled() else 'is done'} on printer {_print.printer.name}." file_url = None try: file_url = _print.printer.pic['img_url'] if not ipaddress.ip_address(urlparse(file_url).hostname).is_global: pb.upload_file(requests.get(file_url).content, 'Snapshot.jpg') except: pass try: if file_url: pb.push_file(file_url=file_url, file_name="Snapshot.jpg", file_type="image/jpeg", body=body, title=title) else: pb.push_link(title, link, body) except (PushError, PushbulletError) as e: LOGGER.error(e)
def push_file(filename): auth_key = _get_pb_authKey() pb = Pushbullet(auth_key) # authenticate with open(filename, 'rb') as file_to_push: file_data = pb.upload_file(file_to_push, filename) push_data = pb.push_file(**file_data)
def send_notification(api_key, message): pb = Pushbullet(api_key) my_channel = pb.channels[0] pushN = my_channel.push_note('CoopDoor', message) #pb.push_note('Chicken Door', message) with open(fileName, "rb") as pic: file_data = pb.upload_file(pic, "coop.jpg", file_type="image/jpeg") pushF = my_channel.push_file(**file_data)
def main(): im = Image.open("taehui.jpg") g_im = im.convert('L') g_im.save('taehui_gray.jpg', 'JPEG') pb = Pushbullet('o.cJzinoZ3SdlW7JxYeDm7tbIrueQAW5aK') with open('taehui_gray.jpg', 'rb') as pic: file_data = pb.upload_file(pic, 'taehui_gray.jpg') print(**file_data)
def send_pushbullet(self): pb = Pushbullet(self.pushbullet_token) if self.file_path is not None: with open(self.file_path, "rb") as f: file_data = pb.upload_file(f, f.name.replace("-", "")) response = pb.push_file(**file_data) else: pb.push_note("Motion detected!", "Motion detected, could not find preview image") print "PiSN: Pushbullet notification succesfully pushed"
def on_file_received(self, file): print "File received " + file #super(MyHandler, self).on_file_sent(self, file) pb = Pushbullet(api_key) with open(file, "rb") as pic: file_data = pb.upload_file(pic, file) push = pb.push_file(**file_data)
def push_chart(self): """ Pushes the chart to a Pushbullet account. """ pb = Pushbullet(config.PB_API_KEY) with open('./today.jpg', 'rb') as pic: file_data = pb.upload_file(pic, 'today.jpg') pb.push_file(**file_data)
def _send_push_attachment(self, api_key, text, file=None): pb = Pushbullet(api_key) # If the file exist than open and push, otherwise attach an error message to the content if os.path.exists(file): with open(file, "rb") as fil: file_data = pb.upload_file(fil, text) pb.push_file(**file_data) else: print('Error: File does not exists. file:' + file)
def send_meme(caption, media_path='Data/meme.jpg', media_type='Photo'): pb = Pushbullet(config.PUSHBULLET_API_KEY) phones = [device for device in pb.devices if device.icon == 'phone'] with open(media_path, 'rb') as pic: file_data = pb.upload_file(pic, 'picture.jpg') for phone in phones: # e.g. with a url # push = pb.push_file(file_url="https://i.imgur.com/IAYZ20i.jpg", file_name="meme.jpg", file_type="image/jpeg") phone.push_note(f'From r/{config.SUBREDDIT}', caption) phone.push_file(**file_data) return phones != []
def push_file(filename): if is_device_connected(DEVICE_MAC): print "Device is connected, not sending" return print "Sending", filename pushbullet = Pushbullet(PUSHBULLET_API_KEY) my_device = pushbullet.get_device(PUSHBULLET_DEVICE_NAME) file_data = pushbullet.upload_file(open(filename, "rb"), filename) pushbullet.push_file(device=my_device, **file_data) print "Sent!"
def on_message(client, userdata, msg): pb = Pushbullet("SECRET TOKEN") push = pb.push_note("Evento", "Se detecto un evento en la puerta") archivo = time.strftime("%Y%m%d%H%M%S", time.localtime())+".png" print("Evento detectado") camara = CamaraIP('url_camara') camara.capturar(archivo) print("Enviando imagen ",archivo) with open(archivo, "rb") as pic: file_data = pb.upload_file(pic, archivo) push = pb.push_file(**file_data)
def push_file(filename): if is_device_connected(DEVICE_MAC): print "Device is connected, not sending" return print "Sending", filename pushbullet = Pushbullet(PUSHBULLET_API_KEY) my_device = pushbullet.get_device(PUSHBULLET_DEVICE_NAME) file_data = pushbullet.upload_file(open(filename, "rb"), filename) pushbullet.push_file(device = my_device, **file_data) print "Sent!"
def send_image(): if len(sys.argv) < 2: print('Missing image in arguments') return pb = Pushbullet(PUSHBULLET_API_KEY) image = sys.argv[1] with open(image, "rb") as pic: file_data = pb.upload_file(pic, "photo.jpg") device = pb.get_device('S10') push = pb.push_file(**file_data, device=device)
def call_pushbullet( self, access_token: str, title: str, body: str, link: str, file_url: str, ) -> None: pb = Pushbullet(access_token) try: if not settings.SITE_IS_PUBLIC: pb.upload_file(requests.get(file_url).content, 'Snapshot.jpg') except: pass if file_url: pb.push_file(file_url=file_url, file_name="Snapshot.jpg", file_type="image/jpeg", body=body, title=title) else: pb.push_link(title, link, body)
class PushbullectHelper(): def __init__(self): self.pb = Pushbullet(api_key) self.iphone = self.pb.devices[0] self.device = self.pb.devices def sendnote(self, title, str): self.pb.push_note(title, str, device=self.iphone) def sendall(self, title, str): self.pb.push_note(title, str) def sendfile(self, file, name): filedata = self.pb.upload_file(file, name) self.pb.push_file(**filedata)
def send_push(file): try: urllib3.disable_warnings() pb = Pushbullet(API_KEY) #push = pb.push_note(pb.devices[3]['iden'],'Alarm', 'Motion detected') push = pb.push_note('Alarm', 'Motion detected') print "push-uploading file.." with open(file, 'rb') as vid: file_data = pb.upload_file(vid, 'video.mkv') push = pb.push_file(**file_data) # only for debug: #pushes = pb.get_pushes() #latest = pushes[0] #print latest except Exception, error: print "Error in send_push: " + str(error)
def sendtophone(): dir = r"/home/pi/weather-station/data/" filename = str(date.today()) humidity, pressure, ambient_temperature = bme280_output.read_all() temperature = round(ambient_temperature,2) humidity = round(humidity,2) tempdata = str(temperature) humdata = str(humidity) pb = Pushbullet('o.SpLVyGfhBJGKv9E8UxPs7sWsO7kyzcwi') with open(os.path.join(dir,filename+'.png'),"rb") as pic: file_data = pb.upload_file(pic, "test.png") push = pb.push_note("Raspberry Pi","°C :"+ tempdata+ " Humidity: " + humdata +"%") push = pb.push_file(**file_data)
def push(): # load config file config = None with open('./config.json') as f: config = json.load(f) # pushbullet pb = Pushbullet(config['access_token']) target = None for dev in pb.devices: if dev.nickname == config['device_name']: target = dev if target == None: print 'target device not found.' else: # push as file if config['send_file']: if os.path.exists(config['send_file']): file_data = None try: with open(config['send_file'], 'rb') as f: file_data = pb.upload_file( f, os.path.basename(config['send_file'])) except: pass target.push_file(**file_data) print 'pushed as file : {0}'.format(config['send_file']) return # push as text target.push_note(config['send_title'], config['send_body']) print 'pushed as text : {0} / {1}'.format(config['send_title'], config['send_body'])
class SnapshotPipeline(Pipeline): def __init__(self): super(SnapshotPipeline, self).__init__('snap_pipe') self.file_source = "" self.pb = Pushbullet('o.cJzinoZ3SdlW7JxYeDm7tbIrueQAW5aK') self.create_snapshot() bus = self.pipe.get_bus() bus.add_signal_watch() bus.connect('message', self.on_message_cb, None) def create_snapshot(self): self.appsrc = Gst.ElementFactory.make('appsrc', 'snapsrc') self.pipe.add(self.appsrc) jpegenc = Gst.ElementFactory.make('jpegenc', 'jpegenc') self.pipe.add(jpegenc) self.filesink = Gst.ElementFactory.make('filesink', 'jpegfilesink') self.pipe.add(self.filesink) self.appsrc.link(jpegenc) jpegenc.link(self.filesink) def send_snapshot(self): dtime = Gst.DateTime.new_now_local_time() g_datetime = dtime.to_g_date_time() timestamp = g_datetime.format("%F_%H%M%S") timestamp = timestamp.replace("-", "") filename = "sshot_" + timestamp + ".jpg" self.file_source = filename print("Filename : %s" % filename) self.filesink.set_property('location', filename) self.filesink.set_property('async', False) self.pipe.set_state(Gst.State.PLAYING) def on_message_cb(self, bus, msg, data): t = msg.type if t == Gst.MessageType.ERROR: name = msg.src.get_path_string() err, debug = msg.parse_error() print("Snapshot pipeline -> Error received : from element %s : %s ." % (name, err.message)) if debug is not None: print("Additional debug info:\n%s" % debug) self.pipe.set_state(Gst.State.NULL) self.file_source = "" elif t == Gst.MessageType.WARNING: name = msg.src.get_path_string() err, debug = msg.parse_warning() print("Snapshot pipeline -> Warning received : from element %s : %s ." % (name, err.message)) if debug is not None: print("Additional debug info:\n%s" % debug) elif t == Gst.MessageType.EOS: print("Snapshot End-Of-Stream received") print(datetime.now()) print("") self.pipe.set_state(Gst.State.NULL) if self.file_source != "": with open(self.file_source, 'rb') as pic: file_data = self.pb.upload_file(pic, self.file_source) for key in file_data.keys(): print("%s in File data of value : %s" % (key , file_data[key])) push = self.pb.push_file(title="Motion detected", **file_data) print(push) self.file_source = ""
settings = json.load(f) if settings['api_key'] == 'put_key_here': print('You should check the README on how to add your API key') exit(0) try: pb = Pushbullet(settings['api_key']) except: print ("Your API key is invalid") exit(1) if settings['command_started_title'].isspace(): if len(sys.argv) == 2: pb.push_note(settings['command_started_title'], 'Running command ' + sys.argv[1] + ' with no arguments') else: pb.push_note(settings['command_started_title'], 'Running command ' + sys.argv[1] + ' with arguments ' + str(sys.argv[2:])) task_output = open('out.txt', 'w') retcode = call(sys.argv[1:], stdout = task_output) task_output.close() with open('out.txt', 'rb') as f: filename = 'out_'+datetime.datetime.fromtimestamp(time.time()).strftime('%Y_%m_%d_%H%M%S')+'.txt' task_output_data = pb.upload_file(f, filename) os.remove('out.txt') if retcode == 0: pb.push_file(**task_output_data, title=settings['command_done_title']) else: pb.push_file(**task_output_data, title=settings['command_error_title'], body='Command failed with errorcode: ' + str(retcode) + '. Output to follow')
pb = Pushbullet("") pb.push_note("ONLINE", "Nest Pension Monitor Online.") print("Pension Monitor - Monitoring") while True: loader.loading() time.sleep(60) try: a.getData() if links != a.links: print("New PDFs Found") links = a.links.copy() pb.push_note("New Nest Data") try: a.loadData() with open("Current_Data.png") as f: lastest_file = pb.upload_file(f, "LatestNestData.png") pb.push_file(**lastest_file) except: pass except: print("Failed") try: pb.push_note("Nest Script Crashed","") except: pass pb.push_note("Nest Script Crashed","")
def download(link, newdevice, video, delete): """Download a youtube video or playlist in best audio and video quality by providing a link, and then send to the preffered device, or override it with `--newdevice` option. Provide the device name for `--newdevice` in quotes for e.g. "OnePlus One". Please run `moboff initialise` if this is your first time. """ if os.path.exists('data.txt'): with open('data.txt') as json_file: data = json.load(json_file) for p in data['user']: api_key = p['api_key'] device = p['device'] else: click.secho("Please run `moboff initialise` first.", fg='red', bold=True) quit() os.chdir('Music') if video is True: downloadcommand = [ "youtube-dl", "--metadata-from-title", "%(artist)s - %(title)s", "-f", "bestvideo+bestaudio", "--add-metadata", "--output", "%(artist)s - %(title)s.%(ext)s", link ] else: downloadcommand = [ "youtube-dl", "--metadata-from-title", "%(artist)s - %(title)s", "--extract-audio", "--audio-format", "mp3", "--audio-quality", "0", "--add-metadata", "--output", "%(artist)s - %(title)s.%(ext)s", link ] try: subprocess.check_output(downloadcommand, stderr=subprocess.STDOUT) except subprocess.CalledProcessError: print( "Please check your URL, it shouldn't be a private playlist link (eg liked videos)" ) quit() click.secho("File successfully downloaded.", fg="green", bold=True) types = ('*.mp3', '*.mp4', '*.mkv') list_of_files = [] for files in types: list_of_files.extend(glob.glob(files)) recent_download = max(list_of_files, key=os.path.getctime) print("File to send : {0}".format(recent_download)) pb = Pushbullet(api_key) phone = device if (newdevice): newdevice = "Device('{0}')".format(newdevice) click.secho("Overriding preffered device : {0} with given device : {1}" ).format(device, newdevice) phone = newdevice with open(recent_download, "rb") as song: file_data = pb.upload_file(song, recent_download) print("Now sending the file to {0}".format(phone)) push = pb.push_file(**file_data) if (delete): os.remove(recent_download)
save_obj_as_pkl(history_1, name="model/history_1.pkl") now_end_1 = datetime.now() # %% [markdown] """##### Plot""" # %% try: m1 = pd.DataFrame(history_1.history).reset_index().rename(columns={'index' : 'epoch'}) plot_losses(m1, "model/plot_losses_1.png", "1") plot_measures(m1, "model/plot_measures_1.png", "1") # pushbullet push = pb.push_note("KerasModelLocClassif {}".format(now_start_1.strftime("%Y-%m-%d (%A)")), "Fit 1\nStarted at {}\nEnded at {}\nDuration {}".format(now_start_1, now_end_1, now_end_1 - now_start_1)) # losses with open("model/plot_losses_1.png", "rb") as pic: file_data = pb.upload_file(pic, "plot_losses_1.jpg") push = pb.push_file(**file_data) # measures with open("model/plot_measures_1.png", "rb") as pic: file_data = pb.upload_file(pic, "plot_measures_1.jpg") push = pb.push_file(**file_data) except: print("Plot does not work.") # %% [markdown] """##### Save""" # %% if is_colab_notebook(): drive_path="/content/gdrive/My Drive/date_detection_models/model_lc_" date = datetime.now().strftime('%Y%m%d') save_path = drive_path + date + "_1B"
import subprocess def takepic(): camera = PiCamera() camera.start_preview() time.sleep(5) camera.capture('/tmp/coop.jpg') camera.stop_preview() if __name__ == '__main__': config = ConfigParser.ConfigParser() config.read('/opt/coopdoor/coopdoor.cfg') api_key = config.get('DEFAULT', 'pushbullet_api_key') pb = Pushbullet(api_key) try: cmd = takepic() subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) time.sleep(1) with open("/tmp/coop.jpg", "rb") as pic: file_data = pb.upload_file(pic, "coop.jpg") push = pb.push_file(**file_data) except: print "BOOM:", sys.exc_info()
accept = ["yes", "Yes", "ho"] #api_key : pushbullet api key pb = Pushbullet("api_key") message = pb.push_note("Verification", "Did you just logged in?") flag = False while time.clock() <= 30: pushes = pb.get_pushes() if pushes[0]["body"] in decline: flag = True break if pushes[0]["body"] in accept: break if flag: cap = cap = cv.VideoCapture(0) ret, frame = cap.read() threat = pb.push_note("threat", "Threat detected") if ret: cv.imwrite("cache/image.jpg", frame) with open("cache/image.jpg", "rb") as pic: file_data = pb.upload_file(pic, "picture.jpg") push = pb.push_file(**file_data) else: error = pb.push_note("error", "Unable to send picture") else: clear = pb.push_note("np", "happy computing")
class RPiSurveillanceCamera: # Init class def __init__(self, configfile='config.json'): # Init config (load from JSON file) self.config = json.load(open(configfile)) # Init camera self.camera = picamera.PiCamera() self.setupCamera() # Init GPIO pis self.initGPIO() # Init more stuff self.pushbullet = Pushbullet(self.config["pushbullet"]["accessToken"]) self.outputDir = self.setOutputDirectory() # Setup camera def setupCamera(self): # Set resolution and framerate resolution = self.config["camera"]["resolution"] self.camera.resolution = (resolution["width"], resolution["height"]) self.camera.framerate = self.config["camera"]["framerate"] # Set tags (Artist & Copyright) - in case of the images/videos getting online self.camera.exif_tags['IFD0.Artist'] = "{}".format(self.config["user"]["name"]) self.camera.exif_tags['IFD0.Copyright'] = "© Copyright {} {}".format( time.strftime("%Y", time.localtime()), self.config["user"]["name"]) # Init GPIO pins def initGPIO(self): # Set pin mode GPIO.setmode(GPIO.BCM) # Define GPIO pins ledSwitch = self.config["gpio"]["ledSwitch"] ledStatus = self.config["gpio"]["ledStatus"] sensorPin = self.config["gpio"]["sensor"] switchPin = self.config["gpio"]["switch"] # Set GPIO IN/OUT GPIO.setup(ledSwitch, GPIO.OUT) GPIO.setup(ledStatus, GPIO.OUT) GPIO.setup(sensorPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.setup(switchPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Set output directory path def setOutputDirectory(self): # Set output directory path from config outputDir = self.config["camera"]["outputDirectory"] # Create dir if necessary if not os.path.exists(outputDir): os.makedirs(outputDir) print("Created image folder: {}".format(outputDir)) # Return directory path return outputDir # Taking a picture def makePicture(self): # Start camera preview self.camera.start_preview() # Set name for name (unique by time) fileName = 'picamera-shot-{}.jpg'.format(time.strftime("%y%m%d%H%M%S")) try: # Capture foto self.camera.capture(self.outputDir + fileName) # Log print("Picture: {}".format(self.outputDir + fileName)) finally: # Close camera and return image path self.camera.close() return self.outputDir + fileName # Push image via Pushbullet def pushImage(self, image): # Open image with open(image, "rb") as pic: # Upload file to Pushbullet server file_data = self.pushbullet.upload_file(pic, "sample_iPod.m4v") # Push file self.pushbullet.push_file(**file_data)
class PushBulletAPI(Thread): ''' api_key has to be get from https://www.pushbullet.com/#settings/account Note: in the __init_ one can specify the channel that wants the communication to go and all comunitcations will go directly to that channel: No need to specify in the queue_push_text and queue_push_file functions the channel ''' def __init__(self, api_key, channel_tag=None): Thread.__init__(self) self.pb = Pushbullet(api_key) self.text_queue = Queue() self.file_queue = Queue() self._mystop = False if channel_tag is not None: try: self.channel = self.get_channel(channel_tag) except: print("[ERROR] Could not load PushBullet channel: " + str(channel_tag)) self.channel = None else: self.channel = None def queue_push_text(self, body, title=socket.gethostname(), channel=None): if self.channel is not None and channel is None: channel = self.channel self.text_queue.put({"title": title, "body": body, "channel": channel}) def queue_push_file(self, filename, channel=None): if self.channel is not None and channel is None: channel = self.channel self.file_queue.put({"filename": filename, "channel": channel}) def _push_text(self, title, body, channel=None): if channel is None: return self.pb.push_note(title, body) else: return self.pb.push_note(title, body, channel=channel) def _push_link(self, title, body, channel=None): if channel is None: return self.pb.push_note(title, body) else: return self.pb.push_note(title, body, channel=channel) def _push_file(self, filename, channel=None): path, fn = os.path.split(filename) with open(filename, "rb") as pic: file_data = self.pb.upload_file(pic, fn) if channel is None: return self.pb.push_file(**file_data) else: return self.pb.push_file(**file_data, channel=channel) def get_all_channels(self): return self.pb.channels def get_channel(self, channel_name): return self.pb.get_channel(channel_name) def mystop(self): self._mystop = True def run(self): while not self._mystop or not self.text_queue.empty() or not self.file_queue.empty(): while not self.text_queue.empty(): item = self.text_queue.get() self._push_text(item["title"], item["body"], channel=item["channel"]) while not self.file_queue.empty(): item = self.file_queue.get() self._push_file(item["filename"], channel=item["channel"]) tm.sleep(1)
class NotificationHandler: def __init__(self, pushBulletAPIKey, didReceiveCommand): # Setup pushBullet manager self.pushBulletAPIKey = pushBulletAPIKey self.didReceiveCommand = didReceiveCommand self.pushBulletManager = Pushbullet(self.pushBulletAPIKey) thread = Thread(target=self.__createListener) thread.start() # Setup Notification Queue self.__setupNotificationQueue() def __createListener(self): self.listener = Listener(account=self.pushBulletManager, on_push=self.on_push, http_proxy_host=HTTP_PROXY_HOST, http_proxy_port=HTTP_PROXY_PORT) self.listener.run_forever() def __setupNotificationQueue(self): print("setupNotificationQueue") self.notificationQueue = Queue(maxsize=QUEUE_MAX_SIZE) for i in range(NUM_THREAD): worker = Thread(target=self.__motionNotify, args=()) worker.setDaemon(True) worker.start() def pushNotificationToMobile(self, filePath): self.notificationQueue.put(filePath) def pushToMobile(self, dataDictionary): print("pushToMobile: ", dataDictionary) self.notificationQueue.put(dataDictionary) def __motionNotify(self): print("__motionNotify called") while True: dataDictionary = self.notificationQueue.get() print("upload and notify: ", dataDictionary) if dataDictionary['type'] == "TEXT_MESSAGE": push = self.pushBulletManager.push_note( dataDictionary['text'], '') print("push result: ", push) elif dataDictionary['type'] == "IMAGE_MESSAGE": filePath = dataDictionary['filePath'] print("upload and push file: ", filePath) with open(filePath, "rb") as pic: fileData = self.pushBulletManager.upload_file( pic, dataDictionary['fileName']) push = self.pushBulletManager.push_file(**fileData) print("push result: ", push) if "iden" in push: os.remove(filePath) elif dataDictionary['type'] == "VIDEO_MESSAGE": push = self.pushBulletManager.push_note( "The motion is out. Video uploading...", '') filePath = dataDictionary['filePath'] print("upload and push file: ", filePath) with open(filePath, "rb") as pic: fileData = self.pushBulletManager.upload_file( pic, dataDictionary['fileName']) push = self.pushBulletManager.push_file(**fileData) print("push result: ", push) if "iden" in push: os.remove(filePath) else: print("Not support type: ", dataDictionary['Type']) self.notificationQueue.task_done() def __delete(self): self.listener.close() # to stop the run_forever() def on_push(self, jsonMessage): if jsonMessage["type"] == "tickle" and jsonMessage["subtype"] == "push": allPushes = self.pushBulletManager.get_pushes() latest = allPushes[0] if 'body' in latest: body = latest['body'] print(body) if body.startswith("@"): self.didReceiveCommand(body) # else: # print("latest pushes: ", latest) # else: # print("latest pushes: ", latest) def notifyWithImage(self, filePath): with open(filePath, "rb") as pic: file_data = self.pushBulletManager.upload_file(pic, "picture.jpg") push = self.pushBulletManager.push_file(**file_data) def notifyWithVideo(self, filePath): with open(filePath, "rb") as pic: file_data = self.pushBulletManager.upload_file(pic, "video.h264") push = self.pushBulletManager.push_file(**file_data)
except: print("Your API key is invalid") exit(1) if settings['command_started_title'].isspace(): if len(sys.argv) == 2: pb.push_note(settings['command_started_title'], 'Running command ' + sys.argv[1] + ' with no arguments') else: pb.push_note( settings['command_started_title'], 'Running command ' + sys.argv[1] + ' with arguments ' + str(sys.argv[2:])) task_output = open('out.txt', 'w') retcode = call(sys.argv[1:], stdout=task_output) task_output.close() with open('out.txt', 'rb') as f: filename = 'out_' + datetime.datetime.fromtimestamp( time.time()).strftime('%Y_%m_%d_%H%M%S') + '.txt' task_output_data = pb.upload_file(f, filename) os.remove('out.txt') if retcode == 0: pb.push_file(**task_output_data, title=settings['command_done_title']) else: pb.push_file(**task_output_data, title=settings['command_error_title'], body='Command failed with errorcode: ' + str(retcode) + '. Output to follow')
def download(link, newdevice, video, delete, send): """Download a youtube video or playlist in best audio and video quality by providing a link, and then send to the preferred device, or override it with `--newdevice` option. Provide the device name for `--newdevice` in quotes for e.g. "OnePlus One". Please run `moboff initialise` if this is your first time. """ os.chdir(real_path_of_MobOff) if os.path.exists('moboff_cfg.json'): with open('moboff_cfg.json') as json_file: data = json.load(json_file) api_key = data['user']['api_key'] device = data['user']['device'] directory = data['user']['directory'] else: click.secho("Please run `moboff initialise` first.", fg='red', bold=True) quit() try: pb = Pushbullet(api_key) except pushbullet.errors.InvalidKeyError: click.secho( "API key you previously entered is no longer valid. Please rerun moboff initialise." ) quit() phone = device if newdevice: click.secho( "Overriding preferred device : {0} with given device : {1}".format( device, newdevice)) phone = newdevice try: to_device = pb.get_device(phone) except pushbullet.errors.PushbulletError: if newdevice: click.secho( "{0} isn't setup with Pushbullet. " "Please either set it up or check the spelling of entered device" .format(newdevice)) else: click.secho( "The default device you entered initially doesn't exist anymore. " "Please rerun moboff initialise.") quit() try: os.chdir(directory) except OSError: click.secho( "The directory previously selected to download music can't be accessed." " Please rerun moboff initialise.") quit() os.mkdir("{0}/temp".format(directory)) os.chdir("{0}/temp".format(directory)) print("This may take a while.") if video is True: downloadcommand = [ "youtube-dl", "--metadata-from-title", "%(artist)s - %(title)s", "-f", "bestvideo+bestaudio", "--add-metadata", "--output", "%(artist)s - %(title)s.%(ext)s", link ] else: downloadcommand = [ "youtube-dl", "--metadata-from-title", "%(artist)s - %(title)s", "--extract-audio", "--audio-format", "mp3", "--audio-quality", "0", "--add-metadata", "--output", "%(artist)s - %(title)s.%(ext)s", link ] try: subprocess.check_output(downloadcommand, stderr=subprocess.STDOUT) except subprocess.CalledProcessError: print( "Please check your URL, it shouldn't be a private playlist link (eg liked videos)" ) quit() click.secho("File successfully downloaded.", fg="green", bold=True) types = ('*.mp3', '*.mp4', '*.mkv') list_of_files = [] for files in types: list_of_files.extend(glob.glob(files)) for file in list_of_files: print("File to send : {0}".format(file)) with open(file, "rb") as song: file_data = pb.upload_file(song, file) to_device.push_file(**file_data) print("The file has been sent to your {0}.".format(to_device)) if send: for i, device in enumerate(pb.chats, 1): print("{0} : {1}".format(i, device)) index = int( rawinput( "Enter the corresponding chat no. for the person you want to send the file to. " )) try: chat = pb.chats[index - 1] for file in list_of_files: print("File to send : {0}".format(file)) with open(file, "rb") as song: file_data = pb.upload_file(song, file) pb.push_file(**file_data, chat=chat) except: print("Contact does not exist.") else: print("The file has been sent to ", chat) for file in list_of_files: if file.endswith((".mp3", "mp4", ".mkv")): os.rename("{0}/temp/{1}".format(directory, file), "{0}/{1}".format(directory, file)) os.rmdir("{0}/temp".format(directory)) os.chdir(directory) if delete: for file in list_of_files: os.remove(file)
class SnapshotPipeline(Pipeline): def __init__(self): super(SnapshotPipeline, self).__init__('snap_pipe') self.file_source = "" self.pb = Pushbullet('o.cJzinoZ3SdlW7JxYeDm7tbIrueQAW5aK') self.create_snapshot() bus = self.pipe.get_bus() bus.add_signal_watch() bus.connect('message', self.on_message_cb, None) def create_snapshot(self): self.appsrc = Gst.ElementFactory.make('appsrc', 'snapsrc') self.pipe.add(self.appsrc) jpegenc = Gst.ElementFactory.make('jpegenc', 'jpegenc') self.pipe.add(jpegenc) self.filesink = Gst.ElementFactory.make('filesink', 'jpegfilesink') self.pipe.add(self.filesink) self.appsrc.link(jpegenc) jpegenc.link(self.filesink) def send_snapshot(self): dtime = Gst.DateTime.new_now_local_time() g_datetime = dtime.to_g_date_time() timestamp = g_datetime.format("%F_%H%M%S") timestamp = timestamp.replace("-", "") filename = "sshot_" + timestamp + ".jpg" self.file_source = filename print("Filename : %s" % filename) self.filesink.set_property('location', filename) self.filesink.set_property('async', False) self.pipe.set_state(Gst.State.PLAYING) def on_message_cb(self, bus, msg, data): t = msg.type if t == Gst.MessageType.ERROR: name = msg.src.get_path_string() err, debug = msg.parse_error() print( "Snapshot pipeline -> Error received : from element %s : %s ." % (name, err.message)) if debug is not None: print("Additional debug info:\n%s" % debug) self.pipe.set_state(Gst.State.NULL) self.file_source = "" elif t == Gst.MessageType.WARNING: name = msg.src.get_path_string() err, debug = msg.parse_warning() print( "Snapshot pipeline -> Warning received : from element %s : %s ." % (name, err.message)) if debug is not None: print("Additional debug info:\n%s" % debug) elif t == Gst.MessageType.EOS: print("Snapshot End-Of-Stream received") print(datetime.now()) print("") self.pipe.set_state(Gst.State.NULL) if self.file_source != "": with open(self.file_source, 'rb') as pic: file_data = self.pb.upload_file(pic, self.file_source) for key in file_data.keys(): print("%s in File data of value : %s" % (key, file_data[key])) push = self.pb.push_file(title="Motion detected", **file_data) print(push) self.file_source = ""
from pushbullet import Pushbullet import urllib.request, os, time pb = Pushbullet("o.58Bh78AJCNGw2RCt8uWD061qxTD7cERZ") with open("/tmp/lastsnap_motion.jpg", "rb") as pic: file_data = pb.upload_file(pic, "Intrusion Last Picture") push = pb.push_file(**file_data)
class PushbulletSkill(MycroftSkill): """ A Skill to send message using Pushbullet """ def __init__(self): super(PushbulletSkill, self).__init__(name="PushbulletSkill") self.audio_effects = "/opt/mycroft/skills/PushbulletSkill/" self.enable_fallback = False self._setup() try: self.settings.set_changed_callback(self._force_setup) except BaseException: LOGGER.debug( 'No auto-update on changed settings (Outdated version)') try: self.settings.set_changed_callback(self._force_setup) except BaseException: LOGGER.debug( 'No auto-update on changed settings (Outdated version)') def _setup(self, force=False): if self.settings is not None: self.api_key = self.settings.get('api_key') self.photo_script = "/opt/mycroft/skills/PushbulletSkill/script/photo.py" self.photo_img = "/tmp/photo.png" self.help_audio = "/tmp/help" """ Register Mycroft device to Pushbullet """ self.pb = Pushbullet(self.api_key) """ Get the contacts list from Pushbullet Mycroft device registered """ self.contactspb = self.pb.chats self.devicespb = self.pb.devices self.contacts={} for i in range(len(self.contactspb)): row_contact = str(self.contactspb[i]) name = row_contact.split("'",1)[1].split("'")[0] name = name.replace(" ","").lower() email = row_contact.split("<",1)[1].split(">")[0] self.contacts[name] = self.contactspb[i] self.devices={} for i in range(len(self.devicespb)): row_device = str(self.devicespb[i]) name = row_device.split("'",1)[1].split("'")[0] name = name.replace(" ","").lower() self.devices[name] = self.devicespb[i] def initialize(self): self.load_data_files(dirname(__file__)) self.load_regex_files(join(dirname(__file__), 'regex', self.lang)) intent = IntentBuilder("PushMessageIntent")\ .require("PushMessageKeyword")\ .require("Contact")\ .require("Message")\ .build() self.register_intent(intent, self.handle_pushmessage) intent = IntentBuilder("PushMeMessageIntent")\ .require("PushMessageKeyword")\ .require("MeKeyword")\ .require("SelfMessage")\ .build() self.register_intent(intent, self.handle_push_me_message) intent = IntentBuilder("PushPhotoIntent")\ .require("PushPhotoKeyword")\ .build() self.register_intent(intent, self.handle_pushphoto) intent = IntentBuilder("PushHelpIntent")\ .require("PushHelpKeyword")\ .build() self.register_intent(intent, self.handle_help) def handle_pushmessage(self, message): try: contact = message.data.get("Contact").lower() if contact in self.contacts: """ Evaluate a exact contact to send message using Pushbullet """ chat = self.contacts.get(contact) msg = message.data.get("Message") push = self.pb.push_note("Message from Mycroft",msg, chat=chat) data = {"contact": contact} self.speak_dialog("push.message",data) elif contact in self.devices: """ Evaluate a exact device to send message using Pushbullet """ device = self.devices.get(contact) msg = message.data.get("Message") push = self.pb.push_note("Message from Mycroft",msg, device=device) data = {"contact": contact} self.speak_dialog("push.device",data) else: """ Evaluate a similar contact to send message using Pushbullet """ matching_contact = [s for s in self.contacts if contact in s] matching_device = [d for d in self.devices if contact in d] matching_contact = str(matching_contact) matching_device = str(matching_device) if len(matching_contact) > 2: name_match = matching_contact.split("'",1)[1].split("'")[0] chat = self.contacts.get(name_match) msg = message.data.get("Message") push = self.pb.push_note("Message from Mycroft",msg, chat=chat) data = {"contact": name_match} self.speak_dialog("push.message",data) elif len(matching_device) > 2: name_match = matching_device.split("'",1)[1].split("'")[0] device = self.devices.get(name_match) msg = message.data.get("Message") full_name = str(device).split("'") full_name = full_name[1] push = self.pb.push_note("Message from Mycroft",msg, device=device) data = {"contact": full_name} self.speak_dialog("push.device",data) except Exception as e: data = {"contact": contact} self.speak_dialog("processing.pushmessage",data) def handle_push_me_message(self, message): msg = message.data.get("SelfMessage") push = self.pb.push_note("Message from Mycroft",msg) self.speak_dialog("push.self.message") def handle_pushphoto(self, message): """ Run photo_cmd (photo.py) outside Mycroft Virtual Environment """ photo_cmd = "/usr/bin/python2.7 " + self.photo_script os.system(photo_cmd) time.sleep(1) with open(self.photo_img,"rb") as png: file_data = self.pb.upload_file(png, "photo.png") #chat = self.chat push = self.pb.push_file(**file_data) def handle_help(self, message): """ Record 10 seconds to help_audio_file.mp3 file """ self.speak_dialog("push.help") time.sleep(7) p = play_wav(self.audio_effects+"ding.wav") p.communicate() r = record(self.help_audio+".wav",10,16000,1) r.communicate() p = play_wav(self.audio_effects+"dong.wav") p.communicate() with open(self.help_audio+".wav","rb") as mp3: file_data = self.pb.upload_file(mp3, "help_audio_file.wav") chat = self.pb.devices push = self.pb.push_file(**file_data) self.speak_dialog("push.help.send") def stop(self): pass
def kill_motion(): """Ensure the motion process is not active (blue webcam light off).""" if process_running('motion'): print('Stopping motion') return subprocess.check_output('sudo killall motion'.split()).decode('utf-8') while (True): if (not is_erics_iphone_in_home_network()): ensure_motion_is_running() for jpg in glob.glob(os.path.join(motion_dir, '*.jpg')): # TODO: log instead with open(jpg, 'rb') as pic: # TODO: only push if cell phone not in house wifi file_data = pb.upload_file(pic, name(pic)) push = pb.push_file(**file_data) # TODO: try-catch with logging os.remove(jpg) # Clean up motion_dir: discard swfs for room for swf in glob.glob(os.path.join(motion_dir, '*.swf')): os.remove(swf) else: kill_motion() for file in glob.glob(os.path.join(motion_dir, '*')): os.remove(file) # TODO: log instead print('Eric is home -- sleeping') time.sleep(30)
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: tabstop=4 shiftwidth=4 softtabstop=4 from pushbullet import Pushbullet import sys import time import ConfigParser import subprocess if __name__ == '__main__': config = ConfigParser.ConfigParser() config.read('chicken_door.cfg') api_key = config.get('pushbullet', 'api_key') pb = Pushbullet(api_key) try: cmd = "v4l2grab -d /dev/video0 -o /tmp/coop_door.jpg" subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) time.sleep(1) with open("/tmp/coop_door.jpg", "rb") as pic: file_data = pb.upload_file(pic, "coop_door.jpg") push = pb.push_file(**file_data) except: print "BOOM:", sys.exc_info()
class Plane: import configparser main_config = configparser.ConfigParser() main_config.read('./configs/mainconf.ini') def __init__(self, icao, config_path, config): """Initializes a plane object from its config file and given icao.""" self.icao = icao.upper() self.callsign = None self.reg = None self.config = config self.conf_file_path = config_path self.alt_ft = None self.below_desired_ft = None self.last_below_desired_ft = None self.feeding = None self.last_feeding = None self.last_on_ground = None self.on_ground = None self.longitude = None self.latitude = None self.takeoff_time = None import tempfile self.map_file_name = f"{tempfile.gettempdir()}/{icao.upper()}_map.png" self.last_latitude = None self.last_longitude = None self.last_pos_datetime = None self.landing_plausible = False self.nav_modes = None self.last_nav_modes = None self.speed = None self.recent_ra_types = {} self.db_flags = None self.sel_nav_alt = None self.last_sel_alt = None self.squawk = None self.emergency_already_triggered = None self.last_emergency = None self.recheck_route_time = None self.known_to_airport = None self.track = None self.last_track = None self.circle_history = None if self.config.has_option('DATA', 'DATA_LOSS_MINS'): self.data_loss_mins = self.config.getint('DATA', 'DATA_LOSS_MINS') else: self.data_loss_mins = Plane.main_config.getint('DATA', 'DATA_LOSS_MINS') #Setup Tweepy if self.config.getboolean('TWITTER', 'ENABLE'): from defTweet import tweepysetup self.tweet_api = tweepysetup(self.config) #Setup PushBullet if self.config.getboolean('PUSHBULLET', 'ENABLE'): from pushbullet import Pushbullet self.pb = Pushbullet(self.config['PUSHBULLET']['API_KEY']) self.pb_channel = self.pb.get_channel(self.config.get('PUSHBULLET', 'CHANNEL_TAG')) def run_opens(self, ac_dict): #Parse OpenSky Vector from colorama import Fore, Back, Style self.printheader("head") #print (Fore.YELLOW + "OpenSky Sourced Data: ", ac_dict) try: self.__dict__.update({'icao' : ac_dict.icao24.upper(), 'callsign' : ac_dict.callsign, 'latitude' : ac_dict.latitude, 'longitude' : ac_dict.longitude, 'on_ground' : bool(ac_dict.on_ground), 'squawk' : ac_dict.squawk, 'track' : float(ac_dict.heading)}) if ac_dict.baro_altitude != None: self.alt_ft = round(float(ac_dict.baro_altitude) * 3.281) elif self.on_ground: self.alt_ft = 0 from mictronics_parse import get_aircraft_reg_by_icao, get_type_code_by_icao self.reg = get_aircraft_reg_by_icao(self.icao) self.type = get_type_code_by_icao(self.icao) self.last_pos_datetime = datetime.fromtimestamp(ac_dict.time_position) except ValueError as e: print("Got data but some data is invalid!") print(e) self.printheader("foot") else: self.feeding = True self.run_check() def run_adsbx_v1(self, ac_dict): #Parse ADBSX V1 Vector from colorama import Fore, Back, Style self.printheader("head") #print (Fore.YELLOW +"ADSBX Sourced Data: ", ac_dict, Style.RESET_ALL) try: #postime is divided by 1000 to get seconds from milliseconds, from timestamp expects secs. self.__dict__.update({'icao' : ac_dict['icao'].upper(), 'callsign' : ac_dict['call'], 'reg' : ac_dict['reg'], 'latitude' : float(ac_dict['lat']), 'longitude' : float(ac_dict['lon']), 'alt_ft' : int(ac_dict['alt']), 'on_ground' : bool(int(ac_dict["gnd"])), 'squawk' : ac_dict['sqk'], 'track' : float(ac_dict["trak"])}) if self.on_ground: self.alt_ft = 0 self.last_pos_datetime = datetime.fromtimestamp(int(ac_dict['postime'])/1000) except ValueError as e: print("Got data but some data is invalid!") print(e) print (Fore.YELLOW +"ADSBX Sourced Data: ", ac_dict, Style.RESET_ALL) self.printheader("foot") else: self.feeding = True self.run_check() def run_adsbx_v2(self, ac_dict): #Parse ADBSX V2 Vector from colorama import Fore, Back, Style self.printheader("head") print(ac_dict) try: self.__dict__.update({'icao' : ac_dict['hex'].upper(), 'latitude' : float(ac_dict['lat']), 'longitude' : float(ac_dict['lon']), 'speed': ac_dict['gs']}) if "r" in ac_dict: self.reg = ac_dict['r'] if "t" in ac_dict: self.type = ac_dict['t'] if ac_dict['alt_baro'] != "ground": self.alt_ft = int(ac_dict['alt_baro']) self.on_ground = False elif ac_dict['alt_baro'] == "ground": self.alt_ft = 0 self.on_ground = True if ac_dict.get('flight') is not None: self.callsign = ac_dict.get('flight').strip() if ac_dict.get('dbFlags') is not None: self.db_flags = ac_dict['dbFlags'] if 'nav_modes' in ac_dict: self.nav_modes = ac_dict['nav_modes'] for idx, mode in enumerate(self.nav_modes): if mode.upper() in ['TCAS', 'LNAV', 'VNAV']: self.nav_modes[idx] = self.nav_modes[idx].upper() else: self.nav_modes[idx] = self.nav_modes[idx].capitalize() self.squawk = ac_dict.get('squawk') if "track" in ac_dict: self.track = ac_dict['track'] if "nav_altitude_fms" in ac_dict: self.sel_nav_alt = ac_dict['nav_altitude_fms'] elif "nav_altitude_mcp" in ac_dict: self.sel_nav_alt = ac_dict['nav_altitude_mcp'] else: self.sel_nav_alt = None #Create last seen timestamp from how long ago in secs a pos was rec self.last_pos_datetime = datetime.now() - timedelta(seconds= ac_dict["seen_pos"]) except (ValueError, KeyError) as e: print("Got data but some data is invalid!") print(e) print (Fore.YELLOW +"ADSBX Sourced Data: ", ac_dict, Style.RESET_ALL) self.printheader("foot") else: #Error Handling for bad data, sometimes it would seem to be ADSB Decode error if (not self.on_ground) and self.speed <= 10: print("Not running check, appears to be bad ADSB Decode") else: self.feeding = True self.run_check() def __str__(self): from colorama import Fore, Back, Style from tabulate import tabulate if self.last_pos_datetime is not None: time_since_contact = self.get_time_since(self.last_pos_datetime) output = [ [(Fore.CYAN + "ICAO" + Style.RESET_ALL), (Fore.LIGHTGREEN_EX + self.icao + Style.RESET_ALL)], [(Fore.CYAN + "Callsign" + Style.RESET_ALL), (Fore.LIGHTGREEN_EX + self.callsign + Style.RESET_ALL)] if self.callsign is not None else None, [(Fore.CYAN + "Reg" + Style.RESET_ALL), (Fore.LIGHTGREEN_EX + self.reg + Style.RESET_ALL)] if self.reg is not None else None, [(Fore.CYAN + "Squawk" + Style.RESET_ALL), (Fore.LIGHTGREEN_EX + self.squawk + Style.RESET_ALL)] if self.squawk is not None else None, [(Fore.CYAN + "Coordinates" + Style.RESET_ALL), (Fore.LIGHTGREEN_EX + str(self.latitude) + ", " + str(self.longitude) + Style.RESET_ALL)] if self.latitude is not None and self.longitude is not None else None, [(Fore.CYAN + "Last Contact" + Style.RESET_ALL), (Fore.LIGHTGREEN_EX + str(time_since_contact).split(".")[0]+ Style.RESET_ALL)] if self.last_pos_datetime is not None else None, [(Fore.CYAN + "On Ground" + Style.RESET_ALL), (Fore.LIGHTGREEN_EX + str(self.on_ground) + Style.RESET_ALL)] if self.on_ground is not None else None, [(Fore.CYAN + "Baro Altitude" + Style.RESET_ALL), (Fore.LIGHTGREEN_EX + str("{:,} ft".format(self.alt_ft)) + Style.RESET_ALL)] if self.alt_ft is not None else None, [(Fore.CYAN + "Nav Modes" + Style.RESET_ALL), (Fore.LIGHTGREEN_EX + ', '.join(self.nav_modes) + Style.RESET_ALL)] if "nav_modes" in self.__dict__ and self.nav_modes != None else None, [(Fore.CYAN + "Sel Alt Ft" + Style.RESET_ALL), (Fore.LIGHTGREEN_EX + str("{:,} ft".format(self.sel_nav_alt)) + Style.RESET_ALL)] if "sel_nav_alt" in self.__dict__ and self.sel_nav_alt is not None else None ] output = list(filter(None, output)) return tabulate(output, [], 'fancy_grid') def printheader(self, type): from colorama import Fore, Back, Style if type == "head": header = str("--------- " + self.conf_file_path + " ---------------------------- ICAO: " + self.icao + " ---------------------------------------") elif type == "foot": header = "----------------------------------------------------------------------------------------------------" print(Back.MAGENTA + header[0:100] + Style.RESET_ALL) def get_time_since(self, datetime_obj): if datetime_obj != None: time_since = datetime.now() - datetime_obj else: time_since = None return time_since def get_adsbx_map_overlays(self): if self.config.has_option('MAP', 'OVERLAYS'): overlays = self.config.get('MAP', 'OVERLAYS') else: overlays = "" return overlays def route_info(self): from lookup_route import lookup_route, clean_data def route_format(extra_route_info, type): from defAirport import get_airport_by_icao to_airport = get_airport_by_icao(self.known_to_airport) code = to_airport['iata_code'] if to_airport['iata_code'] != "" else to_airport['icao'] airport_text = f"{code}, {to_airport['name']}" if 'time_to' in extra_route_info.keys() and type != "divert": arrival_rel = "in ~" + extra_route_info['time_to'] else: arrival_rel = None if self.known_to_airport != self.nearest_from_airport: if type == "inital": header = "Going to" elif type == "change": header = "Now going to" elif type == "divert": header = "Now diverting to" area = f"{to_airport['municipality']}, {to_airport['region']}, {to_airport['iso_country']}" route_to = f"{header} {area} ({airport_text})" + (f" arriving {arrival_rel}" if arrival_rel is not None else "") else: if type == "inital": header = "Will be returning to" elif type == "change": header = "Now returning to" elif type == "divert": header = "Now diverting back to" route_to = f"{header} {airport_text}" + (f" {arrival_rel}" if arrival_rel is not None else "") return route_to if hasattr(self, "type"): extra_route_info = clean_data(lookup_route(self.reg, (self.latitude, self.longitude), self.type, self.alt_ft)) else: extra_route_info = None route_to = None if extra_route_info is None: pass elif extra_route_info is not None: #Diversion if "divert_icao" in extra_route_info.keys(): if self.known_to_airport != extra_route_info["divert_icao"]: self.known_to_airport = extra_route_info['divert_icao'] route_to = route_format(extra_route_info, "divert") #Destination elif "dest_icao" in extra_route_info.keys(): #Inital Destination Found if self.known_to_airport is None: self.known_to_airport = extra_route_info['dest_icao'] route_to = route_format(extra_route_info, "inital") #Destination Change elif self.known_to_airport != extra_route_info["dest_icao"]: self.known_to_airport = extra_route_info['dest_icao'] route_to = route_format(extra_route_info, "change") return route_to def run_empty(self): self.printheader("head") self.feeding = False self.run_check() def run_check(self): """Runs a check of a plane module to see if its landed or takenoff using plane data, and takes action if so.""" print(self) #Ability to Remove old Map import os from colorama import Fore, Style from tabulate import tabulate #Proprietary Route Lookup if os.path.isfile("lookup_route.py") and (self.db_flags is None or not self.db_flags & 1): from lookup_route import lookup_route ENABLE_ROUTE_LOOKUP = True else: ENABLE_ROUTE_LOOKUP = False if self.config.getboolean('DISCORD', 'ENABLE'): from defDiscord import sendDis if self.last_pos_datetime is not None: time_since_contact = self.get_time_since(self.last_pos_datetime) #Check if below desire ft desired_ft = 15000 if self.alt_ft is None or self.alt_ft > desired_ft: self.below_desired_ft = False elif self.alt_ft < desired_ft: self.below_desired_ft = True #Check if tookoff if self.below_desired_ft and self.on_ground is False: if self.last_on_ground: self.tookoff = True trigger_type = "no longer on ground" type_header = "Took off from" elif self.last_feeding is False and self.feeding and self.landing_plausible == False: from defAirport import getClosestAirport nearest_airport_dict = getClosestAirport(self.latitude, self.longitude, self.config.get("AIRPORT", "TYPES")) if nearest_airport_dict['elevation_ft'] != "": alt_above_airport = (self.alt_ft - int(nearest_airport_dict['elevation_ft'])) print(f"AGL nearest airport: {alt_above_airport}") else: alt_above_airport = None if (alt_above_airport != None and alt_above_airport <= 10000) or self.alt_ft <= 15000: self.tookoff = True trigger_type = "data acquisition" type_header = "Took off near" else: self.tookoff = False else: self.tookoff = False #Check if Landed if self.on_ground and self.last_on_ground is False and self.last_below_desired_ft: self.landed = True trigger_type = "now on ground" type_header = "Landed in" self.landing_plausible = False #Set status for landing plausible elif self.below_desired_ft and self.last_feeding and self.feeding is False and self.last_on_ground is False: self.landing_plausible = True print("Near landing conditions, if contiuned data loss for configured time, and if under 10k AGL landing true") elif self.landing_plausible and self.feeding is False and time_since_contact.total_seconds() >= (self.data_loss_mins * 60): from defAirport import getClosestAirport nearest_airport_dict = getClosestAirport(self.latitude, self.longitude, self.config.get("AIRPORT", "TYPES")) if nearest_airport_dict['elevation_ft'] != "": alt_above_airport = (self.alt_ft - int(nearest_airport_dict['elevation_ft'])) print(f"AGL nearest airport: {alt_above_airport}") else: alt_above_airport = None if (alt_above_airport != None and alt_above_airport <= 10000) or self.alt_ft <= 15000: self.landing_plausible = False self.on_ground = None self.landed = True trigger_type = "data loss" type_header = "Landed near" else: print("Alt greater then 10k AGL") self.landing_plausible = False self.on_ground = None else: self.landed = False if self.landed: print ("Landed by", trigger_type) if self.tookoff: print("Tookoff by", trigger_type) #Find nearest airport, and location if self.landed or self.tookoff: from defAirport import getClosestAirport if "nearest_airport_dict" in globals(): pass #Airport already set elif trigger_type in ["now on ground", "data acquisition", "data loss"]: nearest_airport_dict = getClosestAirport(self.latitude, self.longitude, self.config.get("AIRPORT", "TYPES")) elif trigger_type == "no longer on ground": nearest_airport_dict = getClosestAirport(self.last_latitude, self.last_longitude, self.config.get("AIRPORT", "TYPES")) #Convert dictionary keys to sep variables country_code = nearest_airport_dict['iso_country'] state = nearest_airport_dict['region'].strip() municipality = nearest_airport_dict['municipality'].strip() if municipality == "" or state == "" or municipality == state: if municipality != "": area = municipality elif state != "": area = state else: area = "" else: area = f"{municipality}, {state}" location_string = (f"{area}, {country_code}") print (Fore.GREEN + "Country Code:", country_code, "State:", state, "Municipality:", municipality + Style.RESET_ALL) title_switch = { "reg": self.reg, "callsign": self.callsign, "icao": self.icao, } #Set Discord Title if self.config.getboolean('DISCORD', 'ENABLE'): self.dis_title = (title_switch.get(self.config.get('DISCORD', 'TITLE')) or "NA").strip() if self.config.get('DISCORD', 'TITLE') in title_switch.keys() else self.config.get('DISCORD', 'TITLE') #Set Twitter Title if self.config.getboolean('TWITTER', 'ENABLE'): self.twitter_title = (title_switch.get(self.config.get('TWITTER', 'TITLE')) or "NA") if self.config.get('TWITTER', 'TITLE') in title_switch.keys() else self.config.get('TWITTER', 'TITLE') #Takeoff and Land Notification if self.tookoff or self.landed: route_to = None if self.tookoff: self.takeoff_time = datetime.utcnow() landed_time_msg = None #Proprietary Route Lookup if ENABLE_ROUTE_LOOKUP: self.nearest_from_airport = nearest_airport_dict['icao'] route_to = self.route_info() if route_to is None: self.recheck_route_time = 1 else: self.recheck_route_time = 10 elif self.landed and self.takeoff_time != None: landed_time = datetime.utcnow() - self.takeoff_time if trigger_type == "data loss": landed_time -= timedelta(seconds=time_since_contact.total_seconds()) hours, remainder = divmod(landed_time.total_seconds(), 3600) minutes, seconds = divmod(remainder, 60) min_syntax = "Mins" if minutes > 1 else "Min" if hours > 0: hour_syntax = "Hours" if hours > 1 else "Hour" landed_time_msg = (f"Apx. flt. time {int(hours)} {hour_syntax}" + (f" : {int(minutes)} {min_syntax}. " if minutes > 0 else ".")) else: landed_time_msg = (f"Apx. flt. time {int(minutes)} {min_syntax}.") self.takeoff_time = None elif self.landed: landed_time_msg = None message = (f"{type_header} {location_string}.") + ("" if route_to is None else f" {route_to}.") + ((f" {landed_time_msg}") if landed_time_msg != None else "") print (message) #Google Map or tar1090 screenshot if self.config.get('MAP', 'OPTION') == "GOOGLESTATICMAP": from defMap import getMap getMap((municipality + ", " + state + ", " + country_code), self.map_file_name) elif self.config.get('MAP', 'OPTION') == "ADSBX": from defSS import get_adsbx_screenshot url_params = f"icao={self.icao}&zoom=9&largeMode=2&hideButtons&hideSidebar&mapDim=0&overlays=" + self.get_adsbx_map_overlays() get_adsbx_screenshot(self.map_file_name, url_params) from modify_image import append_airport append_airport(self.map_file_name, nearest_airport_dict) else: raise ValueError("Map option not set correctly in this planes conf") #Discord if self.config.getboolean('DISCORD', 'ENABLE'): dis_message = f"{self.dis_title} {message}".strip() role_id = self.config.get('DISCORD', 'ROLE_ID') if self.config.has_option('DISCORD', 'ROLE_ID') else None sendDis(dis_message, self.config, self.map_file_name, role_id = role_id) #PushBullet if self.config.getboolean('PUSHBULLET', 'ENABLE'): with open(self.map_file_name, "rb") as pic: map_data = self.pb.upload_file(pic, "Tookoff IMG" if self.tookoff else "Landed IMG") self.pb_channel.push_note(self.config.get('PUSHBULLET', 'TITLE'), message) self.pb_channel.push_file(**map_data) #Twitter if self.config.getboolean('TWITTER', 'ENABLE'): twitter_media_map_obj = self.tweet_api.media_upload(self.map_file_name) alt_text = f"Reg: {self.reg} On Ground: {str(self.on_ground)} Alt: {str(self.alt_ft)} Last Contact: {str(time_since_contact)} Trigger: {trigger_type}" self.tweet_api.create_media_metadata(media_id= twitter_media_map_obj.media_id, alt_text= alt_text) self.latest_tweet_id = self.tweet_api.update_status(status = ((self.twitter_title + " " + message).strip()), media_ids=[twitter_media_map_obj.media_id]).id os.remove(self.map_file_name) if self.landed: self.latest_tweet_id = None self.recheck_route_time = None self.known_to_airport = None self.nearest_from_airport = None #Recheck Proprietary Route Info. if self.takeoff_time is not None and self.recheck_route_time is not None and (datetime.utcnow() - self.takeoff_time).total_seconds() > 60 * self.recheck_route_time: self.recheck_route_time += 10 route_to = self.route_info() if route_to != None: print(route_to) #Discord if self.config.getboolean('DISCORD', 'ENABLE'): dis_message = f"{self.dis_title} {route_to}".strip() role_id = self.config.get('DISCORD', 'ROLE_ID') if self.config.has_option('DISCORD', 'ROLE_ID') else None sendDis(dis_message, self.config, role_id = role_id) #Twitter if self.config.getboolean('TWITTER', 'ENABLE'): #tweet = self.tweet_api.user_timeline(count = 1)[0] self.latest_tweet_id = self.tweet_api.update_status(status = f"{self.twitter_title} {route_to}".strip(), in_reply_to_status_id = self.latest_tweet_id).id if self.circle_history is not None: #Expires traces for circles if self.circle_history["traces"] != []: for trace in self.circle_history["traces"]: if (datetime.now() - datetime.fromtimestamp(trace[0])).total_seconds() >= 20*60: print("Trace Expire, removed") self.circle_history["traces"].remove(trace) #Expire touchngo if "touchngo" in self.circle_history.keys() and (datetime.now() - datetime.fromtimestamp(self.circle_history['touchngo'])).total_seconds() >= 10*60: self.circle_history.pop("touchngo") if self.feeding: #Squawks emergency_squawks ={"7500" : "Hijacking", "7600" :"Radio Failure", "7700" : "General Emergency"} seen = datetime.now() - self.last_pos_datetime #Only run check if emergency data previously set if self.last_emergency is not None and not self.emergency_already_triggered: time_since_org_emer = datetime.now() - self.last_emergency[0] #Checks times to see x time and still same squawk if time_since_org_emer.total_seconds() >= 60 and self.last_emergency[1] == self.squawk and seen.total_seconds() <= 60: self.emergency_already_triggered = True squawk_message = (f"{self.dis_title} Squawking {self.last_emergency[1]} {emergency_squawks[self.squawk]}").strip() print(squawk_message) #Google Map or tar1090 screenshot if self.config.get('MAP', 'OPTION') == "GOOGLESTATICMAP": getMap((municipality + ", " + state + ", " + country_code), self.map_file_name) if self.config.get('MAP', 'OPTION') == "ADSBX": from defSS import get_adsbx_screenshot url_params = f"icao={self.icao}&zoom=9&largeMode=2&hideButtons&hideSidebar&mapDim=0&overlays=" + self.get_adsbx_map_overlays() get_adsbx_screenshot(self.map_file_name, url_params) if self.config.getboolean('DISCORD', 'ENABLE'): dis_message = (self.dis_title + " " + squawk_message) sendDis(dis_message, self.config, self.map_file_name) os.remove(self.map_file_name) #Realizes first time seeing emergency, stores time and type elif self.squawk in emergency_squawks.keys() and not self.emergency_already_triggered and not self.on_ground: print("Emergency", self.squawk, "detected storing code and time and waiting to trigger") self.last_emergency = (self.last_pos_datetime, self.squawk) elif self.squawk not in emergency_squawks.keys() and self.emergency_already_triggered: self.emergency_already_triggered = None #Nav Modes Notifications if self.nav_modes != None and self.last_nav_modes != None: for mode in self.nav_modes: if mode not in self.last_nav_modes: #Discord print(mode, "enabled") if self.config.getboolean('DISCORD', 'ENABLE'): dis_message = (self.dis_title + " " + mode + " mode enabled.") if mode == "Approach": from defSS import get_adsbx_screenshot url_params = f"icao={self.icao}&zoom=9&largeMode=2&hideButtons&hideSidebar&mapDim=0&overlays={self.get_adsbx_map_overlays()}" get_adsbx_screenshot(self.map_file_name, url_params) sendDis(dis_message, self.config, self.map_file_name) #elif mode in ["Althold", "VNAV", "LNAV"] and self.sel_nav_alt != None: # sendDis((dis_message + ", Sel Alt. " + str(self.sel_nav_alt) + ", Current Alt. " + str(self.alt_ft)), self.config) else: sendDis(dis_message, self.config) #Selected Altitude if self.sel_nav_alt is not None and self.last_sel_alt is not None and self.last_sel_alt != self.sel_nav_alt: #Discord print("Nav altitude is now", self.sel_nav_alt) if self.config.getboolean('DISCORD', 'ENABLE'): dis_message = (self.dis_title + " Sel. alt. " + str("{:,} ft".format(self.sel_nav_alt))) sendDis(dis_message,self.config) #Circling if self.last_track is not None: import time if self.circle_history is None: self.circle_history = {"traces" : [], "triggered" : False} #Add touchngo if self.on_ground or self.alt_ft <= 500: self.circle_history["touchngo"] = time.time() #Add a Trace if self.on_ground is False: from calculate_headings import calculate_deg_change track_change = calculate_deg_change(self.track, self.last_track) track_change = round(track_change, 3) self.circle_history["traces"].append((time.time(), self.latitude, self.longitude, track_change)) total_change = 0 coords = [] for trace in self.circle_history["traces"]: total_change += float(trace[3]) coords.append((float(trace[1]), float(trace[2]))) print("Total Bearing Change", round(total_change, 3)) #Check Centroid when Bearing change meets req if abs(total_change) >= 720 and self.circle_history['triggered'] is False: print("Circling Bearing Change Met") from shapely.geometry import MultiPoint from geopy.distance import geodesic aircraft_coords = (self.latitude, self.longitude) points = MultiPoint(coords) cent = (points.centroid) #True centroid, not necessarily an existing point #rp = (points.representative_point()) #A represenative point, not centroid, print(cent) #print(rp) distance_to_centroid = geodesic(aircraft_coords, cent.coords).mi print(f"Distance to centroid of circling coordinates {distance_to_centroid} miles") if distance_to_centroid <= 15: print("Within 15 miles of centroid, CIRCLING") from defAirport import getClosestAirport nearest_airport_dict = getClosestAirport(self.latitude, self.longitude, ["small_airport", "medium_airport", "large_airport"]) from calculate_headings import calculate_from_bearing, calculate_cardinal from_bearing = calculate_from_bearing((float(nearest_airport_dict['latitude_deg']), float(nearest_airport_dict['longitude_deg'])), (self.latitude, self.longitude)) cardinal = calculate_cardinal(from_bearing) from defSS import get_adsbx_screenshot url_params = f"icao={self.icao}&zoom=10&largeMode=2&hideButtons&hideSidebar&mapDim=0&overlays={self.get_adsbx_map_overlays()}" get_adsbx_screenshot(self.map_file_name, url_params) if nearest_airport_dict['distance_mi'] < 3: if "touchngo" in self.circle_history.keys(): message = f"Doing touch and goes at {nearest_airport_dict['icao']}" else: message = f"Circling over {nearest_airport_dict['icao']} at {self.alt_ft}ft" else: message = f"Circling {round(nearest_airport_dict['distance_mi'], 2)}mi {cardinal} of {nearest_airport_dict['icao']}, {nearest_airport_dict['name']} at {self.alt_ft}ft" print(message) if self.config.getboolean('DISCORD', 'ENABLE'): role_id = self.config.get('DISCORD', 'ROLE_ID') if self.config.has_option('DISCORD', 'ROLE_ID') else None sendDis(message, self.config, self.map_file_name, role_id) if self.config.getboolean('TWITTER', 'ENABLE'): twitter_media_map_obj = self.tweet_api.media_upload(self.map_file_name) alt_text = f"Distance to centroid: {distance_to_centroid}, Total change: {total_change}" self.tweet_api.create_media_metadata(media_id= twitter_media_map_obj.media_id, alt_text= alt_text) tweet = self.tweet_api.user_timeline(count = 1)[0] self.latest_tweet_id = self.tweet_api.update_status(status = f"{self.twitter_title} {message}".strip(), in_reply_to_status_id = self.latest_tweet_id, media_ids=[twitter_media_map_obj.media_id]).id self.circle_history['triggered'] = True elif abs(total_change) <= 360 and self.circle_history["triggered"]: print("No Longer Circling, trigger cleared") self.circle_history['triggered'] = False # #Power Up # if self.last_feeding == False and self.speed == 0 and self.on_ground: # if self.config.getboolean('DISCORD', 'ENABLE'): # dis_message = (self.dis_title + "Powered Up").strip() # sendDis(dis_message, self.config) #Set Variables to compare to next check self.last_track = self.track self.last_feeding = self.feeding self.last_on_ground = self.on_ground self.last_below_desired_ft = self.below_desired_ft self.last_longitude = self.longitude self.last_latitude = self.latitude self.last_nav_modes = self.nav_modes self.last_sel_alt = self.sel_nav_alt if self.takeoff_time != None: elapsed_time = datetime.utcnow() - self.takeoff_time hours, remainder = divmod(elapsed_time.total_seconds(), 3600) minutes, seconds = divmod(remainder, 60) print((f"Time Since Take off {int(hours)} Hours : {int(minutes)} Mins : {int(seconds)} Secs")) self.printheader("foot") def check_new_ras(self, ras): for ra in ras: if self.recent_ra_types == {} or ra['acas_ra']['advisory'] not in self.recent_ra_types.keys(): self.recent_ra_types[ra['acas_ra']['advisory']] = ra['acas_ra']['unix_timestamp'] ra_message = f"TCAS Resolution Advisory: {ra['acas_ra']['advisory']}" if ra['acas_ra']['advisory_complement'] != "": ra_message += f", {ra['acas_ra']['advisory_complement']}" if bool(int(ra['acas_ra']['MTE'])): ra_message += ", Multi threat" from defSS import get_adsbx_screenshot, generate_adsbx_screenshot_time_params url_params = f"&lat={ra['lat']}&lon={ra['lon']}&zoom=11&largeMode=2&hideButtons&hideSidebar&mapDim=0&overlays={self.get_adsbx_map_overlays()}" if "threat_id_hex" in ra['acas_ra'].keys(): from mictronics_parse import get_aircraft_reg_by_icao threat_reg = get_aircraft_reg_by_icao(ra['acas_ra']['threat_id_hex']) threat_id = threat_reg if threat_reg is not None else "ICAO: " + ra['acas_ra']['threat_id_hex'] ra_message += f", invader: {threat_id}" url_params += generate_adsbx_screenshot_time_params(ra['acas_ra']['unix_timestamp']) + f"&icao={ra['acas_ra']['threat_id_hex']},{self.icao.lower()}×tamp={ra['acas_ra']['unix_timestamp']}" else: url_params += f"&icao={self.icao.lower()}&noIsolation" print(url_params) get_adsbx_screenshot(self.map_file_name, url_params, True, True) if self.config.getboolean('DISCORD', 'ENABLE'): from defDiscord import sendDis dis_message = f"{self.dis_title} {ra_message}" role_id = self.config.get('DISCORD', 'ROLE_ID') if self.config.has_option('DISCORD', 'ROLE_ID') else None sendDis(dis_message, self.config, self.map_file_name, role_id = role_id) #if twitter def expire_ra_types(self): if self.recent_ra_types != {}: for ra_type, postime in self.recent_ra_types.copy().items(): timestamp = datetime.fromtimestamp(postime) time_since_ra = datetime.now() - timestamp print(time_since_ra) if time_since_ra.seconds >= 600: print(ra_type) self.recent_ra_types.pop(ra_type)