1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Raspberry PiでC#を使ってTCP通信し、RS-WFWATTCH2からデータ取得する方法

Last updated at Posted at 2025-05-31

Raspberry PiでC#を使ってTCP通信し、RS-WFWATTCH2からデータ取得する方法

📝 はじめに

環境意識向上のため、家の電力の見える化を考えました
こちらの記事を基に、具体的実装をcopilotさんと作成し手順に書き出しました。
@yamaokunousausa (うさうさ)さん
ありがとうございます。
https://qiita.com/yamaokunousausa/items/2faedd6481093e73e2ca

追記

Raspberry Pi上でC#を使用し、TCP通信を行ってRS-WFWATTCH2から温度データを取得する手順を紹介します。本記事では環境構築からデータの取得・解析までを詳細に解説します。

🛠 環境準備

1️⃣ Raspberry Piのセットアップ

まず、Raspberry Piのパッケージを最新に更新します。

sudo apt update && sudo apt upgrade

2️⃣ .NET SDKのインストール
Raspberry Piに.NET SDKをインストールします。

curl -sSL https://dot.net/v1/dotnet-install.sh | bash /dev/stdin --channel STS
echo 'export DOTNET_ROOT=$HOME/.dotnet' >> ~/.bashrc
echo 'export PATH=$PATH:$HOME/.dotnet' >> ~/.bashrc
source ~/.bashrc

インストール確認:

dotnet --version

🚀 C#プロジェクトの作成
1️⃣ 新しいC#プロジェクトの作成

mkdir TcpClientApp
cd TcpClientApp
dotnet new console

2️⃣ Program.cs を編集

nano Program.cs

以下のコードを入力し、保存 (CTRL + X → Y → ENTER)。

using System;
using System.IO;
using System.Net.Sockets;
using System.Text;

class Program
{
    static void Main()
    {
        string host = "192.168.1.101"; // RS-WFWATTCH2 IP Address change IP Address
        int port = 60121; // RS-WFWATTCH" Port
        string csvFile = "rs_wfwattch2_data.csv";

        while (true) // loop
        {
            FetchData(host, port, csvFile);
            Thread.Sleep(15000); // 15 seconds interval
        }
    }

    static void FetchData(string host, int port, string csvFile)
    {
        try
        {
            using TcpClient client = new TcpClient();
            client.Connect(host, port); // connecting
            using NetworkStream stream = client.GetStream();

            byte[] command = { 0xAA, 0x00, 0x02, 0x18, 0x00, 0x65 };
            stream.Write(command, 0, command.Length);

            byte[] response = new byte[30];
            int bytesRead = 0;

            while (bytesRead < response.Length)
            {
                int result = stream.Read(response, bytesRead, response.Length -bytesRead);
                if (result == 0) throw new IOException("Disconnected before reading full response.");//case of disconnect
                bytesRead += result;
            }

            double voltage = ReadValue(response[5..11]) / (1L << 24);
            double current = ReadValue(response[11..17]) / (1L << 30);
            double power = ReadValue(response[17..23]) / (1L << 24);
            string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            using StreamWriter writer = new StreamWriter(csvFile, true, Encoding,UTF8);
            writer.WriteLine($"{timestamp},{voltage:F2},{current:F3},{power:F2}");

            Console.WriteLine($"{timestamp} - Voltage: {voltage:F2}V, Current: {current:F3}A,Power: {power:F2}W");
        }


        catch (SocketException ex)
        {
            LogError("error_log.txt", $"TCP Connect Error : {ex.Message}");
        }
        catch (IOException ex)
        {
            LogError("error_log.txt", $"Data no receive : {ex.Message}");
        }
        catch (Exception ex)
        {
            LogError("error_log.txt", $"Unknown Error :{ex.Message}");
        }
    }

    static long ReadValue(ReadOnlySpan<byte> buffer) =>
        ((long)buffer[5] << 40) +
        ((long)buffer[4] << 32) +
        ((long)buffer[3] << 24) +
        ((long)buffer[2] << 16) +
        ((long)buffer[1] << 8) +
        buffer[0];


    static void LogError(string filePath, string message)
    {
        string logEntry = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss} - {message}";
        File.AppendAllText(filePath, logEntry + Environment.NewLine);
        Console.WriteLine(logEntry);
    }
}

実行は

dotnet add package System.Net.Sockets
dotnet restore

🏗 コードのビルドと実行
1️⃣ コードのコンパイル

dotnet build

2️⃣ TCP通信の実行

dotnet run

実行すると、以下のような出力が得られます。CSVファイルも出力されます

2025-06-01 22:10:47,104.00,0.000,4.00
2025-06-01 22:25:43,103.00,0.000,5.00
2025-06-01 22:25:59,103.00,0.000,2.00
2025-06-01 22:27:00,103.00,0.000,3.00

✅ まとめ
この記事では、Raspberry PiでC#を使用してTCP通信を行い、RS-WFWATTCH2からデータを取得・解析する方法を紹介しました。環境構築から実行までの流れを整理しましたので、ぜひ試してみてください。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?