『瀚思彼岸』» 智能家居技术论坛

 找回密码
 立即注册
查看: 2481|回复: 0

[经验分享] 使用公共 mqtt broker 获取 vps 账单 和 流量信息

[复制链接]

80

主题

388

帖子

1680

积分

金牌会员

Rank: 6Rank: 6

积分
1680
金钱
1292
HASS币
0
发表于 2022-7-17 09:19:03 | 显示全部楼层 |阅读模式
本帖最后由 ciasdmxhxjjpd@c 于 2022-7-17 09:22 编辑

RT,

以 vultr 为例,其他 vps 同理,只要支持 api,查看 api 文档,适当修改。
pycharm 调试
import requests
import json
import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
from requests.structures import CaseInsensitiveDict

# http get
url = 'https://api.vultr.com/v2/'
VULTR_API_KEY = ''
total = 0
headers = CaseInsensitiveDict()
headers["Accept"] = "application/json"
headers["Authorization"] = "Bearer " + VULTR_API_KEY

# mqtt broker
broker_address = "broker.hivemq.com"
port = 1883

# get first instant id
def get_instance():
    getInstance = json.loads(requests.get(url + 'instances', headers=headers).content)
    instanceId = getInstance['instances'][0]['id']
    return instanceId

# billing
accountInfo = json.loads(requests.get(url + 'account', headers=headers).content)
billing = accountInfo['account']['pending_charges']
balance = accountInfo['account']['balance']

# data use
getInstanceBandwidth = requests.get(url + 'instances/' + get_instance() + '/bandwidth', headers=headers).content
bandwidth = json.loads(getInstanceBandwidth)['bandwidth']
for key in bandwidth:
    total = total + bandwidth[key]['incoming_bytes']

# json out
js = {
    "billing": billing,
    'balance': balance,
    "traffic": total
}
message = json.dumps(js)
print(message)

# mqtt broker
publish.single("vps/vultr/billing_and_traffic", payload=message, qos=1, retain=1, hostname=broker_address,
    port=port, client_id="", keepalive=60, will=None, auth=None, tls=None,
    protocol=mqtt.MQTTv311, transport="tcp")
https://gist.github.com/0neday/68c0003514180cc00b2916f2b7ef2483
然后,在nr里获取,再推给本地的mqtt broker,再在 configuration里配置。

  - platform: mqtt
    name: "vultr network traffic"
    unique_id: vultr_network_traffic
    state_topic: "vps/vultr/billing_and_traffic"
    value_template: "{{ value_json.traffic | multiply(1.0/1073741824) | round(2) }}"
    unit_of_measurement: "GB"
    scan_interval: 300

  - platform: mqtt
    name: "vultr billing"
    unique_id: vultr_billing
    state_topic: "vps/vultr/billing_and_traffic"
    value_template: "{{ value_json.billing }}"
    unit_of_measurement: "$"
    scan_interval: 1800

  - platform: mqtt
    name: "vultr balance"
    unique_id: vultr_balance
    state_topic: "vps/vultr/billing_and_traffic"
    value_template: "{{ value_json.balance | abs }}"
    unit_of_measurement: "$"
    scan_interval: 3600
捕获.PNG

其次,可以在nr里写各种告警流程。比如流量超了,费用超了等等


flows.json

2.23 KB, 下载次数: 0

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|Hassbian

GMT+8, 2024-11-29 00:56 , Processed in 0.188845 second(s), 26 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表