| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163 |
- #include "mb.h"
- #include "list.h"
- #include "modbus.h"
- typedef struct {
- mb_inst_t *hinst;
- uint8_t type;
- uint8_t mode;
- uint8_t quit;
-
- rt_thread_t tid;
- handle_t rx;
- handle_t tx;
-
- }mb_handle_t;
- static mb_handle_t mbHandle={0};
- typedef void (*thread_fn_t)(void *arg);
- static void mb_thread(void *arg)
- {
- mb_handle_t *h=(mb_handle_t*)arg;
- while(h->quit==0) {
- if(h->mode==MB_MODE_MASTER) {
-
- }
- else {
- mb_slave_fsm(h->hinst);
- }
- }
- mb_destory(h->hinst);
-
- h->quit = 2;
- }
- static void mb_start(mb_handle_t *h, int flag)
- {
- if(flag) {
- h->tid = rt_thread_create(NULL, mb_thread, h, 2048, 5, 20);
- if(h->tid==NULL) {
- //LOG_E("___ thread create failed\n");
- }
-
- h->quit = 0;
- rt_thread_startup(h->tid);
- }
- else {
- h->quit = 1;
- while(h->quit!=2);
- rt_thread_delete(h->tid);
- }
- }
- void* mb_init(char *dev, int type, int mode)
- {
- list_cfg_t lc={0,LIST_FULL_FIFO,10};
- mb_handle_t *h=(mb_handle_t*)rt_malloc(sizeof(mb_handle_t));
-
- if(h) {
- h->type = (type==MB_TYPE_RTU)?MB_BACKEND_TYPE_RTU:MB_BACKEND_TYPE_TCP;
- h->mode = mode;
-
- mb_backend_param_t param = {
- .rtu.dev = "uart2",
- .rtu.baudrate = 9600,
- .rtu.parity = 0,
- .rtu.pin = -1,
- .rtu.lvl = 0
- };
- h->rx = list_init(&lc);
- h->tx = list_init(&lc);
-
- h->hinst = mb_create(h->type, ¶m);
- if(h->mode==MB_MODE_MASTER) {
-
- }
- else {
-
- }
-
- mb_start(h, 1);
- }
-
- return h;
- }
- int mb_deinit(void *h)
- {
- mb_handle_t *mh=(mb_handle_t*)h;
- if(!mh) {
- return -1;
- }
- mb_start(mh, 0);
- list_free(mh->rx);
- list_free(mh->tx);
- rt_free(mh);
-
- return 0;
- }
- //
- int mb_read(void *h, void *data, int len, int timeout)
- {
- int r=-1,sz=0;
- mb_handle_t *mh=(mb_handle_t*)h;
-
- if(!mh || !data || len<=0) {
- return -1;
- }
-
- rt_tick_t end = rt_tick_get_millisecond()+timeout;
- while(1) {
- sz = list_size(mh->rx);
- if(sz>0) {
- break;
- }
- rt_thread_mdelay(1);
-
- if(timeout>0 && rt_tick_get_millisecond()>end) {
- sz = list_size(mh->rx);
- break;
- }
- }
-
- if(sz>0) {
- list_node_t *ln=NULL;
- r = list_take_node(mh->rx, &ln, 0);
- if(r==0) {
- node_t *nd=&ln->data;
-
- if(len>=nd->dlen) {
- memcpy(data, nd->buf, nd->dlen);
- }
- else {
- r = -1;
- }
- list_back_node(mh->rx, ln);
- }
- }
-
- return r;
- }
- int mb_write(void *h, void *data, int len)
- {
- mb_handle_t *mh=(mb_handle_t*)h;
- if(!mh) {
- return -1;
- }
-
- return list_append(mh->tx, 0, data, len);
- }
|