'[ 충남인력개발원 ] (2019)/┗C#'에 해당되는 글 6건

윈도우 임베이디드 용 E

 

델타 시스템 사용유무

 

제트펄스

AB

 

mosquitto 설치파일들.egg
9.87MB

 

실행 되어있음.

 

 

https://hpoption.tistory.com/201

 

[MQTT] mosquitto 와 통신되는 C# 버전

MQTT 예제를 몇가지 받았는데 라이브러리만 있고 완성된 소스가 없었다. 열심히 찾아 보니 나왔다. 그것도 GUI 형태... using uPLibrary.Networking.M2Mqtt.Messages; 처럼 M2Mqtt.dll 를 사용한 예제인데 출처를..

hpoption.tistory.com

코드 사용하기

 

MQTT-Client-master(c#-cho).zip
0.04MB

 

http://www.hardcopyworld.com/ngine/aduino/index.php/archives/3369

 

[IoT 네트워크 서비스 강좌] #5-3 MQTT 연동 IoT 서비스 | Hard Copy Arduino

 

www.hardcopyworld.com

 

활용 예제

 

이제 사용법을 사용해보자

 

 

 

이렇게 쓰면 된다

 

'[ 충남인력개발원 ] (2019) > ┗C#' 카테고리의 다른 글

6일차 C#과 ModBus  (0) 2020.04.13
4일차 Fuction 3 코드 해석  (0) 2020.04.09
3일차 코드 모두버스의 대하여  (0) 2020.04.08
2일차 코드??  (0) 2020.04.07
1일차 C# 윈폼 EXCEL 데이터 컴파일  (0) 2020.02.24
블로그 이미지

Or71nH

,

### 멀티 쓰레드

private object obj = new object();

lock (obj)
{

}


system.threading.monitor.Enter( obj)
try{

} finally {
	system.threading.Monitor.Exit(obj);
    }

### 사용예 쓰레드 사용하기 1

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;


namespace ConsoleApp3
{
    // 다수의 스레드가 하나의 객체를 사용하는 경우
    class ThisLock
    {
        public void IncreaseCount(ref int count)
        {
            count++;
        }
    }

    class Test
    {
        ThisLock lockObject = new ThisLock();
        int Count = 0;

        public void ThreadProc()
        {
            lock (lockObject) // <-- object형으로 처리해도 결과는 동일하다.
            {
                for (int i = 0; i < 10; i++)
                {
                    lockObject.IncreaseCount(ref Count);
                    Console.WriteLine("Thread ID: {0} result: {1}", Thread.CurrentThread.GetHashCode(), Count);
                }
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Test test = new Test();
            Thread[] threads = new Thread[3];
            for (int i = 0; i < 3; i++)
            {
                threads[i] = new Thread(new ThreadStart(test.ThreadProc));
            }

            for (int i = 0; i < 3; i++)
            {
                threads[i].Start();
            }
        }
    }
}

### 모니터 사용하기 lockr과 차이가 없음

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;


namespace ConsoleApp6
{
    // 다수의 스레드가 하나의 객체를 사용하는 경우
    class Test
    {
        int Count;
        object obj = new object();

        public void IncreaseCount()
        {
            Monitor.Enter(obj);
            for (int i = 0; i < 5; i++)
            {
                Count++;
                Console.WriteLine("Thread Id: {0} Count: {1}", Thread.CurrentThread.GetHashCode(), Count);
            }
            Monitor.Exit(obj);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Test test = new Test();
            Thread th1 = new Thread(new ThreadStart(test.IncreaseCount));
            Thread th2 = new Thread(new ThreadStart(test.IncreaseCount));
            th1.Start();
            th2.Start();
        }
    }
}

### lock 같이쓰기?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;


namespace ConsoleApp7
{
    // 다수의 스레드가 하나의 객체를 사용하는 경우
    class ThisLock
    {
        public void IncreaseCount(ref int count)
        {
            count++;
        }
    }

    class Test
    {
        ThisLock lockObject = new ThisLock();
        public int Count = 0;

        public void ThreadProc()
        {
            Monitor.Enter(lockObject);
            for (int i = 0; i < 10; i++)
            {
               lockObject.IncreaseCount(ref Count);
               Console.WriteLine("Thread ID: {0} result: {1}", Thread.CurrentThread.GetHashCode(), Count);
            }
            Monitor.Exit(lockObject);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Test test = new Test();
            Thread[] threads = new Thread[3];
            for (int i = 0; i < 3; i++)
            {
                threads[i] = new Thread(new ThreadStart(test.ThreadProc));
            }

            for (int i = 0; i < 3; i++)
            {
                threads[i].Start();
            }
        }
    }
}

### mutex 쓰레드 사용하기

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;


namespace ConsoleApp7
{
    // 다수의 스레드가 하나의 객체를 사용하는 경우
    class ThisLock
    {
        public void IncreaseCount(ref int count)
        {
            count++;
        }
    }

    class Test
    {
        ThisLock lockObject = new ThisLock();
        public int Count = 0;

        public void ThreadProc()
        {
            Monitor.Enter(lockObject);
            for (int i = 0; i < 10; i++)
            {
               lockObject.IncreaseCount(ref Count);
               Console.WriteLine("Thread ID: {0} result: {1}", Thread.CurrentThread.GetHashCode(), Count);
            }
            Monitor.Exit(lockObject);
        }
    }
    // Mutex를 메서드에 적용한 예
    class Program
    {
        static Mutex mut = new Mutex();
        static int Count;

        static void ThreadProc()
        {
            mut.WaitOne();
            for (int i = 0; i < 5; i++)
            {
                Count++;
                Console.WriteLine("Tread ID: {0} Count: {1}", Thread.CurrentThread.GetHashCode(), Count);

            }
            mut.ReleaseMutex();
        }

        static void Main(string[] args)
        {
            Test test = new Test();
            Thread[] threads = new Thread[3];
            for (int i = 0; i < 3; i++)
            {
                threads[i] = new Thread(new ThreadStart(test.ThreadProc));
            }

            for (int i = 0; i < 3; i++)
            {
                threads[i].Start();
            }
        }
    }
}


### Mutex를 이용한 코드 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;


namespace ConsoleApp9
{
    // 다수의 스레드가 하나의 객체를 사용하는 경우
    class ThisLock
    {
        public void IncreaseCount(ref int count)
        {
            count++;
        }
    }

    class Test
    {
        ThisLock lockObject = new ThisLock();
        Mutex mut = new Mutex();
        public int Count = 0;

        public void ThreadProc()
        {
            mut.WaitOne();
            for (int i = 0; i < 10; i++)
            {
               lockObject.IncreaseCount(ref Count);
               Console.WriteLine("Thread ID: {0} result: {1}", Thread.CurrentThread.GetHashCode(), Count);
            }
            mut.ReleaseMutex();
        }
    }
    // Mutex를 메서드에 적용한 예
    class Program
    {
        static Mutex mut = new Mutex();
        static int Count;

        static void ThreadProc()
        {
            mut.WaitOne();
            for (int i = 0; i < 5; i++)
            {
                Count++;
                Console.WriteLine("Tread ID: {0} Count: {1}", Thread.CurrentThread.GetHashCode(), Count);

            }
            mut.ReleaseMutex();
        }

        static void Main(string[] args)
        {
            Test test = new Test();
            Thread[] threads = new Thread[3];
            for (int i = 0; i < 3; i++)
            {
                threads[i] = new Thread(new ThreadStart(test.ThreadProc));
            }

            for (int i = 0; i < 3; i++)
            {
                threads[i].Start();
            }
        }
    }
}
블로그 이미지

Or71nH

,
#region Function 3 - Read Registers
        public bool SendFc3(byte address, ushort start, ushort registers, ref short[] values)
        {
            //Ensure port is open:
            if (serialPort.IsOpen)
            {
                //Clear in/out buffers:
                serialPort.DiscardOutBuffer();
                serialPort.DiscardInBuffer();
                //Function 3 request is always 8 bytes:
                if (MyGlobals.serial_mode == MyGlobals.MODBUS_RTU)
                {
                    byte[] message = new byte[1 + 1 + 2 + 2 + 2];
                    byte[] response = new byte[1 + 1 + 1 + (2 * registers) + 2];
                    //Build outgoing modbus message:
                    BuildMessage(address, (byte)3, start, registers, ref message);
                    try
                    {
                        serialPort.Write(message, 0, message.Length);
                        GetResponse(ref response);
                    }
                    catch (Exception err)
                    {
                        modbusStatus = "Error in read event: " + err.Message;
                        return false;
                    }
                    if (CheckResponse(response))
                    {
                        //Return requested register values:
                        for (int i = 0; i < (response.Length - 5) / 2; i++)
                        {
                            values[i] = response[2 * i + 3];
                            values[i] <<= 8;
                            values[i] += response[2 * i + 4];
                        }
                        modbusStatus = "Read successful";
                        return true;
                    }
                    else
                    {
                        modbusStatus = "CRC error";
                        return false;
                    }
                }
                else
                {
                    modbusStatus = "CRC error";
                    return false;
                }
            }
            else
            {
                modbusStatus = "Serial port not open";
                return false;
            }
        }
        #endregion

여기선 사전 검사 를 하는거라고 생각하면 된다

사이즈를 만들고 이제 밑에 빌드 메세지로 간다

 #region Build Message
        public void BuildMessage(byte address, byte type, ushort start, ushort registers, ref byte[] message)
        {
            //Array to receive CRC bytes:
            byte[] CRC = new byte[2];
            byte[] message2 = new byte[20];
            message2 = null;
            
            if (MyGlobals.serial_mode == MyGlobals.MODBUS_RTU)
            {
                message[0] = address;
                message[1] = type;
                message[2] = (byte)(start >> 8);
                message[3] = (byte)start;
                message[4] = (byte)(registers >> 8);
                message[5] = (byte)registers;

                GetCRC(message, ref CRC);
                message[message.Length - 2] = CRC[0];
                message[message.Length - 1] = CRC[1];
            }
            else   //Ascii - FC3
            {
            }
            send_message = null;
            for (int i = 0; i < message.Length; i++)
            {
                send_message += message[i] + " ";
            }
            //send_message+= null;
        }
        #endregion

빈 메세지를 받고 기에 값을 넣기 시작한다 

'[ 충남인력개발원 ] (2019) > ┗C#' 카테고리의 다른 글

8일차 모스키토 사용  (0) 2020.04.16
6일차 C#과 ModBus  (0) 2020.04.13
3일차 코드 모두버스의 대하여  (0) 2020.04.08
2일차 코드??  (0) 2020.04.07
1일차 C# 윈폼 EXCEL 데이터 컴파일  (0) 2020.02.24
블로그 이미지

Or71nH

,

모두버스 코드의 생성방법 

 

모두버스 메모리의 

 

Coils                                      그니깐 출력값 

Holding Register                       붙잡고 계속 받는거

Input Register                          들어온 데이터

Output Register                        나가는 데이터 

한국말로 간단히 바꿔도 뭔 뜻일까 이미지가 생각이 난다

 

 

그리고  운송 단계가 있다

데이터 타입 약속 코드 비고  
Read Discrete Inputs 읽기 별개의 입력값  02 그니깐 분간해주는 값임 Bit access 
Read Coils 
Write Simgle Coil
읽기 코일(bit 읽기)
쓰기 하나 코일(bit 쓰기)
01
05
코일을 읽어올꺼다 라는 명령어
코일에 값을 쓸꺼다 라는 명령어
Write Multiple Coils 쓰기 여러게 코일 15 아마 16개까지 될듯함 16bit Access 
Read Input Register 읽기 들어온값 신청하다 04 그니깐 읽을값을 하나 신청하는 거임 그래서 값을 받는거임
Read Holding Registers 읽기 붙잡아 신청하기 03 음..계속불러오기 인가?
Write Single Register
Write Multiple Register
쓰기 하나 신청하다(16bit)
쓰기 여러게 신청하다
06
16
비트가 많음 한 줄 바꾸는 거임 아!Register 줄이라 생각하면됨
Read/ Write Multiple
Registers
읽기/쓰기 여러게 신청하다 23 ???이건 뭐지???
Read Exception Status 읽기 예외 신분 07 진단하는거??

###대충 이런식 

e

 

Application_Protocol_V1_1b.pdf
0.31MB

 

Program.cs
0.00MB
modbus.cs
0.01MB

다음에 참고하여 더쓰겟움

'[ 충남인력개발원 ] (2019) > ┗C#' 카테고리의 다른 글

8일차 모스키토 사용  (0) 2020.04.16
6일차 C#과 ModBus  (0) 2020.04.13
4일차 Fuction 3 코드 해석  (0) 2020.04.09
2일차 코드??  (0) 2020.04.07
1일차 C# 윈폼 EXCEL 데이터 컴파일  (0) 2020.02.24
블로그 이미지

Or71nH

,

로봇즉 깍기기술 로봇의 외간을 움직이며 깍음

Robot = LMOB #po 이렇게 코드를 부른다

 

로봇이 아닌 깍는 기계를 이용하여 만드는 기계

CNC = Goo #po 이렇게 코드를 부른다

 

 

 

1. 컴파일러 인터프린터 책

 

EMBEDDED RECIPES

 

 

http://recipes.egloos.com/

 

임베디드 레시피

친절한 임베디드 개발자되기 강좌

recipes.egloos.com

DLL (Dynamioc Linking Library)

DLL 만들고 사용하기 

 

 

용접할때는 노이즈가 많이 발생한다 ???

이유는 모르겠지만 그래서 노이즈 방어 선을 많이 쓴다

 

 

nModbus_API_Manual_v1.2_en.pdf
0.77MB

https://docs.microsoft.com/ko-kr/dotnet/api/system.io.ports.serialport?view=netframework-4.8

 

SerialPort 클래스 (System.IO.Ports)

 

직렬 포트 리소스를 나타냅니다.Represents a serial port resource.

docs.microsoft.com

두개를 참조하면 공부하기 쉬워진다

 

 

##########

1.일단 추가해야 할 것들이있다

 

여기를 보고 참조하길 바란다

http://comfilewiki.co.kr/ko/doku.php?id=comfilepi:nmodbus4_k:index

 

comfilepi:nmodbus4_k:index [Comfile Technology's Online Documentation]

NModbus4 사용법 산업현장에서 많이 사용하고 있는 MODBUS 프로토콜을 ComfilePi에서 동작시키는 방법을 알아보겠습니다. Nmodbus4 라이브러리를 이용하면 쉽고 간단하게 MODBUS프로토콜을 구현할 수 있습니다. ComfilePi와 PLC 결선 ComfilePi의 RS232 COM0와 PLC의 RS232 포트에 TX-RX, RX-TX, GND-GND로 연결합니다. ComfilePi와 PLC의 RS232 결선은 아래와 같습니다. ※PLC는

comfilewiki.co.kr

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;

using Xisom.Scada.Browser;
using Xisom.Scada.Core;
using Xisom.Scada.Model;

using Modbus.Device;
using System.IO.Ports;
using Modbus.Utility;
using System.Windows.Forms.DataVisualization.Charting;

namespace XiSOM_DLL_APP
{
    public partial class Form1 : Form
    {

        byte[] PVTable = new byte[30] { 0,0,0,0,0,0,0,0,0,0,
                                        0,0,0,0,0,0,0,0,0,0,
                                        0,0,0,0,0,0,0,0,0,0};
        byte pvCounter = 0;
        public const byte MAX_PVCOUNT = 30;

        private SerialPort serialPort = null;
        public Form1()
        {
            InitializeComponent();
          
        }
        const int SLAVE_ADDRESS = 1;

        #region 호출 함수루틴
         private void Form1_Load(object sender, EventArgs e)
        {
 
            chart1.Series.Clear();
            Series sPVValue = chart1.Series.Add("PV Value");
            sPVValue.ChartType = SeriesChartType.Line;

             try
            {
                serialPort = new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One);  //온도 조절기 매칭
                serialPort.Open();

                ReadOnceData();
                timer1.Enabled = true;
                timer1.Interval = 1000;
                timer1.Start();

            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }
        private void ReadOnceData()
        {
            IModbusMaster masterRTU = ModbusSerialMaster.CreateRtu(serialPort);
            const ushort SLAVE_REGISTER = 0;
            const ushort SLAVE_POINT = 7;
            try
            {
                ushort[] result = masterRTU.ReadHoldingRegisters(1, SLAVE_REGISTER, SLAVE_POINT);
                textBox3.Text = string.Empty;
                foreach (ushort item in result)
                {
                    textBox3.Text += string.Format("{0}/", item);
                }
                string[] array = textBox3.Text.Split('/');
                textBox1.Text = array[2].Insert(array[1].Length - 1, ".");   //SV 
                textBox2.Text = array[1].Insert(array[2].Length - 1, ".");   //PV
            }
            catch (Exception ex)
            {
                ReportError(ex.Message);
            }
        }

        void ReportError(string s)
        {
            MessageBox.Show(s);
        }
        private void SendReadholdingRegisterPV()
        {
            IModbusMaster masterRTU = ModbusSerialMaster.CreateRtu(serialPort);
            try
            {
                ushort[] result = masterRTU.ReadHoldingRegisters(1, 1, 1);
                textBox2.Text = string.Format("{0}", result[0]);
                textBox2.Text = textBox2.Text.Insert(textBox2.Text.Length - 1, ".");
                //result값을 저장하고 나서 
                PVTable[pvCounter++] = (byte)(result[0]);  //나누기 10없이 그대로 찍음
            }
            catch (Exception ex)
            {
                ReportError(ex.Message);
            }
        }
        #endregion

        #region 작성된 폼만의 타이머 통신 쓰기명령
        private void button2_Click(object sender, EventArgs e)
        {
            IModbusMaster masterRTU = ModbusSerialMaster.CreateRtu(serialPort);
            try
            {
                ushort[] result = masterRTU.ReadHoldingRegisters(1, 1, 1);
                //bool[] result = _modbusMaster.ReadCoils(SLAVE_ADDRESS, 2, 1);
                //if (result[0] != 0)
                //{
                //    textBox1.Text = "ON";
                //}
                //else
                //{
                //    textBox1.Text = "OFF";
                //}
                textBox2.Text = string.Format("{0}", result[0]);
                textBox2.Text = textBox2.Text.Insert(textBox2.Text.Length - 1, ".");
            }
            catch (Exception ex)
            {
                ReportError(ex.Message);
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                IModbusMaster masterRTU = ModbusSerialMaster.CreateRtu(serialPort);
                string t = textBox1.Text;
                int cnt_t = t.Length - t.IndexOf('.') - 1;  //소수점 이하자리 카운트
                float ff = (float.Parse(textBox1.Text)) *  cnt_t;
                
                string[] st= t.Split('.');
                t = st[0] + st[1];
                
                ushort[] data = new ushort[] { Convert.ToUInt16(t)};
              
                masterRTU.WriteMultipleRegisters(1, 301, data);
            }
            catch (Exception ex)
            {
                ReportError(ex.Message);
            }
        }
        #endregion

        #region 작성된 폼만의 타이머 통신
        private void timer1_Tick(object sender, EventArgs e)
        {
            SendReadholdingRegisterPV();
            if (pvCounter >= MAX_PVCOUNT)
            {
                for (int i = 0; i < (MAX_PVCOUNT-1); i++)
                {
                    PVTable[i] = PVTable[i + 1];
                }
                pvCounter--;
            }
            chart1.Series[0].Points.DataBindY(PVTable);
        }
        #endregion
    }
}
블로그 이미지

Or71nH

,