57_Calendar.pm 111 KB

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