; _______________________________________________________________________________________
;|                                                                                       |
;| ..::FreshLib::..  Free, open source. Licensed under "BSD 2-clause" license."          |
;|_______________________________________________________________________________________|
;
;  Description: Serial IO interface library. Linux part.
;
;  Target OS: Linux
;
;  Dependencies:
;
;  Notes:
;_________________________________________________________________________________________

macro brate  [baud, mask] {
forward
  dd baud
  dw mask
}



proc SerSetParams, .hSerial, .Baudrate, .Parity, .Flow, .Timeout
.settings termios
begin
        pushad

        mov     esi, .speeds

.speed_loop:
        mov     eax, [esi]

        test    eax, eax
        jz      .error

        cmp     eax, [.Baudrate]
        je      .found

        add     esi, 6
        jmp     .speed_loop

.found:
        movzx   edx, word [esi+4]
        or      edx, CS8 or CREAD or CLOCAL

        cmp     [.Parity], cParityNo
        je      @f
        or      edx, PARENB
@@:
        cmp     [.Parity], cParityOdd
        jne     @f
        or      edx, PARODD
@@:
        cmp     [.Flow], cFlowHW
        jne     @f
        or      edx, CRTSCTS
@@:

        xor     eax, eax        ; zero

        lea     edi, [.settings]
        mov     ecx, sizeof.termios / 4
        rep stosd

        mov     [.settings.c_iflag], IGNBRK
        mov     [.settings.c_cflag], edx

        mov     eax, [.Timeout]         ; in [ms]
        xor     edx, edx
        mov     ecx, 100
        div     ecx
        mov     [.settings.c_cc+VTIME], al       ; in [100ms] units

        mov     eax, sys_ioctl
        mov     ebx, [.hSerial]
        mov     ecx, TCSETS
        lea     edx, [.settings]
        int     $80

        test    eax, eax
        jnz     .error

        clc
        popad
        return


.error:
        stc
        popad
        return

.speeds:
        brate 50, B50
        brate 75, B75
        brate 110, B110
        brate 134, B134
        brate 150, B150
        brate 200, B200
        brate 300, B300
        brate 600, B600
        brate 1200, B1200
        brate 1800, B1800
        brate 2400, B2400
        brate 4800, B4800
        brate 9600, B9600
        brate 19200, B19200
        brate 38400, B38400
        brate 57600, B57600
        brate 115200, B115200
        brate 230400, B230400
        brate 460800, B460800
        brate 500000, B500000
        brate 576000, B576000
        brate 921600, B921600
        brate 1000000, B1000000
        brate 11520000, B1152000
        brate 15000000, B1500000
        brate 20000000, B2000000
        brate 25000000, B2500000
        brate 30000000, B3000000
        brate 35000000, B3500000
        brate 40000000, B4000000
        brate 0, 0
endp


