#define CONFIG_FREERTOS_HZ 1000

TaskHandle_t tH1 = NULL, tH2 = NULL, tH3 = NULL;

struct comT
{
  SemaphoreHandle_t mutSem;
  // k_t * mutSem;
  int memSize;
  void *pMem;
};

// struct comT *buf = malloc ( sizeof(struct comT));

 // buf->mutSem     (*buf).mutSem
 // buf->memSize =4;     (*buf).memSize = 4;

struct comT *
crtMem (int s)
{
  struct comT *pB;

  if (s <= 0)
    return NULL;

  pB = (struct comT *) malloc (sizeof (struct comT));
  if (pB == NULL)
    return NULL;

  pB->pMem = malloc (s);
  if (pB->pMem == NULL)
    {
      free (pB);
      return NULL;
    }

  pB->mutSem = xSemaphoreCreateMutex ();
  // pB->mutSem = k_crt_sem(1,4); // NBNB k_crt_sem do not work AFTER k_init
  if (pB->mutSem == NULL)
    {
      free (pB->pMem);
      free (pB);
      return NULL;
    }

  pB->memSize = s;

  return pB;
}

int
putMem (struct comT *buf, void *mem)
{
  while (xSemaphoreTake (buf->mutSem, (TickType_t) 1000) != pdTRUE);
  // k_wait(buf->mutSem,0);   

  memcpy (buf->pMem, mem, buf->memSize);

  xSemaphoreGive (buf->mutSem);
  //k_signal(buf->mutSem);
  return 0;			//ok
  /*
   * k_wait(buf->mutSem,0);
   * memcpy(buf->pMem, mem, buf->memSize);
   * k_signal(buf->mutSem);
   */
}

int
getMem (struct comT *buf, void *mem)
{
  while (xSemaphoreTake (buf->mutSem, (TickType_t) 1000) != pdTRUE);



  memcpy (mem, buf->pMem, buf->memSize);
  xSemaphoreGive (buf->mutSem);
  return 0;			//ok
}

// -------------------------------


struct comT *myMem;

void
t1 (void *parameter)
{
  char mem[10];
  for (;;)
    {
      Serial.print ("12345678901234567890\n");

      putMem (myMem, (void *) "hellomann");	// \ < 00 bq text string is teminated by 0x00

      vTaskDelay (300 / portTICK_PERIOD_MS);
    }
}

void
t2 (void *parameter)
{
  char mem[10];
  for (;;)
    {
      getMem (myMem, (void *) mem);
      Serial.println (mem);
      vTaskDelay (100 / portTICK_PERIOD_MS);
    }
}

void
t3 (void *parameter)
{
  for (;;)
    {
      Serial.print ("ABCDEFGHIJKLMNOPQRST\n");
      vTaskDelay (500 / portTICK_PERIOD_MS);
    }

}

void
setup ()
{
  Serial.begin (115200);
  delay (3000);

  myMem = crtMem (10);

  if (myMem == NULL)
    {
      Serial.println ("could not crt");
      while (1);
    }
  xTaskCreate (t1, "t1", 10000, NULL, 1, &tH1);
  xTaskCreate (t2, "t1", 10000, NULL, 2, &tH2);
  xTaskCreate (t3, "t1", 10000, NULL, 2, &tH3);

}

void
loop ()
{
  Serial.println (uxTaskPriorityGet (NULL));
  Serial.print ("loop\n");
  vTaskDelay (1000 / portTICK_PERIOD_MS);
}
