Browse Source

https更新

liuq 1 tháng trước cách đây
mục cha
commit
a80e94f443
1 tập tin đã thay đổi với 13 bổ sung6 xóa
  1. 13 6
      backend/utils/ha_client.go

+ 13 - 6
backend/utils/ha_client.go

@@ -12,6 +12,16 @@ import (
 	"gorm.io/datatypes"
 )
 
+// Global HTTP Client for HA
+var haHttpClient = &http.Client{
+	Timeout: 10 * time.Second,
+	Transport: &http.Transport{
+		MaxIdleConns:        100,
+		MaxIdleConnsPerHost: 10,
+		IdleConnTimeout:     90 * time.Second,
+	},
+}
+
 type HAConfig struct {
 	URL   string `json:"url"`
 	Token string `json:"token"`
@@ -46,7 +56,6 @@ func FetchHAEntitiesByDevice(config datatypes.JSON, deviceID string) ([]HAEntity
 		return nil, err
 	}
 
-	client := &http.Client{Timeout: 10 * time.Second}
 	url := normalizeURL(haConfig.URL)
 
 	rawTemplate := `
@@ -73,7 +82,7 @@ func FetchHAEntitiesByDevice(config datatypes.JSON, deviceID string) ([]HAEntity
 `
 	template := strings.ReplaceAll(rawTemplate, "__DEVICE_ID__", deviceID)
 
-	return executeTemplateQuery(client, url, haConfig.Token, template)
+	return executeTemplateQuery(haHttpClient, url, haConfig.Token, template)
 }
 
 // FetchEntityState fetches a single entity state
@@ -83,7 +92,6 @@ func FetchEntityState(config datatypes.JSON, entityID string) (*HAEntity, error)
 		return nil, err
 	}
 
-	client := &http.Client{Timeout: 5 * time.Second}
 	url := normalizeURL(haConfig.URL)
 	
 	req, err := http.NewRequest("GET", fmt.Sprintf("%s/api/states/%s", url, entityID), nil)
@@ -93,7 +101,7 @@ func FetchEntityState(config datatypes.JSON, entityID string) (*HAEntity, error)
 	req.Header.Set("Authorization", "Bearer "+haConfig.Token)
 	req.Header.Set("Content-Type", "application/json")
 
-	resp, err := client.Do(req)
+	resp, err := haHttpClient.Do(req)
 	if err != nil {
 		return nil, err
 	}
@@ -121,7 +129,6 @@ func BatchFetchStates(config datatypes.JSON, entityIDs []string) (map[string]str
 		return nil, err
 	}
 
-	client := &http.Client{Timeout: 10 * time.Second}
 	url := normalizeURL(haConfig.URL)
 
 	// Direct State API fetch - more reliable than Template for large lists or weird IDs
@@ -134,7 +141,7 @@ func BatchFetchStates(config datatypes.JSON, entityIDs []string) (map[string]str
 
 	fmt.Printf("DEBUG: Fetching all states from %s\n", url+"/api/states")
 
-	resp, err := client.Do(req)
+	resp, err := haHttpClient.Do(req)
 	if err != nil {
 		return nil, err
 	}