def notify_no_sources(): try: from constants import NOTIFICATION_FILE, IFTTT_MAKER_KEY, IFTTT_MAKER_EVENT import pyfttt except ImportError: logger.exception('Failed importing notification stuff!') return try: with open(NOTIFICATION_FILE) as f: u = f.read().strip() except Exception: logger.exception('Failed reading notification file!') u = None if u == MY_ICS_URL: logger.info('IFTTT event already triggered.') return try: pyfttt.send_event('dNSxTcir9cIXus2UBo98Xm', 'fb_google_calendar_expired') except Exception: logger.exception('Failed sending IFTTT event trigger!') return try: with open(NOTIFICATION_FILE, 'w') as f: f.write(MY_ICS_URL) except Exception: logger.exception('Failed writing notification file!') logger.info('Successfully triggered IFTTT event.')
def main(): ncid_config = None for loc in os.curdir, os.path.expanduser("~"), "/etc/ncid2ifttt": try: with open(os.path.join(loc, "ncid2ifttt-config.json")) as source: ncid_config = json.load(source) except IOError: pass ncid_host = ncid_config["ncid_host"] ncid_port = ncid_config["ncid_port"] ifttt_key = ncid_config["ifttt_key"] ifttt_event = ncid_config["ifttt_event"] s = socket.socket() try: s.connect((ncid_host, ncid_port)) while True: data = s.recv(1024) if data[:4] == "CID:": nmbr = incomingCall(data[:-1]) pyfttt.send_event(ifttt_key, ifttt_event, nmbr) time.sleep(0.1) except: pass finally: s.close()
def notify(job, title, body): # Send notificaions # title = title for notification # body = body of the notification if job.config.PB_KEY != "": try: from pushbullet import Pushbullet pb = Pushbullet(job.config.PB_KEY) pb.push_note(title, body) except: # noqa: E722 logging.error( "Failed sending PushBullet notification. Continueing processing..." ) if job.config.IFTTT_KEY != "": try: import pyfttt as pyfttt event = job.config.IFTTT_EVENT pyfttt.send_event(job.config.IFTTT_KEY, event, title, body) except: # noqa: E722 logging.error( "Failed sending IFTTT notification. Continueing processing..." ) if job.config.PO_USER_KEY != "": try: from pushover import init, Client init(job.config.PO_APP_KEY) Client(job.config.PO_USER_KEY).send_message(body, title=title) except: # noqa: E722 logging.error( "Failed sending PushOver notification. Continueing processing..." )
def trigger_service(call): """Handle IFTTT trigger service calls.""" event = call.data[ATTR_EVENT] value1 = call.data.get(ATTR_VALUE1) value2 = call.data.get(ATTR_VALUE2) value3 = call.data.get(ATTR_VALUE3) try: import pyfttt pyfttt.send_event(key, event, value1, value2, value3) except requests.exceptions.RequestException: _LOGGER.exception("Error communicating with IFTTT")
def run(self): while not GlobalSettings.SolarExitFlag: sedge = SolarEdge_Access.SolarEdge(self.api_keys['SolarEdge']) try: bdirection, sunit, PVPower, LoadPower, GridPower = sedge.getcurrentpowerflow( self.site_id) except Exception: print(self.threadID + ': Error with Getting Data') SolarCheckThread.__sleeping(self, 5 * 60) continue if bdirection: print(self.threadID + ': Your system is using all power from PV') else: print(self.threadID + ': Your system is importing power from grid') if bdirection and (PVPower > self.AirOnPVLimit) and ( sunit == 'kW') and not GlobalSettings.bAirConOn: print(self.threadID + ': Turning on AirConditioner') GlobalSettings.bAirConOn = True pyfttt.send_event(self.api_keys['IFTTT'], 'press_air_conditioning', value1='On @ ' + str(PVPower) + sunit) elif bdirection and GlobalSettings.bAirConOn and ( PVPower <= self.AirOnPVLimit) and (sunit == 'kW'): print(self.threadID + ': Turning off AirConditioner') GlobalSettings.bAirConOn = False pyfttt.send_event(self.api_keys['IFTTT'], 'press_air_conditioning', value1=('Off @ ' + str(PVPower) + sunit)) elif GlobalSettings.bAirConOn: print(self.threadID + ': Air Conditioning already on') if not bdirection and GlobalSettings.bAirConOn: print(self.threadID + ': Turning off AirConditioner') GlobalSettings.bAirConOn = False pyfttt.send_event(self.api_keys['IFTTT'], 'press_air_conditioning', value1='Off') elif not bdirection: print(self.threadID + ': Still importing') SolarCheckThread.__sleeping(self, 10 * 60) if GlobalSettings.bAirConOn: print(self.threadID + ': Turning off AirConditioner due to exit') GlobalSettings.bAirConOn = False pyfttt.send_event(self.api_keys['IFTTT'], 'press_air_conditioning', value1='Off') print(self.threadID + ': Exiting...')
def __SolarEdge_Run(self, sedge): global AC_CONTROL WritetoLog(self.name, 'Updating Solar @ ' + str(datetime.datetime.now())) success_read = True try: bdirection, sunit, pvpower, loadpower, gridpower = sedge.getcurrentpowerflow( self.site_id) except Exception: WritetoLog(self.name, 'Error with Getting Data') success_read = False sleep(60) if success_read: if bdirection and (pvpower > self.PV_Limit) and ( sunit == 'kW') and not GlobalSettings.bAirConOn: if (AC_CONTROL): WritetoLog(self.name, 'Turning on AirConditioner') GlobalSettings.bAirConOn = True pyfttt.send_event(self.api_keys['IFTTT'], 'press_air_conditioning', value1='On @ ' + str(pvpower) + sunit) else: WritetoLog(self.name, 'We are not in control of AC') elif bdirection and GlobalSettings.bAirConOn and ( pvpower <= self.PV_Limit) and (sunit == 'kW'): if (AC_CONTROL): WritetoLog(self.name, 'Turning off AirConditioner') GlobalSettings.bAirConOn = False pyfttt.send_event(self.api_keys['IFTTT'], 'press_air_conditioning', value1=('Off @ ' + str(pvpower) + sunit)) else: WritetoLog(self.name, 'We are not in control of AC') elif GlobalSettings.bAirConOn: WritetoLog(self.name, 'Air Conditioning already on') if not bdirection and GlobalSettings.bAirConOn: if (AC_CONTROL): WritetoLog(self.name, 'Turning off AirConditioner') GlobalSettings.bAirConOn = False pyfttt.send_event(self.api_keys['IFTTT'], 'press_air_conditioning', value1='Off @ Importing') else: WritetoLog(self.name, 'We are not in control of AC') elif not bdirection: WritetoLog(self.name, 'Still importing')
def main(): """Main function for pyfttt command line tool""" args = parse_arguments() if args.key is None: print("Error: Must provide IFTTT secret key.") sys.exit(1) try: res = pyfttt.send_event(api_key=args.key, event=args.event, value1=args.value1, value2=args.value2, value3=args.value3) except requests.exceptions.ConnectionError: print("Error: Could not connect to IFTTT") sys.exit(2) except requests.exceptions.HTTPError: print("Error: Received invalid response") sys.exit(3) except requests.exceptions.Timeout: print("Error: Request timed out") sys.exit(4) except requests.exceptions.TooManyRedirects: print("Error: Too many redirects") sys.exit(5) except requests.exceptions.RequestException as reqe: print("Error: {e}".format(e=reqe)) sys.exit(6) if res.status_code != requests.codes.ok: try: j = res.json() except ValueError: print('Error: Could not parse server response. Event not sent') sys.exit(7) for err in j['errors']: print('Error: {}'.format(err['message'])) sys.exit(8)
def trigger_service(call): """Handle IFTTT trigger service calls.""" event = call.data[ATTR_EVENT] targets = call.data.get(ATTR_TARGET, list(api_keys)) value1 = call.data.get(ATTR_VALUE1) value2 = call.data.get(ATTR_VALUE2) value3 = call.data.get(ATTR_VALUE3) target_keys = dict() for target in targets: if target not in api_keys: _LOGGER.error("No IFTTT api key for %s", target) continue target_keys[target] = api_keys[target] try: import pyfttt for target, key in target_keys.items(): res = pyfttt.send_event(key, event, value1, value2, value3) if res.status_code != 200: _LOGGER.error("IFTTT reported error sending event to %s.", target) except requests.exceptions.RequestException: _LOGGER.exception("Error communicating with IFTTT")
def prender_lampara( ): #Function to send webhook to IFTTT NOTE THAT YOU HAVE TO ADD YOUR OWN IFTTT CODE TO MAKE IT WORK sense.clear() animacion.prender_foco() pyfttt.send_event('ADD CODE HERE', 'ADD WEBHOOK HERE')
def apagar_lampara( ): #Function to send webhook to IFTTT to turn ligths off NOTE THAT YOU HAVE TO ADD YOUR OWN IFTTT CODE TO MAKE IT WORK animacion.apagar_foco() pyfttt.send_event('ADD CODE HERE', 'ADD WEBHOOK HERE')
else: motion_check = abs(pts[detect_frame_num][0] - pts[0][0]) + abs(pts[detect_frame_num][1] - pts[0][1]) if motion_check < 3: cv2.putText(frame, "Not Moving!!!", (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), thickness=3) if stopped == 0: print "stopped at", datetime.datetime.fromtimestamp( int(time.time())).strftime('%Y-%m-%d %H:%M:%S') logging.info("movement stop") if push: pyfttt.send_event(api_key, event) #IFTTT alart stopped = 1 else: cv2.putText(frame, "Moving!!!", (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), thickness=3) if stopped == 1: logging.info("movement start") stopped = 0 #RPM Calculator if key == ord("r"): #reset original point ref_center = center rep = 0
def send_alert(self, current_time): pyfttt.send_event(self.secure_config['secret'], self.secure_config['hash'], current_time) print "FIRED ALERT: %s" % (current_time)
def main(): settings = config.read_config(namespace='BMW') logger = logging.getLogger(__file__) logger.debug(settings) logger.setLevel(settings.logs.level) logger.addHandler(logging.StreamHandler()) try: reg = get_region_from_name(settings.account.country) except Exception as e: logger.error("Failed to get API URL", e) sys.exit(1) try: bc = ConnectedDriveAccount(username=settings.account.username, password=settings.account.password, region=reg) except Exception as e: logger.error("Failed to connect to BMW servers", e) sys.exit(1) try: for v in bc.vehicles: v.state.update_data() ts = v.state.timestamp last_update_reason = v.state.last_update_reason pos = v.state.gps_position charging_status = v.state.charging_status.name charging_status_human = MAPPINGS[charging_status] # cosmetic tweak to status if charging_status == 'INVALID': if last_update_reason == 'VEHICLE_SHUTDOWN': charging_status_human = 'not charging though the car is parked' if last_update_reason == 'VEHICLE_MOVING': charging_status_human = 'not charging as it is being driven' battery_level = v.state.charging_level_hv time_remaining = v.state.charging_time_remaining if time_remaining is None: time_remaining = 'Unknown' # print(json.dumps(v.state.attributes, indent=4)) driver_door_status = v.state.attributes["STATUS"][ "doorDriverFront"] passenger_door_status = v.state.attributes["STATUS"][ "doorPassengerFront"] door_locks_status = v.state.door_lock_state fuel_level_pct = int( (v.state.attributes["STATUS"]["remainingFuel"] / v.state.attributes["STATUS"]["maxFuel"]) * 100) range_miles = int(v.state.attributes["STATUS"]["remainingRangeFuelMls"]) + \ int(v.state.attributes["STATUS"]["maxRangeElectricMls"]) logger.info('Last update: {}'.format(ts)) logger.info('Last reason: {}'.format(last_update_reason)) logger.info('Position: {}, {}'.format(pos[0], pos[1])) logger.info('Charging status: {}'.format(charging_status)) logger.info('Charge time remaining: {}'.format(time_remaining)) logger.info('Charge percentage: {}'.format(battery_level)) logger.info('Driver door: {}'.format(driver_door_status.title())) logger.info('Passenger door: {}'.format( passenger_door_status.title())) logger.info('Door locks: {}'.format( str(door_locks_status).replace('LockState.', '').title())) logger.info('Fuel level: {}%'.format(fuel_level_pct)) logger.info('Range: {} miles'.format(range_miles)) if settings.actions.ifttt_notify_not_charging: if charging_status in settings.bad_charge_status: logger.warning("Battery is not charging for some reason") send_event(settings.ifttt.api_key, settings.ifttt.event, value1=charging_status_human, value2=battery_level, value3=time_remaining) if settings.actions.slack_notify_charging_status: try: slack_icon = ':electric_plug:' if battery_level < 50: slack_icon = ':warning:' slack_message = "Your BMW is {}.".format( charging_status_human) slack_message = slack_message + \ " Its battery is {}% full.".format(battery_level) if battery_level < 95: slack_message = slack_message + \ " {} remains till fully charged.".format( time_remaining) slack_message = slack_message + " Its maximum drivable range is {} mi".format( range_miles) to_slack(settings.slack, slack_message, icon=slack_icon) except Exception as e: logger.warning("Failed to post to Slack: {}".format(e)) if door_locks_status not in (LockState.LOCKED, LockState.SECURED): if settings.actions.slack_notify_door_unlocked: try: slack_message = ':unlock: Your BMW i3 was found to be *UNLOCKED*!' to_slack(settings.slack, slack_message, icon=slack_icon) except Exception as e: logger.warning("Failed to post to Slack: {}".format(e)) if settings.actions.bmw_trigger_remote_door_lock: try: logger.info('Remotely locking doors!') v.remote_services.trigger_remote_door_lock() except Exception as e: logger.error( '"Failed to remotely lock doors: {}'.format(e)) if fuel_level_pct <= settings.low_fuel_pct: if settings.actions.slack_notify_low_fuel: try: slack_message = ':fuelpump: Your BMW i3 is low on gas ({}%)'.format( fuel_level_pct) to_slack(settings.slack, slack_message, icon=slack_icon) except Exception as e: logger.warning("Failed to post to Slack: {}".format(e)) except Exception as e: logger.error("Failed to iterate over vehicle state", e) sys.exit(1) exit(0)
process_this_frame = True prev_guide = 'Stop' prev_command = states.States.STOP command = states.States.NA frame_count = 0 while True: # Send command to the Arduino only if state has changed if prev_command != command: prev_command = command temp = arduino.send(serial_obj, command) try: temp = float(temp) if temp < 60: pyfttt.send_event(IFTTT_API_KEY, 'temperature_too_extreme', temp, 'COLD') elif temp > 90: pyfttt.send_event(IFTTT_API_KEY, 'temperature_too_extreme', temp, 'HOT') except: print 'Got ', temp, 'Cannot convert to float' # Query Firebase for new instruction if frame_count % 60 == 0: instruction = fire_base.get_instruction() # Extract frame from video feed _, frame = camera.read() frame_count = frame_count + 1 if not instruction: