# Home Assistant Troubleshooting Guide

## YAML Configuration Errors

### Tab Characters Error

**Error:** `found character '\t' that cannot start any token`

**Cause:** YAML file contains tab characters

**Solution:**
- Replace all tabs with spaces (use 2 spaces per indentation level)
- Configure editor to use spaces instead of tabs
- Run validation script: `python3 validate_yaml.py configuration.yaml`

### Boolean State Errors

**Error:** `not a valid value for dictionary value`

**Cause:** Unquoted boolean state values like `on`, `off`, `yes`, `no`

**Solution:**
- Quote state values: `state: "on"` not `state: on`
- YAML interprets `on`, `yes`, `true` as boolean `true`
- Quote them to use as strings: `"on"`, `"off"`, `"yes"`, `"no"`

### Duplicate Keys

**Error:** Automation not working as expected

**Cause:** Duplicate keys in YAML - only last value is used

**Solution:**
```yaml
# Wrong - duplicate 'action' keys
action: light.turn_on
action: notify.notify

# Correct - use list
action:
  - action: light.turn_on
  - action: notify.notify
```

### Indentation Errors

**Error:** `mapping values are not allowed here`

**Cause:** Incorrect indentation

**Solution:**
- Use exactly 2 spaces per indentation level
- Check that list items align properly with `-`
- Validate structure:

```yaml
# Correct
automation:
  - alias: "Test"
    trigger:
      - trigger: state
        entity_id: light.test
```

## Automation Issues

### Automation Not Triggering

**Check:**
1. Automation is enabled (check Developer Tools > States > `automation.your_automation`)
2. Trigger conditions are correct:
   - Entity ID exists and is spelled correctly
   - State values are quoted: `to: "on"` not `to: on`
   - For numeric triggers, ensure sensor provides numeric values
3. Check automation trace (Settings > Automations > automation > Traces)

**Debug:**
```yaml
# Add notification to verify trigger fires
action:
  - action: notify.notify
    data:
      message: "Automation triggered at {{ now() }}"
  # ... rest of actions
```

### Automation Runs But Actions Don't Execute

**Check:**
1. Conditions - if any condition fails, actions won't run
2. Entity IDs in actions are correct
3. Service parameters are valid
4. Check logs for errors: Settings > System > Logs

**Debug:**
```yaml
# Temporarily remove conditions to test actions
# condition:
#   - condition: state
#     entity_id: sun.sun
#     state: "below_horizon"
```

### Template Errors

**Error:** `TemplateError: UndefinedError`

**Cause:** Template references non-existent entity or attribute

**Solution:**
```yaml
# Use default filter for safety
{{ states('sensor.missing') | default('unknown') }}
{{ state_attr('sensor.test', 'missing_attr') | default(0) }}

# Check if entity exists
{% if states('sensor.test') != 'unknown' %}
  {{ states('sensor.test') }}
{% endif %}
```

### "While" Loop Not Working

**Cause:** Using `for` when you meant duration, not iteration

**Solution:**
```yaml
# Wrong - 'for' iterates over value
trigger:
  - trigger: state
    entity_id: motion_sensor
    to: "on"
    for: 5  # This is wrong

# Correct - specify duration
trigger:
  - trigger: state
    entity_id: binary_sensor.motion
    to: "on"
    for:
      seconds: 5
```

## API Issues

### 401 Unauthorized

**Cause:** Invalid or missing access token

**Solution:**
1. Generate new long-lived token at `http://YOUR_HA_URL:8123/profile`
2. Verify token in Authorization header: `Authorization: Bearer YOUR_TOKEN`
3. Check token hasn't been deleted in Home Assistant

### 404 Not Found - Entity

**Cause:** Entity ID doesn't exist or is misspelled

**Solution:**
1. List all entities: `python3 list_entities.py --url YOUR_URL --token YOUR_TOKEN`
2. Check exact entity ID spelling (case-sensitive)
3. Verify entity is not disabled in Home Assistant

### Service Call Fails

**Error:** `Service not found` or `Invalid service data`

**Solution:**
1. List available services: `python3 list_services.py --url YOUR_URL --token YOUR_TOKEN`
2. Verify service parameters match requirements
3. Check service still exists (some integrations change service names)

**Example:**
```python
# Get service details
python3 list_services.py --url YOUR_URL --token YOUR_TOKEN --domain light

# Shows required/optional fields for each service
```

## Integration Issues

### Integration Not Loading

**Check:**
1. Configuration syntax: `configuration.yaml` has correct format
2. Required parameters are provided
3. Check error log: `http://YOUR_HA_URL:8123/config/logs`

**Solution:**
1. Validate configuration: Configuration > Server Controls > Check Configuration
2. Restart Home Assistant: Configuration > Server Controls > Restart
3. Check integration documentation for required setup

### Device Unavailable

**Check:**
1. Device is powered on and connected to network
2. Integration is configured correctly
3. Check integration's specific requirements (API keys, credentials, etc.)

**Debug:**
```yaml
# Check device state in Developer Tools
# Developer Tools > States > search for entity_id
# Status shows as 'unavailable' or 'unknown'
```

## Performance Issues

### Slow Response Times

**Causes:**
- Too many entities or automations
- Database growing too large
- Inefficient automations (templates evaluating frequently)

**Solutions:**
1. Purge old data: Configuration > System > Storage
2. Optimize database: `recorder` configuration in `configuration.yaml`:
```yaml
recorder:
  purge_keep_days: 7
  exclude:
    domains:
      - automation
      - updater
    entity_globs:
      - sensor.weather_*
```

3. Reduce template sensor update frequency
4. Use `homeassistant.reload_core_config` instead of full restart when possible

### Automations Firing Too Often

**Cause:** State changes triggering repeatedly

**Solution:**
```yaml
# Add 'for' duration to prevent rapid triggers
trigger:
  - trigger: state
    entity_id: sensor.temperature
    for:
      minutes: 5

# Or add condition to limit frequency
condition:
  - condition: template
    value_template: >
      {{ (now() - state_attr('automation.this_automation', 'last_triggered') | default(as_datetime(0), true)).total_seconds() > 300 }}
```

## Network Issues

### Can't Connect to Home Assistant

**Check:**
1. Home Assistant is running: `systemctl status home-assistant` (if using systemd)
2. Firewall allows port 8123
3. Using correct URL (http not https, or vice versa)
4. Network connectivity between client and server

**Solutions:**
```bash
# Test connection
curl http://YOUR_HA_URL:8123/api/

# Should return: {"message": "API running."}

# Check from Home Assistant server
curl http://localhost:8123/api/
```

### SSL/Certificate Errors

**Cause:** Using HTTPS with self-signed or invalid certificate

**Solution:**
1. Use HTTP for local testing
2. For production, use valid SSL certificate (Let's Encrypt via DuckDNS)
3. For testing with self-signed cert, disable verification (not recommended for production)

## Debugging Tools

### Check Automation Trace

1. Go to Settings > Automations & Scenes
2. Click automation
3. Click "Traces" tab
4. Shows each trigger, condition check, and action execution

### Developer Tools

**Template Tab:**
- Test templates before using in automations
- See real-time template evaluation

**States Tab:**
- View all entity states and attributes
- Check last_changed and last_updated timestamps

**Services Tab:**
- Test service calls manually
- Verify service parameters

**Events Tab:**
- Listen to all events
- See what events are being fired

### Enable Debug Logging

Add to `configuration.yaml`:
```yaml
logger:
  default: info
  logs:
    homeassistant.core: debug
    homeassistant.components.automation: debug
    homeassistant.helpers.script: debug
```

Restart Home Assistant to enable debug logging.

### Check Error Log

Access via:
- UI: Settings > System > Logs
- API: `GET /api/error_log`
- File: `/config/home-assistant.log`

## Common Gotchas

1. **Entity ID changed:** Integrations sometimes change entity IDs on update
2. **State is string:** All states are strings, use `| int` or `| float` for math
3. **Time zone:** Ensure Home Assistant time zone matches your location
4. **Restart required:** Some configuration changes need full restart, not just reload
5. **YAML anchors:** Not supported in automations.yaml when using UI editor
6. **Case sensitivity:** Entity IDs and states are case-sensitive
7. **Reserved words:** Avoid using YAML reserved words as keys without quotes
8. **Whitespace:** Trailing whitespace can cause parsing issues
