This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

ASSERTION FAIL [net_buf_simple_tailroom(buf) >= len] @ WEST_TOPDIR/zephyr/subsys/net/buf.c:800

Hi everybody, i get this error on a nrf53 with hr_coded on network coded, and UART example modified with multilink and coded_phy, tested by me on an nrf52.

The issue is, later of add the Kconfig necessary (copying the same as nrf52840 of my last project) i get this error when the code enter on filter_match.

This is the line 800 of buf.c

Debugging output is this:

Searching that line 46 on my assert.c:

What i can do to solve it??

Thank you,

regards.

Parents
  • Hi 

    A common problem with the nRF5340 is to forget to configure the network core correctly, since the Bluetooth stack is split between the application and network cores. 

    Can you share the config files you use for the application and network cores?
    Normally the network core configuration is stored in the child_image/hci_rpmsg.conf file. 

    Also, could you share the zephyr.map file with me?
    These kind of fatal errors are often caused by a stack overflow in a thread, and the map file should show which thread the error is related to. 

    Best regards
    Torbjørn

  • Hi, I am not sure of what is the way to configure network core properly, i use child image of hr_coded because of that supports long range. Could you share a link of tutorial for how to custom this child image?

    And for configure other parameters i am used to use Kconfig. But i am desiring learn whats is the correct way to do it

    I will update the files that you ask for on a couple of days.

    Thank you for the support,

    regards.

  • Hi,

    CONFIG_BT_RX_STACK_SIZE=2200 

    And the error keeps.

    The error isn't appear on a connection, so really i don't know if it could have something related with bluetooth.

    The error happens when main finish, and theoretically start to scan. The error can't be reproduce when uses default config on board (no coded).

    I have doubts when u ask me about prj.conf, all configurations that i add are on Kconfig, this is the Kconfig of my application core:

    And this my config of the network core (hr_coded child image):

    On prj.conf is the default one:

    #
    # Copyright (c) 2018 Nordic Semiconductor
    #
    # SPDX-License-Identifier: LicenseRef-Nordic-5-Clause
    #
    
    # Enable the UART driver
    CONFIG_UART_ASYNC_API=y
    CONFIG_NRFX_UARTE0=y
    CONFIG_SERIAL=y
    CONFIG_CONSOLE=y
    CONFIG_UART_CONSOLE=y
    
    # Enable the BLE stack with GATT Client configuration
    CONFIG_BT=y
    CONFIG_BT_CENTRAL=y
    CONFIG_BT_SMP=y
    CONFIG_BT_GATT_CLIENT=y
    
    # Enable the BLE modules from NCS
    CONFIG_BT_NUS_CLIENT=y
    CONFIG_BT_SCAN=y
    CONFIG_BT_SCAN_FILTER_ENABLE=y
    CONFIG_BT_SCAN_UUID_CNT=1
    CONFIG_BT_GATT_DM=y
    CONFIG_HEAP_MEM_POOL_SIZE=2048
    
    # This example requires more workqueue stack
    CONFIG_SYSTEM_WORKQUEUE_STACK_SIZE=2048
    
    # Enable bonding
    CONFIG_BT_SETTINGS=y
    CONFIG_FLASH=y
    CONFIG_FLASH_PAGE_LAYOUT=y
    CONFIG_FLASH_MAP=y
    CONFIG_NVS=y
    CONFIG_SETTINGS=y
    
    # Config logger
    CONFIG_LOG=y
    CONFIG_USE_SEGGER_RTT=y
    CONFIG_LOG_BACKEND_RTT=y
    CONFIG_LOG_BACKEND_UART=n
    
    CONFIG_ASSERT=y
    

    Really i have doubts of where and how is the correct way to apply this configuration. I think that no have sense that on app core I configure things of BT_...

    I wish follow clear steps to succed with this device.

    Another note about, the same configuration on nrf53 but working as peripheral is working properly.

    Thank you for the interest and support,

    regards.

  • Another note about, the same configuration on nrf53 but working as peripheral is working properly.

    In my peripheral project, the nrf53 is working transmiting 200bytes/100ms on coded_s8 properly, so in my opinion the problem could have something related with the scan procedure/config.

  • Debugging central project, the scanning doesn't fail until an peripheral starts to advertising, but don't arrive to trigger filter_match, before that happens the crash.

    regards.

  • Hi

    If I understand you correctly you have modified the central_uart example to use coded phy?

    I tried to do a quick modification of this example myself in order to reproduce the error, but I haven't been able to see the same error yet. 

    Which changes did you make to the main.c file in order to enable coded phy?
    Maybe you can share the main.c file with me?

    Best regards
    Torbjørn

  • The changes that i made are the advertising_params and the conn_params and Kconfig.

    If I understand you correctly you have modified the central_uart example to use coded phy?

    Yes, coded and multilink.

    try with my main:

    /*
     * Copyright (c) 2018 Nordic Semiconductor ASA
     *
     * SPDX-License-Identifier: LicenseRef-Nordic-5-Clause
     */
    
    /** @file
     *  @brief Nordic UART Service Client sample
     */
    
    #include <errno.h>
    #include <zephyr.h>
    #include <sys/byteorder.h>
    #include <sys/printk.h>
    
    #include <bluetooth/bluetooth.h>
    #include <bluetooth/hci.h>
    #include <bluetooth/hci_vs.h>
    #include <bluetooth/conn.h>
    #include <bluetooth/uuid.h>
    #include <bluetooth/gatt.h>
    
    #include <bluetooth/services/nus.h>
    #include <bluetooth/services/nus_client.h>
    #include <bluetooth/gatt_dm.h>
    #include <bluetooth/scan.h>
    //#include <strtol.h>
    
    
    #include <settings/settings.h>
    
    #include <drivers/uart.h>
    
    #include <logging/log.h>
    
    #define LOG_MODULE_NAME central_uart
    LOG_MODULE_REGISTER(LOG_MODULE_NAME);
    
    /* UART payload buffer element size. */
    #define UART_BUF_SIZE 20
    
    #define NUS_WRITE_TIMEOUT K_MSEC(150)
    #define UART_WAIT_FOR_BUF_DELAY K_MSEC(50)
    #define UART_RX_TIMEOUT 50
    #define kartIDsize 4
    
    
    //#define BT_HCI_OP_VS_WRITE_TX_POWER_LEVEL   BT_OP(BT_OGF_VS, 0x000e)
    //FFFFFFFFFFFFFFFFFjejejej
    
    #define STACKSIZE 1024
    #define PRIORITY 7
    
    
    //Parametros de scaneo
    static struct bt_le_scan_param m_scan_param=
              {
              .type = BT_LE_SCAN_TYPE_ACTIVE,
              .options = BT_LE_SCAN_OPT_CODED | BT_LE_SCAN_OPT_NO_1M,
              .interval = BT_GAP_SCAN_FAST_INTERVAL,//BT_GAP_SCAN_SLOW_INTERVAL_1,
              .window = BT_GAP_SCAN_FAST_WINDOW,//BT_GAP_SCAN_SLOW_WINDOW_1,
              };
    
    //Parametros de conexion
    struct bt_le_conn_param m_conn_param=
    {
    	.interval_min=40,//70*0.625ms
    	.interval_max=150,
    	.timeout=1000,
            .latency=0,
          
    };
    
    
    struct MapID
    {
          char ADDR[BT_ADDR_LE_STR_LEN];//addr formato string
          int kartID; 
    };
    
    static struct MapID Mymap[CONFIG_BT_MAX_CONN]={{"EB:B4:10:52:81:E8 (random)",1111},{"E4:94:98:5A:79:AF (random)",2222}};
    
    //Mis propiedades
    struct DeviceProperties
    {
          struct MapID ID;
          const bt_addr_le_t *Addr;//addr
          uint16_t conn_handle;
          bool Connected;
    };
    //Lista de clientes
    static struct bt_nus_client nus_client[CONFIG_BT_MAX_CONN];
    
    struct DeviceProperties Device[CONFIG_BT_MAX_CONN];
    
    uint8_t NumDevices=0;
    uint8_t NumDevicesConnected=0;
    //gestion
    bool IsScanning=false;
    bool masuno=false;
    bool Command=false;
    uint8_t Actualiza;
    int8_t ActualizoConexion1;
    bool NuevaConexion=false;
    bool ConnPending=false;
    uint8_t Devices2Inicialice[CONFIG_BT_MAX_CONN];
    
    //para medida rssi
    static int8_t txp;
    //data_sended()
    uint8_t msgSended;
    
    struct k_mutex Array_mutex;
    struct k_mutex my_mutex;
    struct k_mutex Command_mutex;
    
    //struct k_mutex send_mutex;
    
    
    static const struct device *uart;
    static struct k_work_delayable uart_work;
    
    K_SEM_DEFINE(nus_write_sem, 0, 1);
    //K_SEM_DEFINE(sem, 0, 1);
    
    struct uart_data_t {
    	void *fifo_reserved;
    	uint8_t  data[UART_BUF_SIZE];
    	uint16_t len;
    };
    
    //static const char *Handlers[CONFIG_BT_MAX_CONN]={"fifo_uart_tx_data","fifo_uart_tx_data1","fifo_uart_tx_data2","fifo_uart_tx_data3","fifo_uart_tx_data4","fifo_uart_tx_data5","fifo_uart_tx_data6","fifo_uart_tx_data7","fifo_uart_tx_data8","fifo_uart_tx_data9","fifo_uart_tx_data10","fifo_uart_tx_data11","fifo_uart_tx_data12","fifo_uart_tx_data13","fifo_uart_tx_data14","fifo_uart_tx_data15","fifo_uart_tx_data16","fifo_uart_tx_data17","fifo_uart_tx_data18","fifo_uart_tx_data19"};
    //Mutex para hardware UART
    static K_FIFO_DEFINE(fifo_uart_tx_data);
    static K_FIFO_DEFINE(fifo_uart_rx_data);
    
    static struct bt_conn *default_conn;
    static uint16_t default_conn_handle;
    //static struct bt_nus_client *nus_client[CONFIG_BT_MAX_CONN];
    
    
    //static void ble_data_sent(uint8_t err, const uint8_t *const data, uint16_t len)
    //{
    //	struct uart_data_t *buf;
            
    //        msgSended+=1;
    
    //	/* Retrieve buffer context. */
    //	buf = CONTAINER_OF(data, struct uart_data_t, data);
    
    //        //k_free(buf);
    
    //	if((msgSended==NumDevicesConnected)/*/&&(Noquedan==true)/*/)//Dependiendo si es un mensaje de mas de buff size uart
    //        {
    //              msgSended=0;
    //              printk("CLEAN");
    //              //Mucho ojo con esto, hay que ver cuando ejecutarlo, siempre despues de haber acabado de enviar mensaje
    //              k_free(buf);
    //        }
    //        printk("0DATA sended\n");
    
    //	k_sem_give(&nus_write_sem);
    
    //	if (err) {
    //		LOG_WRN("ATT error code: 0x%02X", err);
    //                printk("ATT error code: 0x%02X", err);
    //	}
    //        printk("DATA sended\n");
    //}
    
    static void restartScan()
    {
            int err;
    
            if((IsScanning==false)&&(NumDevicesConnected<CONFIG_BT_MAX_CONN))
            {
                k_mutex_lock(&my_mutex,K_FOREVER);
                err = bt_scan_start(BT_SCAN_TYPE_SCAN_ACTIVE);
                if (err) {
                        printk("Scanning failed to start (err %d)\n", err);
                        k_mutex_unlock(&my_mutex);
                        return;
                }
                else
                {       
                        IsScanning=true;
                        k_mutex_unlock(&my_mutex);
                        printk("Scan restarted\n");
                }
            }
            else printk("ya esta scanning en teoria\n");
    
    }
    
    static void ble_data_sent(uint8_t err, const uint8_t *const data, uint16_t len)
    {
    	struct uart_data_t *buf;
    
            msgSended+=1;
    
    	/* Retrieve buffer context. */
    	buf = CONTAINER_OF(data, struct uart_data_t, data);
    
            if((ConnPending==true)&&(!err))
            {
                  printk("Nueva conn");
                  // k_free(buf);
                  restartScan();
                  ConnPending=false;
                  //k_mutex_unlock(&send_mutex);
            }
            //printk("DATA sended\n");
            else if((Command==true)||(NumDevicesConnected==1)||(msgSended==NumDevicesConnected))
            {
                  k_free(buf);
                  msgSended=0;
            }
    
    	k_sem_give(&nus_write_sem);
            printk("SendSended\n");
    
    	if (err) {
    		LOG_WRN("ATT error code: 0x%02X", err);
                    printk("ATT error code: 0x%02X", err);
    	}
    }
    
    static uint8_t ble_data_received(const uint8_t *const data, uint16_t len, struct bt_conn *conn)
    {
    	int err;
            char addr[BT_ADDR_LE_STR_LEN];
            uint8_t id;//ignore
    
    	bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));
    
            //Para detectar que cliente lo manda:
             for(int i=0;i<NumDevices;i++){
                    //Si ya esta en mi lista actualizo el estado de conexion y salgo
                    if(strcmp(addr,Device[i].ID.ADDR)==0)
                    {
                        id=i;
                        break;
                    }
             }
              
             //printk("Received from ");
             printk("%d",id);
             printk("  ");
             printk(Device[id].ID.ADDR);//sta ok
            // printk("numKart ");
             printk("%d ",Device[id].ID.kartID);
             //printk("numClient ");
             //printk("%d ",id);
             printk(":   ");
    
    	for (uint16_t pos = 0; pos != len;) {
    		struct uart_data_t *tx = k_malloc(sizeof(*tx));
    
    		if (!tx) {
    			LOG_WRN("Not able to allocate UART send data buffer");
                            printk("Not able to allocate UART send data buffer\n");
    			return BT_GATT_ITER_CONTINUE;
    		}
    
    		/* Keep the last byte of TX buffer for potential LF char. */
    		size_t tx_data_size = sizeof(tx->data) - 1;
    
    		if ((len - pos) > tx_data_size) {
    			tx->len = tx_data_size;
    		} else {
    			tx->len = (len - pos);
    		}
    
    		memcpy(tx->data, &data[pos], tx->len);
    
    		pos += tx->len;
    
    		/* Append the LF character when the CR character triggered
    		 * transmission from the peer.
    		 */
    		if ((pos == len) && (data[len - 1] == '\r')) {
    			tx->data[tx->len] = '\n';
    			tx->len++;
    		}
    
    		err = uart_tx(uart, tx->data, tx->len, SYS_FOREVER_MS);
    		if (err) {
    			k_fifo_put(&fifo_uart_tx_data, tx);
                           // printk("Error receibing\n");
    		}
                    //printk("DATA receibed\n");
    	}
    
    	return BT_GATT_ITER_CONTINUE;
    }
    
    static void ActualizaBlockList()
    {
            bt_scan_blocklist_clear();
            //printk("Actializo blcklist ");
            for(int i=0;i<NumDevices;i++){
                if(Device[i].Connected==true)
                {
                      bt_scan_blocklist_device_add(Device[i].Addr);
                      //printk("%d\n",i);
                }
            } 
    }
    
    
    static void uart_cb(const struct device *dev, struct uart_event *evt, void *user_data)
    {
    	ARG_UNUSED(dev);
    
    	static uint8_t *current_buf;
    	static size_t aborted_len;
    	static bool buf_release;
    	struct uart_data_t *buf;
    	static uint8_t *aborted_buf;
    
    
    	switch (evt->type) {
    	case UART_TX_DONE:
    		if ((evt->data.tx.len == 0) ||
    		    (!evt->data.tx.buf)) {
    			return;
    		}
    
    		if (aborted_buf) {
    			buf = CONTAINER_OF(aborted_buf, struct uart_data_t,
    					   data);
    			aborted_buf = NULL;
    			aborted_len = 0;
    		} else {
    			buf = CONTAINER_OF(evt->data.tx.buf,
    					   struct uart_data_t,
    					   data);
    		}
    
    		k_free(buf);
    
    		buf = k_fifo_get(&fifo_uart_tx_data, K_NO_WAIT);
    		if (!buf) {
    			return;
    		}
    
    		if (uart_tx(uart, buf->data, buf->len, SYS_FOREVER_MS)) {
    			LOG_WRN("Failed to send data over UART");
    		}
    
    		break;
    
    	case UART_RX_RDY://Data received and timeout triggered OR buff filled
    		buf = CONTAINER_OF(evt->data.rx.buf, struct uart_data_t, data);
    		buf->len += evt->data.rx.len;
    		buf_release = false;
    
    		if (buf->len == UART_BUF_SIZE) {//If buff lleno
    			k_fifo_put(&fifo_uart_rx_data, buf);
    		} else if ((evt->data.rx.buf[buf->len - 1] == '\n') ||//else
    			  (evt->data.rx.buf[buf->len - 1] == '\r')) {
    			k_fifo_put(&fifo_uart_rx_data, buf);
    			current_buf = evt->data.rx.buf;
    			buf_release = true;
    			uart_rx_disable(uart);
    		}
    
    		break;
    
    	case UART_RX_DISABLED:
    		buf = k_malloc(sizeof(*buf));
    		if (buf) {
    			buf->len = 0;
    		} else {
    			LOG_WRN("Not able to allocate UART receive buffer");
    			k_work_reschedule(&uart_work, UART_WAIT_FOR_BUF_DELAY);
    			return;
    		}
    
    		uart_rx_enable(uart, buf->data, sizeof(buf->data),
    			       UART_RX_TIMEOUT);
    
    		break;
    
    	case UART_RX_BUF_REQUEST://Uart start to receive on a buff
    		buf = k_malloc(sizeof(*buf));
    		if (buf) {//
    			buf->len = 0;
    			uart_rx_buf_rsp(uart, buf->data, sizeof(buf->data));
    		} else {
    			LOG_WRN("Not able to allocate UART receive buffer");
    		}
    
    		break;
    
    	case UART_RX_BUF_RELEASED://Buff full
    		buf = CONTAINER_OF(evt->data.rx_buf.buf, struct uart_data_t,
    				   data);
    		if (buf_release && (current_buf != evt->data.rx_buf.buf)) {
    			k_free(buf);//Lo libera
    			buf_release = false;
    			current_buf = NULL;
    		}
    
    		break;
    
    	case UART_TX_ABORTED:
    			if (!aborted_buf) {
    				aborted_buf = (uint8_t *)evt->data.tx.buf;
    			}
    
    			aborted_len += evt->data.tx.len;
    			buf = CONTAINER_OF(aborted_buf, struct uart_data_t,
    					   data);
    
    			uart_tx(uart, &buf->data[aborted_len],
    				buf->len - aborted_len, SYS_FOREVER_MS);
    
    		break;
    
    	default:
    		break;
    	}
    }
    
    
    static void read_conn_rssi(uint16_t handle, int8_t *rssi)
    {
    	struct net_buf *buf, *rsp = NULL;
    	struct bt_hci_cp_read_rssi *cp;
    	struct bt_hci_rp_read_rssi *rp;
    
    	int err;
    
    	buf = bt_hci_cmd_create(BT_HCI_OP_READ_RSSI, sizeof(*cp));
    	if (!buf) {
    		printk("Unable to allocate command buffer\n");
    		return;
    	}
    
    	cp = net_buf_add(buf, sizeof(*cp));
    	cp->handle = sys_cpu_to_le16(handle);
    
    	err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_RSSI, buf, &rsp);
    	if (err) {
    		uint8_t reason = rsp ?
    			((struct bt_hci_rp_read_rssi *)rsp->data)->status : 0;
    		printk("Read RSSI err: %d reason 0x%02x\n", err, reason);
    		return;
    	}
    
    	rp = (void *)rsp->data;
    	*rssi = rp->rssi;
    
    	net_buf_unref(rsp);
    }
    
    
    
    //Timer and handler millis delay()
    void my_work_handler(struct k_work *work)
    {
         //if(Device[0].Connected==true)
         //{
         //         int8_t rssi = 0xFF;
         //         read_conn_rssi(default_conn_handle, &rssi);
         //         printk("Connected (%d) - RSSI = %d\n",
         //         default_conn_handle, rssi);
         
         //}
    }
    
    K_WORK_DEFINE(my_work, my_work_handler);
    
    void my_timer_handler(struct k_timer *dummy)
    {
          k_work_submit(&my_work);
    }
    
    K_TIMER_DEFINE(my_timer, my_timer_handler, NULL);
    
    
    ////Timer and handler millis delay()
    //void my_work_handler1(struct k_work *work)
    //{
          
    //}
    
    //K_WORK_DEFINE(my_work1, my_work_handler1);
    
    //void my_timer_handler1(struct k_timer *dummy)
    //{
    //      k_work_submit(&my_work1);
    //}
    
    //K_TIMER_DEFINE(my_timerGDiscovery, my_timer_handler1, NULL);
    
    
    
    
    static void uart_work_handler(struct k_work *item)
    {
    	struct uart_data_t *buf;
    
    	buf = k_malloc(sizeof(*buf));
    	if (buf) {
    		buf->len = 0;
    	} else {
    		LOG_WRN("Not able to allocate UART receive buffer");
                    printk("2Not able to allocate UART receive buffer");
    		k_work_reschedule(&uart_work, UART_WAIT_FOR_BUF_DELAY);
    		return;
    	}
    
    	uart_rx_enable(uart, buf->data, sizeof(buf->data), UART_RX_TIMEOUT);
    }
    
    static int uart_init(void)
    {
    	int err;
    	struct uart_data_t *rx;
    
    	uart = device_get_binding(DT_LABEL(DT_NODELABEL(uart0)));
    	if (!uart) {
    		LOG_ERR("UART binding failed");
                    printk("UART binding failed\n");
    		return -ENXIO;
    	}
    
    	rx = k_malloc(sizeof(*rx));
    	if (rx) {
    		rx->len = 0;
    	} else {
    		return -ENOMEM;
    	}
    
    	k_work_init_delayable(&uart_work, uart_work_handler);
    
    	err = uart_callback_set(uart, uart_cb, NULL);
    	if (err) {
    		return err;
    	}
             printk("UART init\n");
    
    	return uart_rx_enable(uart, rx->data, sizeof(rx->data),
    			      UART_RX_TIMEOUT);
    }
    
    
    
    static int nus_client_init(void)
    {
    	int err;
    	struct bt_nus_client_init_param init = {
    		.cb = {
    			.received = ble_data_received,
    			.sent = ble_data_sent,
    		}
    	};
            
            //for(int i=0;i<12;i++)
            //if(Firsttime==true)
            //{
            //        err = bt_nus_client_init(&nus_client[0], &init);
            //        if (err) {
            //                LOG_ERR("NUS Client initialization failed (err %d)", err);
            //                printk("GENERIC NUS Client  initialized FAIL(err %d)\n",
            //                 err);
            //                return err;
            //        }
            //        else
            //        {
            //                LOG_INF("NUS Client module initialized");
            //                printk("GENERIC NUS Client  initialized OK\n");
            //        }
            //        Firsttime=false;
            //}
            //else
            //{
            err = bt_nus_client_init(&nus_client[NumDevices], &init);
            if (err) {
                    LOG_ERR("NUS Client initialization failed (err %d)", err);
                    printk("%d NUS Client initialization failed FAIL(err %d)\n",NumDevices,
                     err);
                    return err;
            }
            else
            {
                    LOG_INF("NUS Client module initialized");
                    printk("%d NUS Client module initialized OK\n",NumDevices);
            }
               
            return err;
    }
    
    static void CommandConnected(const int8_t ActualizoConexion, const uint8_t NumT)
    {
    
           uint8_t err; 
           //struct uart_data_t *tx = k_malloc(sizeof(*CommandNewConn));
    
           //memcpy(tx->data, CommandNewConn, 4);
    
           // //printk("\n He entrado\n");
           // if(ActualizoConexion==-1)//Actualizo estado de conexion al ultimo qe ha llegado
           // {
           //       err = bt_nus_client_send(&nus_client[NumT], CommandNewConn, 4);//Envio comando de conexion
           //       if (err) {
           //               LOG_WRN("Failed to send data over BLE connection"
           //                       "(err %d)", err);
           //               printk("0Failed to send data over BLE connection"
           //                       "(err %d)", err);
           //       }
           //       else printk("ok");
    
           //       //err = k_sem_take(&nus_write_sem, K_FOREVER);
           //       if (err) {
           //               LOG_WRN("NUS send timeout");
           //               printk("1Failed to send data over BLE connection"
           //                       "(err %d)", err);
           //       }
           //       else
           //       {
           //               NuevaConexion=true;
           //               printk("+1INICIO enviado");
           //       }
           // }
           // else//Actualizo estado de conexion a quien toque
           // {
           //       err = bt_nus_client_send(&nus_client[ActualizoConexion], CommandNewConn, 4);
           //       if (err) {
           //               LOG_WRN("Failed to send data over BLE connection"
           //                       "(err %d)", err);
           //               printk("%d Failed0 to send data over BLE connection"
           //                       "(err %d)", ActualizoConexion, err);
           //       }
    
           //       err = k_sem_take(&nus_write_sem, K_FOREVER);
           //       if (err) {
           //               LOG_WRN("NUS send timeout");
           //               printk("%d Failed1 to send data over BLE connection"
           //                       "(err %d)", ActualizoConexion, err);
           //       }
           //       else
           //       {
           //               NuevaConexion=true;
           //               printk("+2INICIO enviado");
           //       }
           // }
    
              //err = uart_tx(uart, CommandNewConn, 4, SYS_FOREVER_MS);
              //if (err) {
              //        //k_fifo_put(&fifo_uart_tx_data, tx);
              //        printk("Error receibing\n");
              //}
              //else printk("Posted on tx\n");
              //k_free(tx);
    }
    
    //K_THREAD_DEFINE(CommandConnected_id, STACKSIZE, CommandConnected, NULL, NULL,
    	//	NULL, PRIORITY, 0, 0);
    
    
    
    
    static void discovery_complete(struct bt_gatt_dm *dm,
    			       void *context)
    {
            struct bt_nus_client *nus = context;
    
    
    
    	LOG_INF("Service discovery completed");
            printk("%d Service discovery completed",nus);
    
    
    	bt_gatt_dm_data_print(dm);
    
    	bt_nus_handles_assign(dm, nus);
    	bt_nus_subscribe_receive(nus);
    
    	bt_gatt_dm_data_release(dm);
    
    
            k_mutex_lock(&Array_mutex,K_FOREVER);
            k_mutex_lock(&Command_mutex,K_FOREVER);
            if(masuno==true)
            {
                  Device[NumDevices].Connected=true;
                  NumDevices+=1;
                  nus_client_init();
                  Devices2Inicialice[ActualizoConexion1]=NumDevices-1;
                  //ActualizoConexion1=NumDevices-1;
                  masuno=false;
            }
            else
            {
                  Device[Actualiza].Connected=true;
                  Devices2Inicialice[ActualizoConexion1]=Actualiza;
                  //ActualizoConexion1=Actualiza;
            }
            NumDevicesConnected+=1;
            ActualizaBlockList();//Hacer vector de ConnPending
            k_mutex_unlock(&Array_mutex);
            ActualizoConexion1+=1;
            k_mutex_unlock(&Command_mutex);
            //ConnPending=true;
            //CommandConnected(ActualizoConexion1,NumDevices-1);
            k_mutex_unlock(&my_mutex);
    
            //debug
            printk("\nLista: ");
            for(int i=0;i<NumDevices;i++)
            {     //for(int x=0;x<BT_ADDR_LE_STR_LEN;x++)
                  if(Device[i].Connected==true) printk(" %d %s %d, ",i,Device[i].ID.ADDR,Device[i].ID.kartID);
            }
            printk("\n");
            restartScan();
    
    
    }
    
    
    static void discovery_service_not_found(struct bt_conn *conn,
    					void *context)
    {
    	LOG_INF("Service not found");
            printk("Service not found");
            restartScan();
    }
    
    
    static void discovery_error(struct bt_conn *conn,
    			    int err,
    			    void *context)
    {
    	LOG_WRN("Error while discovering GATT database: (%d)", err);
            printk("Error while discovering GATT database:");
            restartScan();
    }
    
    struct bt_gatt_dm_cb discovery_cb = {
    	.completed         = discovery_complete,
    	.service_not_found = discovery_service_not_found,
    	.error_found       = discovery_error,
    };
    
    static void gatt_discover(struct bt_conn *conn)
    {
    	int err;
    
    	if (conn != default_conn) {
    		return;
    	}
    
    	err = bt_gatt_dm_start(conn,
    			       BT_UUID_NUS_SERVICE,
    			       &discovery_cb,
    			       &nus_client[NumDevices]);
    	if (err) {
    		LOG_ERR("could not start the discovery procedure, error "
    			"code: %d", err);
                    printk("%d could not start the discovery procedure, error "
    			"code: %d",NumDevices, err);
                    restartScan();
    	}
            //printk("%d GATT_discover func\n",conn);
            //restartScan();
            //Iniciar timer anti bugs
            //k_timer_start(&my_timerGDiscovery, K_SECONDS(1), K_SECONDS(1));
            //k_timer_start(&my_timer, K_SECONDS(1), K_SECONDS(1));
    
    
    }
    
    static void exchange_func(struct bt_conn *conn, uint8_t err, struct bt_gatt_exchange_params *params)
    {
    	if (!err) {
    		LOG_INF("MTU exchange done");
                    printk("MTU exchange done\n");
    	} else {
    		LOG_WRN("MTU exchange failed (err %" PRIu8 ")", err);
    		printk("MTU exchange failed (err %" PRIu8 ")\n", err);
    	}
    }
    
    
    
    void set_tx_power(uint8_t handle_type, uint16_t handle, int8_t tx_pwr_lvl)
    {
        struct bt_hci_cp_vs_write_tx_power_level *cp;
        struct bt_hci_rp_vs_write_tx_power_level *rp;
        struct net_buf *                          buf, *rsp = NULL;
        int                                       err;
    
        buf = bt_hci_cmd_create(BT_HCI_OP_VS_WRITE_TX_POWER_LEVEL, sizeof(*cp));
        if (!buf) {
            LOG_INF("Unable to allocate command buffer\n");
            return;
        }
    
        cp                 = net_buf_add(buf, sizeof(*cp));
        cp->handle         = sys_cpu_to_le16(handle);
        cp->handle_type    = handle_type;
        cp->tx_power_level = tx_pwr_lvl;
    
        err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_WRITE_TX_POWER_LEVEL, buf, &rsp);
        if (err) {
            uint8_t reason = rsp ? ((struct bt_hci_rp_vs_write_tx_power_level *)rsp->data)->status : 0;
            LOG_INF("Set Tx power err: %d reason 0x%02x\n", err, reason);
            return;
        }
    
        rp = (void *)rsp->data;
        LOG_INF("Actual Tx Power: %d\n", rp->selected_tx_power);
    
        net_buf_unref(rsp);
    }
    
    
    static void get_tx_power(uint8_t handle_type, uint16_t handle, int8_t *tx_pwr_lvl)
    {
    	struct bt_hci_cp_vs_read_tx_power_level *cp;
    	struct bt_hci_rp_vs_read_tx_power_level *rp;
    	struct net_buf *buf, *rsp = NULL;
    	int err;
    
    	*tx_pwr_lvl = 0xFF;
    	buf = bt_hci_cmd_create(BT_HCI_OP_VS_READ_TX_POWER_LEVEL,
    				sizeof(*cp));
    	if (!buf) {
    		printk("Unable to allocate command buffer\n");
    		return;
    	}
    
    	cp = net_buf_add(buf, sizeof(*cp));
    	cp->handle = sys_cpu_to_le16(handle);
    	cp->handle_type = handle_type;
    
    	err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_READ_TX_POWER_LEVEL,
    				   buf, &rsp);
    	if (err) {
    		uint8_t reason = rsp ?
    			((struct bt_hci_rp_vs_read_tx_power_level *)
    			  rsp->data)->status : 0;
    		printk("Read Tx power err: %d reason 0x%02x\n", err, reason);
    		return;
    	}
    
    	rp = (void *)rsp->data;
    	*tx_pwr_lvl = rp->tx_power_level;
    
    	net_buf_unref(rsp);
    }
    
    
    
    
    static void connected(struct bt_conn *conn, uint8_t conn_err)
    {
    	char addr[BT_ADDR_LE_STR_LEN];
            struct bt_conn_info info;
    	int err;
            //Extraigo Addres de la connexion
    	bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));
            //Si hay error hago cosas
    	if (conn_err) {
    		LOG_INF("Failed to connect to %s (%d)", log_strdup(addr),
    			conn_err);
    
    		if (default_conn == conn) {
    			bt_conn_unref(default_conn);
    			default_conn = NULL;
    
    			err = bt_scan_start(BT_SCAN_TYPE_SCAN_ACTIVE);
    			if (err) {
    				LOG_ERR("Scanning failed to start (err %d)",
    					err);
    			}
                            else IsScanning=true;
    		}
    		return;
    	}
    
            //Si no hay error extraigo la info de la conn
            //err = bt_conn_get_info(conn, &info);
            //Para medir rssi*****************************
     //       err = bt_hci_get_conn_handle(conn,&default_conn_handle);
     //       if (err) {
     //               printk("No connection handle (err %d)\n", err);
     //       }
     //       printk("Connection handle %d\n", default_conn_handle);
    
    
     //       const struct bt_conn_le_phy_info *phy_info;
    
            //Historias para tx power
            //phy_info = info.le.phy;
            //printk("%d, Connected: %s, tx_phy %u, rx_phy %u\n",NumDevices,addr, phy_info->tx_phy, phy_info->rx_phy);
            //printk("OJO\n");
            k_mutex_lock(&Array_mutex,K_FOREVER);
            k_mutex_lock(&my_mutex,K_FOREVER);
            printk("Connected: %s", log_strdup(addr));
            //Modifico mi lista segun si es nueva addr o no Anado/actualizo
            if(NumDevices==0)
            {
                 printk("Primer device");
                 bt_addr_le_to_str(bt_conn_get_dst(conn), Device[NumDevices].ID.ADDR, sizeof(addr));
    
                 Device[NumDevices].Addr=bt_conn_get_dst(conn);
                 for(int i=0;i<CONFIG_BT_MAX_CONN;i++)
                    if(strcmp(Mymap[i].ADDR,Device[NumDevices].ID.ADDR)==0)
                    {
                        Device[NumDevices].ID.kartID=Mymap[i].kartID;
                        break;
                    }
                 //Device[NumDevices].Connected=true;
                 masuno=true;
    
            }
            else
            {
                //Recorro mi lista de devices registrados
                for(int i=0;i<NumDevices;i++){
                    //Si ya esta en mi lista actualizo el estado de conexion y salgo
                    if(strcmp(addr,Device[i].ID.ADDR)==0)
                    {
                        printk("%d Actualiza estado conexion a true\n",i);
                        //Device[Actualiza].Connected=true;
                        Actualiza=i;
                        masuno=false;
                        break;
                    }
                    //Si es la ultima iteracion y no esta en mi lista me lo guardo en la lista
                    else if(i==NumDevices-1)
                    {
                        printk("Crea un nuevo estado conecc\n");
                        bt_addr_le_to_str(bt_conn_get_dst(conn), Device[NumDevices].ID.ADDR, sizeof(addr));
                        Device[NumDevices].Addr=bt_conn_get_dst(conn);
                        for(int i=0;i<CONFIG_BT_MAX_CONN;i++)
                        if(strcmp(Mymap[i].ADDR,Device[NumDevices].ID.ADDR)==0)
                        {
                            Device[NumDevices].ID.kartID=Mymap[i].kartID;
                            break;
                        }
                        //Device[NumDevices].Connected=true;
                        masuno=true;
                    }
                }
            }
            
            k_mutex_unlock(&Array_mutex);
            //Subo TX power
    	static struct bt_gatt_exchange_params exchange_params;
            
            set_tx_power(BT_HCI_VS_LL_HANDLE_TYPE_CONN,
    				     default_conn_handle,
    				     +8);
            get_tx_power(BT_HCI_VS_LL_HANDLE_TYPE_CONN,
    				     default_conn_handle, &txp);
    
            //printk("Connection (%d) - Initial Tx Power = %d\n", default_conn_handle, txp);
    
            //Tareas por defecto en conexion
    	exchange_params.func = exchange_func;
    	err = bt_gatt_exchange_mtu(conn, &exchange_params);
    	if (err) {
    		LOG_WRN("MTU exchange failed (err %d)", err);
                    printk("MTU exchange failed (err %d)", err);
    	}
    
    	//err = bt_conn_set_security(conn, BT_SECURITY_L2);
    	//if (err) {
    	//	LOG_WRN("Failed to set security: %d", err);
     //               printk("Failed to set security: %d", err);
    	//	gatt_discover(conn);
    	//}
            gatt_discover(conn);
    }
    
    static void disconnected(struct bt_conn *conn, uint8_t reason)
    {
    	char addr[BT_ADDR_LE_STR_LEN];
            //uint8_t PosDeviceDisconnected;
    	//int err;
    
    	bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));
    
    
            //k_mutex_lock(&my_mutex,K_FOREVER);
            k_mutex_lock(&Array_mutex,K_FOREVER);
    
            //Si est� lo Borro de la lista de conectdos
            for(uint8_t i=0;i<NumDevices;i++)
            {
                  if(strcmp(addr,Device[i].ID.ADDR)==0)
                  {
                        printk("Actualizamos estdo conexion a false\n");
                        Device[i].Connected=false; 
                        LOG_INF("Disconnected: %s (reason %u)", log_strdup(addr),reason);
                        printk("%d Disconnected: %s (reason %u)",i, log_strdup(addr),reason);
                        break;
                  }
            }
    	//if (default_conn != conn) {
    	//	return;
    	//}
            printk("\nLista: ");
            for(int i=0;i<NumDevices;i++)
            {     //for(int x=0;x<BT_ADDR_LE_STR_LEN;x++)
                  if(Device[i].Connected==true) printk("%s",Device[i].ID.ADDR);
            }
            ActualizaBlockList();
            k_mutex_unlock(&Array_mutex);
            NumDevicesConnected-=1;
    
    	bt_conn_unref(conn);
    	default_conn = NULL;
            //k_mutex_unlock(&my_mutex);
    
            printk("Seguimos\n");
            restartScan();
    
    
    }
    
    static void security_changed(struct bt_conn *conn, bt_security_t level,
    			     enum bt_security_err err)
    {
    	char addr[BT_ADDR_LE_STR_LEN];
    
    	bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));
    
    	if (!err) {
    		LOG_INF("Security changed: %s level %u", log_strdup(addr),
    			level);
                    printk("Security changed: %s level %u", log_strdup(addr),
    			level);
    	} else {
    		LOG_WRN("Security failed: %s level %u err %d", log_strdup(addr),
    			level, err);
                    printk("Security failed: %s level %u err %d", log_strdup(addr),
    			level, err);
    	}
    
    	gatt_discover(conn);
    }
    
    static struct bt_conn_cb conn_callbacks = {
    	.connected = connected,
    	.disconnected = disconnected,
    	//.security_changed = security_changed
    };
    
    static void scan_filter_match(struct bt_scan_device_info *device_info,
    			      struct bt_scan_filter_match *filter_match,
    			      bool connectable)
    {
    	int err;
    	char addr[BT_ADDR_LE_STR_LEN];
            uint8_t fich=5;
    	struct bt_conn_le_create_param *conn_params;
    
    	bt_addr_le_to_str(device_info->recv_info->addr, addr, sizeof(addr));
    
    	printk("Filters matched. Address: %s connectable: %s\n",
    		addr, connectable ? "yes" : "no");
    
            k_mutex_lock(&Array_mutex,K_FOREVER);
            
            //Si hay alguien que se quiere conectar pero aun no se ha desconectado no hago nada
            for(uint8_t i=0;i<NumDevices;i++)
            {
                  if((strcmp(addr,Device[i].ID.ADDR)==0)&&(Device[i].Connected==true))
                  {
                        printk("Quiere conectar pero aun no se ha desconectado");
                        k_mutex_unlock(&Array_mutex);
                        return;
                  }
                  else if((strcmp(addr,Device[i].ID.ADDR)==0)&&(Device[i].Connected==false))
                  {
                        fich=i;
                        break;
                  }
            }
            k_mutex_unlock(&Array_mutex);
    
            
    	err = bt_scan_stop();
    	if (err) {
    		printk("Stop LE scan failed (err %d)\n", err);
    	}
            else{
                IsScanning=false;
                printk("Stop Scanning\n");
            }
    	conn_params = BT_CONN_LE_CREATE_PARAM(
    			BT_CONN_LE_OPT_CODED | BT_CONN_LE_OPT_NO_1M,
    			BT_GAP_SCAN_FAST_INTERVAL,
    			BT_GAP_SCAN_FAST_INTERVAL);
    
    	err = bt_conn_le_create(device_info->recv_info->addr, conn_params,
    				&m_conn_param,
    				&default_conn);
    
    	if (err) {
    		printk("Create conn failed (err %d)\n", err);
                    restartScan();
                    //err = bt_scan_start(BT_SCAN_TYPE_SCAN_ACTIVE);
                    //if (err) {
                    //        printk("Scanning failed to start (err %d)\n", err);
                    //        return;
                    //}
                    //printk("Scan restarted\n");
    	}
    	printk("%d Connection pending\n",fich);
    }
    
    
    
    
    //static void scan_filter_match(struct bt_scan_device_info *device_info,
    //			      struct bt_scan_filter_match *filter_match,
    //			      bool connectable)
    //{
    //	char addr[BT_ADDR_LE_STR_LEN];
    
    //	bt_addr_le_to_str(device_info->recv_info->addr, addr, sizeof(addr));
    
    //	LOG_INF("Filters matched. Address: %s connectable: %d",
    //		log_strdup(addr), connectable);
    //}
    
    static void scan_connecting_error(struct bt_scan_device_info *device_info)
    {
    	LOG_WRN("Connecting failed");
            printk("Connecting failed\n");
    }
    
    static void scan_connecting(struct bt_scan_device_info *device_info,
    			    struct bt_conn *conn)
    {
    	default_conn = bt_conn_ref(conn);
    }
    
    
    BT_SCAN_CB_INIT(scan_cb, scan_filter_match, NULL,
    		scan_connecting_error, scan_connecting);
    
    static int scan_init(void)
    {
    	int err;
            const char *perName1="Uart_periph1";//"Uart_periph1";Nordic_UART_Service
            const char *perName2="Nordic_UART_Service";//"Uart_periph1";Nordic_UART_Service
            //static char const test_periph_addr[] = {0x17, 0x49, 0xB7, 0xBE, 0xC4, 0xDC};
    	struct bt_scan_init_param scan_init = {
    		.connect_if_match = 1,
                    .scan_param = &m_scan_param,
                    .conn_param = NULL,//&m_conn_param,
    	};
    
    	bt_scan_init(&scan_init);
    	bt_scan_cb_register(&scan_cb);
    
    	//err = bt_scan_filter_add(BT_SCAN_FILTER_TYPE_UUID, BT_UUID_NUS_SERVICE);
    	//if (err) {
    	//	LOG_ERR("Scanning filters cannot be set (err %d)", err);
    	//	return err;
    	//}
    
    	//err = bt_scan_filter_enable(BT_SCAN_UUID_FILTER, false);
    	//if (err) {
    	//	LOG_ERR("Filters cannot be turned on (err %d)", err);
    	//	return err;
    	//} 
    
            err = bt_scan_filter_add(BT_SCAN_FILTER_TYPE_NAME,perName1);
    
    	if (err) {
    		LOG_ERR("Scanning filters1 cannot be set (err %d)", err);
    		return err;
    	}
            err = bt_scan_filter_add(BT_SCAN_FILTER_TYPE_NAME,perName2);
    
    	if (err) {
    		LOG_ERR("Scanning filters2 cannot be set (err %d)", err);
    		return err;
    	}
    
    	err = bt_scan_filter_enable(BT_SCAN_NAME_FILTER, false);
    	if (err) {
    		LOG_ERR("Filters cannot be turned on (err %d)", err);
    		return err;
    	} 
    
    	LOG_INF("Scan module initialized");
            printk("Scan module initialized\n");
    	return err;
    }
    
    
    static void auth_cancel(struct bt_conn *conn)
    {
    	char addr[BT_ADDR_LE_STR_LEN];
    
    	bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));
    
    	LOG_INF("Pairing cancelled: %s", log_strdup(addr));
            printk("Pairing cancelled: %s", log_strdup(addr));
    
    }
    
    
    static void pairing_confirm(struct bt_conn *conn)
    {
    	char addr[BT_ADDR_LE_STR_LEN];
    
    	bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));
    
    	//bt_conn_auth_pairing_confirm(conn);
    
    	LOG_INF("Pairing confirmed: %s", log_strdup(addr));
            printk("Pairing confirmed: %s", log_strdup(addr));
    }
    
    
    static void pairing_complete(struct bt_conn *conn, bool bonded)
    {
    	char addr[BT_ADDR_LE_STR_LEN];
    
    	bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));
    
    	LOG_INF("Pairing completed: %s, bonded: %d", log_strdup(addr),
    		bonded);
            printk("Pairing completed: %s, bonded: %d", log_strdup(addr),bonded);
    }
    
    
    static void pairing_failed(struct bt_conn *conn, enum bt_security_err reason)
    {
    	char addr[BT_ADDR_LE_STR_LEN];
    
    	bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));
    
    	LOG_WRN("Pairing failed conn: %s, reason %d", log_strdup(addr),
    		reason);
            printk("Pairing failed conn: %s, reason %d", log_strdup(addr),
    		reason);
    }
    
    static struct bt_conn_auth_cb conn_auth_callbacks = {
    	.cancel = auth_cancel,
    	.pairing_confirm = pairing_confirm,
    	.pairing_complete = pairing_complete,
    	.pairing_failed = pairing_failed
    };
    
    
    
    void main(void)
    {
    	int err;
    
    	//err = bt_conn_auth_cb_register(&conn_auth_callbacks);
    	//if (err) {
    	//	LOG_ERR("Failed to register authorization callbacks.");
    	//	return;
    	//}
            //inicializa mutex HACER MUTEX PAR CAMBIAR VECTOR DE CONEXIONES
            //nrfx_mtx_init();
            k_mutex_init(&Array_mutex);
            k_mutex_init(&my_mutex);
            k_mutex_init(&Command_mutex);
    
    	err = bt_enable(NULL);
    	if (err) {
    		LOG_ERR("Bluetooth init failed (err %d)", err);
    		return;
    	}
    	LOG_INF("Bluetooth initialized");
            printk("Bluetooth initialized\n");
    
    	if (IS_ENABLED(CONFIG_SETTINGS)) {
    		settings_load();
    	}
    
    	bt_conn_cb_register(&conn_callbacks);
    
    	int (*module_init[])(void) = {uart_init, scan_init, nus_client_init};
    	for (size_t i = 0; i < ARRAY_SIZE(module_init); i++) {
    		err = (*module_init[i])();
    		if (err) {
    			return;
    		}
    	}
    
    	printk("Starting Bluetooth Central UART example\n");
    
    	err = bt_scan_start(BT_SCAN_TYPE_SCAN_ACTIVE);
    	if (err) {
    		LOG_ERR("Scanning failed to start (err %d)", err);
    		return;
    	}
            else IsScanning=true;
    
    	LOG_INF("Scanning successfully started");
            printk("Scanning successfully started\n");
    
    
            int objective;
            bool checked;  
            uint8_t CommandNewConn[4]={0x4e,0x43,0x41,0x0d};
            uint8_t count=0;
    
    
    	for (;;) {
    
             /* Wait indefinitely for data to be sent over Bluetooth */
             struct uart_data_t *buf = k_fifo_get(&fifo_uart_rx_data,K_SECONDS(2));// K_SECONDS(2)
    
             if((buf->len>0)&&(buf->len<=UART_BUF_SIZE))
             {
                   //printk("%d",buf->len);
                   //                 S     +        C     +    objective(2222) + 14 bytes as max COMANDO PARA ENVIO INDIVIDUAL
                   if((buf->data[0]==0x53)&&(buf->data[1]==0x43)&&(buf->data[buf->len-1]==13))
                   {
                          //printk("%d",buf->len);
                          //printk("Comando recibido:   ");
    
                          objective = strtol(&buf->data[2], NULL, 10);
                          //printk("%d",objective);
                          Command=true;
                   }
                   else Command=false;
    
                   if(Command==false)//ENVIO A TODOS
                   {
                         for(int i=0;i<NumDevices;i++)
                         {
                                if(Device[i].Connected==true)
                                {
                                
                                      err = bt_nus_client_send(&nus_client[i], buf->data, buf->len);
                                      if (err) {
                                              LOG_WRN("Failed to send data over BLE connection"
                                                      "(err %d)", err);
                                      }
    
                                      err = k_sem_take(&nus_write_sem, K_FOREVER);
                                      if (err) {
                                              LOG_WRN("NUS send timeout");
                                      }
                                      printk("Client %d Sended",i);
                                }      
                          }
                    }
                    else if(Command==true)//Envio al que quiero 1
                    {
                          //Buscas en la lista el objetivo del comando
                          for(int i=0;i<NumDevices;i++)
                          {
                                if(Device[i].ID.kartID==objective)
                                {
                                    objective=i;
                                    checked=true;
                                    break;
                                }
                                else checked=false;
                          }
    
                          if(checked==true)
                          {
                                if(Device[objective].Connected==true)
                                {
                                      //printk("Envio solo a %d",objective);
                                      err = bt_nus_client_send(&nus_client[objective], buf->data, buf->len);
                                      if (err) {
                                              LOG_WRN("Failed to send data over BLE connection"
                                                      "(err %d)", err);
                                              printk("Failed to send data over BLE connection"
                                                      "(err %d)", err);
                                      }
    
                                      err = k_sem_take(&nus_write_sem, K_FOREVER);
                                      if (err) {
                                              LOG_WRN("NUS send timeout");
                                              printk("Failed to send data over BLE connection"
                                                      "(err %d)", err);
                                      }
                                }
                                else printk("Dispositivo deseado no conectado\n");
                                //count=0;
                          }
                          else printk("Objetivo no existe\n");
                  
                    }
              }
              else if(ActualizoConexion1!=0)
              {
                     k_mutex_lock(&Command_mutex,K_FOREVER);
    
                     err = bt_nus_client_send(&nus_client[Devices2Inicialice[ActualizoConexion1-1]], CommandNewConn, 4);
                     if (err) {
                             LOG_WRN("Failed to send data over BLE connection"
                                     "(err %d)", err);
                              printk("00Failed to send data over BLE connection"
                                      "(err %d)", err);
                      }
                      else
                      {
                              printk("%d 0ok",ActualizoConexion1-1);
                              count+=1;
                              ConnPending=true;
                              ActualizoConexion1-=1;
                      }
                      k_mutex_unlock(&Command_mutex);
    
              //        err = k_sem_take(&nus_write_sem, K_FOREVER);
              //        if (err) {
              //                LOG_WRN("NUS send timeout");
              //                printk("11Failed to send data over BLE connection"
              //                        "(err %d)", err);
              //        }
              //        else
              //        {
              //                NuevaConexion=true;
              //                printk("+INICIO %d enviado",ActualizoConexion1-1);
              //                if(count==1)
              //                {
              //                      ActualizoConexion1-=1;
              //                      ConnPending=true;
              //                }
              //        }
              //}
              //
          }}
    }
    
    
    
    

Reply
  • The changes that i made are the advertising_params and the conn_params and Kconfig.

    If I understand you correctly you have modified the central_uart example to use coded phy?

    Yes, coded and multilink.

    try with my main:

    /*
     * Copyright (c) 2018 Nordic Semiconductor ASA
     *
     * SPDX-License-Identifier: LicenseRef-Nordic-5-Clause
     */
    
    /** @file
     *  @brief Nordic UART Service Client sample
     */
    
    #include <errno.h>
    #include <zephyr.h>
    #include <sys/byteorder.h>
    #include <sys/printk.h>
    
    #include <bluetooth/bluetooth.h>
    #include <bluetooth/hci.h>
    #include <bluetooth/hci_vs.h>
    #include <bluetooth/conn.h>
    #include <bluetooth/uuid.h>
    #include <bluetooth/gatt.h>
    
    #include <bluetooth/services/nus.h>
    #include <bluetooth/services/nus_client.h>
    #include <bluetooth/gatt_dm.h>
    #include <bluetooth/scan.h>
    //#include <strtol.h>
    
    
    #include <settings/settings.h>
    
    #include <drivers/uart.h>
    
    #include <logging/log.h>
    
    #define LOG_MODULE_NAME central_uart
    LOG_MODULE_REGISTER(LOG_MODULE_NAME);
    
    /* UART payload buffer element size. */
    #define UART_BUF_SIZE 20
    
    #define NUS_WRITE_TIMEOUT K_MSEC(150)
    #define UART_WAIT_FOR_BUF_DELAY K_MSEC(50)
    #define UART_RX_TIMEOUT 50
    #define kartIDsize 4
    
    
    //#define BT_HCI_OP_VS_WRITE_TX_POWER_LEVEL   BT_OP(BT_OGF_VS, 0x000e)
    //FFFFFFFFFFFFFFFFFjejejej
    
    #define STACKSIZE 1024
    #define PRIORITY 7
    
    
    //Parametros de scaneo
    static struct bt_le_scan_param m_scan_param=
              {
              .type = BT_LE_SCAN_TYPE_ACTIVE,
              .options = BT_LE_SCAN_OPT_CODED | BT_LE_SCAN_OPT_NO_1M,
              .interval = BT_GAP_SCAN_FAST_INTERVAL,//BT_GAP_SCAN_SLOW_INTERVAL_1,
              .window = BT_GAP_SCAN_FAST_WINDOW,//BT_GAP_SCAN_SLOW_WINDOW_1,
              };
    
    //Parametros de conexion
    struct bt_le_conn_param m_conn_param=
    {
    	.interval_min=40,//70*0.625ms
    	.interval_max=150,
    	.timeout=1000,
            .latency=0,
          
    };
    
    
    struct MapID
    {
          char ADDR[BT_ADDR_LE_STR_LEN];//addr formato string
          int kartID; 
    };
    
    static struct MapID Mymap[CONFIG_BT_MAX_CONN]={{"EB:B4:10:52:81:E8 (random)",1111},{"E4:94:98:5A:79:AF (random)",2222}};
    
    //Mis propiedades
    struct DeviceProperties
    {
          struct MapID ID;
          const bt_addr_le_t *Addr;//addr
          uint16_t conn_handle;
          bool Connected;
    };
    //Lista de clientes
    static struct bt_nus_client nus_client[CONFIG_BT_MAX_CONN];
    
    struct DeviceProperties Device[CONFIG_BT_MAX_CONN];
    
    uint8_t NumDevices=0;
    uint8_t NumDevicesConnected=0;
    //gestion
    bool IsScanning=false;
    bool masuno=false;
    bool Command=false;
    uint8_t Actualiza;
    int8_t ActualizoConexion1;
    bool NuevaConexion=false;
    bool ConnPending=false;
    uint8_t Devices2Inicialice[CONFIG_BT_MAX_CONN];
    
    //para medida rssi
    static int8_t txp;
    //data_sended()
    uint8_t msgSended;
    
    struct k_mutex Array_mutex;
    struct k_mutex my_mutex;
    struct k_mutex Command_mutex;
    
    //struct k_mutex send_mutex;
    
    
    static const struct device *uart;
    static struct k_work_delayable uart_work;
    
    K_SEM_DEFINE(nus_write_sem, 0, 1);
    //K_SEM_DEFINE(sem, 0, 1);
    
    struct uart_data_t {
    	void *fifo_reserved;
    	uint8_t  data[UART_BUF_SIZE];
    	uint16_t len;
    };
    
    //static const char *Handlers[CONFIG_BT_MAX_CONN]={"fifo_uart_tx_data","fifo_uart_tx_data1","fifo_uart_tx_data2","fifo_uart_tx_data3","fifo_uart_tx_data4","fifo_uart_tx_data5","fifo_uart_tx_data6","fifo_uart_tx_data7","fifo_uart_tx_data8","fifo_uart_tx_data9","fifo_uart_tx_data10","fifo_uart_tx_data11","fifo_uart_tx_data12","fifo_uart_tx_data13","fifo_uart_tx_data14","fifo_uart_tx_data15","fifo_uart_tx_data16","fifo_uart_tx_data17","fifo_uart_tx_data18","fifo_uart_tx_data19"};
    //Mutex para hardware UART
    static K_FIFO_DEFINE(fifo_uart_tx_data);
    static K_FIFO_DEFINE(fifo_uart_rx_data);
    
    static struct bt_conn *default_conn;
    static uint16_t default_conn_handle;
    //static struct bt_nus_client *nus_client[CONFIG_BT_MAX_CONN];
    
    
    //static void ble_data_sent(uint8_t err, const uint8_t *const data, uint16_t len)
    //{
    //	struct uart_data_t *buf;
            
    //        msgSended+=1;
    
    //	/* Retrieve buffer context. */
    //	buf = CONTAINER_OF(data, struct uart_data_t, data);
    
    //        //k_free(buf);
    
    //	if((msgSended==NumDevicesConnected)/*/&&(Noquedan==true)/*/)//Dependiendo si es un mensaje de mas de buff size uart
    //        {
    //              msgSended=0;
    //              printk("CLEAN");
    //              //Mucho ojo con esto, hay que ver cuando ejecutarlo, siempre despues de haber acabado de enviar mensaje
    //              k_free(buf);
    //        }
    //        printk("0DATA sended\n");
    
    //	k_sem_give(&nus_write_sem);
    
    //	if (err) {
    //		LOG_WRN("ATT error code: 0x%02X", err);
    //                printk("ATT error code: 0x%02X", err);
    //	}
    //        printk("DATA sended\n");
    //}
    
    static void restartScan()
    {
            int err;
    
            if((IsScanning==false)&&(NumDevicesConnected<CONFIG_BT_MAX_CONN))
            {
                k_mutex_lock(&my_mutex,K_FOREVER);
                err = bt_scan_start(BT_SCAN_TYPE_SCAN_ACTIVE);
                if (err) {
                        printk("Scanning failed to start (err %d)\n", err);
                        k_mutex_unlock(&my_mutex);
                        return;
                }
                else
                {       
                        IsScanning=true;
                        k_mutex_unlock(&my_mutex);
                        printk("Scan restarted\n");
                }
            }
            else printk("ya esta scanning en teoria\n");
    
    }
    
    static void ble_data_sent(uint8_t err, const uint8_t *const data, uint16_t len)
    {
    	struct uart_data_t *buf;
    
            msgSended+=1;
    
    	/* Retrieve buffer context. */
    	buf = CONTAINER_OF(data, struct uart_data_t, data);
    
            if((ConnPending==true)&&(!err))
            {
                  printk("Nueva conn");
                  // k_free(buf);
                  restartScan();
                  ConnPending=false;
                  //k_mutex_unlock(&send_mutex);
            }
            //printk("DATA sended\n");
            else if((Command==true)||(NumDevicesConnected==1)||(msgSended==NumDevicesConnected))
            {
                  k_free(buf);
                  msgSended=0;
            }
    
    	k_sem_give(&nus_write_sem);
            printk("SendSended\n");
    
    	if (err) {
    		LOG_WRN("ATT error code: 0x%02X", err);
                    printk("ATT error code: 0x%02X", err);
    	}
    }
    
    static uint8_t ble_data_received(const uint8_t *const data, uint16_t len, struct bt_conn *conn)
    {
    	int err;
            char addr[BT_ADDR_LE_STR_LEN];
            uint8_t id;//ignore
    
    	bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));
    
            //Para detectar que cliente lo manda:
             for(int i=0;i<NumDevices;i++){
                    //Si ya esta en mi lista actualizo el estado de conexion y salgo
                    if(strcmp(addr,Device[i].ID.ADDR)==0)
                    {
                        id=i;
                        break;
                    }
             }
              
             //printk("Received from ");
             printk("%d",id);
             printk("  ");
             printk(Device[id].ID.ADDR);//sta ok
            // printk("numKart ");
             printk("%d ",Device[id].ID.kartID);
             //printk("numClient ");
             //printk("%d ",id);
             printk(":   ");
    
    	for (uint16_t pos = 0; pos != len;) {
    		struct uart_data_t *tx = k_malloc(sizeof(*tx));
    
    		if (!tx) {
    			LOG_WRN("Not able to allocate UART send data buffer");
                            printk("Not able to allocate UART send data buffer\n");
    			return BT_GATT_ITER_CONTINUE;
    		}
    
    		/* Keep the last byte of TX buffer for potential LF char. */
    		size_t tx_data_size = sizeof(tx->data) - 1;
    
    		if ((len - pos) > tx_data_size) {
    			tx->len = tx_data_size;
    		} else {
    			tx->len = (len - pos);
    		}
    
    		memcpy(tx->data, &data[pos], tx->len);
    
    		pos += tx->len;
    
    		/* Append the LF character when the CR character triggered
    		 * transmission from the peer.
    		 */
    		if ((pos == len) && (data[len - 1] == '\r')) {
    			tx->data[tx->len] = '\n';
    			tx->len++;
    		}
    
    		err = uart_tx(uart, tx->data, tx->len, SYS_FOREVER_MS);
    		if (err) {
    			k_fifo_put(&fifo_uart_tx_data, tx);
                           // printk("Error receibing\n");
    		}
                    //printk("DATA receibed\n");
    	}
    
    	return BT_GATT_ITER_CONTINUE;
    }
    
    static void ActualizaBlockList()
    {
            bt_scan_blocklist_clear();
            //printk("Actializo blcklist ");
            for(int i=0;i<NumDevices;i++){
                if(Device[i].Connected==true)
                {
                      bt_scan_blocklist_device_add(Device[i].Addr);
                      //printk("%d\n",i);
                }
            } 
    }
    
    
    static void uart_cb(const struct device *dev, struct uart_event *evt, void *user_data)
    {
    	ARG_UNUSED(dev);
    
    	static uint8_t *current_buf;
    	static size_t aborted_len;
    	static bool buf_release;
    	struct uart_data_t *buf;
    	static uint8_t *aborted_buf;
    
    
    	switch (evt->type) {
    	case UART_TX_DONE:
    		if ((evt->data.tx.len == 0) ||
    		    (!evt->data.tx.buf)) {
    			return;
    		}
    
    		if (aborted_buf) {
    			buf = CONTAINER_OF(aborted_buf, struct uart_data_t,
    					   data);
    			aborted_buf = NULL;
    			aborted_len = 0;
    		} else {
    			buf = CONTAINER_OF(evt->data.tx.buf,
    					   struct uart_data_t,
    					   data);
    		}
    
    		k_free(buf);
    
    		buf = k_fifo_get(&fifo_uart_tx_data, K_NO_WAIT);
    		if (!buf) {
    			return;
    		}
    
    		if (uart_tx(uart, buf->data, buf->len, SYS_FOREVER_MS)) {
    			LOG_WRN("Failed to send data over UART");
    		}
    
    		break;
    
    	case UART_RX_RDY://Data received and timeout triggered OR buff filled
    		buf = CONTAINER_OF(evt->data.rx.buf, struct uart_data_t, data);
    		buf->len += evt->data.rx.len;
    		buf_release = false;
    
    		if (buf->len == UART_BUF_SIZE) {//If buff lleno
    			k_fifo_put(&fifo_uart_rx_data, buf);
    		} else if ((evt->data.rx.buf[buf->len - 1] == '\n') ||//else
    			  (evt->data.rx.buf[buf->len - 1] == '\r')) {
    			k_fifo_put(&fifo_uart_rx_data, buf);
    			current_buf = evt->data.rx.buf;
    			buf_release = true;
    			uart_rx_disable(uart);
    		}
    
    		break;
    
    	case UART_RX_DISABLED:
    		buf = k_malloc(sizeof(*buf));
    		if (buf) {
    			buf->len = 0;
    		} else {
    			LOG_WRN("Not able to allocate UART receive buffer");
    			k_work_reschedule(&uart_work, UART_WAIT_FOR_BUF_DELAY);
    			return;
    		}
    
    		uart_rx_enable(uart, buf->data, sizeof(buf->data),
    			       UART_RX_TIMEOUT);
    
    		break;
    
    	case UART_RX_BUF_REQUEST://Uart start to receive on a buff
    		buf = k_malloc(sizeof(*buf));
    		if (buf) {//
    			buf->len = 0;
    			uart_rx_buf_rsp(uart, buf->data, sizeof(buf->data));
    		} else {
    			LOG_WRN("Not able to allocate UART receive buffer");
    		}
    
    		break;
    
    	case UART_RX_BUF_RELEASED://Buff full
    		buf = CONTAINER_OF(evt->data.rx_buf.buf, struct uart_data_t,
    				   data);
    		if (buf_release && (current_buf != evt->data.rx_buf.buf)) {
    			k_free(buf);//Lo libera
    			buf_release = false;
    			current_buf = NULL;
    		}
    
    		break;
    
    	case UART_TX_ABORTED:
    			if (!aborted_buf) {
    				aborted_buf = (uint8_t *)evt->data.tx.buf;
    			}
    
    			aborted_len += evt->data.tx.len;
    			buf = CONTAINER_OF(aborted_buf, struct uart_data_t,
    					   data);
    
    			uart_tx(uart, &buf->data[aborted_len],
    				buf->len - aborted_len, SYS_FOREVER_MS);
    
    		break;
    
    	default:
    		break;
    	}
    }
    
    
    static void read_conn_rssi(uint16_t handle, int8_t *rssi)
    {
    	struct net_buf *buf, *rsp = NULL;
    	struct bt_hci_cp_read_rssi *cp;
    	struct bt_hci_rp_read_rssi *rp;
    
    	int err;
    
    	buf = bt_hci_cmd_create(BT_HCI_OP_READ_RSSI, sizeof(*cp));
    	if (!buf) {
    		printk("Unable to allocate command buffer\n");
    		return;
    	}
    
    	cp = net_buf_add(buf, sizeof(*cp));
    	cp->handle = sys_cpu_to_le16(handle);
    
    	err = bt_hci_cmd_send_sync(BT_HCI_OP_READ_RSSI, buf, &rsp);
    	if (err) {
    		uint8_t reason = rsp ?
    			((struct bt_hci_rp_read_rssi *)rsp->data)->status : 0;
    		printk("Read RSSI err: %d reason 0x%02x\n", err, reason);
    		return;
    	}
    
    	rp = (void *)rsp->data;
    	*rssi = rp->rssi;
    
    	net_buf_unref(rsp);
    }
    
    
    
    //Timer and handler millis delay()
    void my_work_handler(struct k_work *work)
    {
         //if(Device[0].Connected==true)
         //{
         //         int8_t rssi = 0xFF;
         //         read_conn_rssi(default_conn_handle, &rssi);
         //         printk("Connected (%d) - RSSI = %d\n",
         //         default_conn_handle, rssi);
         
         //}
    }
    
    K_WORK_DEFINE(my_work, my_work_handler);
    
    void my_timer_handler(struct k_timer *dummy)
    {
          k_work_submit(&my_work);
    }
    
    K_TIMER_DEFINE(my_timer, my_timer_handler, NULL);
    
    
    ////Timer and handler millis delay()
    //void my_work_handler1(struct k_work *work)
    //{
          
    //}
    
    //K_WORK_DEFINE(my_work1, my_work_handler1);
    
    //void my_timer_handler1(struct k_timer *dummy)
    //{
    //      k_work_submit(&my_work1);
    //}
    
    //K_TIMER_DEFINE(my_timerGDiscovery, my_timer_handler1, NULL);
    
    
    
    
    static void uart_work_handler(struct k_work *item)
    {
    	struct uart_data_t *buf;
    
    	buf = k_malloc(sizeof(*buf));
    	if (buf) {
    		buf->len = 0;
    	} else {
    		LOG_WRN("Not able to allocate UART receive buffer");
                    printk("2Not able to allocate UART receive buffer");
    		k_work_reschedule(&uart_work, UART_WAIT_FOR_BUF_DELAY);
    		return;
    	}
    
    	uart_rx_enable(uart, buf->data, sizeof(buf->data), UART_RX_TIMEOUT);
    }
    
    static int uart_init(void)
    {
    	int err;
    	struct uart_data_t *rx;
    
    	uart = device_get_binding(DT_LABEL(DT_NODELABEL(uart0)));
    	if (!uart) {
    		LOG_ERR("UART binding failed");
                    printk("UART binding failed\n");
    		return -ENXIO;
    	}
    
    	rx = k_malloc(sizeof(*rx));
    	if (rx) {
    		rx->len = 0;
    	} else {
    		return -ENOMEM;
    	}
    
    	k_work_init_delayable(&uart_work, uart_work_handler);
    
    	err = uart_callback_set(uart, uart_cb, NULL);
    	if (err) {
    		return err;
    	}
             printk("UART init\n");
    
    	return uart_rx_enable(uart, rx->data, sizeof(rx->data),
    			      UART_RX_TIMEOUT);
    }
    
    
    
    static int nus_client_init(void)
    {
    	int err;
    	struct bt_nus_client_init_param init = {
    		.cb = {
    			.received = ble_data_received,
    			.sent = ble_data_sent,
    		}
    	};
            
            //for(int i=0;i<12;i++)
            //if(Firsttime==true)
            //{
            //        err = bt_nus_client_init(&nus_client[0], &init);
            //        if (err) {
            //                LOG_ERR("NUS Client initialization failed (err %d)", err);
            //                printk("GENERIC NUS Client  initialized FAIL(err %d)\n",
            //                 err);
            //                return err;
            //        }
            //        else
            //        {
            //                LOG_INF("NUS Client module initialized");
            //                printk("GENERIC NUS Client  initialized OK\n");
            //        }
            //        Firsttime=false;
            //}
            //else
            //{
            err = bt_nus_client_init(&nus_client[NumDevices], &init);
            if (err) {
                    LOG_ERR("NUS Client initialization failed (err %d)", err);
                    printk("%d NUS Client initialization failed FAIL(err %d)\n",NumDevices,
                     err);
                    return err;
            }
            else
            {
                    LOG_INF("NUS Client module initialized");
                    printk("%d NUS Client module initialized OK\n",NumDevices);
            }
               
            return err;
    }
    
    static void CommandConnected(const int8_t ActualizoConexion, const uint8_t NumT)
    {
    
           uint8_t err; 
           //struct uart_data_t *tx = k_malloc(sizeof(*CommandNewConn));
    
           //memcpy(tx->data, CommandNewConn, 4);
    
           // //printk("\n He entrado\n");
           // if(ActualizoConexion==-1)//Actualizo estado de conexion al ultimo qe ha llegado
           // {
           //       err = bt_nus_client_send(&nus_client[NumT], CommandNewConn, 4);//Envio comando de conexion
           //       if (err) {
           //               LOG_WRN("Failed to send data over BLE connection"
           //                       "(err %d)", err);
           //               printk("0Failed to send data over BLE connection"
           //                       "(err %d)", err);
           //       }
           //       else printk("ok");
    
           //       //err = k_sem_take(&nus_write_sem, K_FOREVER);
           //       if (err) {
           //               LOG_WRN("NUS send timeout");
           //               printk("1Failed to send data over BLE connection"
           //                       "(err %d)", err);
           //       }
           //       else
           //       {
           //               NuevaConexion=true;
           //               printk("+1INICIO enviado");
           //       }
           // }
           // else//Actualizo estado de conexion a quien toque
           // {
           //       err = bt_nus_client_send(&nus_client[ActualizoConexion], CommandNewConn, 4);
           //       if (err) {
           //               LOG_WRN("Failed to send data over BLE connection"
           //                       "(err %d)", err);
           //               printk("%d Failed0 to send data over BLE connection"
           //                       "(err %d)", ActualizoConexion, err);
           //       }
    
           //       err = k_sem_take(&nus_write_sem, K_FOREVER);
           //       if (err) {
           //               LOG_WRN("NUS send timeout");
           //               printk("%d Failed1 to send data over BLE connection"
           //                       "(err %d)", ActualizoConexion, err);
           //       }
           //       else
           //       {
           //               NuevaConexion=true;
           //               printk("+2INICIO enviado");
           //       }
           // }
    
              //err = uart_tx(uart, CommandNewConn, 4, SYS_FOREVER_MS);
              //if (err) {
              //        //k_fifo_put(&fifo_uart_tx_data, tx);
              //        printk("Error receibing\n");
              //}
              //else printk("Posted on tx\n");
              //k_free(tx);
    }
    
    //K_THREAD_DEFINE(CommandConnected_id, STACKSIZE, CommandConnected, NULL, NULL,
    	//	NULL, PRIORITY, 0, 0);
    
    
    
    
    static void discovery_complete(struct bt_gatt_dm *dm,
    			       void *context)
    {
            struct bt_nus_client *nus = context;
    
    
    
    	LOG_INF("Service discovery completed");
            printk("%d Service discovery completed",nus);
    
    
    	bt_gatt_dm_data_print(dm);
    
    	bt_nus_handles_assign(dm, nus);
    	bt_nus_subscribe_receive(nus);
    
    	bt_gatt_dm_data_release(dm);
    
    
            k_mutex_lock(&Array_mutex,K_FOREVER);
            k_mutex_lock(&Command_mutex,K_FOREVER);
            if(masuno==true)
            {
                  Device[NumDevices].Connected=true;
                  NumDevices+=1;
                  nus_client_init();
                  Devices2Inicialice[ActualizoConexion1]=NumDevices-1;
                  //ActualizoConexion1=NumDevices-1;
                  masuno=false;
            }
            else
            {
                  Device[Actualiza].Connected=true;
                  Devices2Inicialice[ActualizoConexion1]=Actualiza;
                  //ActualizoConexion1=Actualiza;
            }
            NumDevicesConnected+=1;
            ActualizaBlockList();//Hacer vector de ConnPending
            k_mutex_unlock(&Array_mutex);
            ActualizoConexion1+=1;
            k_mutex_unlock(&Command_mutex);
            //ConnPending=true;
            //CommandConnected(ActualizoConexion1,NumDevices-1);
            k_mutex_unlock(&my_mutex);
    
            //debug
            printk("\nLista: ");
            for(int i=0;i<NumDevices;i++)
            {     //for(int x=0;x<BT_ADDR_LE_STR_LEN;x++)
                  if(Device[i].Connected==true) printk(" %d %s %d, ",i,Device[i].ID.ADDR,Device[i].ID.kartID);
            }
            printk("\n");
            restartScan();
    
    
    }
    
    
    static void discovery_service_not_found(struct bt_conn *conn,
    					void *context)
    {
    	LOG_INF("Service not found");
            printk("Service not found");
            restartScan();
    }
    
    
    static void discovery_error(struct bt_conn *conn,
    			    int err,
    			    void *context)
    {
    	LOG_WRN("Error while discovering GATT database: (%d)", err);
            printk("Error while discovering GATT database:");
            restartScan();
    }
    
    struct bt_gatt_dm_cb discovery_cb = {
    	.completed         = discovery_complete,
    	.service_not_found = discovery_service_not_found,
    	.error_found       = discovery_error,
    };
    
    static void gatt_discover(struct bt_conn *conn)
    {
    	int err;
    
    	if (conn != default_conn) {
    		return;
    	}
    
    	err = bt_gatt_dm_start(conn,
    			       BT_UUID_NUS_SERVICE,
    			       &discovery_cb,
    			       &nus_client[NumDevices]);
    	if (err) {
    		LOG_ERR("could not start the discovery procedure, error "
    			"code: %d", err);
                    printk("%d could not start the discovery procedure, error "
    			"code: %d",NumDevices, err);
                    restartScan();
    	}
            //printk("%d GATT_discover func\n",conn);
            //restartScan();
            //Iniciar timer anti bugs
            //k_timer_start(&my_timerGDiscovery, K_SECONDS(1), K_SECONDS(1));
            //k_timer_start(&my_timer, K_SECONDS(1), K_SECONDS(1));
    
    
    }
    
    static void exchange_func(struct bt_conn *conn, uint8_t err, struct bt_gatt_exchange_params *params)
    {
    	if (!err) {
    		LOG_INF("MTU exchange done");
                    printk("MTU exchange done\n");
    	} else {
    		LOG_WRN("MTU exchange failed (err %" PRIu8 ")", err);
    		printk("MTU exchange failed (err %" PRIu8 ")\n", err);
    	}
    }
    
    
    
    void set_tx_power(uint8_t handle_type, uint16_t handle, int8_t tx_pwr_lvl)
    {
        struct bt_hci_cp_vs_write_tx_power_level *cp;
        struct bt_hci_rp_vs_write_tx_power_level *rp;
        struct net_buf *                          buf, *rsp = NULL;
        int                                       err;
    
        buf = bt_hci_cmd_create(BT_HCI_OP_VS_WRITE_TX_POWER_LEVEL, sizeof(*cp));
        if (!buf) {
            LOG_INF("Unable to allocate command buffer\n");
            return;
        }
    
        cp                 = net_buf_add(buf, sizeof(*cp));
        cp->handle         = sys_cpu_to_le16(handle);
        cp->handle_type    = handle_type;
        cp->tx_power_level = tx_pwr_lvl;
    
        err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_WRITE_TX_POWER_LEVEL, buf, &rsp);
        if (err) {
            uint8_t reason = rsp ? ((struct bt_hci_rp_vs_write_tx_power_level *)rsp->data)->status : 0;
            LOG_INF("Set Tx power err: %d reason 0x%02x\n", err, reason);
            return;
        }
    
        rp = (void *)rsp->data;
        LOG_INF("Actual Tx Power: %d\n", rp->selected_tx_power);
    
        net_buf_unref(rsp);
    }
    
    
    static void get_tx_power(uint8_t handle_type, uint16_t handle, int8_t *tx_pwr_lvl)
    {
    	struct bt_hci_cp_vs_read_tx_power_level *cp;
    	struct bt_hci_rp_vs_read_tx_power_level *rp;
    	struct net_buf *buf, *rsp = NULL;
    	int err;
    
    	*tx_pwr_lvl = 0xFF;
    	buf = bt_hci_cmd_create(BT_HCI_OP_VS_READ_TX_POWER_LEVEL,
    				sizeof(*cp));
    	if (!buf) {
    		printk("Unable to allocate command buffer\n");
    		return;
    	}
    
    	cp = net_buf_add(buf, sizeof(*cp));
    	cp->handle = sys_cpu_to_le16(handle);
    	cp->handle_type = handle_type;
    
    	err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_READ_TX_POWER_LEVEL,
    				   buf, &rsp);
    	if (err) {
    		uint8_t reason = rsp ?
    			((struct bt_hci_rp_vs_read_tx_power_level *)
    			  rsp->data)->status : 0;
    		printk("Read Tx power err: %d reason 0x%02x\n", err, reason);
    		return;
    	}
    
    	rp = (void *)rsp->data;
    	*tx_pwr_lvl = rp->tx_power_level;
    
    	net_buf_unref(rsp);
    }
    
    
    
    
    static void connected(struct bt_conn *conn, uint8_t conn_err)
    {
    	char addr[BT_ADDR_LE_STR_LEN];
            struct bt_conn_info info;
    	int err;
            //Extraigo Addres de la connexion
    	bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));
            //Si hay error hago cosas
    	if (conn_err) {
    		LOG_INF("Failed to connect to %s (%d)", log_strdup(addr),
    			conn_err);
    
    		if (default_conn == conn) {
    			bt_conn_unref(default_conn);
    			default_conn = NULL;
    
    			err = bt_scan_start(BT_SCAN_TYPE_SCAN_ACTIVE);
    			if (err) {
    				LOG_ERR("Scanning failed to start (err %d)",
    					err);
    			}
                            else IsScanning=true;
    		}
    		return;
    	}
    
            //Si no hay error extraigo la info de la conn
            //err = bt_conn_get_info(conn, &info);
            //Para medir rssi*****************************
     //       err = bt_hci_get_conn_handle(conn,&default_conn_handle);
     //       if (err) {
     //               printk("No connection handle (err %d)\n", err);
     //       }
     //       printk("Connection handle %d\n", default_conn_handle);
    
    
     //       const struct bt_conn_le_phy_info *phy_info;
    
            //Historias para tx power
            //phy_info = info.le.phy;
            //printk("%d, Connected: %s, tx_phy %u, rx_phy %u\n",NumDevices,addr, phy_info->tx_phy, phy_info->rx_phy);
            //printk("OJO\n");
            k_mutex_lock(&Array_mutex,K_FOREVER);
            k_mutex_lock(&my_mutex,K_FOREVER);
            printk("Connected: %s", log_strdup(addr));
            //Modifico mi lista segun si es nueva addr o no Anado/actualizo
            if(NumDevices==0)
            {
                 printk("Primer device");
                 bt_addr_le_to_str(bt_conn_get_dst(conn), Device[NumDevices].ID.ADDR, sizeof(addr));
    
                 Device[NumDevices].Addr=bt_conn_get_dst(conn);
                 for(int i=0;i<CONFIG_BT_MAX_CONN;i++)
                    if(strcmp(Mymap[i].ADDR,Device[NumDevices].ID.ADDR)==0)
                    {
                        Device[NumDevices].ID.kartID=Mymap[i].kartID;
                        break;
                    }
                 //Device[NumDevices].Connected=true;
                 masuno=true;
    
            }
            else
            {
                //Recorro mi lista de devices registrados
                for(int i=0;i<NumDevices;i++){
                    //Si ya esta en mi lista actualizo el estado de conexion y salgo
                    if(strcmp(addr,Device[i].ID.ADDR)==0)
                    {
                        printk("%d Actualiza estado conexion a true\n",i);
                        //Device[Actualiza].Connected=true;
                        Actualiza=i;
                        masuno=false;
                        break;
                    }
                    //Si es la ultima iteracion y no esta en mi lista me lo guardo en la lista
                    else if(i==NumDevices-1)
                    {
                        printk("Crea un nuevo estado conecc\n");
                        bt_addr_le_to_str(bt_conn_get_dst(conn), Device[NumDevices].ID.ADDR, sizeof(addr));
                        Device[NumDevices].Addr=bt_conn_get_dst(conn);
                        for(int i=0;i<CONFIG_BT_MAX_CONN;i++)
                        if(strcmp(Mymap[i].ADDR,Device[NumDevices].ID.ADDR)==0)
                        {
                            Device[NumDevices].ID.kartID=Mymap[i].kartID;
                            break;
                        }
                        //Device[NumDevices].Connected=true;
                        masuno=true;
                    }
                }
            }
            
            k_mutex_unlock(&Array_mutex);
            //Subo TX power
    	static struct bt_gatt_exchange_params exchange_params;
            
            set_tx_power(BT_HCI_VS_LL_HANDLE_TYPE_CONN,
    				     default_conn_handle,
    				     +8);
            get_tx_power(BT_HCI_VS_LL_HANDLE_TYPE_CONN,
    				     default_conn_handle, &txp);
    
            //printk("Connection (%d) - Initial Tx Power = %d\n", default_conn_handle, txp);
    
            //Tareas por defecto en conexion
    	exchange_params.func = exchange_func;
    	err = bt_gatt_exchange_mtu(conn, &exchange_params);
    	if (err) {
    		LOG_WRN("MTU exchange failed (err %d)", err);
                    printk("MTU exchange failed (err %d)", err);
    	}
    
    	//err = bt_conn_set_security(conn, BT_SECURITY_L2);
    	//if (err) {
    	//	LOG_WRN("Failed to set security: %d", err);
     //               printk("Failed to set security: %d", err);
    	//	gatt_discover(conn);
    	//}
            gatt_discover(conn);
    }
    
    static void disconnected(struct bt_conn *conn, uint8_t reason)
    {
    	char addr[BT_ADDR_LE_STR_LEN];
            //uint8_t PosDeviceDisconnected;
    	//int err;
    
    	bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));
    
    
            //k_mutex_lock(&my_mutex,K_FOREVER);
            k_mutex_lock(&Array_mutex,K_FOREVER);
    
            //Si est� lo Borro de la lista de conectdos
            for(uint8_t i=0;i<NumDevices;i++)
            {
                  if(strcmp(addr,Device[i].ID.ADDR)==0)
                  {
                        printk("Actualizamos estdo conexion a false\n");
                        Device[i].Connected=false; 
                        LOG_INF("Disconnected: %s (reason %u)", log_strdup(addr),reason);
                        printk("%d Disconnected: %s (reason %u)",i, log_strdup(addr),reason);
                        break;
                  }
            }
    	//if (default_conn != conn) {
    	//	return;
    	//}
            printk("\nLista: ");
            for(int i=0;i<NumDevices;i++)
            {     //for(int x=0;x<BT_ADDR_LE_STR_LEN;x++)
                  if(Device[i].Connected==true) printk("%s",Device[i].ID.ADDR);
            }
            ActualizaBlockList();
            k_mutex_unlock(&Array_mutex);
            NumDevicesConnected-=1;
    
    	bt_conn_unref(conn);
    	default_conn = NULL;
            //k_mutex_unlock(&my_mutex);
    
            printk("Seguimos\n");
            restartScan();
    
    
    }
    
    static void security_changed(struct bt_conn *conn, bt_security_t level,
    			     enum bt_security_err err)
    {
    	char addr[BT_ADDR_LE_STR_LEN];
    
    	bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));
    
    	if (!err) {
    		LOG_INF("Security changed: %s level %u", log_strdup(addr),
    			level);
                    printk("Security changed: %s level %u", log_strdup(addr),
    			level);
    	} else {
    		LOG_WRN("Security failed: %s level %u err %d", log_strdup(addr),
    			level, err);
                    printk("Security failed: %s level %u err %d", log_strdup(addr),
    			level, err);
    	}
    
    	gatt_discover(conn);
    }
    
    static struct bt_conn_cb conn_callbacks = {
    	.connected = connected,
    	.disconnected = disconnected,
    	//.security_changed = security_changed
    };
    
    static void scan_filter_match(struct bt_scan_device_info *device_info,
    			      struct bt_scan_filter_match *filter_match,
    			      bool connectable)
    {
    	int err;
    	char addr[BT_ADDR_LE_STR_LEN];
            uint8_t fich=5;
    	struct bt_conn_le_create_param *conn_params;
    
    	bt_addr_le_to_str(device_info->recv_info->addr, addr, sizeof(addr));
    
    	printk("Filters matched. Address: %s connectable: %s\n",
    		addr, connectable ? "yes" : "no");
    
            k_mutex_lock(&Array_mutex,K_FOREVER);
            
            //Si hay alguien que se quiere conectar pero aun no se ha desconectado no hago nada
            for(uint8_t i=0;i<NumDevices;i++)
            {
                  if((strcmp(addr,Device[i].ID.ADDR)==0)&&(Device[i].Connected==true))
                  {
                        printk("Quiere conectar pero aun no se ha desconectado");
                        k_mutex_unlock(&Array_mutex);
                        return;
                  }
                  else if((strcmp(addr,Device[i].ID.ADDR)==0)&&(Device[i].Connected==false))
                  {
                        fich=i;
                        break;
                  }
            }
            k_mutex_unlock(&Array_mutex);
    
            
    	err = bt_scan_stop();
    	if (err) {
    		printk("Stop LE scan failed (err %d)\n", err);
    	}
            else{
                IsScanning=false;
                printk("Stop Scanning\n");
            }
    	conn_params = BT_CONN_LE_CREATE_PARAM(
    			BT_CONN_LE_OPT_CODED | BT_CONN_LE_OPT_NO_1M,
    			BT_GAP_SCAN_FAST_INTERVAL,
    			BT_GAP_SCAN_FAST_INTERVAL);
    
    	err = bt_conn_le_create(device_info->recv_info->addr, conn_params,
    				&m_conn_param,
    				&default_conn);
    
    	if (err) {
    		printk("Create conn failed (err %d)\n", err);
                    restartScan();
                    //err = bt_scan_start(BT_SCAN_TYPE_SCAN_ACTIVE);
                    //if (err) {
                    //        printk("Scanning failed to start (err %d)\n", err);
                    //        return;
                    //}
                    //printk("Scan restarted\n");
    	}
    	printk("%d Connection pending\n",fich);
    }
    
    
    
    
    //static void scan_filter_match(struct bt_scan_device_info *device_info,
    //			      struct bt_scan_filter_match *filter_match,
    //			      bool connectable)
    //{
    //	char addr[BT_ADDR_LE_STR_LEN];
    
    //	bt_addr_le_to_str(device_info->recv_info->addr, addr, sizeof(addr));
    
    //	LOG_INF("Filters matched. Address: %s connectable: %d",
    //		log_strdup(addr), connectable);
    //}
    
    static void scan_connecting_error(struct bt_scan_device_info *device_info)
    {
    	LOG_WRN("Connecting failed");
            printk("Connecting failed\n");
    }
    
    static void scan_connecting(struct bt_scan_device_info *device_info,
    			    struct bt_conn *conn)
    {
    	default_conn = bt_conn_ref(conn);
    }
    
    
    BT_SCAN_CB_INIT(scan_cb, scan_filter_match, NULL,
    		scan_connecting_error, scan_connecting);
    
    static int scan_init(void)
    {
    	int err;
            const char *perName1="Uart_periph1";//"Uart_periph1";Nordic_UART_Service
            const char *perName2="Nordic_UART_Service";//"Uart_periph1";Nordic_UART_Service
            //static char const test_periph_addr[] = {0x17, 0x49, 0xB7, 0xBE, 0xC4, 0xDC};
    	struct bt_scan_init_param scan_init = {
    		.connect_if_match = 1,
                    .scan_param = &m_scan_param,
                    .conn_param = NULL,//&m_conn_param,
    	};
    
    	bt_scan_init(&scan_init);
    	bt_scan_cb_register(&scan_cb);
    
    	//err = bt_scan_filter_add(BT_SCAN_FILTER_TYPE_UUID, BT_UUID_NUS_SERVICE);
    	//if (err) {
    	//	LOG_ERR("Scanning filters cannot be set (err %d)", err);
    	//	return err;
    	//}
    
    	//err = bt_scan_filter_enable(BT_SCAN_UUID_FILTER, false);
    	//if (err) {
    	//	LOG_ERR("Filters cannot be turned on (err %d)", err);
    	//	return err;
    	//} 
    
            err = bt_scan_filter_add(BT_SCAN_FILTER_TYPE_NAME,perName1);
    
    	if (err) {
    		LOG_ERR("Scanning filters1 cannot be set (err %d)", err);
    		return err;
    	}
            err = bt_scan_filter_add(BT_SCAN_FILTER_TYPE_NAME,perName2);
    
    	if (err) {
    		LOG_ERR("Scanning filters2 cannot be set (err %d)", err);
    		return err;
    	}
    
    	err = bt_scan_filter_enable(BT_SCAN_NAME_FILTER, false);
    	if (err) {
    		LOG_ERR("Filters cannot be turned on (err %d)", err);
    		return err;
    	} 
    
    	LOG_INF("Scan module initialized");
            printk("Scan module initialized\n");
    	return err;
    }
    
    
    static void auth_cancel(struct bt_conn *conn)
    {
    	char addr[BT_ADDR_LE_STR_LEN];
    
    	bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));
    
    	LOG_INF("Pairing cancelled: %s", log_strdup(addr));
            printk("Pairing cancelled: %s", log_strdup(addr));
    
    }
    
    
    static void pairing_confirm(struct bt_conn *conn)
    {
    	char addr[BT_ADDR_LE_STR_LEN];
    
    	bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));
    
    	//bt_conn_auth_pairing_confirm(conn);
    
    	LOG_INF("Pairing confirmed: %s", log_strdup(addr));
            printk("Pairing confirmed: %s", log_strdup(addr));
    }
    
    
    static void pairing_complete(struct bt_conn *conn, bool bonded)
    {
    	char addr[BT_ADDR_LE_STR_LEN];
    
    	bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));
    
    	LOG_INF("Pairing completed: %s, bonded: %d", log_strdup(addr),
    		bonded);
            printk("Pairing completed: %s, bonded: %d", log_strdup(addr),bonded);
    }
    
    
    static void pairing_failed(struct bt_conn *conn, enum bt_security_err reason)
    {
    	char addr[BT_ADDR_LE_STR_LEN];
    
    	bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr));
    
    	LOG_WRN("Pairing failed conn: %s, reason %d", log_strdup(addr),
    		reason);
            printk("Pairing failed conn: %s, reason %d", log_strdup(addr),
    		reason);
    }
    
    static struct bt_conn_auth_cb conn_auth_callbacks = {
    	.cancel = auth_cancel,
    	.pairing_confirm = pairing_confirm,
    	.pairing_complete = pairing_complete,
    	.pairing_failed = pairing_failed
    };
    
    
    
    void main(void)
    {
    	int err;
    
    	//err = bt_conn_auth_cb_register(&conn_auth_callbacks);
    	//if (err) {
    	//	LOG_ERR("Failed to register authorization callbacks.");
    	//	return;
    	//}
            //inicializa mutex HACER MUTEX PAR CAMBIAR VECTOR DE CONEXIONES
            //nrfx_mtx_init();
            k_mutex_init(&Array_mutex);
            k_mutex_init(&my_mutex);
            k_mutex_init(&Command_mutex);
    
    	err = bt_enable(NULL);
    	if (err) {
    		LOG_ERR("Bluetooth init failed (err %d)", err);
    		return;
    	}
    	LOG_INF("Bluetooth initialized");
            printk("Bluetooth initialized\n");
    
    	if (IS_ENABLED(CONFIG_SETTINGS)) {
    		settings_load();
    	}
    
    	bt_conn_cb_register(&conn_callbacks);
    
    	int (*module_init[])(void) = {uart_init, scan_init, nus_client_init};
    	for (size_t i = 0; i < ARRAY_SIZE(module_init); i++) {
    		err = (*module_init[i])();
    		if (err) {
    			return;
    		}
    	}
    
    	printk("Starting Bluetooth Central UART example\n");
    
    	err = bt_scan_start(BT_SCAN_TYPE_SCAN_ACTIVE);
    	if (err) {
    		LOG_ERR("Scanning failed to start (err %d)", err);
    		return;
    	}
            else IsScanning=true;
    
    	LOG_INF("Scanning successfully started");
            printk("Scanning successfully started\n");
    
    
            int objective;
            bool checked;  
            uint8_t CommandNewConn[4]={0x4e,0x43,0x41,0x0d};
            uint8_t count=0;
    
    
    	for (;;) {
    
             /* Wait indefinitely for data to be sent over Bluetooth */
             struct uart_data_t *buf = k_fifo_get(&fifo_uart_rx_data,K_SECONDS(2));// K_SECONDS(2)
    
             if((buf->len>0)&&(buf->len<=UART_BUF_SIZE))
             {
                   //printk("%d",buf->len);
                   //                 S     +        C     +    objective(2222) + 14 bytes as max COMANDO PARA ENVIO INDIVIDUAL
                   if((buf->data[0]==0x53)&&(buf->data[1]==0x43)&&(buf->data[buf->len-1]==13))
                   {
                          //printk("%d",buf->len);
                          //printk("Comando recibido:   ");
    
                          objective = strtol(&buf->data[2], NULL, 10);
                          //printk("%d",objective);
                          Command=true;
                   }
                   else Command=false;
    
                   if(Command==false)//ENVIO A TODOS
                   {
                         for(int i=0;i<NumDevices;i++)
                         {
                                if(Device[i].Connected==true)
                                {
                                
                                      err = bt_nus_client_send(&nus_client[i], buf->data, buf->len);
                                      if (err) {
                                              LOG_WRN("Failed to send data over BLE connection"
                                                      "(err %d)", err);
                                      }
    
                                      err = k_sem_take(&nus_write_sem, K_FOREVER);
                                      if (err) {
                                              LOG_WRN("NUS send timeout");
                                      }
                                      printk("Client %d Sended",i);
                                }      
                          }
                    }
                    else if(Command==true)//Envio al que quiero 1
                    {
                          //Buscas en la lista el objetivo del comando
                          for(int i=0;i<NumDevices;i++)
                          {
                                if(Device[i].ID.kartID==objective)
                                {
                                    objective=i;
                                    checked=true;
                                    break;
                                }
                                else checked=false;
                          }
    
                          if(checked==true)
                          {
                                if(Device[objective].Connected==true)
                                {
                                      //printk("Envio solo a %d",objective);
                                      err = bt_nus_client_send(&nus_client[objective], buf->data, buf->len);
                                      if (err) {
                                              LOG_WRN("Failed to send data over BLE connection"
                                                      "(err %d)", err);
                                              printk("Failed to send data over BLE connection"
                                                      "(err %d)", err);
                                      }
    
                                      err = k_sem_take(&nus_write_sem, K_FOREVER);
                                      if (err) {
                                              LOG_WRN("NUS send timeout");
                                              printk("Failed to send data over BLE connection"
                                                      "(err %d)", err);
                                      }
                                }
                                else printk("Dispositivo deseado no conectado\n");
                                //count=0;
                          }
                          else printk("Objetivo no existe\n");
                  
                    }
              }
              else if(ActualizoConexion1!=0)
              {
                     k_mutex_lock(&Command_mutex,K_FOREVER);
    
                     err = bt_nus_client_send(&nus_client[Devices2Inicialice[ActualizoConexion1-1]], CommandNewConn, 4);
                     if (err) {
                             LOG_WRN("Failed to send data over BLE connection"
                                     "(err %d)", err);
                              printk("00Failed to send data over BLE connection"
                                      "(err %d)", err);
                      }
                      else
                      {
                              printk("%d 0ok",ActualizoConexion1-1);
                              count+=1;
                              ConnPending=true;
                              ActualizoConexion1-=1;
                      }
                      k_mutex_unlock(&Command_mutex);
    
              //        err = k_sem_take(&nus_write_sem, K_FOREVER);
              //        if (err) {
              //                LOG_WRN("NUS send timeout");
              //                printk("11Failed to send data over BLE connection"
              //                        "(err %d)", err);
              //        }
              //        else
              //        {
              //                NuevaConexion=true;
              //                printk("+INICIO %d enviado",ActualizoConexion1-1);
              //                if(count==1)
              //                {
              //                      ActualizoConexion1-=1;
              //                      ConnPending=true;
              //                }
              //        }
              //}
              //
          }}
    }
    
    
    
    

Children
Related