views:

384

answers:

5

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!

+3  A: 

Remember that for pathes Linux uses forward slashes and Windows 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.

Si
ok, I was reading about Mono and it looks like the decision, is it going to work just like that? am i have to install the Mono runtime to run the app?. OMG! that MoMA os great!, me so noob...THANKS EVERYONE, THIS SITE ROCKS!!!
coma
something ate some of my characters...
coma
A: 

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.

Michael Barth
A: 

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

Jimmy
+1  A: 

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.

Michiel Buddingh'
oh thanks for the advice, but right now is working this way without problems under a WAMP, and this tool is only available at the server, there is no other way getting access to this so I don't care about locking.About the old value... this code captures the actual weight in kilos from a lot of different trucks with different loads and it has to be the same as the one on the weighbridge display.
coma
+1  A: 

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

shodanex
I'm using the newest version available for Ubuntu, Mono 2.0. Thanks!
coma