Плазма/Громадський транспорт/Створення нових записів джерел даних

From KDE UserBase Wiki
Revision as of 13:27, 31 December 2010 by Yurchor (talk | contribs) (Created page with "Вказана команда додасть дані щодо відправлення трамвая маршруту "N6", що відправляється о 1:30 до кі...")
Other languages:

Створення нового запису джерела даних

Назви файлів мають починатися з коду країни, потім слід використати символ підкреслювання і вказати скорочену назву джерела (звичайно ж, не слід забувати про суфікс назви). Початком назви файла може бути код країни, "international" або "unknown", потім має бути "_" і скорочена назва джерела даних. Приклади: "de_db", "ch_sbb", "sk_atlas", "international_flightstats". Назва файла XML має завершуватися суфіксом ".xml".


Файл XML

Файл XML має посилатися на файл скрипту, який слід використати і у якому має міститися «шаблон адреси», до якого програма додаватиме назву зупинки та інші вказівки щодо надання даних.


Файл скрипту

У файлі скрипту має бути принаймні одна функція, що називається "parseTimetable" і приймає один аргумент. Через цей аргумент функції має передаватися код HTML повністю. Обробку коду виконує сам скрипт. Нижче наведено список функцій, які використовують рушій даних PublicTransport для обробки документа скриптом:

  • parseTimetable( html ) (використовується для обробки документів щодо відправлення-прибуття)
  • parseJourneys( html ) (використовується для обробки документів маршрутів)
  • parsePossibleStops( html ) (використовується для обробки документів пропозицій щодо зупинок)


Допоміжні функції

Передбачено допоміжний об’єкт з назвою "helper", який можна використовувати у скрипті. Частиною об’єкта є такі функції:

  • trim( рядок ) (вилучає « » з початку та кінця вказаного рядка)
  • stripTags( рядок ) (вилучає всі теґи з вказаного рядка, тобто вилучає <...> або </...>)
  • camelCase( рядок ) (змінює регістр літер так, щоб перший символ кожного зі слід був великою літерою, а решта символів – малими літерами)
  • extractBlock( рядок, рядок_початку, рядок_кінця ) (повертає рядок між першим входженням рядок_початку і першим входженням рядок_кінця або порожній рядок, якщо у рядку не вдасться знайти підрядків рядок_початку і рядок_кінця. Наприклад, extractBlock("<b>Текст жирним</b>", "<b>", "</b>") поверне "Текст жирним")
  • matchTime( рядок, форматування ) (пошук рядка часу у вказаному форматі, наприклад, "hh:mm" повертає список з двох цілих чисел: значень годин і хвилин)
  • formatTime( година, хвилина, форматування ) (створює рядок часу у вказаному форматуванні)
  • duration( sTime1, sTime2, форматування ) (повертає тривалість періоду часу між sTime1 і sTime2, рядками часу у вказаному форматуванні)
  • addMinsToTime( sTime, кількість_доданих_хвилин, форматування ) (обробляє вказаний рядок часу відповідно до вказаного форматування, додає кількість_доданих_хвилин і повертає дані відповідно до форматування)
  • splitSkipEmptyParts( рядок, роздільник ) (поділяє вказаний рядок за роздільником, порожні частини буде пропущено)


Додавання оброблених даних щодо відправлення до набору результатів

Скрипту передається об’єкт з назвою "timetableData". Щоб додати оброблені дані щодо відправлення до результату, встановіть значення таких параметрів:

// Додавання відправлення
 timetableData.clear();
 timetableData.set( 'TransportLine', 'N6' );
 timetableData.set( 'TypeOfVehicle', 'STR' );
 timetableData.set( 'Target', 'Bremen Hbf' );
 timetableData.set( 'DepartureHour', 1 );
 timetableData.set( 'DepartureMinute', 30 );
 result.addData( timetableData );

Вказана команда додасть дані щодо відправлення трамвая маршруту "N6", що відправляється о 1:30 до кінцевої зупинки "Bremen Hbf".


Типи даних

Нижче наведено список всіх типів даних, які можна додати до об’єкта timetableData для відправлення, прибуття або маршруту:

  • DepartureDate (The date of the departure)
  • DepartureHour (Mandatory for departures/arrivals/journeys, the hour of the departure)
  • DepartureMinute (Mandatory for departures/arrivals/journeys, the minute of the departure)
  • TransportLine (Mandatory for departures/arrivals, The name of the public transport line, e.g. "4", "6S", "S 5", "RB 24122")
  • Target (Mandatory for departures/arrivals, The target of a journey / of a public transport line)
  • TypeOfVehicle (The type of vehicle)
  • FlightNumber (Same as TransportLine, used for flights)
  • Platform (The platform at which the vehicle departs/arrives)
  • Delay (The delay of a public transport vehicle)
  • DelayReason (The reason of a delay)
  • JourneyNews (Can contain delay / delay reason / other news)
  • JourneyNewsOther (Other news (not delay / delay reason))
  • JourneyNewsLink (Contains a link to an html page with journey news. The url of the accessor is prepended, if a relative path has been matched (starting with "/"))
  • DepartureHourPrognosis (The prognosis for the departure hour, which is the departure hour plus the delay)
  • DepartureMinutePrognosis (The prognosis for the departure minute, which is the departure minute plus the delay)
  • Operator (The company that is responsible for the journey)
  • DepartureAMorPM (Used to match the string "am" or "pm" for the departure time)
  • DepartureAMorPMPrognosis (Used to match the string "am" or "pm" for the prognosis departure time)
  • ArrivalAMorPM (Used to match the string "am" or "pm" for the arrival time)
  • Status (The current status of the departure/arrival. Currently only used for planes)
  • DepartureYear (The year of the departure, to be used when the year is separated from the date)
  • RouteStops (A list of stops of the departure/arrival to its destination stop or a list of stops of the journey from its start to its destination stop. If RouteStops and RouteTimes are both set, they should contain the same number of elements. And elements with equal indices should be associated (the times at which the vehicle is at the stops). For journeys RouteTimesDeparture and RouteTimesArrival should be used instead of RouteTimes)
  • RouteTimes (A list of times of the departure/arrival to its destination stop. If RouteStops and RouteTimes are both set, they should contain the same number of elements. And elements with equal indices should be associated (the times at which the vehicle is at the stops))
  • RouteTimesDeparture (A list of departure times of the journey. If RouteStops and RouteTimesDeparture are both set, the latter should contain one elements less (because the last stop has no departure, only an arrival time). Elements with equal indices should be associated (the times at which the vehicle departs from the stops))
  • RouteTimesArrival (A list of arrival times of the journey. If RouteStops and RouteTimesArrival are both set, the latter should contain one elements less (because the first stop has no arrival, only a departure time). Elements with equal indices should be associated (the times at which the vehicle arrives at the stops))
  • RouteExactStops (The number of exact route stops. The route stop list isn't complete from the last exact route stop)
  • RouteTypesOfVehicles (The types of vehicles used for each "sub-journey" of a journey)
  • RouteTransportLines (The transport lines used for each "sub-journey" of a journey)
  • RoutePlatformsDeparture (The platforms of departures used for each "sub-journey" of a journey)
  • RoutePlatformsArrival (The platforms of arrivals used for each "sub-journey" of a journey)
  • RouteTimesDepartureDelay (A list of delays in minutes for each departure time of a route (RouteTimesDeparture))
  • RouteTimesArrivalDelay (A list of delays in minutes for each arrival time of a route (RouteTimesArrival))

Ці дані може бути застосовано лише до маршрутів:

  • Duration (The duration of a journey)
  • StartStopName (The name of the starting stop of a journey)
  • StartStopID (The ID of the starting stop of a journey)
  • TargetStopName (The name of the target stop of a journey)
  • TargetStopID (The ID of the target stop of a journey)
  • ArrivalDate (The date of the arrival)
  • ArrivalHour (Mandatory for journeys, The hour of the arrival)
  • ArrivalMinute (Mandatory for journeys, The minute of the arrival)
  • Changes (The number of changes between different vehicles in a journey)
  • TypesOfVehicleInJourney (A list of vehicle types used in a journey)
  • Pricing (Information about the pricing of a journey)

Ці дані може бути застосовано лише до пропозицій щодо зупинок:

  • StopName (Mandatory for stop suggestions, The name of a stop / station)
  • StopID (The ID of a stop / station)
  • StopWeight (The weight of a stop suggestion)

Інформація

Згодом тут буде наведено шаблони файлів XML і скрипту. Зараз же ви можете скористатися прикладами цих файлів для вже створених записів джерел даних.