87 lines
2.3 KiB
C

/*
* This file is part of the pl2303 project.
* Copyright 2022 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <string.h>
#include <stm32f3.h>
#include "ringbuffer.h"
#include "usb.h"
#include "usb_lib.h"
// ring buffer
static char ringbuffer[RBSIZE];
// head - position of first data byte
// tail - position of last data byte + 1
// head == tail - empty! So, buffer can't store more than RBSIZE-1 bytes of data!
static volatile int head = 0, tail = 0;
static int datalen(){
if(tail >= head) return (tail - head);
else return (RBSIZE - head + tail);
}
static int restlen(){
return (RBSIZE - 1 - datalen());
}
TRUE_INLINE void incr(volatile int *what, int n){
*what += n;
if(*what >= RBSIZE) *what -= RBSIZE;
}
int RB_read(char s[BLOCKSIZE]){
int l = datalen();
if(!l) return 0;
if(l > BLOCKSIZE) l = BLOCKSIZE;
int _1st = RBSIZE - head;
if(_1st > l) _1st = l;
if(_1st > BLOCKSIZE) _1st = BLOCKSIZE;
memcpy(s, ringbuffer+head, _1st);
if(_1st < BLOCKSIZE && l > _1st){
memcpy(s+_1st, ringbuffer, l-_1st);
incr(&head, l);
return l;
}
incr(&head ,_1st);
return _1st;
}
static int addportion(const char *str, int l){
int r = restlen();
if(l > r) l = r;
if(!l) return 0;
int _1st = RBSIZE - tail;
if(_1st > l) _1st = l;
memcpy(ringbuffer+tail, str, _1st);
if(_1st < l){ // add another piece from start
memcpy(ringbuffer, str+_1st, l-_1st);
}
incr(&tail, l);
return l;
}
void RB_write(const char *str, int l){
if(!str || !*str) return;
if(!usbON) return;
while(l){
send_next();
int a = addportion(str, l);
l -= a;
str += a;
}
}