venerdì 11 febbraio 2022

Ser2Net Go

 Premesso che questo non e' il sistema corretto di usare una goroutine in quanto non termina mai ho provato a fare questo programma che in una goroutine legge i valori da una porta seriale e tramite un channel manda i dati ad un'altra goroutine che invia sulla rete

non e' un codice da copiare

package main
import (
    "bufio"
    "fmt"
    "io"
    "log"
    "net"
    "time"

    "github.com/tarm/serial"
)

/*
per fare i test si puo' creare una porta seriale virtuale con
socat -d -d pty,raw,echo=0 pty,raw,echo=0
il sistema risponde con messaggi del tipo
socat -d -d pty,raw,echo=0 pty,raw,echo=0

2022/01/02 14:53:04 socat[18636] N PTY is /dev/pts/3
2022/01/02 14:53:04 socat[18636] N PTY is /dev/pts/4
2022/01/02 14:53:04 socat[18636] N starting data transfer loop with FDs [5,5] and [7,7]

si apre un altro terminale e si inviano i messaggi sulla seconda porta
echo "messaggio" > /dev/pts/4
il programma in Go deve andare in ascolto sull /dev/pts/3
*/

func main() {
    canale := make(chan []byte, 1024)

    usbRead := &serial.Config{Name: "/dev/pts/3", Baud: 9600}
    //s, err := serial.OpenPort(c)
    port, err := serial.OpenPort(usbRead)
    if err != nil {
        log.Fatal(err)
    }
    scanner := bufio.NewScanner(port)
    go scrivi_channel(canale, scanner)

    listener, err := net.Listen("tcp", "localhost:8000")
    if err != nil {
        log.Fatal(err)
    }
    for {
        conn, err := listener.Accept()
        if err != nil {
            log.Print(err) // e.g., connection aborted
            continue
        }
        handleConn(conn, canale) // handle one connection at a time
    }
}

func handleConn(c net.Conn, canale chan []byte) {
    defer c.Close()
    for {
        _, err := io.WriteString(c, string(<-canale)+" "+time.Now().Format("15:04:05\n"))
        if err != nil {
            return // e.g., client disconnected
        }
        time.Sleep(1 * time.Second)
    }
}

func scrivi_channel(canale chan []byte, scanner *bufio.Scanner) {
    buf := make([]byte, 128)
    scanner.Buffer(buf, 128)
    for {

        //scanner.Buffer(buf, 128)
        scanner.Scan()
        input := scanner.Text()
        fmt.Println(input)
        canale <- []byte(input)
        time.Sleep(1 * time.Second)
    }

    //time.Sleep(1 * time.Second)
    //canale <- []byte("test")
}

Nessun commento:

Posta un commento

Physics informed neural network Fukuzono

Visto che puro ML non funziona per le serie tempo di cui mi sto occupando ed le regressioni basate su formule analitiche mostrano dei limiti...