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

发布于 2024-07-24 03:58:18 字数 3763 浏览 0 评论 0原文

我是一个 Linux 菜鸟,想要将这段 C# 代码迁移

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());
        }
    }
}

到其他地方,任何建议将不胜感激!

顺便说一句,您认为直接在 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));

    }

}

谢谢!

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

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:

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

寂寞陪衬 2024-07-31 03:58:18

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

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

除此之外,当您编译为 mono 时,什么不起作用?

另外,通过 MoMA 运行您的应用。

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

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.

北音执念 2024-07-31 03:58:18

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

看看是否可以实现某种缓存(如果适用),以便您的脚本可以提供旧值,而不是错误消息(如果串行端口被其他方式占用)。

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.

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.

游魂 2024-07-31 03:58:18

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

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

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

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

此生挚爱伱 2024-07-31 03:58:18

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

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.

眼眸印温柔 2024-07-31 03:58:18

您尝试过仅使用 C# 吗? Mono 项目 提供 .NET 框架的开源、跨平台 .NET 端口。 这样您就可以避免重新编写代码(大概已经可以运行并经过测试)。

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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文