AlexxIT/go2rtc · error

failed to initialize token

Error message

failed to initialize token: %w

What it means

TuyaSmartApiClient.Init begins by calling initToken to obtain/refresh the cloud access token; any failure there is wrapped as 'failed to initialize token'. This is the entry-point failure of the WebRTC flow — without a valid token nothing else (webrtc config, hub config) can load. The wrapped inner error carries the actual HTTP/sign/JSON cause.

Solutions

  1. Verify accessId and accessSecret are correct and unrotated
  2. Check the base URL/region matches your Tuya data center
  3. Ensure system clock is accurate (NTP) since signing is time-sensitive
  4. Unwrap the inner error (errors.Unwrap / %v) to see whether it's network, HTTP status, or JSON, and fix accordingly

Example fix

// before
if err := apiClient.Init(); err != nil { return err }
// after
if err := apiClient.Init(); err != nil {
    return fmt.Errorf("token init failed (check credentials/region/clock): %w", err)
}
Defensive patterns

Strategy: try-catch

Validate before calling

if accessID == "" || accessSecret == "" { return errors.New("missing tuya credentials") }

Try / catch

if err := apiClient.Init(); err != nil {
    var inner error
    for e := err; e != nil; e = errors.Unwrap(e) { inner = e }
    log.Printf("token init failed: %v (inner: %v)", err, inner)
    return err
}

Prevention

When it happens

Trigger: Init() when initToken fails: wrong accessId/accessSecret, unreachable base URL, HTTP errors from the token endpoint, signature mismatch, or invalid JSON response from Tuya's token API.

Common situations: Rotated or mistyped credentials, wrong region endpoint, clock skew breaking the HMAC signature, network/firewall blocking the cloud endpoint, or Tuya API changes.

Related errors


AI-assisted analysis of AlexxIT/go2rtc@c245815e75 (2026-09-07). Data as JSON: /api/errors/40444d311f070b39. Report an issue: GitHub.

Appendix: source

Thrown at pkg/tuya/smart_api.go:300

		TuyaClient: TuyaClient{
			httpClient: httpClient,
			mqtt:       mqttClient,
			deviceId:   deviceId,
			expireTime: 0,
			baseUrl:    baseUrl,
		},
		email:       email,
		password:    password,
		countryCode: region.Continent,
	}

	return client, nil
}

// WebRTC Flow
func (c *TuyaSmartApiClient) Init() error {
	if err := c.initToken(); err != nil {
		return fmt.Errorf("failed to initialize token: %w", err)
	}

	webrtcConfig, err := c.loadWebrtcConfig()
	if err != nil {
		return fmt.Errorf("failed to load webrtc config: %w", err)
	}

	hubConfig, err := c.loadHubConfig()
	if err != nil {
		return fmt.Errorf("failed to load hub config: %w", err)
	}

	if err := c.mqtt.Start(hubConfig, webrtcConfig, c.skill.WebRTC); err != nil {
		return fmt.Errorf("failed to start MQTT: %w", err)
	}

	if c.skill.LowPower > 0 {
		_ = c.mqtt.WakeUp(c.localKey)

View on GitHub (pinned to c245815e75)