11import json, strformat, options, times, strutils, httpclient
22import frameos/ types
3+ import frameos/ utils/ http_client
34
45const
56 RequestTimeoutMs = 10000
@@ -37,13 +38,6 @@ proc log*(self: App, message: string) =
3738proc error * (self: App , message: string ) =
3839 self.scene.logger.log (%* {" event" : " legacy/haSensor:error" , " error" : message})
3940
40- proc guardResponseProgress (startedAt: float ): proc (total, progress, speed: BiggestInt ) {.closure , gcsafe .} =
41- result = proc (total, progress, speed: BiggestInt ) {.closure , gcsafe .} =
42- if total > MaxResponseBytes .BiggestInt or progress > MaxResponseBytes .BiggestInt :
43- raise newException (IOError , & " Home Assistant response exceeded { MaxResponseBytes } bytes " )
44- if epochTime () > startedAt + MaxResponseSeconds :
45- raise newException (IOError , & " Home Assistant response exceeded { MaxResponseSeconds } seconds " )
46-
4741proc run * (self: App , context: ExecutionContext ) =
4842 let haUrl = self.frameConfig.settings{" homeAssistant" }{" url" }.getStr
4943 if haUrl == " " :
@@ -55,48 +49,37 @@ proc run*(self: App, context: ExecutionContext) =
5549 self.error (" Please provide a Home Assistant access token in the settings." )
5650 return
5751
58- var client = newHttpClient (timeout = RequestTimeoutMs )
59- try :
60- client.headers = newHttpHeaders ([
52+ let headers = newHttpHeaders ([
6153 (" Authorization" , " Bearer " & accessToken),
6254 (" Accept" , " application/json" ),
6355 (" Accept-Encoding" , " identity" ),
6456 (" Connection" , " close" )
65- ])
66- var slashlessUrl = haUrl
67- slashlessUrl.removeSuffix (" /" )
68- let url = & " { slashlessUrl} /api/states/{ self.appConfig.entityId} "
69- if self.appConfig.debug:
70- self.log (" Fetching Home Assistant status from " & url)
57+ ])
58+ var slashlessUrl = haUrl
59+ slashlessUrl.removeSuffix (" /" )
60+ let url = & " { slashlessUrl} /api/states/{ self.appConfig.entityId} "
61+ if self.appConfig.debug:
62+ self.log (" Fetching Home Assistant status from " & url)
7163
72- if self.json.isNone or self.lastFetchAt == 0 or self.lastFetchAt +
73- self.appConfig.cacheSeconds < epochTime ():
74- try :
75- client.onProgressChanged = guardResponseProgress (epochTime ())
76- let response = client.request (url)
77- if response.code != Http200 :
78- self.error " Error fetching Home Assistant status: HTTP " &
79- $ response.status
80- return
81- if response.contentLength () > MaxResponseBytes :
82- self.error & " Error fetching Home Assistant status: response exceeded { MaxResponseBytes } bytes "
83- return
84- if response.body.len > MaxResponseBytes :
85- self.error & " Error fetching Home Assistant status: response exceeded { MaxResponseBytes } bytes "
86- return
87- self.json = some (parseJson (response.body))
88- self.lastFetchAt = epochTime ()
89- except CatchableError as e:
90- self.error " Error fetching Home Assistant status: " & $ e.msg
91- return
64+ if self.json.isNone or self.lastFetchAt == 0 or self.lastFetchAt +
65+ self.appConfig.cacheSeconds < epochTime ():
66+ try :
67+ let responseBody = boundedGetContent (url,
68+ headers = headers,
69+ timeoutMs = RequestTimeoutMs ,
70+ maxBytes = MaxResponseBytes ,
71+ maxSeconds = MaxResponseSeconds )
72+ self.json = some (parseJson (responseBody))
73+ self.lastFetchAt = epochTime ()
74+ except CatchableError as e:
75+ self.error " Error fetching Home Assistant status: " & $ e.msg
76+ return
9277
93- if self.json.isSome:
94- let stateKey = if self.appConfig.stateKey ==
95- " " : " state" else : self.appConfig.stateKey
96- self.scene.state[stateKey] = self.json.get ()
97- if self.appConfig.debug:
98- self.log ($ self.scene.state[stateKey])
99- else :
100- self.error " No JSON response from Home Assistant"
101- finally :
102- client.close ()
78+ if self.json.isSome:
79+ let stateKey = if self.appConfig.stateKey ==
80+ " " : " state" else : self.appConfig.stateKey
81+ self.scene.state[stateKey] = self.json.get ()
82+ if self.appConfig.debug:
83+ self.log ($ self.scene.state[stateKey])
84+ else :
85+ self.error " No JSON response from Home Assistant"
0 commit comments