def create_trip_data_from_station(self, station_from, timestamp): """ timestamp format: DD-MM-YYYY hh:mm """ via = "" data = {'stations': []} data['stations'].append({ 'name': station_from.get_name(), 'id': station_from.get_code(), 'travel_time_min': 0, 'travel_time_planned': "0:00" }) nsapi = ns_api.NSAPI(USERNAME, APIKEY) for station in self.stations: if station.get_code() == station_from.get_code(): continue trips = [] try: trips = nsapi.get_trips(timestamp, station_from.get_code(), via, station.get_code()) except TypeError as error: # this is a bug in ns-api, should return empty trips in case there are no results logger.error( 'Error while trying to get trips for destination: ' + station.get_name() + ', from: ' + station_from.get_name()) continue except requests.exceptions.HTTPError as error: # 500: Internal Server Error does always happen for some stations (example are Eijs-Wittem and Kerkrade-West) logger.error( 'HTTP Error while trying to get trips for destination: ' + station.get_name() + ', from: ' + station_from.get_name()) continue if not trips: continue shortest_trip = trips[0] for trip in trips: travel_time = datetime.strptime(trip.travel_time_planned, "%H:%M").time() trip.travel_time_min = travel_time.hour * 60 + travel_time.minute if trip.travel_time_min < shortest_trip.travel_time_min: shortest_trip = trip logger.info(shortest_trip.departure + ' - ' + shortest_trip.destination) data['stations'].append({ 'name': shortest_trip.destination, 'id': self.get_station_code(shortest_trip.destination), 'travel_time_min': shortest_trip.travel_time_min, 'travel_time_planned': shortest_trip.travel_time_planned }) # time.sleep(0.3) # balance load on the NS server json_data = json.dumps(data, indent=4, sort_keys=True, ensure_ascii=False) return json_data
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the departure sensor.""" import ns_api nsapi = ns_api.NSAPI(config.get(CONF_EMAIL), config.get(CONF_PASSWORD)) try: stations = nsapi.get_stations() except ( requests.exceptions.ConnectionError, requests.exceptions.HTTPError, ) as error: _LOGGER.error("Couldn't fetch stations, API password correct?: %s", error) return sensors = [] for departure in config.get(CONF_ROUTES): if not valid_stations( stations, [departure.get(CONF_FROM), departure.get(CONF_VIA), departure.get(CONF_TO)], ): continue sensors.append( NSDepartureSensor( nsapi, departure.get(CONF_NAME), departure.get(CONF_FROM), departure.get(CONF_TO), departure.get(CONF_VIA), ) ) if sensors: add_entities(sensors, True)
def __init__(self, data_dir, test=False): self.data_dir = data_dir self.stations = [] nsapi = ns_api.NSAPI(USERNAME, APIKEY) nsapi_stations = nsapi.get_stations() for i, nsapi_station in enumerate(nsapi_stations): if test and i > 5 and nsapi_station.code != 'UT': continue if nsapi_station.country != 'NL': continue station = Station(nsapi_station, data_dir) self.stations.append(station)
def setup_platform( hass: HomeAssistant, config: ConfigType, add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the departure sensor.""" nsapi = ns_api.NSAPI(config[CONF_API_KEY]) try: stations = nsapi.get_stations() except ( requests.exceptions.ConnectionError, requests.exceptions.HTTPError, ) as error: _LOGGER.error("Could not connect to the internet: %s", error) raise PlatformNotReady() from error except RequestParametersError as error: _LOGGER.error( "Could not fetch stations, please check configuration: %s", error) return sensors = [] for departure in config.get(CONF_ROUTES, {}): if not valid_stations( stations, [ departure.get(CONF_FROM), departure.get(CONF_VIA), departure.get(CONF_TO) ], ): continue sensors.append( NSDepartureSensor( nsapi, departure.get(CONF_NAME), departure.get(CONF_FROM), departure.get(CONF_TO), departure.get(CONF_VIA), departure.get(CONF_TIME), )) if sensors: add_entities(sensors, True)
def check_connections(departure, destination, time, config_dir): """ Send 'ns-notifcations was updated' message after (automatic) upgrade """ settings = get_config(config_dir) nsapi = ns_api.NSAPI( settings['General'].get('apikey','')) print(departure + " " + destination + " " + str(time)) openhab = OpenHAB(settings['Openhab'].get('openhab_url')) item_ns_routeName = openhab.get_item(settings['Openhab'].get('openhab_item_route_name')) item_ns_routeName.command(departure + "->" + destination + " (" + str(time)+")") current_trips = nsapi.get_trips(time, departure, None, destination, True) ns_trains = json.loads(settings['Openhab'].get('openhab_item_trains',[])) for index, trip in enumerate(current_trips): print(index) if(trip.status == "NORMAL"): text = "🟢 " else: text = "🔴 " text = text + str(trip.product_shortCategoryName) + " " text = text + " " + str(ns_api.simple_time(trip.departure_time_planned)) text = text + " ➡ " + str(ns_api.simple_time(trip.arrival_time_planned)) text = text + " ⏱ " + (str(datetime.timedelta(minutes=(trip.travel_time_actual))))[:-3] if(trip.status == "NORMAL"): print("according to plan captain!") else: print(trip.disruptions_head) print(trip.disruptions_text) #print(trip.delay) print(trip.status) print(trip.departure_platform_actual) item_ns_train = openhab.get_item(ns_trains[index]) item_ns_train.command(text)
def setUp(self): self.nsapi = ns_api.NSAPI(USERNAME, APIKEY)
def run_all_notifications(): """ Check for both disruptions and configured trips """ logger = get_logger() ## Open memcache mc = MemcacheClient(('127.0.0.1', 11211), serializer=json_serializer, deserializer=json_deserializer) ## Check whether there's a new version of this notifier update_message = check_versions(mc) try: if update_message and settings.auto_update: # Create (touch) file that the run_notifier script checks on for 'update needed' open(os.path.dirname(os.path.realpath(__file__)) + '/needs_updating', 'a').close() update_message = None except AttributeError: # 'auto_update' likely not defined in settings.py, default to False pass ## NS Notifier userkey (will come from url/cli parameter in the future) try: userkey = settings.userkey except AttributeError: userkey = 1 ## Are we planned to run? (E.g., not disabled through web) try: should_run = mc.get('nsapi_run') except: should_run = True if should_run == None: should_run = True #logger.info('no run tuple in memcache, creating') mc.set('nsapi_run', should_run, MEMCACHE_DISABLING_TTL) # HACK, change when moved to Click and parameters try: if settings.skip_trips == True and settings.skip_disruptions == False: should_run = True except AttributeError: logger.error('Tried overriding should_run, but no skip_* found') #print('should run? ' + str(should_run)) logger.debug('Should run: ' + str(should_run)) if not should_run: sys.exit(0) errors = [] nsapi = ns_api.NSAPI(settings.username, settings.apikey) ## Get the list of stations stations = get_stations(mc, nsapi) ## Get the current disruptions (globally) changed_disruptions = [] get_disruptions = True try: if settings.skip_disruptions: get_disruptions = False except AttributeError: logger.error('Missing skip_disruptions setting') if get_disruptions: try: disruptions = nsapi.get_disruptions() changed_disruptions = get_changed_disruptions(mc, disruptions) except (requests.exceptions.ConnectionError, requests.exceptions.HTTPError) as e: #print('[ERROR] connectionerror doing disruptions') logger.error('Exception doing disruptions ' + repr(e)) errors.append(('Exception doing disruptions', e)) ## Get the information on the list of trips configured by the user trips = [] get_trips = True try: if settings.skip_trips: get_trips = False except AttributeError: logger.error('Missing skip_trips setting') if get_trips: try: trips = get_changed_trips(mc, nsapi, settings.routes, userkey) #print(trips) except (requests.exceptions.ConnectionError, requests.exceptions.HTTPError) as e: #print('[ERROR] connectionerror doing trips') logger.error('Exception doing trips ' + repr(e)) errors.append(('Exception doing trips', e)) # User is interested in arrival delays arrival_delays = True try: arrival_delays = settings.arrival_delays except AttributeError: pass if settings.notification_type == 'pb': p, sendto_device = get_pushbullet_config(logger) if not sendto_device: sys.exit(1) if update_message: p.push_note(update_message['header'], update_message['message'], sendto_device) if changed_disruptions: # There are disruptions that are new or changed since last run sendto_channel = None try: if settings.pushbullet_use_channel: channels = p.channels for channel in channels: #print dev.device_iden + ' ' + dev.nickname if channel.channel_tag == settings.pushbullet_channel_tag: sendto_channel = channel if not sendto_channel: logger.error('PushBullet channel configured, but tag "' + settings.pushbullet_channel_tag + '" not found') print('PushBullet channel configured, but tag "' + settings.pushbullet_channel_tag + '" not found') except AttributeError as e: logger.error('PushBullet channel settings not found - ' + str(e)) print('PushBullet channel settings not found, see settings_example.py - ' + str(e)) for disruption in changed_disruptions: message = format_disruption(disruption) logger.debug(message) #print message if sendto_channel: sendto_channel.push_note(message['header'], message['message']) else: p.push_note(message['header'], message['message'], sendto_device) if trips: for trip in trips: if not arrival_delays: # User is only interested in departure notification_needed = trip.has_delay(arrival_check=False) else: notification_needed = trip.has_delay() if notification_needed: message = format_trip(trip) #print message logger.debug(message) #p.push_note('title', 'body', sendto_device) p.push_note(message['header'], message['message'], sendto_device)
except ImportError: print('Copy settings_example.py to settings.py and set the configuration to your own preferences') sys.exit(1) # Only plan routes that are at maximum half an hour in the past or an hour in the future MAX_TIME_PAST = 1800 MAX_TIME_FUTURE = 3600 # Set max time to live for a key to an hour MEMCACHE_TTL = 3600 MEMCACHE_VERSIONCHECK_TTL = 3600 * 12 MEMCACHE_DISABLING_TTL = 3600 * 6 VERSION_NSAPI = '2.7.3' nsapi = ns_api.NSAPI(settings.username, settings.apikey) ## Helper functions for memcache serialisation def json_serializer(key, value): if type(value) == str: return value, 1 #if issubclass(value, ns_api.BaseObject): # print ("instance of NS-API object") # return value.to_json(), 3 return json.dumps(value), 2 def json_deserializer(key, value, flags): if flags == 1: return value if flags == 2:
def run_all_notifications(config_dir): """ Check for both disruptions and configured trips """ logger = get_logger() settings = get_config(config_dir) ## Open memcache mc = MemcacheClient(('127.0.0.1', 11211), serializer=json_serializer, deserializer=json_deserializer) ## Check whether there's a new version of this notifier update_message = check_versions(mc) try: if update_message and settings.auto_update: # Create (touch) file that the run_notifier script checks on for 'update needed' open(os.path.dirname(os.path.realpath(__file__)) + '/needs_updating', 'a').close() update_message = None except AttributeError: # 'auto_update' likely not defined in settings.py, default to False pass ## NS Notifier userkey (will come from url/cli parameter in the future) try: userkey = settings.userkey except AttributeError: userkey = 1 ## Are we planned to run? (E.g., not disabled through web) try: should_run = mc.get('nsapi_run') except: should_run = True if should_run == None: should_run = True #logger.info('no run tuple in memcache, creating') mc.set('nsapi_run', should_run, MEMCACHE_DISABLING_TTL) # HACK, change when moved to Click and parameters try: if settings.skip_trips == True and settings.skip_disruptions == False: should_run = True except AttributeError: logger.error('Tried overriding should_run, but no skip_* found') #print('should run? ' + str(should_run)) logger.debug('Should run: ' + str(should_run)) if not should_run: sys.exit(0) errors = [] nsapi = ns_api.NSAPI( settings.apikey) ## Get the list of stations #stations = get_stations(mc, nsapi) ## Get the current disruptions (globally) changed_disruptions = [] get_disruptions = True try: if settings.skip_disruptions: get_disruptions = False except AttributeError: logger.error('Missing skip_disruptions setting') if get_disruptions: try: disruptions = nsapi.get_disruptions() changed_disruptions = get_changed_disruptions(mc, disruptions) except (requests.exceptions.ConnectionError, requests.exceptions.HTTPError) as e: #print('[ERROR] connectionerror doing disruptions') logger.error('Exception doing disruptions ' + repr(e)) errors.append(('Exception doing disruptions', e)) ## Get the information on the list of trips configured by the user trips = [] get_trips = True try: if settings.skip_trips: get_trips = False except AttributeError: logger.error('Missing skip_trips setting') if get_trips: try: trips = get_changed_trips(mc, nsapi, settings.routes, userkey) print(trips) except (requests.exceptions.ConnectionError, requests.exceptions.HTTPError) as e: #print('[ERROR] connectionerror doing trips') logger.error('Exception doing trips ' + repr(e)) errors.append(('Exception doing trips', e)) # User is interested in arrival delays arrival_delays = True try: arrival_delays = settings.arrival_delays except AttributeError: pass if settings.notification_type == 'pb': if changed_disruptions: # There are disruptions that are new or changed since last run sendto_channel = None for disruption in changed_disruptions: message = format_disruption(disruption)