Untitled

mail@pastecode.io avatar
unknown
plain_text
23 days ago
11 kB
1
Indexable
Never
//Cam_Rapi.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using OpenCvSharp;
using System.Windows.Forms;
using System.ComponentModel;

namespace ICSys
{
    /// <summary>
    /// カメラ画像取得用ラズパイ通信
    /// </summary>
    public class Cam_Rapi
    {
        /// <summary>
        /// 終了イベント用
        /// </summary>
        /// <param name="sender"></param>
        public delegate void TerminateEventHandler(object sender); //デリゲート(処理終了用) 
        /// <summary>
        /// 終了イベント
        /// </summary>
        public event TerminateEventHandler OnTerminate;
        /// <summary>
        /// 終了フラグ
        /// </summary>
        bool FTerminate = false;
        /// <summary>
        /// スレッド
        /// </summary>
       // Thread ThreadMain;
        /// <summary>
        /// スレッドカウント
        /// </summary>
        private int ThreadCount = 0;
        /// <summary>
        /// 終了フラグ
        /// </summary>
        public bool Terminate
        {
            set
            {
                FTerminate = value;
            }
        }
        /// <summary>
        /// 周期時間
        /// </summary>
        public int WaitTime
        {
            get;
            set;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="Msg"></param>
        /// <param name="Ex"></param>
        public delegate void DoOnErrStatus(string Msg, Exception Ex);
        /// <summary>
        /// 
        /// </summary>
        public event DoOnErrStatus OnErrStatus;
        //public event DoOnErrStatus OnErrStatus2;
        /// <summary>
        /// 
        /// </summary>
        public event DataEventHandler OnSendMsg;
        //public event DataEventHandler OnSendMsg2;
        /// <summary>
        /// 
        /// </summary>
        public event DataEventHandler OnRecvMsg;
        //public event DataEventHandler OnRecvMsg2;
        /// <summary>
        /// 送信データ格納エリア
        /// </summary>
        public byte[] SendD { get; set; }
        /// <summary>
        /// 受信データ格納エリア
        /// </summary>
        //public byte[] RecvD;
        //public byte[] RecvD2;
        /// <summary>
        /// ソケット通信
        /// </summary>
        TcpClient Tcp;
        /// <summary>
        /// 通信状態
        /// </summary>
        public bool State { get; set; }
        /// <summary>
        /// 状態表示
        /// </summary>
        /// <param name="StrErr"></param>
        public void DoOnStatus(string Msg, Exception Ex)
        {
            if (OnErrStatus != null)
            {
                OnErrStatus(Msg, Ex);
            }
        }
        /// <summary>
        /// 接続IPアドレス
        /// </summary>
        public string IPAdr = "192.168.56.1";
        /// <summary>
        /// 接続ポート番号
        /// </summary>
        public int PortNo = 10050;

        // public Timer timer;

        /// <summary>
        /// 構築子
        /// </summary>
        public Cam_Rapi(string _IPAdr, int _PortNo)
        {
            WaitTime = 1;
            PortNo = _PortNo;
            IPAdr = _IPAdr;
            //RecvD = new byte[200000];


            //string Text = "abc\n";
            //ASCII エンコード
            //SendD = System.Text.Encoding.ASCII.GetBytes(Text);
            SendD = new byte[8];

        }
        /// <summary>
        /// 
        /// </summary>
        private TcpClient client;
        private NetworkStream stream;
        private const string serverIP = "192.168.56.1";
        private const int port = 10050;
        //private Timer timer;
        public byte[] RecvD;
        private BackgroundWorker backgroundWorker;

        public void Run()
        {
            StartClient();
            StartBackgroundWorker();
        }

        public void StartClient()
        {
            try
            {
                client = new TcpClient();
                client.Connect(IPAdr, PortNo);
                stream = client.GetStream();
                stream.ReadTimeout = 1000;
                State = false;
                //MessageBox.Show("Connected to the server");
            }
            catch (Exception ex)
            {
                //throw new Exception($"Error: {ex.Message}");
            }
        }

        public void StartBackgroundWorker()
        {
            backgroundWorker = new BackgroundWorker();
            backgroundWorker.DoWork += BackgroundWorker_DoWork;
            backgroundWorker.WorkerSupportsCancellation = true;
            backgroundWorker.RunWorkerAsync();
        }

        private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            while (!backgroundWorker.CancellationPending)
            {
                ReceiveImage();
            }
        }

        public void ReceiveImage()
        {
            try
            {
                byte[] lengthBuffer = new byte[4];
                int bytesRead = stream.Read(lengthBuffer, 0, lengthBuffer.Length);
                if (bytesRead == 0)
                {
                    return;
                }
                State = true;

                int dataLength = BitConverter.ToInt32(lengthBuffer.Reverse().ToArray(), 0);
                RecvD = new byte[dataLength];

                int totalBytesRead = 0;
                while (totalBytesRead < dataLength)
                {
                    bytesRead = stream.Read(RecvD, totalBytesRead, dataLength - totalBytesRead);
                    if (bytesRead == 0)
                    {
                        return;
                    }
                    totalBytesRead += bytesRead;
                }

                // Trigger the OnRecvMsg event handler
                OnRecvMsg(RecvD, totalBytesRead);
            }
            catch (Exception ex)
            {
                //throw new Exception($"Error: {ex.Message}");
            }
        }


        /*public void Run()
        {
            do
            {
                try
                {
                    Tcp = new TcpClient();
                    State = false;
                    Tcp.Connect(IPAdr, PortNo);
                    NetworkStream NS = Tcp.GetStream();
                    NS.ReadTimeout = 2000;
                    //NS.CanTimeout = false;
                    try
                    {
                        while (!FTerminate)
                        {
                            NS.Write(SendD, 0, SendD.Length);
                            if (OnSendMsg != null)
                            {
                                OnSendMsg(SendD, SendD.Length);
                            }


                            Thread.Sleep(10);

                            int i = 0;
                            while (!FTerminate)
                            {
                                if (NS.CanRead)
                                {
                                    try
                                    {
                                        byte Work = (byte)NS.ReadByte();
                                        //Console.WriteLine("Work Length: " + Work);
                                        State = true;
                                        RecvD[i] = (byte)Work;
                                        i++;
                                        if (i >= RecvD.Length || !NS.DataAvailable)
                                        {
                                            break;
                                        }
                                        if (!NS.DataAvailable)
                                        {
                                            break;
                                        }

                                        *//*byte[] lengthBuffer = new byte[4];
                                        int bytesRead = NS.Read(lengthBuffer, 0, lengthBuffer.Length);
                                        if (bytesRead < 4)
                                        {
                                            throw new Exception("Could not read frame length");
                                        }

                                        int messageLength = BitConverter.ToInt32(lengthBuffer, 0);
                                        RecvD = new byte[messageLength];

                                        int totalBytesRead = 0;
                                        while (totalBytesRead < messageLength)
                                        {
                                            bytesRead = NS.Read(RecvD, totalBytesRead, messageLength - totalBytesRead);
                                            if (bytesRead == 0)
                                            {
                                                throw new Exception("Connection closed by the server");
                                            }
                                            totalBytesRead += bytesRead;
                                        }*/

        /*State = true;

        if (OnRecvMsg != null)
        {
            OnRecvMsg(RecvD, totalBytesRead);
        }*//*

        // DisplayFrame(RecvD);


        if (!NS.DataAvailable)
        {
            break;
        }
    }
    catch (Exception Ex)
    {
        DoOnStatus("Run", Ex);
        State = false;
        Thread.Sleep(10);
        break;
    }
}
else
{
    Thread.Sleep(10);
    break;
}
}
if (i > 0)
{

if (OnRecvMsg != null)
{
    OnRecvMsg(RecvD, i);
}
}
Thread.Sleep(WaitTime);
}
}
catch (Exception Ex)
{
DoOnStatus("Run", Ex);
State = false;
}
}
catch (SocketException Ex)
{
Console.WriteLine($"SocketException: {Ex.Message}");
DoOnStatus("Run", Ex);
State = false;
Thread.Sleep(1000);
Tcp.Close();
Tcp.Dispose();
}
Thread.Sleep(100);
}
while (!FTerminate);
ThreadCount--;
if (OnTerminate != null)
{
OnTerminate(this);
}
}*/
        /*private void DisplayFrame(byte[] frameData)
        {
            try
            {
                Mat frame = Cv2.ImDecode(frameData, ImreadModes.Color);
                Cv2.ImShow("Webcam", frame);
                Cv2.WaitKey(1);
            }
            catch (Exception ex)
            {
                DoOnStatus("DisplayFrame", ex);
            }
        }*//*
    }*/
    }
}
Leave a Comment