smartmeter

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 9, 2026 License: MIT Imports: 15 Imported by: 3

README

go-smartmeter

Wi-SUNモジュールを使って電力スマートメーターにアクセスするGoライブラリです。

特徴

  • 致命的エラーとリトライ可能エラーを区別して可能ならリトライする(Wi-SUNの通信は不安定なので実用上はリトライ実装が重要)
  • SKSCANで指定チャンネルだけスキャンできるようにしたので、チャンネルがわかっていれば再スキャンが高速
  • ECHONET Liteの複数プロパティを1コマンドにまとめられるので、920MHz帯の節約になる
  • Bルート専用モジュールとデュアルスタックモジュール両対応
  • 実行ファイルが外部ライブラリ依存のない小さいバイナリになるので、Raspberry Piなど低スペック環境でも動作させやすい

サンプルコード

次のようなコードでスマートメーターの瞬時電力計測値にアクセスできます。(Wi-SUNモジュールの入手とBルートサービスの申し込みは必須です)

package main

import (
	"fmt"

	smartmeter "github.com/hnw/go-smartmeter"
)

func main() {
	dev, err := smartmeter.Open("/dev/ttyACM0",
		smartmeter.DualStackSK(), // Bルート専用モジュールを使う場合はコメントアウト
		smartmeter.ID("00000000000000000000000000000000"), // Bルート認証ID
		smartmeter.Password("AB0123456789"),               // パスワード
		smartmeter.Channel("33"))                          // チャンネル。各環境でScan()で取得した値に書き換える。

	if err != nil {
		fmt.Printf("%+v", err)
		return
	}

	err = dev.Authenticate()
	if err != nil {
		fmt.Printf("%+v\n", err)
		return
	}

	request := smartmeter.NewFrame(smartmeter.LvSmartElectricEnergyMeter, smartmeter.Get, []*smartmeter.Property{
		smartmeter.NewProperty(smartmeter.LvSmartElectricEnergyMeter_InstantaneousElectricPower, nil),
	})
	response, err = dev.QueryEchonetLite(request, smartmeter.Retry(3))
	if err != nil {
		fmt.Printf("%+v\n", err)
		return
	}

	for _, p := range response.Properties {
		fmt.Print(p.Desc())
	}
}

これを実行すると、次のように自宅の消費電力がわかります。

Instantaneous Electric Power: 389.000000 [W]

examples/以下に利用例がありますので参考にしてください。

Documentation

Overview

Package smartmeter provides an ECHONET Lite client for smart meters.

Index

Constants

View Source
const (
	HeaderEchonetLite          uint16      = 0x1081   // 0x10=ECHONET Lite, 0x81=電文形式1
	Controller                 ClassCode   = 0x05ff01 // コントローラ
	NodeProfile                ClassCode   = 0x0ef001 // ノードプロファイル
	LvSmartElectricEnergyMeter ClassCode   = 0x028801 // 低圧スマート電力量メータ
	Get                        ServiceCode = 0x62
	GetRes                     ServiceCode = 0x72
)

ECHONET Lite constants.

Variables

View Source
var ErrRetryable = errors.New("retrying")

ErrRetryable marks an error that should trigger a retry.

Functions

This section is empty.

Types

type ClassCode

type ClassCode uint32

ClassCode identifies an ECHONET Lite class code.

type Device

type Device struct {
	SerialPort  string
	ID          string
	Password    string
	Channel     string
	IPAddr      string
	DualStackSK bool
	Verbosity   int
	// contains filtered or unexported fields
}

Device represents a smart meter connection and its settings.

func Open

func Open(path string, opts ...Option) (d *Device, err error)

Open opens the serial port and returns a Device configured with opts.

func (*Device) Authenticate

func (d *Device) Authenticate(opts ...Option) (err error)

Authenticate performs scan, register configuration, and join.

func (*Device) GetInfo

func (d *Device) GetInfo(opts ...Option) (info string, err error)

GetInfo returns the info string from SKINFO.

func (*Device) GetNeibourIP

func (d *Device) GetNeibourIP(opts ...Option) (ipAddr string, err error)

GetNeibourIP returns the neighbor IP address from SKTABLE 2.

func (*Device) GetRegisterValue

func (d *Device) GetRegisterValue(
	regName string,
	opts ...Option,
) (registerValue string, err error)

GetRegisterValue returns a register value from SKSREG.

func (*Device) GetVersion

func (d *Device) GetVersion(opts ...Option) (version string, err error)

GetVersion returns the version string from SKVER.

func (*Device) Join

func (d *Device) Join(opts ...Option) (err error)

Join connects to the meter using SKJOIN.

func (*Device) QueryEchonetLite

func (d *Device) QueryEchonetLite(req *Frame, opts ...Option) (res *Frame, err error)

QueryEchonetLite sends an ECHONET Lite request and waits for the response.

func (*Device) QuerySKCommand

func (d *Device) QuerySKCommand(cmd string, opts ...Option) (res string, err error)

QuerySKCommand sends an SK command and returns the response text.

func (*Device) Scan

func (d *Device) Scan(opts ...Option) (err error)

Scan performs an active scan and populates channel, PAN ID, MAC address, and IP address.

func (*Device) SetID

func (d *Device) SetID(opts ...Option) (err error)

SetID sets the B-route authentication ID on the device.

func (*Device) SetPassword

func (d *Device) SetPassword(opts ...Option) (err error)

SetPassword sets the B-route authentication password on the device.

func (*Device) SetRegisterValue

func (d *Device) SetRegisterValue(regName string, regValue string, opts ...Option) (err error)

SetRegisterValue sets a register value via SKSREG.

type Frame

type Frame struct {
	TID        uint16      // トランザクションID
	SEOJ       ClassCode   // 送信元ECHONET Liteオブジェクト
	DEOJ       ClassCode   // 相手先ECHONET Liteオブジェクト
	ESV        ServiceCode // ECHONET Liteサービス
	Properties []*Property // ECHONETプロパティ
}

Frame はECHONET Liteのフレームに対応する構造体。 複数のプロパティの操作を1フレームにまとめて送信することができる。

func NewFrame

func NewFrame(dstClassCode ClassCode, esv ServiceCode, props []*Property) *Frame

NewFrame は Frame構造体のコンストラクタ関数。

func ParseFrame

func ParseFrame(raw []byte) (f *Frame, err error)

ParseFrame は ECHONET Liteフレームのバイト列を受け取り、Frame構造体として返す。

func (*Frame) Build

func (f *Frame) Build() []byte

Build はフレームをバイト列として組み立てる。

func (*Frame) CorrespondTo

func (f *Frame) CorrespondTo(target *Frame) bool

CorrespondTo は fとtargetとがリクエスト/レスポンスとして対応しているか確認する。

func (*Frame) RegenerateTID

func (f *Frame) RegenerateTID()

RegenerateTID はFrameのTIDを再生成する。

type Option

type Option func(interface{}) error

Option configures a Device or query.

func Channel

func Channel(channel string) Option

Channel sets the channel used for scanning or joining.

func DualStackSK

func DualStackSK(v bool) Option

DualStackSK enables or disables the dual stack SK behavior.

func ID

func ID(id string) Option

ID sets the B-route authentication ID.

func IPAddr

func IPAddr(ipAddr string) Option

IPAddr sets the IPv6 address of the smart meter.

func Logger

func Logger(logger *log.Logger) Option

Logger sets the logger for Device and query.

func Password

func Password(pw string) Option

Password sets the B-route authentication password.

func Reader

func Reader(callback func(string) (bool, error)) Option

Reader sets a custom line reader callback for SK command responses.

func Retry

func Retry(count int) Option

Retry sets how many times a query should retry on ErrRetryable.

func RetryInterval

func RetryInterval(d time.Duration) Option

RetryInterval sets the duration between retries.

func Timeout

func Timeout(d time.Duration) Option

Timeout sets the query timeout duration.

func Verbosity

func Verbosity(v int) Option

Verbosity sets the logging verbosity for Device and query.

type Property

type Property struct {
	EPC PropertyCode // ECHONETプロパティ
	EDT []byte       // 要求電文プロパティ値データ(EDT)
}

Property はECHONET Liteのプロパティに対応する構造体。

func NewProperty

func NewProperty(epc PropertyCode, edt []byte) *Property

NewProperty は Property構造体のコンストラクタ関数。

func (*Property) Build

func (p *Property) Build() []byte

Build はプロパティをバイト列として組み立てる。

func (*Property) Desc

func (p *Property) Desc() string

Desc はプロパティの内容を文字列として返す。

type PropertyCode

type PropertyCode byte

PropertyCode identifies an ECHONET Lite property code (EPC).

const (
	NodeProfileVersionInformation   PropertyCode = 0x82 // Version情報
	NodeProfileIdentificationNumber PropertyCode = 0x83 // 識別番号
	NodeProfileFaultStatus          PropertyCode = 0x88
	NodeProfileFaultContent         PropertyCode = 0x89
	NodeProfileManufacturerCode     PropertyCode = 0x8a // メーカコード
	NodeProfileBusinessFacilityCode PropertyCode = 0x8b // 事業場コード
	NodeProfileProductCode          PropertyCode = 0x8c // 商品コード
	NodeProfileProductionNumber     PropertyCode = 0x8d // 製造番号
	NodeProfileProductionDate       PropertyCode = 0x8e // 製造年月日
	NodeProfileUniqueIdentifierData PropertyCode = 0xbf // 個体識別情報
	// NodeProfileNumberOfSelfNodeInstances PropertyCode = 0xd3
	// 自ノードインスタンス数(作者の環境では1)
	// 自ノードクラス数(作者の環境では2)
	NodeProfileNumberOfSelfNodeClasses  PropertyCode = 0xd4
	NodeProfileInstanceListNotification PropertyCode = 0xd5
	NodeProfileSelfNodeInstanceListS    PropertyCode = 0xd6 // 自ノードインスタンスリストS
	NodeProfileSelfNodeClassListS       PropertyCode = 0xd7 // 自ノードクラスリストS

	// 係数(作者の環境では1)
	LvSmartElectricEnergyMeterCoefficient PropertyCode = 0xd3
	// 積算電力量(正方向)
	LvSmartElectricEnergyMeterNormalDirectionCumulativeElectricEnergy PropertyCode = 0xe0
	// 積算電力量単位(作者の環境では0.1kWh)
	LvSmartElectricEnergyMeterUnitForCumulativeAmountsOfElectricEnergy PropertyCode = 0xe1
	// 積算電力量(逆方向)
	LvSmartElectricEnergyMeterReverseDirectionCumulativeElectricEnergy PropertyCode = 0xe3
	// 瞬時電力計測値
	LvSmartElectricEnergyMeterInstantaneousElectricPower PropertyCode = 0xe7
	// 瞬時電流計測値
	LvSmartElectricEnergyMeterInstantaneousCurrent PropertyCode = 0xe8
	// 定時積算電力量(正方向)
	LvSmartElectricEnergyMeterNormalDirectionCumulativeElectricEnergyAtEvery30Min PropertyCode = 0xea
	// 定時積算電力量(逆方向)
	LvSmartElectricEnergyMeterReverseDirectionCumulativeElectricEnergyAtEvery30Min PropertyCode = 0xeb
)

Property codes for node profile and low-voltage smart electric energy meter.

type ServiceCode

type ServiceCode byte

ServiceCode identifies an ECHONET Lite service code.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL