将小型C#控制台应用程序迁移到在Ubuntu Server 9.04上运行的程序

时间:2022-07-18 20:43:35

I'm a linux noob wanting to migrate this piece of C# code:

我是一个想要迁移这段C#代码的linux菜鸟:

using System;
using System.IO;
using System.IO.Ports;

public class LoadCell
{
    private static string configFile = Directory.GetCurrentDirectory() + "\\LoadCell.config";
    private static string errorLog = Directory.GetCurrentDirectory() + "\\LoadCell.log";
    private static string puerto = "COM1";

    public static void Main (string[] args)
    {
        if(File.Exists(configFile))
        {
            TextReader tr = new StreamReader(configFile);
            puerto = tr.ReadToEnd();
            tr.Close();
        }

        if(args.Length > 0)
        {
            switch(args[0])
            {
                case "-ayuda":
                    Console.WriteLine("\r\nEste programa esta diseñado para capturar el peso medido actualmente por la báscula a través de un puerto (por defecto es el COM1). Recuerde que el indicador debe estar configurado para:");
                    Console.WriteLine("\r\npuerto: " + puerto);
                    Console.WriteLine("baud rate: 4800");
                    Console.WriteLine("parity: none");
                    Console.WriteLine("data bits: 8");
                    Console.WriteLine("stop bit: one");
                    Console.WriteLine("\r\nEn caso de ocurrir un error recuerde revisar el log de errores (" + errorLog + ").");
                    Console.WriteLine("\r\nLos posibles argumentos son:");
                    Console.WriteLine("\r\n-ayuda: este ya lo sabes usar...");
                    Console.WriteLine("\r\n-puerto <nombre>: cambia el puerto al nuevo valor creando un archivo de configuración (" + configFile + ")");
                    Console.WriteLine("\r\n-default: elimina el archivo de configuración para retomar la configuración inicial");
                    break;

                case "-default":
                    File.Delete(configFile);
                    Console.WriteLine("\r\narchivo de configuración eliminado");
                    break;

                case "-puerto":
                    if(args.Length > 1)
                    {
                        puerto = args[1];
                        TextWriter tw = new StreamWriter(configFile);
                        tw.Write(puerto);
                        tw.Close();
                        Console.WriteLine("\r\npuerto cambiado a " + puerto);
                    }
                    else
                    {
                        Console.WriteLine("\r\nse esperaba un nombre de puerto");
                    }
                    break;
            }
        }
        else
        {
            new LoadCell();
        }
    }

    private static void log(string text)
    {
        Console.Write("ha ocurrido un error...");
        TextWriter sw = File.AppendText(errorLog);
        sw.WriteLine("[" + System.DateTime.Now.ToString() + "] " + text);
        sw.Close();
    }

    public LoadCell()
    {
        try
        {
            SerialPort port = new SerialPort(puerto, 4800, Parity.None, 8,  StopBits.One);
            port.NewLine = "\r";
            port.ReadTimeout = 10000;
            port.Open();
            port.WriteLine("RA:");
            port.DiscardInBuffer();
            Console.Write(port.ReadLine());
        }
        catch(Exception e)
        {
            log("Error: " + e.ToString());
        }
    }
}

to something else, any suggestion will be appreciated!

对其他事情,任何建议将不胜感激!

btw, what do you think about doing that directly within PHP?, because the result is used in a PHP file like:

顺便问一下,您如何直接在PHP中做到这一点?,因为结果用于PHP文件,如:

function peso() {

    $resultado = utf8_encode(exec('loadcell'));

    if(preg_match('/^RA:\s*([0-9]{1,8})$/i', $resultado, $m) > 0) {

        json_exit(array('peso' => $m[1]));

    } else {

        json_exit(array('error' => $resultado));

    }

}

thanks!

5 个解决方案

#1


Remember Linux uses forward slashes for paths, whilst Windows uses backslashes, so you'll need to do something like:

请记住,Linux使用正斜杠表示路径,而Windows使用反斜杠,因此您需要执行以下操作:

private static string configFile = Path.Combine(Directory.GetCurrentDirectory(), "LoadCell.config");
// Or...
private static string configFile = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "LoadCell.config";

Aside from that, what's not working when you compile to mono?

除此之外,编译成单声道时什么不起作用?

Also, run your app through MoMA.

此外,通过MoMA运行您的应用程序。

#2


I realise this doesn't answer your question, but if that php script is invoked from the web, you're going to need some kind of locking to ensure two different http requests don't try to open the serial port concurrently.

我意识到这不能回答你的问题,但是如果从网上调用那个php脚本,你将需要某种锁定来确保两个不同的http请求不会同时尝试打开串口。

See if you can implement some kind of caching (if appropriate) so your script can supply an old value, rather than an error message, if the serial port is otherwise occupied.

看看你是否可以实现某种缓存(如果适用),这样如果串口被占用,你的脚本可以提供旧值而不是错误消息。

#3


If you want to use the serial port with Mono on linux, check your version is up to date. If your version is too old, you might encounter this bug
I think it was fixed in version > 1.9, but I know it was still in 1.9.1

如果你想在Linux上使用Mono的串口,请检查你的版本是否是最新的。如果您的版本太旧,您可能会遇到此错误我认为它已在版本> 1.9中修复,但我知道它仍然在1.9.1

If your application does not do a lot of write to the serial port, you should be fine, otherwise, you can try this workaround

如果您的应用程序没有对串口进行大量写操作,那么您应该没问题,否则,您可以尝试这种解决方法

#4


I am not quite sure what the problem here is, but if you're using it in PHP anyway, sure, port the Code to PHP. As PHP runs on any machine that can run a server with PHP support, you're pretty independent of platforms with this approach.

我不太确定这里的问题是什么,但如果你在PHP中使用它,当然,请将代码移植到PHP。由于PHP可以在任何可以运行支持PHP的服务器的机器上运行,因此您可以完全独立于采用这种方法的平台。

#5


Have you tried just using C#? The Mono project provides an open-source, cross-platform .NET port of the .NET framework. That way you can avoid the having to re-write your code (which presumably is already functional and tested).

你尝试过使用C#吗? Mono项目提供.NET框架的开源,跨平台.NET端口。这样你就可以避免重新编写你的代码(可能已经在功能和测试中)了。

#1


Remember Linux uses forward slashes for paths, whilst Windows uses backslashes, so you'll need to do something like:

请记住,Linux使用正斜杠表示路径,而Windows使用反斜杠,因此您需要执行以下操作:

private static string configFile = Path.Combine(Directory.GetCurrentDirectory(), "LoadCell.config");
// Or...
private static string configFile = Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "LoadCell.config";

Aside from that, what's not working when you compile to mono?

除此之外,编译成单声道时什么不起作用?

Also, run your app through MoMA.

此外,通过MoMA运行您的应用程序。

#2


I realise this doesn't answer your question, but if that php script is invoked from the web, you're going to need some kind of locking to ensure two different http requests don't try to open the serial port concurrently.

我意识到这不能回答你的问题,但是如果从网上调用那个php脚本,你将需要某种锁定来确保两个不同的http请求不会同时尝试打开串口。

See if you can implement some kind of caching (if appropriate) so your script can supply an old value, rather than an error message, if the serial port is otherwise occupied.

看看你是否可以实现某种缓存(如果适用),这样如果串口被占用,你的脚本可以提供旧值而不是错误消息。

#3


If you want to use the serial port with Mono on linux, check your version is up to date. If your version is too old, you might encounter this bug
I think it was fixed in version > 1.9, but I know it was still in 1.9.1

如果你想在Linux上使用Mono的串口,请检查你的版本是否是最新的。如果您的版本太旧,您可能会遇到此错误我认为它已在版本> 1.9中修复,但我知道它仍然在1.9.1

If your application does not do a lot of write to the serial port, you should be fine, otherwise, you can try this workaround

如果您的应用程序没有对串口进行大量写操作,那么您应该没问题,否则,您可以尝试这种解决方法

#4


I am not quite sure what the problem here is, but if you're using it in PHP anyway, sure, port the Code to PHP. As PHP runs on any machine that can run a server with PHP support, you're pretty independent of platforms with this approach.

我不太确定这里的问题是什么,但如果你在PHP中使用它,当然,请将代码移植到PHP。由于PHP可以在任何可以运行支持PHP的服务器的机器上运行,因此您可以完全独立于采用这种方法的平台。

#5


Have you tried just using C#? The Mono project provides an open-source, cross-platform .NET port of the .NET framework. That way you can avoid the having to re-write your code (which presumably is already functional and tested).

你尝试过使用C#吗? Mono项目提供.NET框架的开源,跨平台.NET端口。这样你就可以避免重新编写你的代码(可能已经在功能和测试中)了。