MultiTread application on Raspberry Pi with C# .NET 5.0

Continue with the Raspberry Pi work.

 

Deliverables

Temperature Reading

Read the temperature value form DS18B20 int a sub thread, this is because the temperature reading really cost some time.

Everytime it read the temperature value, send the value to the client with a TCP connection which the port Number is 1300(Mainely for sending messages). 

PWM Adjustment

 As I wish to make a PID controller, so ,To accomplish this goal, also need to adjust the PWM timely. I'm prepared to use Labview to control PWM with anothe port: 1200(Mainely for recieving messages). 

As the two reason above,  it's better to use multiple thread to implement the program.

 

ScreenShot

 f:id:sesnail:20210208194840p:plain

 

code

using System;
using System.Net;
using System.Net.Sockets;
using System.Device.Gpio;
using System.Device.Pwm.Drivers;
using System.Threading;
using System.Threading.Tasks;
using Iot.Device.OneWire;
using System.Text;
using System.Collections.Generic;

namespace ConsoleApp1
{
    class Program
    {

         static  void Main(string[] args)
            {
                OneWireThermometerDevice theDs = null;
                GpioController controller = new GpioController();

                //TCP connection define
                int PortTemperature = 1300;
                int PortPWM = 1200;
                IPAddress serverAddr = IPAddress.Parse("192.168.11.10");
                TcpListener listenerTemp = null;
                TcpListener listenerPWM = null;
                NetworkStream streamTemp = null;
                NetworkStream streamPWM = null;
                string temperature = string.Empty;
                float pwm = 0;

                //PWM define
                int pin = 18;
                SoftwarePwmChannel theChannel = null;
                DeviceInitialize(ref theChannel, ref controller, pin, ref theDs);
                Console.WriteLine("Blinking LED. Press Ctrl+C to end.");
            #region TCP
            // Set the TcpListener on port 13000.
            Task.Run(() => ThreadReadTemperature());
            // Enter the listening loop.
            while (true)
                {
                    //pwm = float.Parse(Console.ReadLine());
                    //Console.Write(pwm);
                    LEDSwitch();
                }

                //// Shutdown and end connection
                //client.Close();
                #endregion
                void ThreadReadTemperature()
                {
                    try
                    {

                        while (true)
                        {
                            Byte[] sendBytes = null;

                            Console.Write("Temperature Waiting for a connection... ");
                            // TcpListener server = new TcpListener(port);
                            listenerTemp = new TcpListener(serverAddr, PortTemperature);
                            listenerTemp.Start();
                            // Perform a blocking call to accept requests.
                            TcpClient client = listenerTemp.AcceptTcpClient();
                            Console.WriteLine("Temperature Connected!");

                            // Get a stream object for reading and writing
                            streamTemp = client.GetStream();
                            // Loop to receive all the data sent by the client.

                            // Start listening for client requests.
                           
                            while (true)
                            {
                                temperature = theDs.ReadTemperature().ToString();
                                sendBytes = Encoding.ASCII.GetBytes(temperature);
                                streamTemp.Write(sendBytes, 0, sendBytes.Length);
                                Console.WriteLine(temperature);
                            }
                        }
                    }
                    catch (SocketException e)
                    {
                        Console.WriteLine("SocketException: {0}", e);
                        // Stop listening for new clients.
                        listenerTemp.Stop();
                    }
                }
                void LEDSwitch()
                {

                    try
                    {
                        Byte[] readBytes = new Byte[256];

                        Console.Write("PWM Waiting for a connection... ");
                        // TcpListener server = new TcpListener(port);
                        listenerPWM = new TcpListener(serverAddr, PortPWM);

                        // Start listening for client requests.
                        listenerPWM.Start();
                        // Perform a blocking call to accept requests.
                        TcpClient client = listenerPWM.AcceptTcpClient();
                        Console.WriteLine("PWM Connected!");

                        // Get a stream object for reading and writing
                        streamPWM = client.GetStream();
                        // Loop to receive all the data sent by the client.
                        int i;

         
                            while ((i = streamPWM.Read(readBytes, 0, readBytes.Length)) != 0)
                            {
                                pwm = float.Parse(Encoding.ASCII.GetString(readBytes));
                                Console.WriteLine($"PWM:  {pwm}");
                                Console.WriteLine(temperature);
                                if(0<=pwm && pwm<=1)theChannel.DutyCycle = pwm;
                            
                            //streamPWM.Flush();
                        }
                    
                    }
                    catch (SocketException e)
                    {
                        Console.WriteLine("SocketException: {0}", e);
                        // Stop listening for new clients.
                        listenerPWM.Stop();
                        controller.ClosePin(pin);
                        theChannel.Stop();
                    }

                    //controller.Write(pin, ((ledOn) ? PinValue.High : PinValue.Low));
                    //ledOn = !ledOn;
           }
                void DeviceInitialize(ref SoftwarePwmChannel channel, ref GpioController theController, int ControlPin, ref OneWireThermometerDevice theDal)
                {
                    string busID = "", devieID = "";
                    channel = new SoftwarePwmChannel(ControlPin, 400, 0.5, false, theController, false);
                    channel.Start();
                    //theController.OpenPin(ControlPin, PinMode.Output);
                    foreach (var device in OneWireThermometerDevice.EnumerateDevices())
                    {
                        busID = device.BusId;
                        devieID = device.DeviceId;
                        Console.WriteLine(busID + "," + devieID + ","+device.Family);
                    }
                    theDal = new OneWireThermometerDevice(busID, devieID);
                
                }
            }
    }
}