# ===== OpenClash 控制面板 =====
rest_command:
openclash_select_node:
# ===== IP替换成自己的OpenClash管理地址 =====
url: "http://192.168.31.254:9090/proxies/{{ group | urlencode }}"
method: PUT
headers:
# ===== kKMeQaxb 替换成自己的Secret密钥 =====
Authorization: "Bearer kKMeQaxb"
Content-Type: "application/json"
payload: >
{"name":"{{ node }}"}
rest:
# ===== 需替换 =====
- resource: "http://192.168.31.254:9090/proxies"
method: GET
headers:
# ===== 需替换 =====
Authorization: "Bearer kKMeQaxb"
# ===== HA组件刷新时间,按需更改 =====
scan_interval: 3
sensor:
- name: Clash Proxies JSON
value_template: "{{ value_json.proxies | length if value_json is defined and value_json.proxies is defined else 0 }}"
json_attributes:
- proxies
template:
- sensor:
- name: Clash Control Group
state: >
{% set p = state_attr('sensor.clash_proxies_json','proxies') %}
{% if not p %}unknown{% else %}
{# 这些 type 代表“不是机场节点”,不计入真实节点数 #}
{% set non_leaf_types = ['Selector','URLTest','Fallback','Direct','Reject','RejectDrop','Pass','Compatible'] %}
{% set best = namespace(name='unknown', score=-1) %}
{% for g,v in p.items() %}
{% if v is mapping and v.get('type') == 'Selector' and v.get('all') is iterable %}
{% set score = 0 %}
{% for n in v.get('all') %}
{% if n in p and (p[n].get('type') not in non_leaf_types) %}
{% set score = score + 1 %}
{% endif %}
{% endfor %}
{# 如果你无论如何都不想选 GLOBAL,可以在这里直接跳过 #}
{% if g == 'GLOBAL' %}{% set score = -1 %}{% endif %}
{% if score > best.score %}
{% set best.name = g %}
{% set best.score = score %}
{% endif %}
{% endif %}
{% endfor %}
{{ best.name }}
{% endif %}
- name: Clash Nodes List
state: "ok"
attributes:
nodes: >
{% set p = state_attr('sensor.clash_proxies_json','proxies') %}
{% set g = states('sensor.clash_control_group') %}
{% if p and g not in ['unknown','unavailable'] and g in p and 'all' in p[g] %}
{{ p[g]['all'] | list }}
{% else %}
[]
{% endif %}
- name: Clash 当前节点
state: >
{% set p = state_attr('sensor.clash_proxies_json','proxies') %}
{% set g = states('sensor.clash_control_group') %}
{% if p and g not in ['unknown','unavailable'] and g in p and 'now' in p[g] %}
{{ p[g]['now'] }}
{% else %}
unknown
{% endif %}
# ===== HA下拉选择组件 =====
input_select:
clash_node:
name: Clash 节点选择
options:
- 同步中...
(需要修改处已注释,按需填写)
4.右上角保存之后,重启HA-选择重新启动系统
Step 3:设置自动化同步节点状态
1.重启后点击设置->自动化-创建新的自动化
2.如图按照步骤添加三个自动化代码如下:
alias: OpenClash-选择下拉框切换节点
triggers:
- entity_id: input_select.clash_node
trigger: state
conditions:
- condition: template
value_template: |
{{ states('sensor.clash_control_group') not in ['unknown','unavailable']
and trigger.to_state.state not in ['unknown','unavailable','同步中...'] }}
actions:
- data:
group: "{{ states('sensor.clash_control_group') }}"
node: "{{ states('input_select.clash_node') }}"
action: rest_command.openclash_select_node