57_Calendar.pm 118 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582
  1. # $Id: 57_Calendar.pm 15612 2017-12-15 09:26:59Z neubert $
  2. ##############################################################################
  3. #
  4. # 57_Calendar.pm
  5. # Copyright by Dr. Boris Neubert
  6. # e-mail: omega at online dot de
  7. #
  8. # This file is part of fhem.
  9. #
  10. # Fhem is free software: you can redistribute it and/or modify
  11. # it under the terms of the GNU General Public License as published by
  12. # the Free Software Foundation, either version 2 of the License, or
  13. # (at your option) any later version.
  14. #
  15. # Fhem is distributed in the hope that it will be useful,
  16. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. # GNU General Public License for more details.
  19. #
  20. # You should have received a copy of the GNU General Public License
  21. # along with fhem. If not, see <http://www.gnu.org/licenses/>.
  22. #
  23. ##############################################################################
  24. use strict;
  25. use warnings;
  26. use HttpUtils;
  27. use Storable qw(freeze thaw);
  28. ##############################################
  29. package main;
  30. no if $] >= 5.017011, warnings => 'experimental::smartmatch';
  31. #
  32. # *** Potential isses:
  33. #
  34. # There might be issues when turning to daylight saving time and back that
  35. # need further investigation. For counterpart please see
  36. # http://forum.fhem.de/index.php?topic=18707
  37. # http://forum.fhem.de/index.php?topic=15827
  38. #
  39. # *** Potential future extensions:
  40. #
  41. # sequence of events fired sorted by time
  42. # http://forum.fhem.de/index.php?topic=29112
  43. #
  44. # document ownCloud ical use
  45. # http://forum.fhem.de/index.php?topic=28667
  46. #
  47. # high load when parsing
  48. # http://forum.fhem.de/index.php/topic,40783.0.html
  49. =for comment
  50. RFC
  51. ---
  52. https://tools.ietf.org/html/rfc5545
  53. Data structures
  54. ---------------
  55. We call a set of calendar events (short: events) a series, even for sets
  56. consisting only of a single event. A series may consist of only one single
  57. event, a series of regularly reccuring events and reccuring events with
  58. exceptions. A series is identified by a UID.
  59. *** VEVENT record, class ICal::Entry
  60. In the iCalendar, a series is represented by one or more VEVENT records.
  61. The unique key for a VEVENT record is UID, RECURRENCE-ID (3.8.4.4, p. 112) and
  62. SEQUENCE (3.8.7.4, p. 138).
  63. The internal primary key for a VEVENT is ID.
  64. FHEM keeps a set of VEVENT records (record set). When the calendar is updated,
  65. a new record set is retrieved from the iCalendar and updates the old record set
  66. to form the resultant record set.
  67. A record in the resultant record set can be in exactly one of these states:
  68. - deleted:
  69. a record from the old record set for which no record with the same
  70. (UID, RECURRENCE-ID) was in the new record set.
  71. - new:
  72. a record from the new record set for which no record with same
  73. (UID, RECURRENCE-ID) was in the old record set.
  74. - changed-old:
  75. a record from the old record set for which a record with the same
  76. (UID, RECURRENCE-ID) but different SEQUENCE was in the new record
  77. set.
  78. - changed-new:
  79. a record from the new record set for which a record with the same
  80. (UID, RECURRENCE-ID) but different SEQUENCE was in the old record
  81. set.
  82. - known:
  83. a record with this (UID, RECURRENCE-ID, SEQUENCE) was both in the
  84. old and in the new record set and both records have the same
  85. LAST-MODIFIED. The record from the old record set was
  86. kept and the record from the new record set was discarded.
  87. - modified-new:
  88. a record with this (UID, RECURRENCE-ID, SEQUENCE) was both in the
  89. old and in the new record set and both records differ in
  90. LAST-MODIFIED. This is the record from the new record set.
  91. - modified-old:
  92. a record with this (UID, RECURRENCE-ID, SEQUENCE) was both in the
  93. old and in the new record set and both records differ in
  94. LAST-MODIFIED. This is the record from the old record set.
  95. Records in states modified-old and changed-old refer to the corresponding records
  96. in states modified-new and change-new, and vice versa.
  97. Records in state deleted, modified-old or changed-old are removed upon
  98. the next update. They are said to be "obsolete".
  99. A record is said to be "recurring" if it has a RRULE property.
  100. A record is said to be an "exception" if it has a RECURRENCE-ID property.
  101. Each records has a set of events attached.
  102. *** calendar event, class Calendar::Event
  103. Events are attached to single records (VEVENTs).
  104. The uid of the event is the UID of the record with all non-alphanumerical
  105. characters removed.
  106. At a given point in time t, an event is in exactly one of these modes:
  107. - upcoming:
  108. the start time of the event is in the future
  109. - alarm:
  110. alarm time <= t < start time for any of the alarms for the event
  111. - start:
  112. start time <= t <= end time of the event
  113. - end:
  114. end time < t
  115. An event is said to be "changed", when its mode has changed during the most
  116. recent run of calendar event processing.
  117. An event is said to be "hidden", when
  118. - it was in mode end and end time of the event < t - horizonPast, or
  119. - it was in mode upcoming and start time of the event > t + horizonFuture
  120. at the most recent run of calendar event processing. horizonPast defaults to 0,
  121. horizonFuture defaults to 366 days.
  122. Processing of iCalendar
  123. -----------------------
  124. *** Initial situation:
  125. We have an old record set of VEVENTs. It is empty on a restart of FHEM or upon
  126. issueing the "set ... reload" command.
  127. *** Step 1: Retrieval of new record set (Calendar_GetUpdate)
  128. 1) The iCalendar is downloaded from its location into FHEM memory.
  129. 2) It is parsed into a new record set of VEVENTs.
  130. *** Step 2: Update of internal record set (Calendar_UpdateCalendar)
  131. 1) All records in the old record set that are in state deleted or obsolete are
  132. removed.
  133. 2) All states of all records in the old record set are set to blank.
  134. 3) The old and new record sets are merged to create a resultant record set
  135. according to the following procedure:
  136. If the new record set contains a record with the same (UID, RECURRENCE-ID,
  137. SEQUENCE) as a record in the old record set:
  138. - if the two records differ in LAST-MODIFIED, then both records
  139. are kept. The state of the record from the old record set is set to
  140. modified-old, the state of the record from the new record set is set to
  141. modified-new.
  142. - else the record from the old record set is kept, state set to known, and the
  143. record from the new record set is discarded.
  144. If the new record set contains a record with the same (UID, RECURRENCE-ID) but
  145. different SEQUENCE as a record in the old record set, then both records are
  146. kept. The state of the record from the new record set is set to changed-new,
  147. and the state of record from the old record set is set to changed-old.
  148. If the new record set contains a record that differs from any record in the old
  149. record set by both UID and RECURRENCE-ID, the record from the new record set
  150. id added to the resultant record set and its state is set to new.
  151. 4) The state of all records in the old record set that have not been touched
  152. in 3) are set to deleted.
  153. Notes:
  154. - This procedure favors records from the new record set over records from the
  155. old record set, even if the SEQUENCE is lower or LAST-MODIFIED is earlier.
  156. - DTSTAMP is the time stamp of the creation of the iCalendar entry. For Google
  157. Calendar it is the time stamp of the latest retrieval of the calendar.
  158. *** Step 3: Update of calendar events (Calendar_UpdateCalendar)
  159. We walk over all records and treat the corresponding events according to
  160. the state of the record:
  161. - deleted, changed-old, modified-old:
  162. all events are removed
  163. - new, changed-new, modified-new:
  164. all events are removed and events are created anew
  165. - known:
  166. all events are left alone
  167. No events older than 400 days or more than 400 days in the future will be
  168. created.
  169. Creation of events in a series works as follows:
  170. If we have several events in a series, the main series has the RRULE tag and
  171. the exceptions have RECURRENCE-IDs. The RECURRENCE-ID match the start
  172. dates in the series created from the RRULE that need to be exempted. We
  173. therefore collect all events from records with same UID and RECURRENCE-ID set
  174. as they form the list of records with the exceptions for the UID.
  175. Before the regular creation is done, events for RDATEs are added as long as
  176. an RDATE is not superseded by an EXDATE. An RDATE takes precedence over a
  177. regularly created recurring event.
  178. Starting with the start date of the series, one event is created after the
  179. other. Creation stops when the series ends or when an event more than 400 days
  180. in the future has been created. If the event is in the list of exceptions
  181. (either defined by other events with same UID and a RECURRENCE-ID or by the
  182. EXDATE property), it is not added.
  183. What attributes are recognized and which of these are honored or ignored?
  184. The following frequencies (FREQ) are recognized and honored:
  185. SECONDLY
  186. MINUTELY
  187. HOURLY
  188. DAILY
  189. WEEKLY
  190. BYDAY: recognizes and honors one or several weekdays without prefix (e.g. -1SU, 2MO)
  191. MONTHLY
  192. BYDAY: recognizes and honors one or several weekdays with and without prefix (e.g. -1SU, 2MO)
  193. BYMONTHDAY: recognized but ignored
  194. BYMONTH: recognized but ignored
  195. YEARLY
  196. For all of the above:
  197. INTERVAL: recognized and honored
  198. UNTIL: recognized and honored
  199. COUNT: recognized and honored
  200. WKST: recognized but ignored
  201. EXDATE: recognized and honored
  202. RDATE: recognized and honored
  203. *** Step 4: The device readings related to updates are set
  204. - calname
  205. - lastUpdate
  206. - nextUpdate
  207. - nextWakeup
  208. - state
  209. Note: the state... readings from the previous version of this module (2015 and
  210. earlier) are not available any more.
  211. Processing of calendar events
  212. -----------------------------
  213. Calendar_CheckTimes
  214. In case of a series of calendar events, several calendar events may exist for
  215. the same uid which may be in different modes. Therefore only the most
  216. interesting mode is chosen over any other mode of any calendar event with
  217. the same uid. The most interesting mode is the first applicable from the
  218. following list:
  219. - start
  220. - alarm
  221. - upcoming
  222. - end
  223. Apart from these actual modes, virtual modes apply:
  224. - changed: the actual mode has changed during this call of Calendar_CheckTimes
  225. - alarmed: modes are alarm and changed
  226. - started: modes are start and changed
  227. - ended: modes are end and changed
  228. - alarm or start: mode is alarm or start
  229. If the mode has changed to <mode>, the following FHEM events are created:
  230. changed uid <mode>
  231. <mode> uid
  232. Note: there is no colon in these FHEM events.
  233. Program flow
  234. ------------
  235. Calendar_Initialize sets the Calendar_Notify to watch for notifications.
  236. Calendar_Notify acts on the INITIALIZED and REREADCFG events by starting the
  237. timer to call Calendar_Wakeup between 10 and 29 seconds after the
  238. notification.
  239. Calendar_Wakeup starts a processing run.
  240. It sets the current time t as baseline for process.
  241. If the time for the next update has been reached,
  242. Calendar_GetUpdate is called
  243. else
  244. Calendar_CheckTimes
  245. Calendar_RearmTimer
  246. are called.
  247. Calendar_GetUpdate retrieves the iCal file. If the source is url, this is
  248. done asynchronously. Upon successfull retrieval of the iCal file, we
  249. continue with Calendar_ProcessUpdate.
  250. Calendar_ProcessUpdate calls
  251. Calendar_UpdateCalendar
  252. Calendar_CheckTimes
  253. Calendar_RearmTimer
  254. in sequence.
  255. Calendar_UpdateCalendar updates the VEVENT records in the
  256. $hash->{".fhem"}{vevents} hash and creates the associated calendar events.
  257. Calendar_CheckTimes checks for a mode change of the calendar events and
  258. creates the readings and FHEM events.
  259. Calendar_RearmTimer sets the timer to call Calendar_Wakeup to time of the
  260. next mode change or update, whatever comes earlier.
  261. What's new?
  262. -----------
  263. This module version replaces the 2015 version that has been widely. Noteworthy
  264. changes
  265. - No more state... readings; "all" reading has been removed as well.
  266. - The mode... readings (modeAlarm, modeAlarmOrStart, etc.) are deprecated
  267. and will be removed in a future version. Use the mode=<regex> filter instead.
  268. - Handles recurring calendar events with out-of-order events and exceptions
  269. (EXDATE).
  270. - Keeps ALL calendar events within plus/minus 400 days from the date of the
  271. in FHEM: this means that you can have more than one calendar event with the
  272. same UID.
  273. - You can restrict visible calendar events with attributes hideLaterThan,
  274. hideOlderThan.
  275. - Nonblocking retrieval of calendar from URL.
  276. - New get commands:
  277. get <name> vevents
  278. get <name> vcalendar
  279. get <name> <format> <mode>
  280. get <name> <format> mode=<regex>
  281. get <name> <format> uid=<regex>
  282. - The get commands
  283. get <name> <format> ...
  284. may not work as before since several calendar events may exist for a
  285. single UID, particularly the get command
  286. get <name> <format> all
  287. show all calendar events from a series (past, current, and future); you
  288. probably want to replace "all" by "next":
  289. get <name> <format> next
  290. to get only the first (not past but current or future) calendar event from
  291. each series.
  292. - Migration hints:
  293. Replace
  294. get <name> <format> all
  295. by
  296. get <name> <format> next
  297. Replace
  298. get <name> <format> <uid>
  299. by
  300. get <name> <format> uid=<uid> 1
  301. Replace
  302. get <name> <format> modeAlarmOrStart
  303. by
  304. get <name> <format> mode=alarm|start
  305. - The FHEM events created for mode changes of single calendar events have been
  306. amended:
  307. changed: UID <mode>
  308. <mode>: UID (this is new)
  309. <mode> is the current mode of the calendar event after the change. It is
  310. highly advisable to trigger actions based on these FHEM events instead of
  311. notifications for changes of the mode... readings.
  312. =cut
  313. #####################################
  314. #
  315. # Event
  316. #
  317. #####################################
  318. package Calendar::Event;
  319. sub new {
  320. my $class= shift;
  321. my $self= {}; # I am a hash
  322. bless $self, $class;
  323. $self->{_previousMode}= "undefined";
  324. $self->{_mode}= "undefined";
  325. return($self);
  326. }
  327. sub uid {
  328. my ($self)= @_;
  329. return $self->{uid};
  330. }
  331. sub start {
  332. my ($self)= @_;
  333. return $self->{start};
  334. }
  335. sub end {
  336. my ($self)= @_;
  337. return $self->{end};
  338. }
  339. sub setNote($$) {
  340. my ($self,$note)= @_;
  341. $self->{_note}= $note;
  342. return $note;
  343. }
  344. sub getNote($) {
  345. my ($self)= @_;
  346. return $self->{_note};
  347. }
  348. sub hasNote($) {
  349. my ($self)= @_;
  350. return defined($self->{_note}) ? 1 : 0;
  351. }
  352. sub setMode {
  353. my ($self,$mode)= @_;
  354. $self->{_previousMode}= $self->{_mode};
  355. $self->{_mode}= $mode;
  356. #main::Debug "After setMode $mode: Modes(" . $self->uid() . ") " . $self->{_previousMode} . " -> " . $self->{_mode};
  357. return $mode;
  358. }
  359. sub setModeUnchanged {
  360. my ($self)= @_;
  361. $self->{_previousMode}= $self->{_mode};
  362. }
  363. sub getMode {
  364. my ($self)= @_;
  365. return $self->{_mode};
  366. }
  367. sub lastModified {
  368. my ($self)= @_;
  369. return $self->{lastModified};
  370. }
  371. sub modeChanged {
  372. my ($self)= @_;
  373. return (($self->{_mode} ne $self->{_previousMode}) and
  374. ($self->{_previousMode} ne "undefined")) ? 1 : 0;
  375. }
  376. sub summary {
  377. my ($self)= @_;
  378. return $self->{summary};
  379. }
  380. sub location {
  381. my ($self)= @_;
  382. return $self->{location};
  383. }
  384. sub description {
  385. my ($self)= @_;
  386. return $self->{description};
  387. }
  388. sub categories {
  389. my ($self)= @_;
  390. return $self->{categories};
  391. }
  392. sub ts($$) {
  393. my ($self,$tm)= @_;
  394. return "" unless($tm);
  395. my ($second,$minute,$hour,$day,$month,$year,$wday,$yday,$isdst)= localtime($tm);
  396. return sprintf("%02d.%02d.%4d %02d:%02d:%02d", $day,$month+1,$year+1900,$hour,$minute,$second);
  397. }
  398. sub ts0($$) {
  399. my ($self,$tm)= @_;
  400. return "" unless($tm);
  401. my ($second,$minute,$hour,$day,$month,$year,$wday,$yday,$isdst)= localtime($tm);
  402. return sprintf("%02d.%02d.%2d %02d:%02d", $day,$month+1,$year-100,$hour,$minute);
  403. }
  404. sub asText {
  405. my ($self)= @_;
  406. return sprintf("%s %s",
  407. $self->ts0($self->{start}),
  408. $self->{summary}
  409. );
  410. }
  411. sub asFull {
  412. my ($self)= @_;
  413. return sprintf("%s %9s %s %s-%s %s %s %s",
  414. $self->uid(),
  415. $self->getMode(),
  416. $self->{alarm} ? $self->ts($self->{alarm}) : " ",
  417. $self->ts($self->{start}),
  418. $self->ts($self->{end}),
  419. $self->{summary},
  420. $self->{categories},
  421. $self->{location}
  422. );
  423. }
  424. sub asDebug {
  425. my ($self)= @_;
  426. return sprintf("%s %s %9s %s %s-%s %s %s %s %s",
  427. $self->uid(),
  428. $self->modeChanged() ? "*" : " ",
  429. $self->getMode(),
  430. $self->{alarm} ? $self->ts($self->{alarm}) : " ",
  431. $self->ts($self->{start}),
  432. $self->ts($self->{end}),
  433. $self->{summary},
  434. $self->{categories},
  435. $self->{location},
  436. $self->hasNote() ? $self->getNote() : ""
  437. );
  438. }
  439. sub alarmTime {
  440. my ($self)= @_;
  441. return $self->ts($self->{alarm});
  442. }
  443. sub startTime {
  444. my ($self)= @_;
  445. return $self->ts($self->{start});
  446. }
  447. sub endTime {
  448. my ($self)= @_;
  449. return $self->ts($self->{end});
  450. }
  451. # returns 1 if time is before alarm time and before start time, else 0
  452. sub isUpcoming {
  453. my ($self,$t) = @_;
  454. if($self->{alarm}) {
  455. return $t< $self->{alarm} ? 1 : 0;
  456. } else {
  457. return $t< $self->{start} ? 1 : 0;
  458. }
  459. }
  460. # returns 1 if time is between alarm time and start time, else 0
  461. sub isAlarmed {
  462. my ($self,$t) = @_;
  463. return $self->{alarm} ?
  464. (($self->{alarm}<= $t && $t< $self->{start}) ? 1 : 0) : 0;
  465. }
  466. # return 1 if time is between start time and end time, else 0
  467. sub isStarted {
  468. my ($self,$t) = @_;
  469. return 0 unless(defined($self->{start}));
  470. return 0 if($t < $self->{start});
  471. if(defined($self->{end})) {
  472. return 0 if($t>= $self->{end});
  473. }
  474. return 1;
  475. }
  476. sub isSeries {
  477. my ($self)= @_;
  478. #main::Debug " freq= " . $self->{freq};
  479. return exists($self->{freq}) ? 1 : 0;
  480. }
  481. sub isAfterSeriesEnded {
  482. my ($self,$t) = @_;
  483. #main::Debug " isSeries? " . $self->isSeries();
  484. return 0 unless($self->isSeries());
  485. #main::Debug " until= " . $self->{until};
  486. return 0 unless(exists($self->{until}));
  487. #main::Debug " has until!";
  488. return $self->{until}< $t ? 1 : 0;
  489. }
  490. sub isEnded {
  491. my ($self,$t) = @_;
  492. #main::Debug "isEnded for " . $self->asFull();
  493. #main::Debug " isAfterSeriesEnded? " . $self->isAfterSeriesEnded($t);
  494. #return 1 if($self->isAfterSeriesEnded($t));
  495. #main::Debug " has end? " . (defined($self->{end}) ? 1 : 0);
  496. return 0 unless(defined($self->{end}));
  497. return $self->{end}<= $t ? 1 : 0;
  498. }
  499. sub nextTime {
  500. my ($self,$t) = @_;
  501. my @times= ( );
  502. push @times, $self->{start} if(defined($self->{start}));
  503. push @times, $self->{end} if(defined($self->{end}));
  504. unshift @times, $self->{alarm} if($self->{alarm});
  505. @times= sort grep { $_ > $t } @times;
  506. # main::Debug "Calendar: " . $self->asFull();
  507. # main::Debug "Calendar: Start " . main::FmtDateTime($self->{start});
  508. # main::Debug "Calendar: End " . main::FmtDateTime($self->{end});
  509. # main::Debug "Calendar: Alarm " . main::FmtDateTime($self->{alarm}) if($self->{alarm});
  510. # main::Debug "Calendar: times[0] " . main::FmtDateTime($times[0]);
  511. # main::Debug "Calendar: times[1] " . main::FmtDateTime($times[1]);
  512. # main::Debug "Calendar: times[2] " . main::FmtDateTime($times[2]);
  513. if(@times) {
  514. return $times[0];
  515. } else {
  516. return undef;
  517. }
  518. }
  519. #####################################
  520. #
  521. # Events
  522. #
  523. #####################################
  524. package Calendar::Events;
  525. sub new {
  526. my $class= shift;
  527. my $self= []; # I am an array
  528. bless $self, $class;
  529. return($self);
  530. }
  531. sub addEvent($$) {
  532. my ($self,$event)= @_;
  533. return push @{$self}, $event;
  534. }
  535. sub clear($) {
  536. my ($self)= @_;
  537. return @{$self}= ();
  538. }
  539. #####################################
  540. #
  541. # ICal
  542. # the ical format is governed by RFC2445 http://www.ietf.org/rfc/rfc2445.txt
  543. #
  544. #####################################
  545. package ICal::Entry;
  546. sub getNextMonthlyDateByDay($$$);
  547. sub new($$) {
  548. my $class= shift;
  549. my ($type)= @_;
  550. #main::Debug "new ICal::Entry $type";
  551. my $self= {};
  552. bless $self, $class;
  553. $self->{type}= $type;
  554. #$self->clearState(); set here:
  555. $self->{state}= "<none>";
  556. #$self->clearCounterpart(); unnecessary
  557. #$self->clearReferences(); set here:
  558. $self->{references}= [];
  559. #$self->clearTags(); unnecessary
  560. $self->{entries}= []; # array of subordinated ICal::Entry
  561. $self->{events}= Calendar::Events->new();
  562. $self->{skippedEvents}= Calendar::Events->new();
  563. return($self);
  564. }
  565. #
  566. # keys, properties, values
  567. #
  568. # is key a repeated property?
  569. sub isMultiple($$) {
  570. my ($self,$key)= @_;
  571. return $self->{properties}{$key}{multiple};
  572. }
  573. # has a property named key?
  574. sub hasKey($$) {
  575. my ($self,$key)= @_;
  576. return exists($self->{properties}{$key}) ? 1 : 0;
  577. }
  578. # value for single property key
  579. sub value($$) {
  580. my ($self,$key)= @_;
  581. return undef if($self->isMultiple($key));
  582. return $self->{properties}{$key}{VALUE};
  583. }
  584. # value for property key or default, if non-existant
  585. sub valueOrDefault($$$) {
  586. my ($self,$key,$default)= @_;
  587. return $self->hasKey($key) ? $self->value($key) : $default;
  588. }
  589. # value for multiple property key (array counterpart)
  590. sub values($$) {
  591. my ($self,$key)= @_;
  592. return undef unless($self->isMultiple($key));
  593. return $self->{properties}{$key}{VALUES};
  594. }
  595. # true, if the property exists at both entries and have the same value
  596. # or neither entry has this property
  597. sub sameValue($$$) {
  598. my ($self,$other,$key)= @_;
  599. my $value1= $self->hasKey($key) ? $self->value($key) : "";
  600. my $value2= $other->hasKey($key) ? $other->value($key) : "";
  601. return $value1 eq $value2;
  602. }
  603. sub parts($$) {
  604. my ($self,$key)= @_;
  605. return split(";", $self->{properties}{$key}{PARTS});
  606. }
  607. #
  608. # state
  609. #
  610. sub setState {
  611. my ($self,$state)= @_;
  612. $self->{state}= $state;
  613. return $state;
  614. }
  615. sub clearState {
  616. my ($self)= @_;
  617. $self->{state}= "<none>";
  618. }
  619. sub state($) {
  620. my($self)= @_;
  621. return $self->{state};
  622. }
  623. sub inState($$) {
  624. my($self, $state)= @_;
  625. return ($self->{state} eq $state ? 1 : 0);
  626. }
  627. sub isObsolete($) {
  628. my($self)= @_;
  629. # VEVENT records in these states are obsolete
  630. my @statesObsolete= qw/deleted changed-old modified-old/;
  631. return $self->state() ~~ @statesObsolete ? 1 : 0;
  632. }
  633. sub hasChanged($) {
  634. my($self)= @_;
  635. # VEVENT records in these states have changed
  636. my @statesChanged= qw/new changed-new modified-new/;
  637. return $self->state() ~~ @statesChanged ? 1 : 0;
  638. }
  639. #
  640. # type
  641. #
  642. sub type($) {
  643. my($self)= @_;
  644. return $self->{type};
  645. }
  646. #
  647. # counterpart, for changed or modified records
  648. #
  649. sub counterpart($) {
  650. my($self)= @_;
  651. return $self->{counterpart};
  652. }
  653. sub setCounterpart($$) {
  654. my ($self, $id)= @_;
  655. $self->{counterpart}= $id;
  656. return $id;
  657. }
  658. sub hasCounterpart($) {
  659. my($self)= @_;
  660. return (defined($self->{counterpart}) ? 1 : 0);
  661. }
  662. sub clearCounterpart($) {
  663. my($self)= @_;
  664. delete $self->{counterpart} if(defined($self->{counterpart}));
  665. }
  666. #
  667. # series
  668. #
  669. sub isRecurring($) {
  670. my($self)= @_;
  671. return $self->hasKey("RRULE");
  672. }
  673. sub isException($) {
  674. my($self)= @_;
  675. return $self->hasKey("RECURRENCE-ID");
  676. }
  677. sub hasReferences($) {
  678. my($self)= @_;
  679. return scalar(@{$self->references()});
  680. }
  681. sub references($) {
  682. my($self)= @_;
  683. return $self->{references};
  684. }
  685. sub clearReferences($) {
  686. my($self)= @_;
  687. $self->{references}= [];
  688. }
  689. #
  690. # tags
  691. #
  692. # sub tags($) {
  693. # my($self)= @_;
  694. # return $self->{tags};
  695. # }
  696. #
  697. # sub clearTags($) {
  698. # my($self)= @_;
  699. # $self->{tags}= [];
  700. # }
  701. #
  702. # sub tagAs($$) {
  703. # my ($self, $tag)= @_;
  704. # push @{$self->{tags}}, $tag unless($self->isTaggedAs($tag));
  705. # }
  706. #
  707. # sub isTaggedAs($$) {
  708. # my ($self, $tag)= @_;
  709. # return grep { $_ eq $tag } @{$self->{tags}} ? 1 : 0;
  710. # }
  711. #
  712. # sub numTags($) {
  713. # my ($self)= @_;
  714. # return scalar @{$self->{tags}};
  715. # }
  716. #
  717. # parsing
  718. #
  719. sub addproperty($$) {
  720. my ($self,$line)= @_;
  721. # contentline = name *(";" param ) ":" value CRLF [Page 13]
  722. # example:
  723. # TRIGGER;VALUE=DATE-TIME:20120531T150000Z
  724. #main::Debug "line=\'$line\'";
  725. # for DTSTART, DTEND there are several variants:
  726. # DTSTART;TZID=Europe/Berlin:20140205T183600
  727. # * DTSTART;TZID="(UTC+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna":20140904T180000
  728. # DTSTART:20140211T212000Z
  729. # DTSTART;VALUE=DATE:20130619
  730. my ($key,$parts,$parameter);
  731. if($line =~ /^([\w\d\-]+)(;(.*))?:(.*)$/) {
  732. $key= $1;
  733. $parts= $3 // "";
  734. $parameter= $4 // "";
  735. } else {
  736. return;
  737. }
  738. return unless($key);
  739. #main::Debug "addproperty for key $key";
  740. # ignore some properties
  741. # commented out: it is faster to add the property than to do the check
  742. # return if(($key eq "ATTENDEE") or ($key eq "TRANSP") or ($key eq "STATUS"));
  743. return if(substr($key,0,2) eq "^X-");
  744. if(($key eq "RDATE") or ($key eq "EXDATE")) {
  745. #main::Debug "addproperty for dates";
  746. # handle multiple properties
  747. my @values;
  748. @values= @{$self->values($key)} if($self->hasKey($key));
  749. push @values, $parameter;
  750. #main::Debug "addproperty pushed parameter $parameter to key $key";
  751. $self->{properties}{$key}= {
  752. multiple => 1,
  753. VALUES => \@values,
  754. }
  755. } else {
  756. # handle single properties
  757. $self->{properties}{$key}= {
  758. multiple => 0,
  759. PARTS => "$parts",
  760. VALUE => "$parameter",
  761. }
  762. };
  763. }
  764. sub parse($$) {
  765. my ($self,$ics)= @_;
  766. # This is the proper way to do it, with \R corresponding to (?>\r\n|\n|\x0b|\f|\r|\x85|\x2028|\x2029)
  767. # my @ical= split /\R/, $ics;
  768. # Tt does not treat some unicode emojis correctly, though.
  769. # We thus go for the the DOS/Windows/Unix/Mac classic variants.
  770. # Suggested reading:
  771. # http://stackoverflow.com/questions/3219014/what-is-a-cross-platform-regex-for-removal-of-line-breaks
  772. my @ical= split /(?>\r\n|[\r\n])/, $ics;
  773. return $self->parseSub(0, \@ical);
  774. }
  775. sub parseSub($$$) {
  776. my ($self,$ln,$icalref)= @_;
  777. my $len= scalar @$icalref;
  778. #main::Debug "lines= $len";
  779. #main::Debug "ENTER @ $ln";
  780. while($ln< $len) {
  781. my $line= $$icalref[$ln];
  782. $ln++;
  783. # check for and handle continuation lines (4.1 on page 12)
  784. while($ln< $len) {
  785. my $line1= $$icalref[$ln];
  786. last if(substr($line1,0,1) ne " ");
  787. $line.= substr($line1,1);
  788. $ln++;
  789. };
  790. #main::Debug "$ln: $line";
  791. next if($line eq ""); # ignore empty line
  792. last if(substr($line,0,4) eq "END:");
  793. if(substr($line,0,6) eq "BEGIN:") {
  794. my $entry= ICal::Entry->new(substr($line,6));
  795. $entry->{ln}= $ln;
  796. push @{$self->{entries}}, $entry;
  797. $ln= $entry->parseSub($ln,$icalref);
  798. } else {
  799. $self->addproperty($line);
  800. }
  801. }
  802. #main::Debug "BACK";
  803. return $ln;
  804. }
  805. #
  806. # events
  807. #
  808. sub events($) {
  809. my ($self)= @_;
  810. return $self->{events};
  811. }
  812. sub clearEvents($) {
  813. my ($self)= @_;
  814. $self->{events}->clear();
  815. }
  816. sub numEvents($) {
  817. my ($self)= @_;
  818. return scalar(@{$self->{events}});
  819. }
  820. sub addEvent($$) {
  821. my ($self, $event)= @_;
  822. $self->{events}->addEvent($event);
  823. }
  824. sub skippedEvents($) {
  825. my ($self)= @_;
  826. return $self->{skippedEvents};
  827. }
  828. sub clearSkippedEvents($) {
  829. my ($self)= @_;
  830. $self->{skippedEvents}->clear();
  831. }
  832. sub numSkippedEvents($) {
  833. my ($self)= @_;
  834. return scalar(@{$self->{skippedEvents}});
  835. }
  836. sub addSkippedEvent($$) {
  837. my ($self, $event)= @_;
  838. $self->{skippedEvents}->addEvent($event);
  839. }
  840. sub createEvent($) {
  841. my ($self)= @_;
  842. my $event= Calendar::Event->new();
  843. $event->{uid}= $self->value("UID");
  844. $event->{uid}=~ s/\W//g; # remove all non-alphanumeric characters, this makes life easier for perl specials
  845. return $event;
  846. }
  847. # converts a date/time string to the number of non-leap seconds since the epoch
  848. # 20120520T185202Z: date/time string in ISO8601 format, time zone GMT
  849. # 20121129T222200: date/time string in ISO8601 format, time zone local
  850. # 20120520: a date string has no time zone associated
  851. sub tm($$) {
  852. my ($self, $t)= @_;
  853. return undef if(!$t);
  854. #main::Debug "convert >$t<";
  855. my ($year,$month,$day)= (substr($t,0,4), substr($t,4,2),substr($t,6,2));
  856. if(length($t)>8) {
  857. my ($hour,$minute,$second)= (substr($t,9,2), substr($t,11,2),substr($t,13,2));
  858. my $z;
  859. $z= substr($t,15,1) if(length($t) == 16);
  860. #main::Debug "$day.$month.$year $hour:$minute:$second $z";
  861. if($z) {
  862. return main::fhemTimeGm($second,$minute,$hour,$day,$month-1,$year-1900);
  863. } else {
  864. return main::fhemTimeLocal($second,$minute,$hour,$day,$month-1,$year-1900);
  865. }
  866. } else {
  867. #main::Debug "$day.$month.$year";
  868. return main::fhemTimeLocal(0,0,0,$day,$month-1,$year-1900);
  869. }
  870. }
  871. # DURATION RFC2445
  872. # dur-value = (["+"] / "-") "P" (dur-date / dur-time / dur-week)
  873. #
  874. # dur-date = dur-day [dur-time]
  875. # dur-time = "T" (dur-hour / dur-minute / dur-second)
  876. # dur-week = 1*DIGIT "W"
  877. # dur-hour = 1*DIGIT "H" [dur-minute]
  878. # dur-minute = 1*DIGIT "M" [dur-second]
  879. # dur-second = 1*DIGIT "S"
  880. # dur-day = 1*DIGIT "D"
  881. #
  882. # example: -P0DT0H30M0S
  883. sub d($$) {
  884. my ($self, $d)= @_;
  885. #main::Debug "Duration $d";
  886. my $sign= 1;
  887. my $t= 0;
  888. my @c= split("P", $d);
  889. $sign= -1 if($c[0] eq "-");
  890. my ($dw,$dt)= split("T", $c[1]);
  891. $dt="" unless defined($dt);
  892. if($dw =~ m/(\d+)D$/) {
  893. $t+= 86400*$1; # days
  894. } elsif($dw =~ m/(\d+)W$/) {
  895. $t+= 604800*$1; # weeks
  896. }
  897. if($dt =~ m/(\d+)H/) {
  898. $t+= $1*3600;
  899. }
  900. if($dt =~ m/(\d+)M/) {
  901. $t+= $1*60;
  902. }
  903. if($dt =~ m/(\d+)S/) {
  904. $t+= $1;
  905. }
  906. $t*= $sign;
  907. #main::Debug "sign: $sign dw: $dw dt: $dt t= $t";
  908. return $t;
  909. }
  910. sub dt($$$$) {
  911. my ($self,$t0,$value,$parts)= @_;
  912. #main::Debug "t0= $t0 parts= $parts value= $value";
  913. if(defined($parts) && $parts =~ m/VALUE=DATE/) {
  914. return $self->tm($value);
  915. } else {
  916. return $t0+$self->d($value);
  917. }
  918. }
  919. sub makeEventDetails($$) {
  920. my ($self, $event)= @_;
  921. $event->{summary}= $self->valueOrDefault("SUMMARY", "");
  922. $event->{location}= $self->valueOrDefault("LOCATION", "");
  923. $event->{description}= $self->valueOrDefault("DESCRIPTION", "");
  924. $event->{categories}= $self->valueOrDefault("CATEGORIES", "");
  925. return $event;
  926. }
  927. sub makeEventAlarms($$) {
  928. my ($self, $event)= @_;
  929. # alarms
  930. my @valarms= grep { $_->{type} eq "VALARM" } @{$self->{entries}};
  931. my @alarmtimes= sort map { $self->dt($event->{start}, $_->value("TRIGGER"), $_->parts("TRIGGER")) } @valarms;
  932. if(@alarmtimes) {
  933. $event->{alarm}= $alarmtimes[0];
  934. } else {
  935. $event->{alarm}= undef;
  936. }
  937. return $event;
  938. }
  939. sub DSTOffset($$) {
  940. my ($t1,$t2)= @_;
  941. my @lt1 = localtime($t1);
  942. my @lt2 = localtime($t2);
  943. return 3600 *($lt1[8] - $lt2[8]);
  944. }
  945. # This function adds $n times $seconds to $t1 (seconds from the epoch).
  946. # A correction of 3600 seconds (one hour) is applied if and only if
  947. # one of $t1 and $t1+$n*$seconds falls into wintertime and the other
  948. # into summertime. Thus, e.g., adding a multiple of 24*60*60 seconds
  949. # to 5 o'clock always gives 5 o'clock and not 4 o'clock or 6 o'clock
  950. # upon a change of summertime to wintertime or vice versa.
  951. sub plusNSeconds($$$) {
  952. my ($t1, $seconds, $n)= @_;
  953. $n= 1 unless defined($n);
  954. my $t2= $t1+$n*$seconds;
  955. return $t2+DSTOffset($t1,$t2);
  956. }
  957. sub plusNMonths($$) {
  958. my ($tm, $n)= @_;
  959. my ($second,$minute,$hour,$day,$month,$year,$wday,$yday,$isdst)= localtime($tm);
  960. #main::Debug "Adding $n months to $day.$month.$year $hour:$minute:$second= " . ts($tm);
  961. $month+= $n;
  962. $year+= int($month / 12);
  963. $month %= 12;
  964. #main::Debug " gives $day.$month.$year $hour:$minute:$second= " . ts(main::fhemTimeLocal($second,$minute,$hour,$day,$month,$year));
  965. return main::fhemTimeLocal($second,$minute,$hour,$day,$month,$year);
  966. }
  967. # This function gets the next date according to interval and byDate
  968. # Alex, 2016-11-24
  969. # 1. parameter: startTime
  970. # 2. parameter: interval (months)
  971. # 3. parameter: byDay (string with byDay-value(s), e.g. "FR" or "4SA" or "-1SU" or "4SA,4SU" (not sure if this is possible, i just take the first byDay))
  972. sub getNextMonthlyDateByDay($$$) {
  973. my ( $ipTimeLocal, $ipByDays, $ipInterval )= @_;
  974. my ($lSecond, $lMinute, $lHour, $lDay, $lMonth, $lYear, $lWday, $lYday, $lIsdst )= localtime( $ipTimeLocal );
  975. #main::Debug "getNextMonthlyDateByDay($ipTimeLocal, $ipByDays, $ipInterval)";
  976. my @lByDays = split(",", $ipByDays);
  977. my $lByDay = $lByDays[0]; #only get first day element within string
  978. my $lByDayLength = length( $lByDay );
  979. my $lDayStr; # which day to set the date
  980. my $lDayInterval; # e.g. 2 = 2nd $lDayStr of month or -1 = last $lDayStr of month
  981. if ( $lByDayLength > 2 ) {
  982. $lDayStr= substr( $lByDay, -2 );
  983. $lDayInterval= int( substr( $lByDay, 0, $lByDayLength - 2 ) );
  984. } else {
  985. $lDayStr= $lByDay;
  986. $lDayInterval= 1;
  987. }
  988. my @weekdays = qw(SU MO TU WE TH FR SA);
  989. my ($lDayOfWeek)= grep { $weekdays[$_] eq $lDayStr } 0..$#weekdays;
  990. # get next day from beginning of the month, e.g. "4FR" = 4th friday of the month
  991. my $lNextMonth;
  992. my $lNextYear;
  993. my $lDayOfWeekNew;
  994. my $lDaysToAddOrSub;
  995. my $lNewTime;
  996. if ( $lDayInterval > 0 ) {
  997. #get next month and year according to $ipInterval
  998. $lNextMonth= $lMonth + $ipInterval;
  999. $lNextYear= $lYear;
  1000. $lNextYear += int( $lNextMonth / 12);
  1001. $lNextMonth %= 12;
  1002. my $lFirstOfNextMonth = main::fhemTimeLocal( $lSecond, $lMinute, $lHour, 1, $lNextMonth, $lNextYear );
  1003. ($lSecond, $lMinute, $lHour, $lDay, $lMonth, $lYear, $lDayOfWeekNew, $lYday, $lIsdst )= localtime( $lFirstOfNextMonth );
  1004. if ( $lDayOfWeekNew <= $lDayOfWeek ) {
  1005. $lDaysToAddOrSub = $lDayOfWeek - $lDayOfWeekNew;
  1006. } else {
  1007. $lDaysToAddOrSub = 7 - $lDayOfWeekNew + $lDayOfWeek;
  1008. }
  1009. $lDaysToAddOrSub += ( 7 * ( $lDayInterval - 1 ) ); #add day interval, e.g. 4th friday...
  1010. $lNewTime = plusNSeconds( $lFirstOfNextMonth, 24*60*60*$lDaysToAddOrSub, 1);
  1011. ($lSecond, $lMinute, $lHour, $lDay, $lMonth, $lYear, $lWday, $lYday, $lIsdst )= localtime( $lNewTime );
  1012. if ( $lMonth ne $lNextMonth ) { #skip this date and move on to the next interval...
  1013. $lNewTime = getNextMonthlyDateByDay( $lFirstOfNextMonth, $ipByDays, $ipInterval );
  1014. }
  1015. } else { #calculate date from end of month
  1016. #get next month and year according to ipInterval
  1017. $lNextMonth = $lMonth + $ipInterval + 1; #first get the month after the desired month
  1018. $lNextYear = $lYear;
  1019. $lNextYear += int( $lNextMonth / 12);
  1020. $lNextMonth %= 12;
  1021. my $lLastOfNextMonth = main::fhemTimeLocal( $lSecond, $lMinute, $lHour, 1, $lNextMonth, $lNextYear ); # get time
  1022. $lLastOfNextMonth = plusNSeconds( $lLastOfNextMonth, -24*60*60, 1 ); #subtract one day
  1023. ($lSecond, $lMinute, $lHour, $lDay, $lMonth, $lYear, $lDayOfWeekNew, $lYday, $lIsdst )= localtime( $lLastOfNextMonth );
  1024. if ( $lDayOfWeekNew >= $lDayOfWeek )
  1025. {
  1026. $lDaysToAddOrSub = $lDayOfWeekNew - $lDayOfWeek;
  1027. }
  1028. else
  1029. {
  1030. $lDaysToAddOrSub = 7 - $lDayOfWeek + $lDayOfWeekNew;
  1031. }
  1032. $lDaysToAddOrSub += ( 7 * ( abs( $lDayInterval ) - 1 ) );
  1033. $lNewTime = plusNSeconds( $lLastOfNextMonth, -24*60*60*$lDaysToAddOrSub, 1);
  1034. }
  1035. #main::Debug "lByDay = $lByDay, lByDayLength = $lByDayLength, lDay = $lDay, lDayInterval = $lDayInterval, lDayOfWeek = $lDayOfWeek, lFirstOfNextMonth = $lFirstOfNextMonth, lNextYear = $lNextYear, lNextMonth = $lNextMonth";
  1036. #main::Debug main::FmtDateTime($lNewTime);
  1037. return $lNewTime;
  1038. }
  1039. use constant eventsLimitMinus => -34560000; # -400d
  1040. use constant eventsLimitPlus => 34560000; # +400d
  1041. sub addEventLimited($$$) {
  1042. my ($self, $t, $event)= @_;
  1043. return -1 if($event->start()< $t+eventsLimitMinus);
  1044. return 1 if($event->start()> $t+eventsLimitPlus);
  1045. #main::Debug " addEvent: " . $event->asFull();
  1046. $self->addEvent($event);
  1047. return 0;
  1048. }
  1049. sub createSingleEvent($$$) {
  1050. my ($self, $nextstart, $onCreateEvent)= @_;
  1051. my $event= $self->createEvent();
  1052. my $start= $self->tm($self->value("DTSTART"));
  1053. $nextstart= $start unless(defined($nextstart));
  1054. $event->{start}= $nextstart;
  1055. if($self->hasKey("DTEND")) {
  1056. my $end= $self->tm($self->value("DTEND"));
  1057. $event->{end}= $nextstart+($end-$start);
  1058. } elsif($self->hasKey("DURATION")) {
  1059. my $duration= $self->d($self->value("DURATION"));
  1060. $event->{end}= $nextstart + $duration;
  1061. }
  1062. $self->makeEventDetails($event);
  1063. $self->makeEventAlarms($event);
  1064. #main::Debug "createSingleEvent DTSTART=" . $self->value("DTSTART") . " DTEND=" . $self->value("DTEND");
  1065. #main::Debug "createSingleEvent Start " . main::FmtDateTime($event->{start});
  1066. #main::Debug "createSingleEvent End " . main::FmtDateTime($event->{end});
  1067. # plug-in
  1068. if(defined($onCreateEvent)) {
  1069. my $e= $event;
  1070. #main::Debug "Executing $onCreateEvent for " . $e->asDebug();
  1071. eval $onCreateEvent;
  1072. if($@) {
  1073. main::Log3 undef, 2, "Erroneous onCreateEvent $onCreateEvent: $@";
  1074. } else {
  1075. $event= $e;
  1076. }
  1077. }
  1078. return $event;
  1079. }
  1080. sub createEvents($$$%) {
  1081. my ($self, $t, $onCreateEvent, %vevents)= @_;
  1082. $self->clearEvents();
  1083. $self->clearSkippedEvents();
  1084. if($self->isRecurring()) {
  1085. #
  1086. # recurring event creates a series
  1087. #
  1088. my $rrule= $self->value("RRULE");
  1089. my @rrparts= split(";", $rrule);
  1090. my %r= map { split("=", $_); } @rrparts;
  1091. my @keywords= qw(FREQ INTERVAL UNTIL COUNT BYMONTHDAY BYDAY BYMONTH WKST);
  1092. foreach my $k (keys %r) {
  1093. if(not($k ~~ @keywords)) {
  1094. main::Log3 undef, 2, "Calendar: keyword $k in RRULE $rrule is not supported";
  1095. } else {
  1096. #main::Debug "keyword $k in RRULE $rrule has value $r{$k}";
  1097. }
  1098. }
  1099. # Valid values for freq: SECONDLY, MINUTELY, HOURLY, DAILY, WEEKLY, MONTHLY, YEARLY
  1100. my $freq = $r{"FREQ"};
  1101. #main::Debug "FREQ= $freq";
  1102. # According to RFC, interval defaults to 1
  1103. my $interval = exists($r{"INTERVAL"}) ? $r{"INTERVAL"} : 1;
  1104. my $until = exists($r{"UNTIL"}) ? $self->tm($r{"UNTIL"}) : 99999999999999999;
  1105. my $count = exists($r{"COUNT"}) ? $r{"COUNT"} : 999999;
  1106. my $bymonthday = $r{"BYMONTHDAY"} if(exists($r{"BYMONTHDAY"})); # stored but ignored
  1107. my $byday = exists($r{"BYDAY"}) ? $r{"BYDAY"} : "";
  1108. #main::Debug "byday is $byday";
  1109. my $bymonth = $r{"BYMONTH"} if(exists($r{"BYMONTH"})); # stored but ignored
  1110. my $wkst = $r{"WKST"} if(exists($r{"WKST"})); # stored but ignored
  1111. my @weekdays = qw(SU MO TU WE TH FR SA);
  1112. #main::Debug "createEvents: " . $self->asString();
  1113. #
  1114. # we first add all RDATEs
  1115. #
  1116. if($self->hasKey('RDATE')) {
  1117. foreach my $rdate (@{$self->values("RDATE")}) {
  1118. my $event= $self->createSingleEvent($self->tm($rdate), $onCreateEvent);
  1119. my $skip= 0;
  1120. if($self->hasKey('EXDATE')) {
  1121. foreach my $exdate (@{$self->values("EXDATE")}) {
  1122. if($self->tm($exdate) == $event->start()) {
  1123. $event->setNote("EXDATE: $exdate for RDATE: $rdate");
  1124. $self->addSkippedEvent($event);
  1125. $skip++;
  1126. last;
  1127. }
  1128. }
  1129. }
  1130. if(!$skip) {
  1131. # add event
  1132. # and return if we exceed storage limit
  1133. $event->setNote("RDATE: $rdate");
  1134. $self->addEventLimited($t, $event);
  1135. }
  1136. }
  1137. }
  1138. #
  1139. # now we build the series
  1140. #
  1141. # first event in the series
  1142. my $event= $self->createSingleEvent(undef, $onCreateEvent);
  1143. my $n= 0;
  1144. while(1) {
  1145. my $skip= 0;
  1146. # check if superseded by out-of-series event
  1147. if($self->hasReferences()) {
  1148. foreach my $id (@{$self->references()}) {
  1149. my $vevent= $vevents{$id};
  1150. my $recurrenceid= $vevent->value("RECURRENCE-ID");
  1151. my $originalstart= $vevent->tm($recurrenceid);
  1152. if($originalstart == $event->start()) {
  1153. $event->setNote("RECURRENCE-ID: $recurrenceid");
  1154. $self->addSkippedEvent($event);
  1155. $skip++;
  1156. last;
  1157. }
  1158. }
  1159. }
  1160. # RFC 5545 p. 120
  1161. # The final recurrence set is generated by gathering all of the
  1162. # start DATE-TIME values generated by any of the specified "RRULE"
  1163. # and "RDATE" properties, and then excluding any start DATE-TIME
  1164. # values specified by "EXDATE" properties. This implies that start
  1165. # DATE-TIME values specified by "EXDATE" properties take precedence
  1166. # over those specified by inclusion properties (i.e., "RDATE" and
  1167. # "RRULE"). Where duplicate instances are generated by the "RRULE"
  1168. # and "RDATE" properties, only one recurrence is considered.
  1169. # Duplicate instances are ignored.
  1170. # check if excluded by EXDATE
  1171. if($self->hasKey('EXDATE')) {
  1172. foreach my $exdate (@{$self->values("EXDATE")}) {
  1173. if($self->tm($exdate) == $event->start()) {
  1174. $event->setNote("EXDATE: $exdate");
  1175. $self->addSkippedEvent($event);
  1176. $skip++;
  1177. last;
  1178. }
  1179. }
  1180. }
  1181. # check if excluded by a duplicate RDATE
  1182. # this is only to avoid duplicates from previously added RDATEs
  1183. if($self->hasKey('RDATE')) {
  1184. foreach my $rdate (@{$self->values("RDATE")}) {
  1185. if($self->tm($rdate) == $event->start()) {
  1186. $event->setNote("RDATE: $rdate");
  1187. $self->addSkippedEvent($event);
  1188. $skip++;
  1189. last;
  1190. }
  1191. }
  1192. }
  1193. return if($event->{start} > $until); # return if we are after end of series
  1194. if(!$skip) {
  1195. # add event
  1196. # and return if we exceed storage limit
  1197. return if($self->addEventLimited($t, $event) > 0);
  1198. }
  1199. $n++;
  1200. return if($n>= $count); # return if we exceeded occurances
  1201. # advance to next occurence
  1202. my $nextstart = $event->{start};
  1203. if($freq eq "SECONDLY") {
  1204. $nextstart = plusNSeconds($nextstart, 1, $interval);
  1205. } elsif($freq eq "MINUTELY") {
  1206. $nextstart = plusNSeconds($nextstart, 60, $interval);
  1207. } elsif($freq eq "HOURLY") {
  1208. $nextstart = plusNSeconds($nextstart, 60*60, $interval);
  1209. } elsif($freq eq "DAILY") {
  1210. $nextstart = plusNSeconds($nextstart, 24*60*60, $interval);
  1211. } elsif($freq eq "WEEKLY") {
  1212. # special handling for WEEKLY and BYDAY
  1213. #main::Debug "weekly event, BYDAY= $byday";
  1214. if($byday ne "") {
  1215. # BYDAY with prefix (e.g. -1SU or 2MO) is not recognized
  1216. my @bydays= split(',', $byday);
  1217. # we skip interval-1 weeks
  1218. $nextstart = plusNSeconds($nextstart, 7*24*60*60, $interval-1);
  1219. my ($msec, $mmin, $mhour, $mday, $mmon, $myear, $mwday, $yday, $isdat);
  1220. my $preventloop = 0;
  1221. do {
  1222. $nextstart = plusNSeconds($nextstart, 24*60*60, 1); # forward day by day
  1223. ($msec, $mmin, $mhour, $mday, $mmon, $myear, $mwday, $yday, $isdat) =
  1224. localtime($nextstart);
  1225. #main::Debug "Skip to: start " . $event->ts($nextstart) . " = " . $weekdays[$mwday];
  1226. $preventloop++;
  1227. if($preventloop > 7) {
  1228. main::Log3 undef, 2,
  1229. "Calendar: something is wrong for RRULE $rrule in " .
  1230. $self->asString();
  1231. last;
  1232. }
  1233. #main::Debug "weekday= " . $weekdays[$mwday] . "($mwday), smartmatch " . join(" ",@bydays) ."= " . ($weekdays[$mwday] ~~ @bydays ? "yes" : "no");
  1234. } until($weekdays[$mwday] ~~ @bydays);
  1235. }
  1236. else {
  1237. # default WEEKLY handling
  1238. $nextstart = plusNSeconds($nextstart, 7*24*60*60, $interval);
  1239. }
  1240. } elsif($freq eq "MONTHLY") {
  1241. if ( $byday ne "" ) {
  1242. $nextstart = getNextMonthlyDateByDay( $nextstart, $byday, $interval );
  1243. }
  1244. else {
  1245. # here we ignore BYMONTHDAY as we consider the day of month of $self->{start}
  1246. # to be equal to BYMONTHDAY.
  1247. $nextstart= plusNMonths($nextstart, $interval);
  1248. }
  1249. } elsif($freq eq "YEARLY") {
  1250. $nextstart= plusNMonths($nextstart, 12*$interval);
  1251. } else {
  1252. main::Log3 undef, 2, "Calendar: event frequency '$freq' not implemented";
  1253. return;
  1254. }
  1255. # the next event
  1256. $event= $self->createSingleEvent($nextstart, $onCreateEvent);
  1257. }
  1258. } else {
  1259. #
  1260. # single event
  1261. #
  1262. my $event= $self->createSingleEvent(undef, $onCreateEvent);
  1263. $self->addEventLimited($t, $event);
  1264. }
  1265. }
  1266. #
  1267. # friendly string
  1268. #
  1269. sub asString($$) {
  1270. my ($self,$level)= @_;
  1271. $level= "" unless(defined($level));
  1272. my $s= $level . $self->{type};
  1273. $s.= " @" . $self->{ln} if(defined($self->{ln}));
  1274. $s.= " [";
  1275. $s.= "obsolete, " if($self->isObsolete());
  1276. $s.= $self->state();
  1277. $s.= ", refers to " . $self->counterpart() if($self->hasCounterpart());
  1278. $s.= ", in a series with " . join(",", sort @{$self->references()}) if($self->hasReferences());
  1279. $s.= "]";
  1280. #$s.= " (tags: " . join(",", @{$self->tags()}) . ")" if($self->numTags());
  1281. $s.= "\n";
  1282. $level .= " ";
  1283. for my $key (sort keys %{$self->{properties}}) {
  1284. $s.= $level . "$key: ";
  1285. if($self->{properties}{$key}{multiple}) {
  1286. $s.= "(" . join(" ", @{$self->values($key)}) . ")";
  1287. } else {
  1288. $s.= $self->value($key);
  1289. }
  1290. $s.= "\n";
  1291. }
  1292. if($self->{type} eq "VEVENT") {
  1293. if($self->isRecurring()) {
  1294. $s.= $level . ">>> is a series\n";
  1295. }
  1296. if($self->isException()) {
  1297. $s.= $level . ">>> is an exception\n";
  1298. }
  1299. $s.= $level . ">>> Events:\n";
  1300. foreach my $event (@{$self->{events}}) {
  1301. $s.= "$level " . $event->asDebug() . "\n";
  1302. }
  1303. $s.= $level . ">>> Skipped events:\n";
  1304. foreach my $event (@{$self->{skippedEvents}}) {
  1305. $s.= "$level " . $event->asDebug() . "\n";
  1306. }
  1307. }
  1308. my @entries= @{$self->{entries}};
  1309. for(my $i= 0; $i<=$#entries; $i++) {
  1310. $s.= $entries[$i]->asString($level);
  1311. }
  1312. return $s;
  1313. }
  1314. ##########################################################################
  1315. #
  1316. # main
  1317. #
  1318. ##########################################################################
  1319. package main;
  1320. #####################################
  1321. sub Calendar_Initialize($) {
  1322. my ($hash) = @_;
  1323. $hash->{DefFn} = "Calendar_Define";
  1324. $hash->{UndefFn} = "Calendar_Undef";
  1325. $hash->{GetFn} = "Calendar_Get";
  1326. $hash->{SetFn} = "Calendar_Set";
  1327. $hash->{AttrFn} = "Calendar_Attr";
  1328. $hash->{NotifyFn}= "Calendar_Notify";
  1329. $hash->{AttrList}= "update:sync,async,none removevcalendar:0,1 cutoffOlderThan hideOlderThan hideLaterThan onCreateEvent SSLVerify:0,1 $readingFnAttributes";
  1330. }
  1331. #####################################
  1332. sub Calendar_Define($$) {
  1333. my ($hash, $def) = @_;
  1334. # define <name> Calendar ical URL [interval]
  1335. my @a = split("[ \t][ \t]*", $def);
  1336. return "syntax: define <name> Calendar ical url <URL> [interval]\n".\
  1337. " define <name> Calendar ical file <FILENAME> [interval]"
  1338. if(($#a < 4 && $#a > 5) || ($a[2] ne 'ical') || (($a[3] ne 'url') && ($a[3] ne 'file')));
  1339. $hash->{NOTIFYDEV} = "global";
  1340. readingsSingleUpdate($hash, "state", "initialized", 1);
  1341. my $name = $a[0];
  1342. my $type = $a[3];
  1343. my $url = $a[4];
  1344. my $interval = 3600;
  1345. $interval= $a[5] if($#a==5);
  1346. $hash->{".fhem"}{type}= $type;
  1347. $hash->{".fhem"}{url}= $url;
  1348. $hash->{".fhem"}{interval}= $interval;
  1349. $hash->{".fhem"}{lastid}= 0;
  1350. $hash->{".fhem"}{vevents}= {};
  1351. $hash->{".fhem"}{nxtUpdtTs}= 0;
  1352. #$attr{$name}{"hideOlderThan"}= 0;
  1353. #main::Debug "Interval: ${interval}s";
  1354. # if initialization is not yet done, we do not wake up at this point already to
  1355. # avoid the following race condition:
  1356. # events are loaded from fhem.save and data are updated asynchronousy from
  1357. # non-blocking Http get
  1358. Calendar_Wakeup($hash, 0) if($init_done);
  1359. return undef;
  1360. }
  1361. #####################################
  1362. sub Calendar_Undef($$) {
  1363. my ($hash, $arg) = @_;
  1364. Calendar_DisarmTimer($hash);
  1365. if(exists($hash->{".fhem"}{subprocess})) {
  1366. my $subprocess= $hash->{".fhem"}{subprocess};
  1367. $subprocess->terminate();
  1368. $subprocess->wait();
  1369. }
  1370. return undef;
  1371. }
  1372. #####################################
  1373. sub Calendar_Attr(@) {
  1374. my ($cmd, $name, @a) = @_;
  1375. return undef unless($cmd eq "set");
  1376. my $hash= $defs{$name};
  1377. return "attr $name needs at least one argument." if(!@a);
  1378. my $arg= $a[1];
  1379. if($a[0] eq "onCreateEvent") {
  1380. if($arg !~ m/^{.*}$/s) {
  1381. return "$arg must be a perl command in curly brackets but you supplied $arg.";
  1382. }
  1383. } elsif($a[0] eq "update") {
  1384. my @args= qw/none sync async/;
  1385. return "Argument for update must be one of " . join(" ", @args) .
  1386. " instead of $arg." unless($arg ~~ @args);
  1387. }
  1388. return undef;
  1389. }
  1390. ###################################
  1391. sub Calendar_Notify($$)
  1392. {
  1393. my ($hash,$dev) = @_;
  1394. my $name = $hash->{NAME};
  1395. my $type = $hash->{TYPE};
  1396. return if($dev->{NAME} ne "global");
  1397. return if(!grep(m/^INITIALIZED|REREADCFG$/, @{$dev->{CHANGED}}));
  1398. return if($attr{$name} && $attr{$name}{disable});
  1399. # update calendar after initialization or change of configuration
  1400. # wait 10 to 29 seconds to avoid congestion due to concurrent activities
  1401. Calendar_DisarmTimer($hash);
  1402. my $delay= 10+int(rand(20));
  1403. # delay removed until further notice
  1404. $delay= 2;
  1405. Log3 $hash, 5, "Calendar $name: FHEM initialization or rereadcfg triggered update, delay $delay seconds.";
  1406. InternalTimer(time()+$delay, "Calendar_Wakeup", $hash, 0) ;
  1407. return undef;
  1408. }
  1409. ###################################
  1410. sub Calendar_Set($@) {
  1411. my ($hash, @a) = @_;
  1412. my $cmd= $a[1];
  1413. $cmd= "?" unless($cmd);
  1414. my $t= time();
  1415. # usage check
  1416. if((@a == 2) && ($a[1] eq "update")) {
  1417. Calendar_DisarmTimer($hash);
  1418. Calendar_GetUpdate($hash, $t, 0);
  1419. return undef;
  1420. } elsif((@a == 2) && ($a[1] eq "reload")) {
  1421. Calendar_DisarmTimer($hash);
  1422. Calendar_GetUpdate($hash, $t, 1); # remove all events before update
  1423. return undef;
  1424. } else {
  1425. return "Unknown argument $cmd, choose one of update:noArg reload:noArg";
  1426. }
  1427. }
  1428. ###################################
  1429. sub Calendar_Get($@) {
  1430. my ($hash, @a) = @_;
  1431. my $t= time();
  1432. my $eventsObj= $hash->{".fhem"}{events};
  1433. my @events;
  1434. my $cmd= $a[1];
  1435. $cmd= "?" unless($cmd);
  1436. if($cmd eq "update") {
  1437. # this is the same as set update for convenience
  1438. Calendar_DisarmTimer($hash);
  1439. Calendar_GetUpdate($hash, $t, 0);
  1440. return undef;
  1441. }
  1442. if($cmd eq "reload") {
  1443. # this is the same as set reload for convenience
  1444. Calendar_DisarmTimer($hash);
  1445. Calendar_GetUpdate($hash, $t, 1); # remove all events before update
  1446. return undef;
  1447. }
  1448. if($cmd eq "events") {
  1449. # see https://forum.fhem.de/index.php/topic,46608.msg397309.html#msg397309 for ideas
  1450. # get myCalendar events filter:mode=alarm|start|upcoming format=custom:{ sprintf("...") } select:series=next,max=8,from=-3d,to=10d
  1451. # attr myCalendar defaultFormat <format>
  1452. my @texts;
  1453. my @events= Calendar_GetEvents($hash, $t, undef, undef);
  1454. foreach my $event (@events) {
  1455. push @texts, $event->asFull();
  1456. }
  1457. return "" if($#texts<0);
  1458. return join("\n", @texts);
  1459. }
  1460. my @cmds2= qw/text full summary location description categories alarm start end uid debug/;
  1461. if($cmd ~~ @cmds2) {
  1462. return "argument is missing" if($#a < 2);
  1463. my $filter= $a[2];
  1464. # $reading is alarm, all, changed, start, end, upcoming
  1465. my $filterref;
  1466. my $param= undef;
  1467. my $keeppos= 3;
  1468. if($filter eq "changed") {
  1469. $filterref= \&filter_changed;
  1470. } elsif($filter eq "alarm") {
  1471. $filterref= \&filter_alarm;
  1472. } elsif($filter eq "start") {
  1473. $filterref= \&filter_start;
  1474. } elsif($filter eq "end") {
  1475. $filterref= \&filter_end;
  1476. } elsif($filter eq "upcoming") {
  1477. $filterref= \&filter_upcoming;
  1478. } elsif($filter =~ /^uid=(.+)$/) {
  1479. $filterref= \&filter_uids;
  1480. $param= $1;
  1481. } elsif($filter =~ /^mode=(.+)$/) {
  1482. $filterref= \&filter_modes;
  1483. $param= $1;
  1484. } elsif(($filter =~ /^mode\w+$/) and (defined($hash->{READINGS}{$filter}))) {
  1485. #main::Debug "apply filter_reading";
  1486. $filterref= \&filter_reading;
  1487. my @uids= split(";", $hash->{READINGS}{$filter}{VAL});
  1488. $param= \@uids;
  1489. } elsif($filter eq "all") {
  1490. $filterref= undef;
  1491. } elsif($filter eq "next") {
  1492. $filterref= \&filter_notend;
  1493. $param= { }; # reference to anonymous (unnamed) empty hash, thus $ in $param
  1494. } else { # everything else is interpreted as uid
  1495. $filterref= \&filter_uid;
  1496. $param= $a[2];
  1497. }
  1498. @events= Calendar_GetEvents($hash, $t, $filterref, $param);
  1499. # special treatment for next
  1500. if($filter eq "next") {
  1501. my %uids; # remember the UIDs
  1502. # the @events are ordered by start time ascending
  1503. # they do contain all events that have not ended
  1504. @events= grep {
  1505. my $seen= defined($uids{$_->uid()});
  1506. $uids{$_->uid()}= 1;
  1507. not $seen;
  1508. } @events;
  1509. }
  1510. my @texts;
  1511. if(@events) {
  1512. foreach my $event (sort { $a->start() <=> $b->start() } @events) {
  1513. push @texts, $event->uid() if $cmd eq "uid";
  1514. push @texts, $event->asText() if $cmd eq "text";
  1515. push @texts, $event->asFull() if $cmd eq "full";
  1516. push @texts, $event->asDebug() if $cmd eq "debug";
  1517. push @texts, $event->summary() if $cmd eq "summary";
  1518. push @texts, $event->location() if $cmd eq "location";
  1519. push @texts, $event->description() if $cmd eq "description";
  1520. push @texts, $event->categories() if $cmd eq "categories";
  1521. push @texts, $event->alarmTime() if $cmd eq "alarm";
  1522. push @texts, $event->startTime() if $cmd eq "start";
  1523. push @texts, $event->endTime() if $cmd eq "end";
  1524. }
  1525. }
  1526. if(defined($a[$keeppos])) {
  1527. my $keep= $a[$keeppos];
  1528. return "Argument $keep is not a number." unless($keep =~ /\d+/);
  1529. $keep= $#texts+1 if($keep> $#texts);
  1530. splice @texts, $keep if($keep>= 0);
  1531. }
  1532. return "" if($#texts<0);
  1533. return join("\n", @texts);
  1534. } elsif($cmd eq "vevents") {
  1535. my %vevents= %{$hash->{".fhem"}{vevents}};
  1536. my $s= "";
  1537. foreach my $key (sort {$a<=>$b} keys %vevents) {
  1538. $s .= "$key: ";
  1539. $s .= $vevents{$key}->asString();
  1540. $s .= "\n";
  1541. }
  1542. return $s;
  1543. } elsif($cmd eq "vcalendar") {
  1544. return undef unless(defined($hash->{".fhem"}{iCalendar}));
  1545. return $hash->{".fhem"}{iCalendar}
  1546. } elsif($cmd eq "find") {
  1547. return "argument is missing" if($#a != 2);
  1548. my $regexp= $a[2];
  1549. my %vevents= %{$hash->{".fhem"}{vevents}};
  1550. my %uids;
  1551. foreach my $id (keys %vevents) {
  1552. my $v= $vevents{$id};
  1553. my @events= @{$v->{events}};
  1554. if(@events) {
  1555. eval {
  1556. if($events[0]->summary() =~ m/$regexp/) {
  1557. $uids{$events[0]->uid()}= 1; #
  1558. }
  1559. }
  1560. }
  1561. Log3($hash, 2, "Calendar " . $hash->{NAME} .
  1562. ": The regular expression $regexp caused a problem: $@") if($@);
  1563. }
  1564. return join(";", keys %uids);
  1565. } else {
  1566. return "Unknown argument $cmd, choose one of update:noArg reload:noArg find text full summary location description categories alarm start end vcalendar:noArg vevents:noArg";
  1567. }
  1568. }
  1569. ###################################
  1570. sub Calendar_Wakeup($$) {
  1571. my ($hash, $removeall) = @_;
  1572. Log3 $hash, 4, "Calendar " . $hash->{NAME} . ": Wakeup";
  1573. my $t= time(); # baseline
  1574. # we could arrive here 1 second before nextWakeTs for unknown reasons
  1575. use constant delta => 5; # avoid waking up again in a few seconds
  1576. if($t>= $hash->{".fhem"}{nxtUpdtTs} - delta) {
  1577. # GetUpdate does CheckTimes and RearmTimer asynchronously
  1578. Calendar_GetUpdate($hash, $t, $removeall);
  1579. } else {
  1580. Calendar_CheckTimes($hash, $t);
  1581. Calendar_RearmTimer($hash, $t);
  1582. }
  1583. }
  1584. ###################################
  1585. sub Calendar_RearmTimer($$) {
  1586. my ($hash, $t) = @_;
  1587. #main::Debug "RearmTimer now " . FmtDateTime($t);
  1588. my $nt= $hash->{".fhem"}{nxtUpdtTs};
  1589. #main::Debug "RearmTimer next update " . FmtDateTime($nt);
  1590. # find next event
  1591. my %vevents= %{$hash->{".fhem"}{vevents}};
  1592. foreach my $uid (keys %vevents) {
  1593. my $v= $vevents{$uid};
  1594. foreach my $e (@{$v->{events}}) {
  1595. my $et= $e->nextTime($t);
  1596. # we only consider times in the future to avoid multiple
  1597. # invocations for calendar events with the event time
  1598. $nt= $et if(defined($et) && ($et< $nt) && ($et > $t));
  1599. }
  1600. }
  1601. $hash->{".fhem"}{nextWakeTs}= $nt;
  1602. $hash->{".fhem"}{nextWake}= FmtDateTime($nt);
  1603. #main::Debug "RearmTimer for " . $hash->{".fhem"}{nextWake};
  1604. readingsSingleUpdate($hash, "nextWakeup", $hash->{".fhem"}{nextWake}, 1);
  1605. if($nt< $t) { $nt= $t+1 }; # sanity check / do not wake-up at or before the same second
  1606. InternalTimer($nt, "Calendar_Wakeup", $hash, 0) ;
  1607. }
  1608. sub Calendar_DisarmTimer($) {
  1609. my ($hash)= @_;
  1610. RemoveInternalTimer($hash);
  1611. }
  1612. #
  1613. ###################################
  1614. sub Calendar_GetSecondsFromTimeSpec($) {
  1615. my ($tspec) = @_;
  1616. # days
  1617. if($tspec =~ m/^([0-9]+)d$/) {
  1618. return ("", $1*86400);
  1619. }
  1620. # seconds
  1621. if($tspec =~ m/^[0-9]+s?$/) {
  1622. return ("", $tspec);
  1623. }
  1624. # D:HH:MM:SS
  1625. if($tspec =~ m/^([0-9]+):([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/) {
  1626. return ("", $4+60*($3+60*($2+24*$1)));
  1627. }
  1628. # HH:MM:SS
  1629. if($tspec =~ m/^([0-9]+):([0-5][0-9]):([0-5][0-9])$/) { # HH:MM:SS
  1630. return ("", $3+60*($2+(60*$1)));
  1631. }
  1632. # HH:MM
  1633. if($tspec =~ m/^([0-9]+):([0-5][0-9])$/) {
  1634. return ("", 60*($2+60*$1));
  1635. }
  1636. return ("Wrong time specification $tspec", undef);
  1637. }
  1638. ###################################
  1639. # Filters
  1640. sub filter_modes($$) {
  1641. my ($event,$regex)= @_;
  1642. my $hit;
  1643. eval { $hit= ($event->getMode() =~ $regex); };
  1644. return 0 if($@);
  1645. return $hit ? 1 : 0;
  1646. }
  1647. sub filter_uids($$) {
  1648. my ($event,$regex)= @_;
  1649. my $hit;
  1650. eval { $hit= ($event->uid() =~ $regex); };
  1651. return 0 if($@);
  1652. return $hit ? 1 : 0;
  1653. }
  1654. sub filter_changed($) {
  1655. my ($event)= @_;
  1656. return $event->modeChanged();
  1657. }
  1658. sub filter_alarm($) {
  1659. my ($event)= @_;
  1660. return $event->getMode() eq "alarm" ? 1 : 0;
  1661. }
  1662. sub filter_start($) {
  1663. my ($event)= @_;
  1664. return $event->getMode() eq "start" ? 1 : 0;
  1665. }
  1666. sub filter_end($) {
  1667. my ($event)= @_;
  1668. return $event->getMode() eq "end" ? 1 : 0;
  1669. }
  1670. sub filter_notend($) {
  1671. my ($event)= @_;
  1672. return $event->getMode() eq "end" ? 0 : 1;
  1673. }
  1674. sub filter_upcoming($) {
  1675. my ($event)= @_;
  1676. return $event->getMode() eq "upcoming" ? 1 : 0;
  1677. }
  1678. sub filter_uid($$) {
  1679. my ($event, $param)= @_;
  1680. return $event->uid() eq "$param" ? 1 : 0;
  1681. }
  1682. sub filter_reading($$) {
  1683. my ($event, $param)= @_;
  1684. my @uids= @{$param};
  1685. #foreach my $u (@uids) { main::Debug "UID $u"; }
  1686. my $uid= $event->uid();
  1687. #main::Debug "SUCHE $uid";
  1688. #main::Debug "GREP: " . grep(/^$uid$/, @uids);
  1689. return grep(/^$uid$/, @uids);
  1690. }
  1691. ###################################
  1692. sub Calendar_GetEvents($$$$) {
  1693. my ($hash, $t, $filterref, $param)= @_;
  1694. my $name= $hash->{NAME};
  1695. my @result= ();
  1696. # time window
  1697. my ($error, $t1, $t2)= (undef, undef, undef);
  1698. my $hideOlderThan= AttrVal($name, "hideOlderThan", undef);
  1699. my $hideLaterThan= AttrVal($name, "hideLaterThan", undef);
  1700. # start of time window
  1701. if(defined($hideOlderThan)) {
  1702. ($error, $t1)= Calendar_GetSecondsFromTimeSpec($hideOlderThan);
  1703. if($error) {
  1704. Log3 $hash, 2, "$name: attribute hideOlderThan: $error";
  1705. } else {
  1706. $t1= $t- $t1;
  1707. }
  1708. }
  1709. # end of time window
  1710. if(defined($hideLaterThan)) {
  1711. ($error, $t2)= Calendar_GetSecondsFromTimeSpec($hideLaterThan);
  1712. if($error) {
  1713. Log3 $hash, 2, "$name: attribute hideLaterThan: $error";
  1714. } else {
  1715. $t2= $t+ $t2;
  1716. }
  1717. }
  1718. # get and filter events
  1719. my %vevents= %{$hash->{".fhem"}{vevents}};
  1720. foreach my $id (keys %vevents) {
  1721. my $v= $vevents{$id};
  1722. my @events= @{$v->{events}};
  1723. foreach my $event (@events) {
  1724. if(defined($filterref)) {
  1725. next unless(&$filterref($event, $param));
  1726. }
  1727. if(defined($t1)) { next if(defined($event->end()) && $event->end() < $t1); }
  1728. if(defined($t2)) { next if(defined($event->start()) && $event->start() > $t2); }
  1729. push @result, $event;
  1730. }
  1731. }
  1732. return sort { $a->start() <=> $b->start() } @result;
  1733. }
  1734. ###################################
  1735. sub Calendar_GetUpdate($$$) {
  1736. my ($hash, $t, $removeall) = @_;
  1737. my $name= $hash->{NAME};
  1738. $hash->{".fhem"}{lstUpdtTs}= $t;
  1739. $hash->{".fhem"}{lastUpdate}= FmtDateTime($t);
  1740. my $nut= $t+ $hash->{".fhem"}{interval};
  1741. $hash->{".fhem"}{nxtUpdtTs}= $nut;
  1742. $hash->{".fhem"}{nextUpdate}= FmtDateTime($nut);
  1743. #main::Debug "Getting update now: " . $hash->{".fhem"}{lastUpdate};
  1744. #main::Debug "Next Update is at : " . $hash->{".fhem"}{nextUpdate};
  1745. # If update is disable, shortcut to time checking and rearming timer.
  1746. # Why is this here and not in Calendar_Wakeup? Because the next update time needs to be set
  1747. if(AttrVal($hash->{NAME},"update","") eq "none") {
  1748. Calendar_CheckTimes($hash, $t);
  1749. Calendar_RearmTimer($hash, $t);
  1750. return;
  1751. }
  1752. Log3 $hash, 4, "Calendar $name: Updating...";
  1753. my $type = $hash->{".fhem"}{type};
  1754. my $url= $hash->{".fhem"}{url};
  1755. my $errmsg= "";
  1756. my $ics;
  1757. if($type eq "url") {
  1758. my $SSLVerify= AttrVal($name, "SSLVerify", undef);
  1759. my $SSLArgs= { };
  1760. if(defined($SSLVerify)) {
  1761. eval "use IO::Socket::SSL";
  1762. if($@) {
  1763. Log3 $hash, 2, $@;
  1764. } else {
  1765. my $SSLVerifyMode= eval("$SSLVerify ? SSL_VERIFY_PEER : SSL_VERIFY_NONE");
  1766. Log3 $hash, 5, "SSL verify mode set to $SSLVerifyMode";
  1767. $SSLArgs= { SSL_verify_mode => $SSLVerifyMode };
  1768. }
  1769. }
  1770. HttpUtils_NonblockingGet({
  1771. url => $url,
  1772. hideurl => 1,
  1773. noshutdown => 1,
  1774. hash => $hash,
  1775. timeout => 30,
  1776. type => 'caldata',
  1777. removeall => $removeall,
  1778. sslargs => $SSLArgs,
  1779. t => $t,
  1780. callback => \&Calendar_ProcessUpdate,
  1781. });
  1782. Log3 $hash, 4, "Calendar $name: Getting data from URL <hidden>"; # $url
  1783. } elsif($type eq "file") {
  1784. Log3 $hash, 4, "Calendar $name: Getting data from file $url";
  1785. if(open(ICSFILE, $url)) {
  1786. while(<ICSFILE>) {
  1787. $ics .= $_;
  1788. }
  1789. close(ICSFILE);
  1790. my $paramhash;
  1791. $paramhash->{hash} = $hash;
  1792. $paramhash->{removeall} = $removeall;
  1793. $paramhash->{t} = $t;
  1794. $paramhash->{type} = 'caldata';
  1795. Calendar_ProcessUpdate($paramhash, '', $ics);
  1796. return undef;
  1797. } else {
  1798. Log3 $hash, 1, "Calendar $name: Could not open file $url";
  1799. readingsSingleUpdate($hash, "state", "error (could not open file)", 1);
  1800. return 0;
  1801. }
  1802. } else {
  1803. # this case never happens by virtue of _Define, so just
  1804. die "Software Error";
  1805. }
  1806. }
  1807. ###################################
  1808. sub Calendar_ProcessUpdate($$$) {
  1809. my ($param, $errmsg, $ics) = @_;
  1810. my $hash = $param->{hash};
  1811. my $name = $hash->{NAME};
  1812. my $removeall = $param->{removeall};
  1813. my $t= $param->{t};
  1814. if(exists($hash->{".fhem"}{subprocess})) {
  1815. Log3 $hash, 2, "Calendar $name: update in progress, process aborted.";
  1816. return 0;
  1817. }
  1818. # not for the developer:
  1819. # we must be sure that code that starts here ends with Calendar_CheckAndRearm()
  1820. # no matter what branch is taken in the following
  1821. delete($hash->{".fhem"}{iCalendar});
  1822. if($errmsg) {
  1823. Log3 $name, 1, "Calendar $name: retrieval failed with error message $errmsg";
  1824. readingsSingleUpdate($hash, "state", "error ($errmsg)", 1);
  1825. } else {
  1826. readingsSingleUpdate($hash, "state", "retrieved", 1);
  1827. }
  1828. if($errmsg or !defined($ics) or ("$ics" eq "") ) {
  1829. Log3 $hash, 1, "Calendar $name: retrieved no or empty data";
  1830. readingsSingleUpdate($hash, "state", "error (no or empty data)", 1);
  1831. Calendar_CheckAndRearm($hash, $t);
  1832. } else {
  1833. $hash->{".fhem"}{iCalendar}= $ics; # the plain text iCalendar
  1834. $hash->{".fhem"}{t}= $t;
  1835. $hash->{".fhem"}{removeall}= $removeall;
  1836. if(AttrVal($name, "update", "sync") eq "async") {
  1837. Calendar_AsynchronousUpdateCalendar($hash);
  1838. } else {
  1839. Calendar_SynchronousUpdateCalendar($hash);
  1840. }
  1841. }
  1842. }
  1843. sub Calendar_Cleanup($) {
  1844. my ($hash)= @_;
  1845. delete($hash->{".fhem"}{t});
  1846. delete($hash->{".fhem"}{removeall});
  1847. delete($hash->{".fhem"}{serialized});
  1848. delete($hash->{".fhem"}{subprocess});
  1849. my $name= $hash->{NAME};
  1850. delete($hash->{".fhem"}{iCalendar}) if(AttrVal($name,"removevcalendar",0));
  1851. Log3 $hash, 4, "Calendar $name: process ended.";
  1852. }
  1853. sub Calendar_CheckAndRearm($) {
  1854. my ($hash)= @_;
  1855. my $t= $hash->{".fhem"}{t};
  1856. Calendar_CheckTimes($hash, $t);
  1857. Calendar_RearmTimer($hash, $t);
  1858. }
  1859. sub Calendar_SynchronousUpdateCalendar($) {
  1860. my ($hash) = @_;
  1861. my $name= $hash->{NAME};
  1862. Log3 $hash, 4, "Calendar $name: parsing data synchronously";
  1863. my $ical= Calendar_ParseICS($hash->{".fhem"}{iCalendar});
  1864. Calendar_UpdateCalendar($hash, $ical);
  1865. Calendar_CheckAndRearm($hash);
  1866. Calendar_Cleanup($hash);
  1867. }
  1868. use constant POLLINTERVAL => 1;
  1869. sub Calendar_AsynchronousUpdateCalendar($) {
  1870. require "SubProcess.pm";
  1871. my ($hash) = @_;
  1872. my $name= $hash->{NAME};
  1873. my $subprocess= SubProcess->new({ onRun => \&Calendar_OnRun });
  1874. $subprocess->{ics}= $hash->{".fhem"}{iCalendar};
  1875. my $pid= $subprocess->run();
  1876. if(!defined($pid)) {
  1877. Log3 $hash, 1, "Calendar $name: Cannot parse asynchronously";
  1878. Calendar_CheckAndRearm($hash);
  1879. Calendar_Cleanup($hash);
  1880. return undef;
  1881. }
  1882. Log3 $hash, 4, "Calendar $name: parsing data asynchronously (PID= $pid)";
  1883. $hash->{".fhem"}{subprocess}= $subprocess;
  1884. $hash->{".fhem"}{serialized}= "";
  1885. InternalTimer(gettimeofday()+POLLINTERVAL, "Calendar_PollChild", $hash, 0);
  1886. # go and do your thing while the timer polls and waits for the child to terminate
  1887. Log3 $hash, 5, "Calendar $name: control passed back to main loop.";
  1888. }
  1889. sub Calendar_OnRun() {
  1890. # This routine runs in a process separate from the main process.
  1891. my $subprocess= shift;
  1892. my $ical= Calendar_ParseICS($subprocess->{ics});
  1893. my $serialized= freeze $ical;
  1894. $subprocess->writeToParent($serialized);
  1895. }
  1896. sub Calendar_PollChild($) {
  1897. my ($hash)= @_;
  1898. my $name= $hash->{NAME};
  1899. my $subprocess= $hash->{".fhem"}{subprocess};
  1900. my $data= $subprocess->readFromChild();
  1901. if(!defined($data)) {
  1902. Log3 $name, 4, "Calendar $name: still waiting (". $subprocess->{lasterror} .").";
  1903. InternalTimer(gettimeofday()+POLLINTERVAL, "Calendar_PollChild", $hash, 0);
  1904. return;
  1905. } else {
  1906. Log3 $name, 4, "Calendar $name: got result from asynchronous parsing.";
  1907. $subprocess->wait();
  1908. Log3 $name, 4, "Calendar $name: asynchronous parsing finished.";
  1909. my $ical= thaw($data);
  1910. Calendar_UpdateCalendar($hash, $ical);
  1911. Calendar_CheckAndRearm($hash);
  1912. Calendar_Cleanup($hash);
  1913. }
  1914. }
  1915. sub Calendar_ParseICS($) {
  1916. #main::Debug "Calendar $name: parsing data";
  1917. my ($ics)= @_;
  1918. my ($error, $state)= (undef, "");
  1919. # we parse the calendar into a recursive ICal::Entry structure
  1920. my $ical= ICal::Entry->new("root");
  1921. $ical->parse($ics);
  1922. #main::Debug "*** Result:";
  1923. #main::Debug $ical->asString();
  1924. my $numentries= scalar @{$ical->{entries}};
  1925. if($numentries<= 0) {
  1926. eval { require Compress::Zlib; };
  1927. if($@) {
  1928. $error= "data not in ICal format; maybe gzip data, but cannot load Compress::Zlib";
  1929. }
  1930. else {
  1931. $ics = Compress::Zlib::memGunzip($ics);
  1932. $ical->parse($ics);
  1933. $numentries= scalar @{$ical->{entries}};
  1934. if($numentries<= 0) {
  1935. $error= "data not in ICal format; even not gzip data";
  1936. } else {
  1937. $state= "parsed (gzip data)";
  1938. }
  1939. }
  1940. } else {
  1941. $state= "parsed";
  1942. };
  1943. $ical->{error}= $error;
  1944. $ical->{state}= $state;
  1945. return $ical;
  1946. }
  1947. ###################################
  1948. sub Calendar_UpdateCalendar($$) {
  1949. my ($hash, $ical)= @_;
  1950. # *******************************
  1951. # *** Step 1 Digest Parser Result
  1952. # *******************************
  1953. my $name= $hash->{NAME};
  1954. my $error= $ical->{error};
  1955. my $state= $ical->{state};
  1956. if(defined($error)) {
  1957. Log3 $hash, 2, "Calendar $name: error ($error)";
  1958. readingsSingleUpdate($hash, "state", "error ($error)", 1);
  1959. return 0;
  1960. } else {
  1961. readingsSingleUpdate($hash, "state", $state, 1);
  1962. }
  1963. my $t= $hash->{".fhem"}{t};
  1964. my $removeall= $hash->{".fhem"}{removeall};
  1965. my @entries= @{$ical->{entries}};
  1966. my $root= @{$ical->{entries}}[0];
  1967. my $calname= "?";
  1968. if($root->{type} ne "VCALENDAR") {
  1969. Log3 $hash, 1, "Calendar $name: root element is not VCALENDAR";
  1970. readingsSingleUpdate($hash, "state", "error (root element is not VCALENDAR)", 1);
  1971. return 0;
  1972. } else {
  1973. $calname= $root->value("X-WR-CALNAME");
  1974. }
  1975. # *********************
  1976. # *** Step 2 Merging
  1977. # *********************
  1978. Log3 $hash, 4, "Calendar $name: merging data";
  1979. #main::Debug "Calendar $name: merging data";
  1980. # this the hash of VEVENTs that have been created on the previous update
  1981. my %vevents;
  1982. %vevents= %{$hash->{".fhem"}{vevents}} if(!$removeall);
  1983. # the keys to the hash are numbers taken from a sequence
  1984. my $lastid= $hash->{".fhem"}{lastid};
  1985. #
  1986. # 1, 2, 4
  1987. #
  1988. # we first discard all VEVENTs that have been tagged as deleted in the previous run
  1989. # and untag the rest
  1990. foreach my $key (keys %vevents) {
  1991. #main::Debug "Preparing id $key...";
  1992. if($vevents{$key}->isObsolete() ) {
  1993. delete($vevents{$key});
  1994. } else {
  1995. $vevents{$key}->setState("deleted"); # will be changed if record is touched in the next step
  1996. $vevents{$key}->clearCounterpart();
  1997. $vevents{$key}->clearReferences();
  1998. }
  1999. }
  2000. #
  2001. # 3
  2002. #
  2003. # we now run through the list of freshly retrieved VEVENTs and merge them into
  2004. # the hash
  2005. my ($n, $nknown, $nmodified, $nnew, $nchanged)= (0,0,0,0,0,0);
  2006. # this code is O(n^2) and stalls FHEM for large numbers of VEVENTs
  2007. # to speed up the code we first build a reverse hash (UID,RECURRENCE-ID) -> id
  2008. sub kf($) { my ($v)= @_; return $v->value("UID").$v->valueOrDefault("RECURRENCE-ID","") }
  2009. my %lookup;
  2010. foreach my $id (keys %vevents) {
  2011. my $k= kf($vevents{$id});
  2012. Log3 $hash, 2, "Calendar $name: Duplicate VEVENT" if(defined($lookup{$k}));
  2013. $lookup{$k}= $id;
  2014. #main::Debug "Adding event $id with key $k to lookup hash.";
  2015. }
  2016. # start of time window for cutoff
  2017. my $cutoffOlderThan = AttrVal($name, "cutoffOlderThan", undef);
  2018. my $cutoffT= 0;
  2019. my $cutoff;
  2020. if(defined($cutoffOlderThan)) {
  2021. ($error, $cutoffT)= Calendar_GetSecondsFromTimeSpec($cutoffOlderThan);
  2022. if($error) {
  2023. Log3 $hash, 2, "$name: attribute cutoffOlderThan: $error";
  2024. };
  2025. $cutoff= $t- $cutoffT;
  2026. }
  2027. foreach my $v (grep { $_->{type} eq "VEVENT" } @{$root->{entries}}) {
  2028. # totally skip outdated calendar entries
  2029. next if(
  2030. defined($cutoffOlderThan) &&
  2031. $v->hasKey("DTEND") &&
  2032. $v->tm($v->value("DTEND")) < $cutoff &&
  2033. !$v->hasKey("RRULE")
  2034. );
  2035. #main::Debug "Merging " . $v->asString();
  2036. my $found= 0;
  2037. my $added= 0; # flag to prevent multiple additions
  2038. $n++;
  2039. # some braindead calendars provide no UID - add one:
  2040. $v->addproperty(sprintf("UID:synthetic-%06d", $v->{ln}))
  2041. unless($v->hasKey("UID") or !defined($v->{ln}));
  2042. # look for related records in the old record set
  2043. my $k= kf($v);
  2044. #main::Debug "Looking for event with key $k";
  2045. my $id= $lookup{$k};
  2046. if(defined($id)) {
  2047. my $v0= $vevents{$id};
  2048. #main::Debug "Found $id";
  2049. #
  2050. # same UID and RECURRENCE-ID
  2051. #
  2052. $found++;
  2053. if($v0->sameValue($v, "SEQUENCE")) {
  2054. #
  2055. # and same SEQUENCE
  2056. #
  2057. if($v0->sameValue($v, "LAST-MODIFIED")) {
  2058. #
  2059. # is not modified
  2060. #
  2061. # we only keep the record from the old record set
  2062. $v0->setState("known");
  2063. $nknown++;
  2064. } else {
  2065. #
  2066. # is modified
  2067. #
  2068. # we keep both records
  2069. next if($added);
  2070. $added++;
  2071. $vevents{++$lastid}= $v;
  2072. $v->setState("modified-new");
  2073. $v->setCounterpart($id);
  2074. $v0->setState("modified-old");
  2075. $v0->setCounterpart($lastid);
  2076. $nmodified++;
  2077. }
  2078. } else {
  2079. #
  2080. # and different SEQUENCE
  2081. #
  2082. # we keep both records
  2083. next if($added);
  2084. $added++;
  2085. $vevents{++$lastid}= $v;
  2086. $v->setState("changed-new");
  2087. $v->setCounterpart($id);
  2088. $v0->setState("changed-old");
  2089. $v0->setCounterpart($lastid);
  2090. $nchanged++;
  2091. }
  2092. }
  2093. if(!$found) {
  2094. $v->setState("new");
  2095. $vevents{++$lastid}= $v;
  2096. $added++;
  2097. $nnew++;
  2098. }
  2099. }
  2100. #
  2101. # Cross-referencing series
  2102. #
  2103. # this code is O(n^2) and stalls FHEM for large numbers of VEVENTs
  2104. # to speed up the code we build a hash of a hash UID => {id => VEVENT}
  2105. %lookup= ();
  2106. foreach my $id (keys %vevents) {
  2107. my $v= $vevents{$id};
  2108. $lookup{$v->value("UID")}{$id}= $v unless($v->isObsolete);
  2109. }
  2110. for my $idref (values %lookup) {
  2111. my %vs= %{$idref};
  2112. foreach my $v (values %vs) {
  2113. foreach my $id (keys %vs) {
  2114. push @{$v->references()}, $id unless($vs{$id} eq $v);
  2115. }
  2116. }
  2117. }
  2118. # foreach my $id (keys %vevents) {
  2119. # my $v= $vevents{$id};
  2120. # next if($v->isObsolete());
  2121. # foreach my $id0 (keys %vevents) {
  2122. # next if($id==$id0);
  2123. # my $v0= $vevents{$id0};
  2124. # next if($v0->isObsolete());
  2125. # push @{$v0->references()}, $id if($v->sameValue($v0, "UID"));
  2126. # }
  2127. # }
  2128. Log3 $hash, 4, "Calendar $name: $n records processed, $nnew new, ".
  2129. "$nknown known, $nmodified modified, $nchanged changed.";
  2130. # save the VEVENTs hash and lastid
  2131. $hash->{".fhem"}{vevents}= \%vevents;
  2132. $hash->{".fhem"}{lastid}= $lastid;
  2133. # *********************
  2134. # *** Step 3 Events
  2135. # *********************
  2136. #
  2137. # Recreating the events
  2138. #
  2139. Log3 $hash, 4, "Calendar $name: creating calendar events";
  2140. #main::Debug "Calendar $name: creating calendar events";
  2141. foreach my $id (keys %vevents) {
  2142. my $v= $vevents{$id};
  2143. if($v->isObsolete()) {
  2144. $v->clearEvents();
  2145. next;
  2146. }
  2147. my $onCreateEvent= AttrVal($name, "onCreateEvent", undef);
  2148. if($v->hasChanged() or !$v->numEvents()) {
  2149. #main::Debug "createEvents";
  2150. $v->createEvents($t, $onCreateEvent, %vevents);
  2151. }
  2152. }
  2153. #main::Debug "*** Result:";
  2154. #main::Debug $ical->asString();
  2155. # *********************
  2156. # *** Step 4 Readings
  2157. # *********************
  2158. readingsBeginUpdate($hash);
  2159. readingsBulkUpdate($hash, "calname", $calname);
  2160. readingsBulkUpdate($hash, "lastUpdate", $hash->{".fhem"}{lastUpdate});
  2161. readingsBulkUpdate($hash, "nextUpdate", $hash->{".fhem"}{nextUpdate});
  2162. readingsEndUpdate($hash, 1); # DoTrigger, because sub is called by a timer instead of dispatch
  2163. return 1;
  2164. }
  2165. ###################################
  2166. sub Calendar_CheckTimes($$) {
  2167. my ($hash, $t) = @_;
  2168. Log3 $hash, 4, "Calendar " . $hash->{NAME} . ": Checking times...";
  2169. #
  2170. # determine the uids of all events and their most interesting mode
  2171. #
  2172. my %priority= (
  2173. "none" => 0,
  2174. "end" => 1,
  2175. "upcoming" => 2,
  2176. "alarm" => 3,
  2177. "start" => 4,
  2178. );
  2179. my %mim; # most interesting mode per id
  2180. my %changed; # changed per id
  2181. my %vevents= %{$hash->{".fhem"}{vevents}};
  2182. foreach my $uid (keys %vevents) {
  2183. my $v= $vevents{$uid};
  2184. foreach my $e (@{$v->{events}}) {
  2185. my $uid= $e->uid();
  2186. my $mode= defined($mim{$uid}) ? $mim{$uid} : "none";
  2187. if($e->isEnded($t)) {
  2188. $e->setMode("end");
  2189. } elsif($e->isUpcoming($t)) {
  2190. $e->setMode("upcoming");
  2191. } elsif($e->isStarted($t)) {
  2192. $e->setMode("start");
  2193. } elsif($e->isAlarmed($t)) {
  2194. $e->setMode("alarm");
  2195. }
  2196. if($priority{$e->getMode()} > $priority{$mode}) {
  2197. $mim{$uid}= $e->getMode();
  2198. }
  2199. $changed{$uid}= 0 unless(defined($changed{$uid}));
  2200. # create the FHEM event
  2201. if($e->modeChanged()) {
  2202. $changed{$uid}= 1;
  2203. addEvent($hash, "changed: $uid " . $e->getMode());
  2204. addEvent($hash, $e->getMode() . ": $uid ");
  2205. }
  2206. }
  2207. }
  2208. #
  2209. # determine the uids of events in certain modes
  2210. #
  2211. my @changed;
  2212. my @upcoming;
  2213. my @start;
  2214. my @started;
  2215. my @alarm;
  2216. my @alarmed;
  2217. my @end;
  2218. my @ended;
  2219. foreach my $uid (keys %mim) {
  2220. push @changed, $uid if($changed{$uid});
  2221. push @upcoming, $uid if($mim{$uid} eq "upcoming");
  2222. if($mim{$uid} eq "alarm") {
  2223. push @alarm, $uid;
  2224. push @alarmed, $uid if($changed{$uid});
  2225. }
  2226. if($mim{$uid} eq "start") {
  2227. push @start, $uid;
  2228. push @started, $uid if($changed{$uid});
  2229. }
  2230. if($mim{$uid} eq "end") {
  2231. push @end, $uid;
  2232. push @ended, $uid if($changed{$uid});
  2233. }
  2234. }
  2235. #sub uniq { my %uids; return grep {!$uids{$_->uid()}++} @_; }
  2236. #@allevents= sort { $a->start() <=> $b->start() } uniq(@allevents);
  2237. #foreach my $event (@allevents) {
  2238. # main::Debug $event->asFull();
  2239. #}
  2240. sub es(@) {
  2241. my (@events)= @_;
  2242. return join(";", @events);
  2243. }
  2244. sub rbu($$$) {
  2245. my ($hash, $reading, $value)= @_;
  2246. if(!defined($hash->{READINGS}{$reading}) or
  2247. ($hash->{READINGS}{$reading}{VAL} ne $value)) {
  2248. readingsBulkUpdate($hash, $reading, $value);
  2249. }
  2250. }
  2251. # clears all events in CHANGED, thus must be called first
  2252. readingsBeginUpdate($hash);
  2253. # we update the readings
  2254. rbu($hash, "modeUpcoming", es(@upcoming));
  2255. rbu($hash, "modeAlarm", es(@alarm));
  2256. rbu($hash, "modeAlarmed", es(@alarmed));
  2257. rbu($hash, "modeAlarmOrStart", es(@alarm,@start));
  2258. rbu($hash, "modeChanged", es(@changed));
  2259. rbu($hash, "modeStart", es(@start));
  2260. rbu($hash, "modeStarted", es(@started));
  2261. rbu($hash, "modeEnd", es(@end));
  2262. rbu($hash, "modeEnded", es(@ended));
  2263. readingsBulkUpdate($hash, "state", "triggered");
  2264. # DoTrigger, because sub is called by a timer instead of dispatch
  2265. readingsEndUpdate($hash, 1);
  2266. }
  2267. #####################################
  2268. # filter:next count:3
  2269. sub CalendarAsHtml($;$) {
  2270. my ($d,$o) = @_;
  2271. $d = "<none>" if(!$d);
  2272. return "$d is not a Calendar instance<br>"
  2273. if(!$defs{$d} || $defs{$d}{TYPE} ne "Calendar");
  2274. my $l= Calendar_Get($defs{$d}, split("[ \t]+", "- text $o"));
  2275. my @lines= split("\n", $l);
  2276. my $ret = '<table class="calendar">';
  2277. foreach my $line (@lines) {
  2278. my @fields= split(" ", $line, 3);
  2279. $ret.= sprintf("<tr><td>%s</td><td>%s</td><td>%s</td></tr>", @fields);
  2280. }
  2281. $ret .= '</table>';
  2282. return $ret;
  2283. }
  2284. #####################################
  2285. 1;
  2286. =pod
  2287. =item device
  2288. =item summary handles calendar events from iCal file or URL
  2289. =item summary_DE handhabt Kalendertermine aus iCal-Dateien und URLs
  2290. =begin html
  2291. <a name="Calendar"></a>
  2292. <h3>Calendar</h3>
  2293. <ul>
  2294. <br>
  2295. <a name="Calendardefine"></a>
  2296. <b>Define</b><br><br>
  2297. <ul>
  2298. <code>define &lt;name&gt; Calendar ical url &lt;URL&gt; [&lt;interval&gt;]</code><br>
  2299. <code>define &lt;name&gt; Calendar ical file &lt;FILENAME&gt; [&lt;interval&gt;]</code><br>
  2300. <br>
  2301. Defines a calendar device.<br><br>
  2302. A calendar device periodically gathers calendar events from the source calendar at the given URL or from a file.
  2303. The file must be in ICal format.<br><br>
  2304. If the URL
  2305. starts with <code>https://</code>, the perl module IO::Socket::SSL must be installed
  2306. (use <code>cpan -i IO::Socket::SSL</code>).<br><br>
  2307. Note for users of Google Calendar: You can literally use the private ICal URL from your Google Calendar.
  2308. If your Google Calendar
  2309. URL starts with <code>https://</code> and the perl module IO::Socket::SSL is not installed on your system, you can
  2310. replace it by <code>http://</code> if and only if there is no redirection to the <code>https://</code> URL.
  2311. Check with your browser first if unsure.<br><br>
  2312. The optional parameter <code>interval</code> is the time between subsequent updates
  2313. in seconds. It defaults to 3600 (1 hour).<br><br>
  2314. Examples:
  2315. <pre>
  2316. define MyCalendar Calendar ical url https://www.google.com&shy;/calendar/ical/john.doe%40example.com&shy;/private-foo4711/basic.ics
  2317. define YourCalendar Calendar ical url http://www.google.com&shy;/calendar/ical/jane.doe%40example.com&shy;/private-bar0815/basic.ics 86400
  2318. define SomeCalendar Calendar ical file /home/johndoe/calendar.ics
  2319. </pre>
  2320. </ul>
  2321. <br>
  2322. <a name="Calendarset"></a>
  2323. <b>Set </b><br><br>
  2324. <ul>
  2325. <code>set &lt;name&gt; update</code><br>
  2326. Forces the retrieval of the calendar from the URL. The next automatic retrieval is scheduled to occur <code>interval</code> seconds later.<br><br>
  2327. <code>set &lt;name&gt; reload</code><br>
  2328. Same as <code>update</code> but all calendar events are removed first.<br><br>
  2329. </ul>
  2330. <br>
  2331. <a name="Calendarget"></a>
  2332. <b>Get</b><br><br>
  2333. <ul>
  2334. <code>get &lt;name&gt; update</code><br>
  2335. Same as <code>set &lt;name&gt; update</code><br><br>
  2336. <code>get &lt;name&gt; reload</code><br>
  2337. Same as <code>set &lt;name&gt; update</code><br><br>
  2338. <code>get &lt;name&gt; &lt;format&gt; &lt;filter&gt; [&lt;max&gt;]</code><br>
  2339. Returns, line by line, information on the calendar events in the calendar &lt;name&gt;. The content depends on the
  2340. &lt;format&gt specifier:<br><br>
  2341. <table>
  2342. <tr><th>&lt;format&gt;</th><th>content</th></tr>
  2343. <tr><td>uid</td><td>the UID of the event</td></tr>
  2344. <tr><td>text</td><td>a user-friendly textual representation, best suited for display</td></tr>
  2345. <tr><td>summary</td><td>the content of the summary field (subject, title)</td></tr>
  2346. <tr><td>location</td><td>the content of the location field</td></tr>
  2347. <tr><td>categories</td><td>the content of the categories field</td></tr>
  2348. <tr><td>alarm</td><td>alarm time in human-readable format</td></tr>
  2349. <tr><td>start</td><td>start time in human-readable format</td></tr>
  2350. <tr><td>end</td><td>end time in human-readable format</td></tr>
  2351. <tr><td>categories</td><td>the content of the categories field</td></tr>
  2352. <tr><td>full</td><td>the full state</td></tr>
  2353. <tr><td>debug</td><td>like full with additional information for debugging purposes</td></tr>
  2354. </table><br>
  2355. The &lt;filter&gt; specifier determines the selected subset of calendar events:<br><br>
  2356. <table>
  2357. <tr><th>&lt;filter&gt;</th><th>selection</th></tr>
  2358. <tr><td>mode=&lt;regex&gt;</td><td>all calendar events with mode matching the regular expression &lt;regex&gt</td></tr>
  2359. <tr><td>&lt;mode&gt;</td><td>all calendar events in the mode &lt;mode&gt</td></tr>
  2360. <tr><td>uid=&lt;regex&gt;</td><td>all calendar events identified by UIDs that match the regular expression &lt;regex&gt;.</td></tr>
  2361. <tr><td>&lt;uid&gt;</td><td>all calendar events identified by the UID &lt;uid&gt;</td></tr>
  2362. <tr><td>&lt;reading&gt;</td><td>all calendar events listed in the reading &lt;reading&gt; (modeAlarm, modeAlarmed, modeStart, etc.) - this is deprecated and will be removed in a future version, use mode=&lt;regex&gt; instead.</td></tr>
  2363. <tr><td>all</td><td>all calendar events (past, current and future)</td></tr>
  2364. <tr><td>next</td><td>only calendar events that have not yet ended and among these only the first in a series, best suited for display</td></tr>
  2365. </table><br>
  2366. The <code>mode=&lt;regex&gt;</code> and <code>uid=&lt;regex&gt;</code> filters should be preferred over the
  2367. <code>&lt;mode&gt;</code> and <code>&lt;uid&gt;</code> filters.<br><br>
  2368. The optional parameter <code>&lt;max&gt;</code> limits
  2369. the number of returned lines.<br><br>
  2370. See attributes <code>hideOlderThan</code> and
  2371. <code>hideLaterThan</code> for how to return events within a certain time window.
  2372. Please remember that the global &pm;400 days limits apply.<br><br>
  2373. Examples:<br>
  2374. <code>get MyCalendar text next</code><br>
  2375. <code>get MyCalendar summary uid:435kjhk435googlecom 1</code><br>
  2376. <code>get MyCalendar summary 435kjhk435googlecom 1</code><br>
  2377. <code>get MyCalendar full all</code><br>
  2378. <code>get MyCalendar text mode=alarm|start</code><br>
  2379. <code>get MyCalendar text uid=.*6286.*</code><br>
  2380. <br>
  2381. <code>get &lt;name&gt; find &lt;regexp&gt;</code><br>
  2382. Returns, line by line, the UIDs of all calendar events whose summary matches the regular expression
  2383. &lt;regexp&gt;.<br><br>
  2384. <code>get &lt;name&gt; vcalendar</code><br>
  2385. Returns the calendar in ICal format as retrieved from the source.<br><br>
  2386. <code>get &lt;name&gt; vevents</code><br>
  2387. Returns a list of all VEVENT entries in the calendar with additional information for
  2388. debugging. Only properties that have been kept during processing of the source
  2389. are shown. The list of calendar events created from each VEVENT entry is shown as well
  2390. as the list of calendar events that have been omitted.
  2391. </ul>
  2392. <br>
  2393. <a name="Calendarattr"></a>
  2394. <b>Attributes</b>
  2395. <br><br>
  2396. <ul>
  2397. <li><code>update sync|async|none</code><br>
  2398. If this attribute is not set or if it is set to <code>sync</code>, the processing of
  2399. the calendar is done in the foreground. Large calendars will block FHEM on slow
  2400. systems. If this attribute is set to <code>async</code>, the processing is done in the
  2401. background and FHEM will not block during updates. If this attribute is set to
  2402. <code>none</code>, the calendar will not be updated at all.
  2403. </li><p>
  2404. <li><code>removevcalendar 0|1</code><br>
  2405. If this attribute is set to 1, the vCalendar will be discarded after the processing to reduce the memory consumption of the module.
  2406. A retrieval via <code>get &lt;name&gt; vcalendar</code> is then no longer possible.
  2407. </li><p>
  2408. <li><code>hideOlderThan &lt;timespec&gt;</code><br>
  2409. <code>hideLaterThan &lt;timespec&gt;</code><br><p>
  2410. These attributes limit the list of events shown by
  2411. <code>get &lt;name&gt; full|debug|text|summary|location|alarm|start|end ...</code>.<p>
  2412. The time is specified relative to the current time t. If hideOlderThan is set,
  2413. calendar events that ended before t-hideOlderThan are not shown. If hideLaterThan is
  2414. set, calendar events that will start after t+hideLaterThan are not shown.<p>
  2415. Please note that an action triggered by a change to mode "end" cannot access the calendar event
  2416. if you set hideOlderThan to 0 because the calendar event will already be hidden at that time. Better set
  2417. hideOlderThan to 10.<p>
  2418. <code>&lt;timespec&gt;</code> must have one of the following formats:<br>
  2419. <table>
  2420. <tr><th>format</th><th>description</th><th>example</th></tr>
  2421. <tr><td>SSS</td><td>seconds</td><td>3600</td></tr>
  2422. <tr><td>SSSs</td><td>seconds</td><td>3600s</td></tr>
  2423. <tr><td>HH:MM</td><td>hours:minutes</td><td>02:30</td></tr>
  2424. <tr><td>HH:MM:SS</td><td>hours:minutes:seconds</td><td>00:01:30</td></tr>
  2425. <tr><td>D:HH:MM:SS</td><td>days:hours:minutes:seconds</td><td>122:10:00:00</td></tr>
  2426. <tr><td>DDDd</td><td>days</td><td>100d</td></tr>
  2427. </table></li>
  2428. <p>
  2429. <li><code>cutoffOlderThan &lt;timespec&gt;</code><br>
  2430. This attribute cuts off all non-recurring calendar events that ended a timespan cutoffOlderThan
  2431. before the last update of the calendar. The purpose of setting this attribute is to save memory.
  2432. Such calendar events cannot be accessed at all from FHEM. Calendar events are not cut off if
  2433. they are recurring or if they have no end time (DTEND).
  2434. </li><p>
  2435. <li><code>onCreateEvent &lt;perl-code&gt;</code><br>
  2436. This attribute allows to run the Perl code &lt;perl-code&gt; for every
  2437. calendar event that is created. See section <a href="#CalendarPlugIns">Plug-ins</a> below.
  2438. </li><p>
  2439. <li><code>SSLVerify</code><br>
  2440. This attribute sets the verification mode for the peer certificate for connections secured by
  2441. SSL. Set attribute either to 0 for SSL_VERIFY_NONE (no certificate verification) or
  2442. to 1 for SSL_VERIFY_PEER (certificate verification). Disabling verification is useful
  2443. for local calendar installations (e.g. OwnCloud, NextCloud) without valid SSL certificate.
  2444. </li><p>
  2445. <li><a href="#readingFnAttributes">readingFnAttributes</a></li>
  2446. </ul>
  2447. <br>
  2448. <b>Description</b>
  2449. <ul>
  2450. <br>
  2451. A calendar is a set of calendar events. The calendar events are
  2452. fetched from the source calendar at the given URL on a regular basis.<p>
  2453. A calendar event has a summary (usually the title shown in a visual
  2454. representation of the source calendar), a start time, an end time, and zero, one or more alarm times. In case of multiple alarm times for a calendar event, only the
  2455. earliest alarm time is kept.<p>
  2456. Recurring calendar events (series) are currently supported to an extent:
  2457. FREQ INTERVAL UNTIL COUNT are interpreted, BYMONTHDAY BYMONTH WKST
  2458. are recognized but not interpreted. BYDAY is correctly interpreted for weekly and monthly events.
  2459. The module will get it most likely wrong
  2460. if you have recurring calendar events with unrecognized or uninterpreted keywords.
  2461. Out-of-order events and events excluded from a series (EXDATE) are handled.
  2462. <p>
  2463. Calendar events are created when FHEM is started or when the respective entry in the source
  2464. calendar has changed and the calendar is updated or when the calendar is reloaded with
  2465. <code>get &lt;name&gt; reload</code>.
  2466. Only calendar events within &pm;400 days around the event creation time are created. Consider
  2467. reloading the calendar from time to time to avoid running out of upcoming events. You can use something like <code>define reloadCalendar at +*240:00:00 set MyCalendar reload</code> for that purpose.<p>
  2468. Some dumb calendars do not use LAST-MODIFIED. This may result in modifications in the source calendar
  2469. go unnoticed. Reload the calendar if you experience this issue.<p>
  2470. A calendar event is identified by its UID. The UID is taken from the source calendar.
  2471. All events in a series including out-of-order events habe the same UID.
  2472. All non-alphanumerical characters
  2473. are stripped off the original UID to make your life easier.<p>
  2474. A calendar event can be in one of the following modes:
  2475. <table>
  2476. <tr><td>upcoming</td><td>Neither the alarm time nor the start time of the calendar event is reached.</td></tr>
  2477. <tr><td>alarm</td><td>The alarm time has passed but the start time of the calendar event is not yet reached.</td></tr>
  2478. <tr><td>start</td><td>The start time has passed but the end time of the calendar event is not yet reached.</td></tr>
  2479. <tr><td>end</td><td>The end time of the calendar event has passed.</td></tr>
  2480. </table><br>
  2481. A calendar event transitions from one mode to another immediately when the time for the change has come. This is done by waiting
  2482. for the earliest future time among all alarm, start or end times of all calendar events.
  2483. <p>
  2484. A calendar device has several readings. Except for <code>calname</code>, each reading is a semicolon-separated list of UIDs of
  2485. calendar events that satisfy certain conditions:
  2486. <table>
  2487. <tr><td>calname</td><td>name of the calendar</td></tr>
  2488. <tr><td>modeAlarm</td><td>events in alarm mode</td></tr>
  2489. <tr><td>modeAlarmOrStart</td><td>events in alarm or start mode</td></tr>
  2490. <tr><td>modeAlarmed</td><td>events that have just transitioned from upcoming to alarm mode</td></tr>
  2491. <tr><td>modeChanged</td><td>events that have just changed their mode somehow</td></tr>
  2492. <tr><td>modeEnd</td><td>events in end mode</td></tr>
  2493. <tr><td>modeEnded</td><td>events that have just transitioned from start to end mode</td></tr>
  2494. <tr><td>modeStart</td><td>events in start mode</td></tr>
  2495. <tr><td>modeStarted</td><td>events that have just transitioned to start mode</td></tr>
  2496. <tr><td>modeUpcoming</td><td>events in upcoming mode</td></tr>
  2497. </table>
  2498. </ul>
  2499. <p>
  2500. For recurring events, usually several calendar events exists with the same UID. In such a case,
  2501. the UID is only shown in the mode reading for the most interesting mode. The most
  2502. interesting mode is the first applicable of start, alarm, upcoming, end.<p>
  2503. In particular, you will never see the UID of a series in modeEnd or modeEnded as long as the series
  2504. has not yet ended - the UID will be in one of the other mode... readings. This means that you better
  2505. do not trigger FHEM events for series based on mode... readings. See below for a recommendation.<p>
  2506. <b>Events</b>
  2507. <ul><br>
  2508. When the calendar was reloaded or updated or when an alarm, start or end time was reached, one
  2509. FHEM event is created:<p>
  2510. <code>triggered</code><br><br>
  2511. When you receive this event, you can rely on the calendar's readings being in a consistent and
  2512. most recent state.<p>
  2513. When a calendar event has changed, two FHEM events are created:<p>
  2514. <code>changed: UID &lt;mode&gt;</code><br>
  2515. <code>&lt;mode&gt;: UID</code><br><br>
  2516. &lt;mode&gt; is the current mode of the calendar event after the change. Note: there is a
  2517. colon followed by a single space in the FHEM event specification.<p>
  2518. The recommended way of reacting on mode changes of calendar events is to get notified
  2519. on the aforementioned FHEM events and do not check for the FHEM events triggered
  2520. by a change of a mode reading.
  2521. <p>
  2522. </ul>
  2523. <a name="CalendarPlugIns"></a>
  2524. <b>Plug-ins</b>
  2525. <ul>
  2526. <br>
  2527. This is experimental. Use with caution.<p>
  2528. A plug-in is a piece of Perl code that modifies a calendar event on the fly. The Perl code operates on the
  2529. hash reference <code>$e</code>. The most important elements are as follows:
  2530. <table>
  2531. <tr><th>code</th><th>description</th></tr>
  2532. <tr><td>$e->{start}</td><td>the start time of the calendar event, in seconds since the epoch</td></tr>
  2533. <tr><td>$e->{end}</td><td>the end time of the calendar event, in seconds since the epoch</td></tr>
  2534. <tr><td>$e->{alarm}</td><td>the alarm time of the calendar event, in seconds since the epoch</td></tr>
  2535. <tr><td>$e->{summary}</td><td>the summary (caption, title) of the calendar event</td></tr>
  2536. <tr><td>$e->{location}</td><td>the location of the calendar event</td></tr>
  2537. </table><br>
  2538. To add or change the alarm time of a calendar event for all events with the string "Tonne" in the
  2539. summary, the following plug-in can be used:<br><br>
  2540. <code>attr MyCalendar onCreateEvent { $e->{alarm}= $e->{start}-86400 if($e->{summary} =~ /Tonne/);; }</code><br>
  2541. <br>The double semicolon masks the semicolon. <a href="#perl">Perl specials</a> cannot be used.<br>
  2542. </ul>
  2543. <br><br>
  2544. <b>Usage scenarios</b>
  2545. <ul><br><br>
  2546. <i>Show all calendar events with details</i><br><br>
  2547. <ul>
  2548. <code>
  2549. get MyCalendar full all<br>
  2550. 2767324dsfretfvds7dsfn3e4&shy;dsa234r234sdfds6bh874&shy;googlecom alarm 31.05.2012 17:00:00 07.06.2012 16:30:00-07.06.2012 18:00:00 Erna for coffee<br>
  2551. 992hydf4y44awer5466lhfdsr&shy;gl7tin6b6mckf8glmhui4&shy;googlecom upcoming 08.06.2012 00:00:00-09.06.2012 00:00:00 Vacation
  2552. </code><br><br>
  2553. </ul>
  2554. <i>Show calendar events in your photo frame</i><br><br>
  2555. <ul>
  2556. Put a line in the <a href="#RSSlayout">layout description</a> to show calendar events in alarm or start mode:<br><br>
  2557. <code>text 20 60 { fhem("get MyCalendar text next 2") }</code><br><br>
  2558. This may look like:<br><br>
  2559. <code>
  2560. 07.06.12 16:30 Erna for coffee<br>
  2561. 08.06.12 00:00 Vacation
  2562. </code><br><br>
  2563. </ul>
  2564. <i>Switch the light on when Erna comes</i><br><br>
  2565. <ul>
  2566. First find the UID of the calendar event:<br><br>
  2567. <code>
  2568. get MyCalendar find .*Erna.*<br>
  2569. 2767324dsfretfvds7dsfn3e4&shy;dsa234r234sdfds6bh874&shy;googlecom
  2570. </code><br><br>
  2571. Then define a notify (the dot after the second colon matches the space):<br><br>
  2572. <code>
  2573. define ErnaComes notify MyCalendar:start:.2767324dsfretfvds7dsfn3e4&shy;dsa234r234sdfds6bh874&shy;googlecom set MyLight on
  2574. </code><br><br>
  2575. You can also do some logging:<br><br>
  2576. <code>
  2577. define LogErna notify MyCalendar:alarm:.2767324dsfretfvds7dsfn3e4&shy;dsa234r234sdfds6bh874&shy;googlecom { Log3 $NAME, 1, "ALARM name=$NAME event=$EVENT part1=$EVTPART0 part2=$EVTPART1" }
  2578. </code><br><br>
  2579. </ul>
  2580. <i>Switch actors on and off</i><br><br>
  2581. <ul>
  2582. Think about a calendar with calendar events whose summaries (subjects, titles) are the names of devices in your fhem installation.
  2583. You want the respective devices to switch on when the calendar event starts and to switch off when the calendar event ends.<br><br>
  2584. <code>
  2585. define SwitchActorOn notify MyCalendar:start:.* {
  2586. my $reading="$EVTPART0";;
  2587. my $uid= "$EVTPART1";;
  2588. my $actor= fhem("get MyCalendar summary $uid");;
  2589. if(defined $actor) {
  2590. fhem("set $actor on")
  2591. }
  2592. }<br><br>
  2593. define SwitchActorOff notify MyCalendar:end:.* {
  2594. my $reading="$EVTPART0";;
  2595. my $uid= "$EVTPART1";;
  2596. my $actor= fhem("get MyCalendar summary $uid");;
  2597. if(defined $actor) {
  2598. fhem("set $actor off")
  2599. }
  2600. }
  2601. </code><br><br>
  2602. You can also do some logging:<br><br>
  2603. <code>
  2604. define LogActors notify MyCalendar:(start|end):.* { my $reading= "$EVTPART0";; my $uid= "$EVTPART1";; my $actor= fhem("get MyCalendar summary $uid");; Log 3 $NAME, 1, "Actor: $actor, Reading $reading" }
  2605. </code><br><br>
  2606. </ul>
  2607. </ul>
  2608. <b>Embedded HTML</b>
  2609. <ul><br>
  2610. The module provides an additional function <code>CalendarAsHtml(&lt;name&gt;,&lt;options&gt;)</code>. It
  2611. returns the HTML code for a list of calendar events. <code>&lt;name&gt;</code> is the name of the
  2612. Calendar device and <code>&lt;options&gt;</code> is what you would write after <code>get &lt;name&gt; text ...</code>.
  2613. <br><br>
  2614. Example: <code>define MyCalendarWeblink weblink htmlCode { CalendarAsHtml("MyCalendar","next 3") }</code>
  2615. <br><br>
  2616. This is a rudimentary function which might be extended in a future version.
  2617. <p>
  2618. </ul>
  2619. </ul>
  2620. =end html
  2621. =begin html_DE
  2622. <a name="Calendar"></a>
  2623. <h3>Calendar</h3>
  2624. <ul>
  2625. <br>
  2626. <a name="Calendardefine"></a>
  2627. <b>Define</b>
  2628. <ul>
  2629. <code>define &lt;name&gt; Calendar ical url &lt;URL&gt; [&lt;interval&gt;]</code><br>
  2630. <code>define &lt;name&gt; Calendar ical file &lt;FILENAME&gt; [&lt;interval&gt;]</code><br>
  2631. <br>
  2632. Definiert ein Kalender-Device.<br><br>
  2633. Ein Kalender-Device ermittelt (Serien-) Termine aus einem Quell-Kalender. Dieser kann eine URL oder eine Datei sein.
  2634. Die Datei muss im iCal-Format vorliegen.<br><br>
  2635. Beginnt die URL mit <code>https://</code>, muss das Perl-Modul IO::Socket::SSL installiert sein
  2636. (use <code>cpan -i IO::Socket::SSL</code>).<br><br>
  2637. Hinweis f&uuml;r Nutzer des Google-Kalenders: Du kann direkt die private iCal-URL des Google Kalender nutzen.
  2638. Sollte Deine Google-Kalender-URL mit <code>https://</code> beginnen und das Perl-Modul IO::Socket::SSL ist nicht auf Deinem Systeme installiert,
  2639. kannst Du in der URL <code>https://</code> durch <code>http://</code> ersetzen, falls keine automatische Umleitung auf die <code>https://</code> URL erfolgt.
  2640. Solltest Du unsicher sein, ob dies der Fall ist, &uuml;berpr&uuml;fe es bitte zuerst mit Deinem Browser.<br><br>
  2641. Der optionale Parameter <code>interval</code> bestimmt die Zeit in Sekunden zwischen den Updates. Default-Wert ist 3600 (1 Stunde).<br><br>
  2642. Beispiele:
  2643. <pre>
  2644. define MeinKalender Calendar ical url https://www.google.com&shy;/calendar/ical/john.doe%40example.com&shy;/private-foo4711/basic.ics
  2645. define DeinKalender Calendar ical url http://www.google.com&shy;/calendar/ical/jane.doe%40example.com&shy;/private-bar0815/basic.ics 86400
  2646. define IrgendeinKalender Calendar ical file /home/johndoe/calendar.ics
  2647. </pre>
  2648. </ul>
  2649. <br>
  2650. <a name="Calendarset"></a>
  2651. <b>Set </b><br><br>
  2652. <ul>
  2653. <code>set &lt;name&gt; update</code><br>
  2654. Erzwingt das Einlesen des Kalenders von der definierten URL. Das n&auml;chste automatische Einlesen erfolgt in
  2655. <code>interval</code> Sekunden sp&auml;ter.<br><br>
  2656. <code>set &lt;name&gt; reload</code><br>
  2657. Dasselbe wie <code>update</code>, jedoch werden zuerst alle Termine entfernt.<br><br>
  2658. </ul>
  2659. <br>
  2660. <a name="Calendarget"></a>
  2661. <b>Get</b><br><br>
  2662. <ul>
  2663. <code>get &lt;name&gt; update</code><br>
  2664. Entspricht <code>set &lt;name&gt; update</code><br><br>
  2665. <code>get &lt;name&gt; reload</code><br>
  2666. Entspricht <code>set &lt;name&gt; reload</code><br><br>
  2667. <code>get &lt;name&gt; &lt;format&gt; &lt;filter&gt; [&lt;max&gt;]</code><br>
  2668. Die Termine f&uuml;r den Kalender &lt;name&gt; werden Zeile f&uuml;r Zeile ausgegeben.<br><br>
  2669. Folgende Selektoren/Filter stehen zur Verf&uuml;gung:<br><br>
  2670. Der Selektor &lt;format&gt legt den zur&uuml;ckgegeben Inhalt fest:<br><br>
  2671. <table>
  2672. <tr><th>&lt;format&gt;</th><th>Inhalt</th></tr>
  2673. <tr><td>uid</td><td>UID des Termins</td></tr>
  2674. <tr><td>text</td><td>Benutzer-/Monitorfreundliche Textausgabe.</td></tr>
  2675. <tr><td>summary</td><td>&Uuml;bersicht (Betreff, Titel)</td></tr>
  2676. <tr><td>location</td><td>Ort</td></tr>
  2677. <tr><td>categories</td><td>Kategorien</td></tr>
  2678. <tr><td>alarm</td><td>Alarmzeit</td></tr>
  2679. <tr><td>start</td><td>Startzeit</td></tr>
  2680. <tr><td>end</td><td>Endezeit</td></tr>
  2681. <tr><td>full</td><td>Vollst&auml;ndiger Status</td></tr>
  2682. <tr><td>debug</td><td>wie &lt;full&gt; mit zus&auml;tzlichen Informationen zur Fehlersuche</td></tr>
  2683. </table><br>
  2684. Der Filter &lt;filter&gt; grenzt die Termine ein:<br><br>
  2685. <table>
  2686. <tr><th>&lt;filter&gt;</th><th>Inhalt</th></tr>
  2687. <tr><td>mode=&lt;regex&gt;</td><td>alle Termine, deren Modus durch den regul&auml;ren Ausdruck &lt;regex&gt beschrieben werden.</td></tr>
  2688. <tr><td>&lt;mode&gt;</td><td>alle Termine mit Modus &lt;mode&gt.</td></tr>
  2689. <tr><td>uid=&lt;regex&gt;</td><td>Alle Termine, deren UIDs durch den regul&auml;ren Ausdruck &lt;regex&gt beschrieben werden.</td></tr>
  2690. <tr><td>&lt;uid&gt;</td><td>Alle Termine mit der UID &lt;uid&gt;</td></tr>
  2691. <tr><td>&lt;reading&gt;</td><td>Alle Termine die im Reading &lt;reading&gt; aufgelistet werden (modeAlarm, modeAlarmed, modeStart, etc.)
  2692. - dieser Filter ist abgek&uuml;ndigt und steht in einer zuk&uuml;nftigen Version nicht mehr zur Verf&uuml;gung, bitte mode=&lt;regex&gt; benutzen.</td></tr>
  2693. <tr><td>all</td><td>Alle Termine (vergangene, aktuelle und zuk&uuml;nftige)</td></tr>
  2694. <tr><td>next</td><td>Alle Termine, die noch nicht beendet sind. Bei Serienterminen der erste Termin. Benutzer-/Monitorfreundliche Textausgabe</td></tr>
  2695. </table><br>
  2696. Die Filter <code>mode=&lt;regex&gt;</code> und <code>uid=&lt;regex&gt;</code> sollten den Filtern
  2697. <code>&lt;mode&gt;</code> und <code>&lt;uid&gt;</code> vorgezogen werden.<br><br>
  2698. Der optionale Parameter <code>&lt;max&gt;</code> schr&auml;nkt die Anzahl der zur&uuml;ckgegebenen Zeilen ein.<br><br>
  2699. Bitte beachte die Attribute <code>hideOlderThan</code> und
  2700. <code>hideLaterThan</code> f&uuml;r die Seletion von Terminen in einem bestimmten Zeitfenster.
  2701. Bitte ber&uuml;cksichtige, dass das globale &pm;400 Tageslimit gilt .<br><br>
  2702. Beispiele:<br>
  2703. <code>get MyCalendar text next</code><br>
  2704. <code>get MyCalendar summary uid:435kjhk435googlecom 1</code><br>
  2705. <code>get MyCalendar summary 435kjhk435googlecom 1</code><br>
  2706. <code>get MyCalendar full all</code><br>
  2707. <code>get MyCalendar text mode=alarm|start</code><br>
  2708. <code>get MyCalendar text uid=.*6286.*</code><br>
  2709. <br>
  2710. <code>get &lt;name&gt; find &lt;regexp&gt;</code><br>
  2711. Gibt Zeile f&uuml;r Zeile die UIDs aller Termine deren Zusammenfassungen durch den regul&auml;ren Ausdruck &lt;regex&gt beschrieben werden.
  2712. &lt;regexp&gt;.<br><br>
  2713. <code>get &lt;name&gt; vcalendar</code><br>
  2714. Gibt den Kalender ICal-Format, so wie er von der Quelle gelesen wurde, zur&uuml;ck.<br><br>
  2715. <code>get &lt;name&gt; vevents</code><br>
  2716. Gibt eine Liste aller VEVENT-Eintr&auml;ge des Kalenders &lt;name&gt;, angereichert um Ausgaben f&uuml;r die Fehlersuche, zur&uuml;ck.
  2717. Es werden nur Eigenschaften angezeigt, die w&auml;hrend der Programmausf&uuml;hrung beibehalten wurden. Es wird sowohl die Liste
  2718. der Termine, die von jedem VEVENT-Eintrag erzeugt wurden, als auch die Liste der ausgelassenen Termine angezeigt.
  2719. </ul>
  2720. <br>
  2721. <a name="Calendarattr"></a>
  2722. <b>Attributes</b>
  2723. <br><br>
  2724. <ul>
  2725. <li><code>update sync|async|none</code><br>
  2726. Wenn dieses Attribut nicht gesetzt ist oder wenn es auf <code>sync</code> gesetzt ist,
  2727. findet die Verarbeitung des Kalenders im Vordergrund statt. Gro&szlig;e Kalender werden FHEM
  2728. auf langsamen Systemen blockieren. Wenn das Attribut auf <code>async</code> gesetzt ist,
  2729. findet die Verarbeitung im Hintergrund statt, und FHEM wird w&auml;hrend der Verarbeitung
  2730. nicht blockieren. Wenn dieses Attribut auf <code>none</code> gesetzt ist, wird der
  2731. Kalender &uuml;berhaupt nicht aktualisiert.
  2732. </li><p>
  2733. <li><code>removevcalendar 0|1</code><br>
  2734. Wenn dieses Attribut auf 1 gesetzt ist, wird der vCalendar nach der Verarbeitung verworfen,
  2735. gleichzeitig reduziert sich der Speicherverbrauch des Moduls.
  2736. Ein Abruf &uuml;ber <code>get &lt;name&gt; vcalendar</code> ist dann nicht mehr m&ouml;glich.
  2737. </li><p>
  2738. <li><code>hideOlderThan &lt;timespec&gt;</code><br>
  2739. <code>hideLaterThan &lt;timespec&gt;</code><br><p>
  2740. Dieses Attribut grenzt die Liste der durch <code>get &lt;name&gt; full|debug|text|summary|location|alarm|start|end ...</code> gezeigten Termine ein.
  2741. Die Zeit wird relativ zur aktuellen Zeit t angegeben.<br>
  2742. Wenn &lt;hideOlderThan&gt; gesetzt ist, werden Termine, die vor &lt;t-hideOlderThan&gt; enden, ingnoriert.<br>
  2743. Wenn &lt;hideLaterThan&gt; gesetzt ist, werden Termine, die nach &lt;t+hideLaterThan&gt; anfangen, ignoriert.<p>
  2744. Bitte beachten, dass eine Aktion, die durch einen Wechsel in den Modus "end" ausgel&ouml;st wird, nicht auf den Termin
  2745. zugreifen kann, wenn hideOlderThan 0 ist, weil der Termin dann schon versteckt ist. Besser hideOlderThan auf 10 setzen.<p>
  2746. <code>&lt;timespec&gt;</code> muss einem der folgenden Formate entsprechen:<br>
  2747. <table>
  2748. <tr><th>Format</th><th>Beschreibung</th><th>Beispiel</th></tr>
  2749. <tr><td>SSS</td><td>Sekunden</td><td>3600</td></tr>
  2750. <tr><td>SSSs</td><td>Sekunden</td><td>3600s</td></tr>
  2751. <tr><td>HH:MM</td><td>Stunden:Minuten</td><td>02:30</td></tr>
  2752. <tr><td>HH:MM:SS</td><td>Stunden:Minuten:Sekunden</td><td>00:01:30</td></tr>
  2753. <tr><td>D:HH:MM:SS</td><td>Tage:Stunden:Minuten:Sekunden</td><td>122:10:00:00</td></tr>
  2754. <tr><td>DDDd</td><td>Tage</td><td>100d</td></tr>
  2755. </table></li>
  2756. <p>
  2757. <li><code>cutoffOlderThan &lt;timespec&gt;</code><br>
  2758. Dieses Attribut schneidet alle nicht wiederkehrenden Termine weg, die eine Zeitspanne cutoffOlderThan
  2759. vor der letzten Aktualisierung des Kalenders endeten. Der Zweck dieses Attributs ist es Speicher zu
  2760. sparen. Auf solche Termine kann gar nicht mehr aus FHEM heraus zugegriffen werden. Serientermine und
  2761. Termine ohne Endezeitpunkt (DTEND) werden nicht weggeschnitten.
  2762. </li><p>
  2763. <li><code>onCreateEvent &lt;perl-code&gt;</code><br>
  2764. Dieses Attribut f&uuml;hrt ein Perlprogramm &lt;perl-code&gt; f&uuml;r jeden erzeugten Termin aus.
  2765. Weitere Informationen unter <a href="#CalendarPlugIns">Plug-ins</a> im Text.
  2766. </li><p>
  2767. <li><code>SSLVerify</code><br>
  2768. Dieses Attribut setzt die Art der &Uuml;berpr&uuml;fung des Zertifikats des Partners
  2769. bei mit SSL gesicherten Verbindungen. Entweder auf 0 setzen f&uuml;r
  2770. SSL_VERIFY_NONE (keine &Uuml;berpr&uuml;fung des Zertifikats) oder auf 1 f&uuml;r
  2771. SSL_VERIFY_PEER (&Uuml;berpr&uuml;fung des Zertifikats). Die &Uuml;berpr&uuml;fung auszuschalten
  2772. ist n&uuml;tzlich f&uuml;r lokale Kalenderinstallationen(e.g. OwnCloud, NextCloud)
  2773. ohne g&uuml;tiges SSL-Zertifikat.
  2774. </li><p>
  2775. <li><a href="#readingFnAttributes">readingFnAttributes</a></li>
  2776. </ul>
  2777. <br>
  2778. <b>Beschreibung</b>
  2779. <ul><br>
  2780. Ein Kalender ist eine Menge von Terminen. Ein Termin hat eine Zusammenfassung (normalerweise der Titel, welcher im Quell-Kalender angezeigt wird), eine Startzeit, eine Endzeit und keine, eine oder mehrere Alarmzeiten. Die Termine werden
  2781. aus dem Quellkalender ermittelt, welcher &uuml;ber die URL angegeben wird. Sollten mehrere Alarmzeiten f&uuml;r einen Termin existieren, wird nur der fr&uuml;heste Alarmzeitpunkt beibehalten. Wiederkehrende Kalendereintr&auml;ge werden in einem gewissen Umfang unterst&uuml;tzt:
  2782. FREQ INTERVAL UNTIL COUNT werden ausgewertet, BYMONTHDAY BYMONTH WKST
  2783. werden erkannt aber nicht ausgewertet. BYDAY wird f&uuml;r w&ouml;chentliche und monatliche Termine
  2784. korrekt behandelt. Das Modul wird es sehr wahrscheinlich falsch machen, wenn Du wiederkehrende Termine mit unerkannten oder nicht ausgewerteten Schl&uuml;sselw&ouml;rtern hast.<p>
  2785. Termine werden erzeugt, wenn FHEM gestartet wird oder der betreffende Eintrag im Quell-Kalender ver&auml;ndert
  2786. wurde oder der Kalender mit <code>get &lt;name&gt; reload</code> neu geladen wird. Es werden nur Termine
  2787. innerhalb &pm;400 Tage um die Erzeugungs des Termins herum erzeugt. Ziehe in Betracht, den Kalender von Zeit zu Zeit
  2788. neu zu laden, um zu vermeiden, dass die k&uuml;nftigen Termine ausgehen. Du kann so etwas wie <code>define reloadCalendar at +*240:00:00 set MyCalendar reload</code> daf&uuml;r verwenden.<p>
  2789. Manche dummen Kalender benutzen LAST-MODIFIED nicht. Das kann dazu f&uuml;hren, dass Ver&auml;nderungen im
  2790. Quell-Kalender unbemerkt bleiben. Lade den Kalender neu, wenn Du dieses Problem hast.<p>
  2791. Ein Termin wird durch seine UID identifiziert. Die UID wird vom Quellkalender bezogen. Um das Leben leichter zu machen, werden alle nicht-alphanumerischen Zeichen automatisch aus der UID entfernt.<p>
  2792. Ein Termin kann sich in einem der folgenden Modi befinden:
  2793. <table>
  2794. <tr><td>upcoming</td><td>Weder die Alarmzeit noch die Startzeit des Kalendereintrags ist erreicht.</td></tr>
  2795. <tr><td>alarm</td><td>Die Alarmzeit ist &uuml;berschritten, aber die Startzeit des Kalender-Ereignisses ist noch nicht erreicht.</td></tr>
  2796. <tr><td>start</td><td>Die Startzeit ist &uuml;berschritten, aber die Ende-Zeit des Kalender-Ereignisses ist noch nicht erreicht.</td></tr>
  2797. <tr><td>end</td><td>Die Ende-Zeit des Kalender-Ereignisses wurde &uuml;berschritten.</td></tr>
  2798. </table><br>
  2799. Ein Kalender-Ereignis wechselt umgehend von einem Modus zum Anderen, wenn die Zeit f&uuml;r eine &Auml;nderung erreicht wurde. Dies wird dadurch erreicht, dass auf die fr&uuml;heste zuk&uuml;nftige Zeit aller Alarme, Start- oder Endezeiten aller Kalender-Ereignisse gewartet wird.
  2800. <p>
  2801. Ein Kalender-Device hat verschiedene Readings. Mit Ausnahme von <code>calname</code> stellt jedes Reading eine Semikolon-getrennte Liste von UIDs von Kalender-Ereignisse dar, welche bestimmte Zust&auml;nde haben:
  2802. <table>
  2803. <tr><td>calname</td><td>Name des Kalenders</td></tr>
  2804. <tr><td>modeAlarm</td><td>Ereignisse im Alarm-Modus</td></tr>
  2805. <tr><td>modeAlarmOrStart</td><td>Ereignisse im Alarm- oder Startmodus</td></tr>
  2806. <tr><td>modeAlarmed</td><td>Ereignisse, welche gerade in den Alarmmodus gewechselt haben</td></tr>
  2807. <tr><td>modeChanged</td><td>Ereignisse, welche gerade in irgendeiner Form ihren Modus gewechselt haben</td></tr>
  2808. <tr><td>modeEnd</td><td>Ereignisse im Endemodus</td></tr>
  2809. <tr><td>modeEnded</td><td>Ereignisse, welche gerade vom Start- in den Endemodus gewechselt haben</td></tr>
  2810. <tr><td>modeStart</td><td>Ereignisse im Startmodus</td></tr>
  2811. <tr><td>modeStarted</td><td>Ereignisse, welche gerade in den Startmodus gewechselt haben</td></tr>
  2812. <tr><td>modeUpcoming</td><td>Ereignisse im zuk&uuml;nftigen Modus</td></tr>
  2813. </table>
  2814. <p>
  2815. F&uuml;r Serientermine werden mehrere Termine mit der selben UID erzeugt. In diesem Fall
  2816. wird die UID nur im interessantesten gelesenen Modus-Reading angezeigt.
  2817. Der interessanteste Modus ist der erste zutreffende Modus aus der Liste der Modi start, alarm, upcoming, end.<p>
  2818. Die UID eines Serientermins wird nicht angezeigt, solange sich der Termin im Modus: modeEnd oder modeEnded befindet
  2819. und die Serie nicht beendet ist. Die UID befindet sich in einem der anderen mode... Readings.
  2820. Hieraus ergibts sich, das FHEM-Events nicht auf einem mode... Reading basieren sollten.
  2821. Weiter unten im Text gibt es hierzu eine Empfehlung.<p>
  2822. </ul>
  2823. <b>Events</b>
  2824. <ul><br>
  2825. Wenn der Kalendar neu geladen oder aktualisiert oder eine Alarm-, Start- oder Endezeit
  2826. erreicht wurde, wird ein FHEM-Event erzeugt:<p>
  2827. <code>triggered</code><br><br>
  2828. Man kann sich darauf verlassen, dass alle Readings des Kalenders in einem konsistenten und aktuellen
  2829. Zustand befinden, wenn dieses Event empfangen wird.<p>
  2830. Wenn ein Termin ge&auml;ndert wurde, werden zwei FHEM-Events erzeugt:<p>
  2831. <code>changed: UID &lt;mode&gt;</code><br>
  2832. <code>&lt;mode&gt;: UID</code><br><br>
  2833. &lt;mode&gt; ist der aktuelle Modus des Termins nach der &auml;nderung. Bitte beachten: Im FHEM-Event befindet sich ein Doppelpunkt gefolgt von einem Leerzeichen.<p>
  2834. FHEM-Events sollten nur auf den vorgenannten Events basieren und nicht auf FHEM-Events, die durch &auml;ndern eines mode... Readings ausgel&ouml;st werden.
  2835. <p>
  2836. </ul>
  2837. <a name="CalendarPlugIns"></a>
  2838. <b>Plug-ins</b>
  2839. <ul>
  2840. <br>
  2841. Experimentell, bitte mit Vorsicht nutzen.<p>
  2842. Ein Plug-In ist ein kleines Perl-Programm, dass Termine nebenher ver&auml;ndern kann.
  2843. Das Perl-Programm arbeitet mit der Hash-Referenz <code>$e</code>.<br>
  2844. Die wichtigsten Elemente sind:
  2845. <table>
  2846. <tr><th>code</th><th>description</th></tr>
  2847. <tr><td>$e->{start}</td><td>Startzeit des Termins, in Sekunden seit 1.1.1970</td></tr>
  2848. <tr><td>$e->{end}</td><td>Endezeit des Termins, in Sekunden seit 1.1.1970</td></tr>
  2849. <tr><td>$e->{alarm}</td><td>Alarmzeit des Termins, in Sekunden seit 1.1.1970</td></tr>
  2850. <tr><td>$e->{summary}</td><td>die Zusammenfassung (Betreff, Titel) des Termins</td></tr>
  2851. <tr><td>$e->{location}</td><td>Der Ort des Termins</td></tr>
  2852. </table><br>
  2853. Um f&uuml;r alle Termine mit dem Text "Tonne" in der Zusammenfassung die Alarmzeit zu erg&auml;nzen / zu &auml;ndern,
  2854. kann folgendes Plug-In benutzt werden:<br><br>
  2855. <code>attr MyCalendar onCreateEvent { $e->{alarm}= $e->{start}-86400 if($e->{summary} =~ /Tonne/);; }</code><br>
  2856. <br>Das doppelte Semikolon maskiert das Semikolon. <a href="#perl">Perl specials</a> k&ouml;nnen nicht genutzt werden.<br>
  2857. </ul>
  2858. <br><br>
  2859. <b>Anwendungsbeispiele</b>
  2860. <ul><br>
  2861. <i>Alle Termine inkl. Details anzeigen</i><br><br>
  2862. <ul>
  2863. <code>
  2864. get MyCalendar full all<br>
  2865. 2767324dsfretfvds7dsfn3e4&shy;dsa234r234sdfds6bh874&shy;googlecom known alarm 31.05.2012 17:00:00 07.06.2012 16:30:00-07.06.2012 18:00:00 Erna for coffee<br>
  2866. 992hydf4y44awer5466lhfdsr&shy;gl7tin6b6mckf8glmhui4&shy;googlecom known upcoming 08.06.2012 00:00:00-09.06.2012 00:00:00 Vacation
  2867. </code><br><br>
  2868. </ul>
  2869. <i>Zeige Termine in Deinem Bilderrahmen</i><br><br>
  2870. <ul>
  2871. F&uuml;ge eine Zeile in die <a href="#RSSlayout">layout description</a> ein, um Termine im Alarm- oder Startmodus anzuzeigen:<br><br>
  2872. <code>text 20 60 { fhem("get MyCalendar text next 2") }</code><br><br>
  2873. Dies kann dann z.B. so aussehen:<br><br>
  2874. <code>
  2875. 07.06.12 16:30 Erna zum Kaffee<br>
  2876. 08.06.12 00:00 Urlaub
  2877. </code><br><br>
  2878. </ul>
  2879. <i>Schalte das Licht ein, wenn Erna kommt</i><br><br>
  2880. <ul>
  2881. Finde zuerst die UID des Termins:<br><br>
  2882. <code>
  2883. get MyCalendar find .*Erna.*<br>
  2884. 2767324dsfretfvds7dsfn3e4&shy;dsa234r234sdfds6bh874&shy;googlecom
  2885. </code><br><br>
  2886. Definiere dann ein notify: (Der Punkt nach dem zweiten Doppelpunkt steht f&uuml;r ein Leerzeichen)<br><br>
  2887. <code>
  2888. define ErnaComes notify MyCalendar:start:.2767324dsfretfvds7dsfn3e4&shy;dsa234r234sdfds6bh874&shy;googlecom.* set MyLight on
  2889. </code><br><br>
  2890. Du kannst auch ein Logging aufsetzen:<br><br>
  2891. <code>
  2892. define LogErna notify MyCalendar:alarm:.2767324dsfretfvds7dsfn3e4&shy;dsa234r234sdfds6bh874&shy;googlecom.* { Log3 $NAME, 1, "ALARM name=$NAME event=$EVENT part1=$EVTPART0 part2=$EVTPART1" }
  2893. </code><br><br>
  2894. </ul>
  2895. <i>Schalte die Aktoren an und aus</i><br><br>
  2896. <ul>
  2897. Stell Dir einen Kalender vor, dessen Zusammenfassungen (Betreff, Titel) die Namen von Devices in Deiner fhem-Installation sind.
  2898. Du willst nun die entsprechenden Devices an- und ausschalten, wenn das Kalender-Ereignis beginnt bzw. endet.<br><br>
  2899. <code>
  2900. define SwitchActorOn notify MyCalendar:start:.* {}<br>
  2901. </code>
  2902. Dann auf DEF klicken und im DEF-Editor folgendes zwischen die beiden geschweiften Klammern {} eingeben:
  2903. <code>
  2904. my $reading="$EVTPART0";
  2905. my $uid= "$EVTPART1";
  2906. my $actor= fhem("get MyCalendar summary $uid");
  2907. if(defined $actor) {
  2908. fhem("set $actor on")
  2909. }
  2910. <br><br>
  2911. define SwitchActorOff notify MyCalendar:end:.* {}<br>
  2912. </code>
  2913. Dann auf DEF klicken und im DEF-Editor folgendes zwischen die beiden geschweiften Klammern {} eingeben:
  2914. <code>
  2915. my $reading="$EVTPART0";
  2916. my $uid= "$EVTPART1";
  2917. my $actor= fhem("get MyCalendar summary $uid");
  2918. if(defined $actor) {
  2919. fhem("set $actor off")
  2920. }
  2921. </code><br><br>
  2922. Auch hier kann ein Logging aufgesetzt werden:<br><br>
  2923. <code>
  2924. define LogActors notify MyCalendar:(start|end).* {}<br>
  2925. </code>
  2926. Dann auf DEF klicken und im DEF-Editor folgendes zwischen die beiden geschweiften Klammern {} eingeben:
  2927. <code>
  2928. my $reading= "$EVTPART0";
  2929. my $uid= "$EVTPART1";
  2930. my $actor= fhem("get MyCalendar summary $uid");
  2931. Log 3 $NAME, 1, "Actor: $actor, Reading $reading";
  2932. </code><br><br>
  2933. </ul>
  2934. </ul>
  2935. <b>Eingebettetes HTML</b>
  2936. <ul><br>
  2937. Das Modul stellt eine zus&auml;tzliche Funktion <code>CalendarAsHtml(&lt;name&gt;,&lt;options&gt;)</code> bereit.
  2938. Diese gibt den HTML-Kode f&uuml;r eine Liste von Terminen zur&uuml;ck. <code>&lt;name&gt;</code> ist der Name des
  2939. Kalendar-Device und <code>&lt;options&gt;</code> ist das, was Du hinter <code>get &lt;name&gt; text ...</code>
  2940. schreiben w&uuml;rdest.
  2941. <br><br>
  2942. Beispiel: <code>define MyCalendarWeblink weblink htmlCode { CalendarAsHtml("MyCalendar","next 3") }</code>
  2943. <br><br>
  2944. Dies ist eine rudiment&auml;re Funktion, die vielleicht in k&uuml;nftigen Versionen erweitert wird.
  2945. <p>
  2946. </ul>
  2947. </ul>
  2948. =end html_DE
  2949. =cut