Sample Header Ad - 728x90

c# script waiting in terminal but exiting directly as a daemon

0 votes
1 answer
479 views
- i am a complete c# noob (i know Java though) - i have a c# script i modified. I want to run it at startup using a daemon and systemctl (the original is this NZXT automatic fan controller script ) - the code created a repeating timer to execute a piece of code every 4 seconds and blocks exiting the script using Console.ReadLine(); - i compiled and tested the script using msc and mono. it works as intended in a terminal (it is NOT exiting directly) - when run as a daemon, Console.ReadLine(); doesn't wait and the script directly completes the main method and exits - NOTES: - - i am also a linux moob, so please point out if i am doing something wrong in the daemon. My goal is having a background script that i can start and stop, which the system starts from me on boot - please find all code attached below main code:
using System;
using System.IO;
using System.Timers;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Text.RegularExpressions;

public class Program
{

    private static string root;
    private static string confFile = "/home/mohammadah/scripts/grid+v2/conf.d";
    private static System.Timers.Timer aTimer;

    private static int maxSpeed = 100;
    private static int minSpeed = 35;
    // do not change this. all fan speeds have to rounded to the nearest multiple of 5
    private static int minimumRound = 5;
    private static int timerTime = 4000;
    private static int defaultFanSpeed = 40;

    // fans: 
    // 1: empty
    // 2: empty
    // 3: bottom
    // 4: top
    // 5: CPU
    // 6: Back
    private static int[] gpuFans;
    private static int gpuMaxTemp;
    private static int gpuMinTemp;

    private static int[] cpuFans;
    private static int cpuMaxTemp;
    private static int cpuMinTemp;

    private static float lastCPUSpeed = 0;
    private static float lastGPUSpeed = 0;

    public static void Main()
    {
    //    Console.WriteLine(System.IO.Path.GetDirectoryName(Application.ExecutablePath));
       ParseConfigFile(confFile);


        if(!Regex.IsMatch(DoGridCommand("get fan 1"), @"Fan 1: \d{1,5} RPM")){
            DoGridCommand("init");
        }

        DoGridCommand("set fans all speed " + defaultFanSpeed);

        

        SetTimer();
        Console.WriteLine("\nPress the Enter key to exit the application...\n");
        // Process.GetCurrentProcess().WaitForExit();

        Console.ReadLine();
        aTimer.Stop();
        aTimer.Dispose();
        Console.WriteLine("Terminating the application...");
    }

    private static float GetGPUTemp(){
        ProcessStartInfo procStartInfo = new ProcessStartInfo("/bin/bash", "-c nvidia-smi -q -d temperature");
        procStartInfo.RedirectStandardOutput = true;
        procStartInfo.UseShellExecute = false;
        procStartInfo.CreateNoWindow = true;

        System.Diagnostics.Process proc = new System.Diagnostics.Process();
        proc.StartInfo = procStartInfo;
        proc.Start();
        string result = proc.StandardOutput.ReadToEnd();
        
        char first = '-';
        char second = '-';
        string temp = "";

        foreach (char c in result)
        {
            if(c=='1' || c == '2'|| c == '3'|| c == '4'|| c == '5'|| c == '6'|| c == '7'|| c == '8'|| c == '9'|| c == '0'|| c == 'C'){
                if(first == '-'){
                    first = c;
                }else if(second == '-'){
                    second = c;
                }else if(c == 'C'){
                    temp = "" + first + second;
                    break;
                }
            }else{
                first = '-';
                second = '-';
            }
        }
        return float.Parse(temp);
    }

    private static int GetCPUTemp(){

        string tempLineStart = "Packageid0:+";

        ProcessStartInfo procStartInfo = new ProcessStartInfo("/bin/bash", "-c sensors");
        procStartInfo.RedirectStandardOutput = true;
        procStartInfo.UseShellExecute = false;
        procStartInfo.CreateNoWindow = true;

        System.Diagnostics.Process proc = new System.Diagnostics.Process();
        proc.StartInfo = procStartInfo;
        proc.Start();

        int temp = 0;
        string line = "";
        while ((line = proc.StandardOutput.ReadLine()) != null) {
            line = Regex.Replace(line, @"\s+", "");
            if(Regex.IsMatch(line, tempLineStart)){
                line = line.Trim().Replace(tempLineStart.Trim(), "");
                line = line.Substring(0, 6);
                line = Regex.Replace(line, "[^0-9.]", "");
                float t = float.Parse(line);
                temp = (int)t;
                break;
            }
        }

        return temp;
    }

    private static void SetTimer()
    {
        // Create a timer with a two second interval.
        aTimer = new System.Timers.Timer(timerTime);
        // Hook up the Elapsed event for the timer. 
        aTimer.Elapsed += OnTimedEvent;
        aTimer.AutoReset = true;
        aTimer.Enabled = true;
    }    

    private static void ParseConfigFile(string fileName){
        string gridfanLocation = "GridfanLocation:";
        string gpuFanLineStart = "GPUFans:";
        string gpuMaxLineStart = "GPUMaxTemp:";
        string gpuMinLineStart = "GPUMinTemp:";
        string cpuFanLineStart = "CPUFans:";
        string cpuMinLineStart = "CPUMinTemp:";
        string cpuMaxLineStart = "CPUMaxTemp:";
    
        StreamReader reader = File.OpenText(fileName);
        string line;    
        while ((line = reader.ReadLine()) != null) {

            line = line.Trim();
            // Regex.Replace(line, @"\s+", "");
            // ignore commented out (starts with "//") or empty lines
            if(line.StartsWith("//") || line.Equals("")) continue;
            // set gpu temp at which gpu fans will be set at 100% speed
            else if(Regex.IsMatch(line, gridfanLocation)){
                root = line.Trim().Replace(gridfanLocation, "");
            // set gpu fan list using the numbering found on gridfan git repo
            }else if(Regex.IsMatch(line, gpuFanLineStart)){
                line = line.Trim().Replace(gpuFanLineStart, "");
                string[] fans = line.Split(",");
                gpuFans = new int[fans.Length];
                for (int i =0;i maxSpeed ? maxSpeed : gpuPercentage  maxSpeed ? maxSpeed : cpuPercentage
// gridFan repo = https://github.com/CapitalF/gridfan // root of gridFan script location GridfanLocation:/home/mohammadah/scripts/grid+v2 // GPU fans id/ports as per the schema in gridFan repo readme GPUFans: 3 // GPU temp at which GPU fans will be set at 100% speed GPUMaxTemp: 75 // GPU temp at which GPU fans will be set at lowest speed GPUMinTemp: 35 // GPU fans id/port as per the schema in gridFan repo readme CPUFans: 4, 5, 6 // CPU temp at which CPU fans will be set at 100% speed CPUMaxTemp: 75 // CPU temp at which CPU fans will be set at lowest speed CPUMinTemp: 35
daemon .service file
[Unit] Description=Grid+ v2 automatic fan controller [Service] ExecStart=/usr/bin/mono /home/mohammadah/scripts/grid+v2/LinuxGrid-v2Controller.exe Restart=on-failure [Install] WantedBy=multi-user.target ```
Asked by Mohammad Al-Hajj (1 rep)
Nov 21, 2020, 05:38 PM
Last activity: Nov 22, 2020, 02:40 AM