GfxTextBuffer::GfxTextBuffer (GfxFont *font)
  : font(font), currentDrawnDimensions(0,0), currentLeft(0), currentTop(0),
    lastTop(0), lastBottom(0), wrap(0), dirty(false)
{   
    APP_ASSERT(font != NULL);

    vBuf.setNull();
    iBuf.setNull();
    vData.vertexBufferBinding->setBinding(0, vBuf);
    vData.vertexStart = 0;
    vData.vertexCount = 0;

    iData.indexBuffer = iBuf;
    iData.indexStart = 0;
    iData.indexCount = 0;
    currentGPUCapacity = 0;


    op.useIndexes = true;
    op.vertexData = &vData;
    op.indexData = &iData;
    op.operationType = Ogre::RenderOperation::OT_TRIANGLE_LIST;


    unsigned vdecl_sz = 0;
    vdecl_sz += vData.vertexDeclaration->addElement(0, vdecl_sz, Ogre::VET_FLOAT2, Ogre::VES_POSITION, 0).getSize();
    vdecl_sz += vData.vertexDeclaration->addElement(0, vdecl_sz, Ogre::VET_FLOAT2, Ogre::VES_TEXTURE_COORDINATES, 0).getSize(); // uv
    vdecl_sz += vData.vertexDeclaration->addElement(0, vdecl_sz, Ogre::VET_FLOAT4, Ogre::VES_TEXTURE_COORDINATES, 1).getSize(); // colour
    APP_ASSERT(vdecl_sz == VERT_BYTE_SZ);
}
/**************************************************************************//**
* 
* task_2
* 
* @brief      task 2 example
*
* @param[in]  param     task parameter input (unused)
* 
* @return     -
* 
******************************************************************************/
void task_2(void *param)
{
  static uint8_t counter = 0;
  mss_mque_msg_t* msg;

  MSS_BEGIN(task2_ctx)

  while(1)
  {
    switch(counter)
    {
      case 0:
        // allocate msg
    	msg = (mss_mque_msg_t*) mss_mem_alloc(mem_hdl);
    	APP_ASSERT(msg != NULL);

    	// create message
        memcpy(msg->data, "LED1", 4);

        // send message
        mss_mque_send(mque_hdl, msg);

      case 1:

        // allocate msg
      	msg = (mss_mque_msg_t*) mss_mem_alloc(mem_hdl);
      	APP_ASSERT(msg != NULL);

      	// create message
        memcpy(msg->data, "LED2", 4);

        // send message
        mss_mque_send(mque_hdl, msg);

        break;


    }

    // increment counter
    counter = ++counter & 0x01;

    // delay
    MSS_TIMER_DELAY_MS(timer_hdl, 500, task2_ctx);
  }
  
  MSS_FINISH();
}
Example #3
0
void GfxBody::Sub::getWorldTransforms(Ogre::Matrix4* xform) const
{
    if (!parent->numBoneMatrixes) {
        // No skeletal animation, or software skinning
        *xform = parent->node->_getFullTransform();
        return;
    }

    // Hardware skinning, pass all actually used matrices
    const Ogre::Mesh::IndexMap& indexMap = subMesh->useSharedVertices ?
        subMesh->parent->sharedBlendIndexToBoneIndexMap : subMesh->blendIndexToBoneIndexMap;
    APP_ASSERT(indexMap.size() <= parent->numBoneMatrixes);

    if (parent->boneWorldMatrixes) {

        // Bones, use cached matrices built when _updateRenderQueue was called
        for (Ogre::Mesh::IndexMap::const_iterator i=indexMap.begin(),i_=indexMap.end() ; i!=i_; ++i) {
            *(xform++) = parent->boneWorldMatrixes[*i];
        }

    } else {

        // All animations disabled, use parent GfxBody world transform only
        std::fill_n(xform, indexMap.size(), parent->node->_getFullTransform());
    }
}
Example #4
0
// handle .. in paths
static std::string path_collapse (const std::string &p, bool &err)
{
    APP_ASSERT(p[0] == '/');
    std::vector<std::string> new_path;
    size_t last = 0;
    //CVERB<<"Starting with: "<<p<<std::endl;
    do {
        size_t next = p.find('/', last+1);
        std::string dir(p, last+1, next-last-1);
        //CVERB<<"Piece: "<<last<<" "<<next<<" "<<dir<<std::endl;
        if (dir == "..") {
            if (new_path.size()==0) {
                err = true;
                return "";
            }
            new_path.pop_back();
        } else {
            new_path.push_back(dir);
        }
        if (next == std::string::npos) break;
        last = next;
    } while (true);
    std::string r;
    for (size_t i=0 ; i<new_path.size(); ++i) {
        r.append("/");
        r.append(new_path[i]);
    }
    return r;
}
Example #5
0
static int disconnect_server(void)
{
	APP_ASSERT(sockfd2 > 0);
	close(sockfd2);
	sockfd2 = -1;
	return 0;
}
Example #6
0
static int start_server(void)
{
	int flag = 1;
	struct sockaddr_in server_addr;

	APP_ASSERT(sockfd <= 0);
	if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		APP_ERROR("socket failed %d !\n", sockfd);
		return -1;
	}
	if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag)) < 0) {
		APP_ERROR("setsockopt\n");
		return -1;
	}

	memset(&server_addr, 0, sizeof(server_addr));
	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(IMAGE_SERVER_PORT);
	server_addr.sin_addr.s_addr = htons(INADDR_ANY);

	if (bind(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
		APP_ERROR("bind\n");
		return -1;
	}
	if (listen(sockfd, 10) < 0) {
		APP_ERROR("listen\n");
		return -1;
	}
	return 0;
}
Example #7
0
void net_send(NetChannel channel, NetAddress& address, const char* packet, uint32_t packetLength)
{
    APP_ASSERT(netManager != NULL);

    std::string s = std::string(packet, packetLength);
    netManager->sendPacket(channel, address, s);
}
Example #8
0
void GfxNode::notifyParentDead (void)
{
    ensureAlive();
    APP_ASSERT(!par.isNull());
    par = GfxNodePtr(NULL);
    updateParentBoneId();
}   
Example #9
0
void net_set_callbacks(ExternalTable& table, lua_State* L)
{
    APP_ASSERT(netManager != NULL);

    netManager->setCBTable(table);
    
    table.clear(L); //ensure setNil() is called so we don't get LuaPtr shutdown error
}
Example #10
0
void input_filter_shutdown (lua_State *L)
{
    IFMap m = ifmap;
    for (IFMap::const_iterator i=m.begin(), i_=m.end() ; i != i_ ; ++i) {
        InputFilter *f = i->second;
        f->destroy(L);
    }
    APP_ASSERT(ifmap.size() == 0);
}
/**************************************************************************//**
* 
* init_task_1
* 
* @brief      initialize task 1 example
*
* @param      -
* 
* @return     -
* 
******************************************************************************/
void init_task_app(void)
{
  // init hal
  hal_init();

  // initialize parameters
  task1_ctx.led_num = 1;
  task1_ctx.freq = LED_1_FREQ_MS;

  task2_ctx.led_num = 2;
  task2_ctx.freq = LED_2_FREQ_MS;

  // create timers
  task1_ctx.timer_hdl = mss_timer_create(TASK_1_ID);
  APP_ASSERT(task1_ctx.timer_hdl != MSS_TIMER_INVALID_HDL);
  task2_ctx.timer_hdl = mss_timer_create(TASK_2_ID);
  APP_ASSERT(task2_ctx.timer_hdl != MSS_TIMER_INVALID_HDL);
}
Example #12
0
static std::pair<Combo, std::string> split_bind (const std::string &bind)
{
    // This code assumes keys do not contain - and are non-empty.
    size_t last = bind.rfind('-');
    if (last == std::string::npos) return std::pair<Combo, std::string>(empty_combo, bind);
    APP_ASSERT(last + 1 < bind.length());
    std::string prefix = bind.substr(0, last + 1);
    std::string button = bind.substr(last + 1);
    return std::pair<Combo, std::string>(prefix_to_combo(prefix), button);
}
Example #13
0
void InputFilter::flushAll (lua_State *L)
{
    ensureAlive();
    // 'down' modified by acceptButton (and also potentially by callbacks).
    ButtonStatus d = down;
    for (ButtonStatus::iterator i=d.begin(), i_=d.end() ; i != i_ ; ++i) {
        acceptButton(L, "-" + i->first);
    }
    APP_ASSERT(down.size() == 0);
}
Example #14
0
void InputFilter::flushSet (lua_State *L, const BindingSet &s)
{
    ensureAlive();
    // 'down' modified by acceptButton (and also potentially by callbacks).
    ButtonStatus d = down;
    for (ButtonStatus::iterator i=d.begin(), i_=d.end() ; i != i_ ; ++i) {
        if (masked_by(i->second, s))
            acceptButton(L, "-" + i->first);
    }
    APP_ASSERT(down.size() == 0);
}
Example #15
0
struct sockaddr_in HICHIP_DISCOVER_multicast_addr()
{
    int ret = 0;
    struct sockaddr_in sock_addr;
    memset(&sock_addr, 0, sizeof(sock_addr));
    sock_addr.sin_family = AF_INET;
    sock_addr.sin_port = htons(HICHIP_MULTICAST_PORT);
    ret = inet_aton(HICHIP_MULTICAST_IPADDR, &sock_addr.sin_addr);
    APP_ASSERT(ret > 0, "HICHIP get multicast address error!");
    return sock_addr;
}
/**************************************************************************//**
*
* init_tasks
*
* @brief      initialize tasks
*
* @param      -
*
* @return     -
*
******************************************************************************/
static void init_tasks(void)
{
  // initialize hal module for MSS demo
  hal_init();

  // create memory for message queue
  mem_hdl = mss_mem_create(MQUE_MEM_BLK_SIZE + sizeof(void*),
		                   MQUE_MEM_NUM_OF_BLKS);
  APP_ASSERT(mem_hdl != MSS_MEM_INVALID_HDL);

  // activate task 1 for the first time
  mss_activate_task(TASK_1_ID);

  // create message queue
  mque_hdl = mss_mque_create(TASK_1_ID);
  APP_ASSERT(mque_hdl != MSS_MQUE_INVALID_HDL);

  // create timer
  timer_hdl = mss_timer_create(TASK_2_ID);
  APP_ASSERT(timer_hdl != MSS_TIMER_INVALID_HDL);
}
Example #17
0
int HICHIP_DISCOVER_sock_create(const char *local_ip)
{
    int sock = 0;
    int ret = 0, flag = 0;

    struct sockaddr_in my_addr, to_addr;
    struct ip_mreq mreq;

    memset(&my_addr, 0, sizeof(struct sockaddr_in));
    memset(&to_addr, 0, sizeof(struct sockaddr_in));
    memset(&mreq, 0, sizeof(struct ip_mreq));

    my_addr.sin_family = AF_INET;
    my_addr.sin_port = htons(HICHIP_MULTICAST_PORT);
    inet_aton(HICHIP_MULTICAST_IPADDR, &my_addr.sin_addr);

    // create udp socket
    sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    APP_ASSERT(sock > 0, "HICHIP create udp socket failed!");

    ret = bind(sock, (struct sockaddr *)&my_addr, sizeof(my_addr));
    APP_ASSERT(0 == ret, "HICHIP udp socket bind failed!");

    inet_aton(HICHIP_MULTICAST_IPADDR, &mreq.imr_multiaddr);
    mreq.imr_interface.s_addr = htonl(INADDR_ANY);

    ret = setsockopt(sock, SOL_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq));
    APP_ASSERT(0 == ret, "HICHP add member failed!");

    flag = 0; // not backrush
    ret = setsockopt(sock, IPPROTO_IP, IP_MULTICAST_LOOP, &flag, sizeof(flag));
    APP_ASSERT(0 == ret, "HICHIP clear multicast loop failed!");

    ret = fcntl(sock, F_SETFL,O_NONBLOCK);
    assert(0 == ret);

    return sock;
}
Example #18
0
unsigned short GfxBody::Sub::getNumWorldTransforms(void) const
{
    if (!parent->numBoneMatrixes) {
        // No skeletal animation, or software skinning
        return 1;
    }

    // Hardware skinning, count all actually used matrices
    const Ogre::Mesh::IndexMap& indexMap = subMesh->useSharedVertices ?
        subMesh->parent->sharedBlendIndexToBoneIndexMap : subMesh->blendIndexToBoneIndexMap;
    APP_ASSERT(indexMap.size() <= parent->numBoneMatrixes);

    return static_cast<unsigned short>(indexMap.size());
}
void nrx_write(int nrx_fd, struct ifreq* ifr)
{
   int status;
   struct nanoioctl* nr = (struct nanoioctl*) ifr->ifr_data;

   APP_INFO("Writing packet to target\n"); 
     
   APP_ASSERT(ifr != NULL);

   status = ioctl(nrx_fd, SIOCNRXRAWTX, ifr);

   if(status < 0) err(1, "ioctl (rawtx)");

}
Example #20
0
static int connect_server(void)
{
	struct sockaddr_in client_addr;

	APP_ASSERT(sockfd2 <= 0);
	socklen_t length = sizeof(client_addr);

	APP_INFO("Listen to %d\n", IMAGE_SERVER_PORT);
	if ((sockfd2 = accept(sockfd, (struct sockaddr *)&client_addr, &length)) < 0) {
		APP_PRINTF("accept failed %d\n", sockfd2);
		return -1;
	}
	APP_INFO("Port [%d] connected!\n", IMAGE_SERVER_PORT);
	return 0;
}
Example #21
0
/*******************************************************************************
* @brief   Configures the GPIO for ADC1
* @param   void
* @retval  void
*******************************************************************************/
float ADC_SampleAndConv(ADC_TypeDef* ADCx)
{
    /* Check the parameters */
    APP_ASSERT(ADCx == ADC1);
    
	uint32_t TimeCnt=0;
	
	#ifdef DYNAMENT_DEBUG
		printf("batt require start \r\n");
	#endif 
    /* Re-enable DMA and ADC conf and start Temperature Data acquisition */ 
    acquireVoltageValue();
	
	TimeCnt = 160000;
    /* for DEBUG purpose uncomment the following line and comment the __WFI call to do not enter STOP mode */
    while ((!flag_ADCDMA_TransferComplete) && (TimeCnt !=0))
	{
			TimeCnt--;
	}
    
    if(!TimeCnt)
    {
        #ifdef DYNAMENT_DEBUG
		printf("ADC timeout.\r\n");
        #endif
    }
    
    /* Clear global flag for DMA transfert complete */
    ClearADCDMA_TransferComplete(); 
	
	#ifdef DYNAMENT_DEBUG
		printf("batt require stop \r\n");
	#endif 
	
    powerDownADC();
    
    #ifdef DYNAMENT_DEBUG
//    for(int32_t index = 0;index < ADC_CONV_BUFF_SIZE;index ++)
//    {
//        printf("ADC_ConvertedValueBuff[%d] = 0x%x.\r\n",index,ADC_ConvertedValueBuff[index]);
//    }
    #endif
    
    return (ComputeRealVoltage());
}
// searching for the i such that cT[i].top <= top && cT[i+1].top > top, or sz-1 if cT[sz-1] < top
unsigned long GfxTextBuffer::binaryChopBottom (unsigned long begin, unsigned long end, unsigned long bottom_top)
{   
    unsigned long middle = (end + begin) / 2;
    if (middle == colouredText.size() - 1) return middle;
    const ColouredChar &c = colouredText[middle];
    const ColouredChar &d = colouredText[middle+1];
    if (c.top > bottom_top) {
        // too close to the end of the text, look left
        APP_ASSERT(middle != end); // this leads to infinite recursion
        return binaryChopBottom(begin, middle, bottom_top);
    } else if (d.top > bottom_top) {
        // found it
        return middle;
    } else {
        // too close to the beginning of the text, look right
        return binaryChopBottom(middle+1, end, bottom_top);
    }
}
Example #23
0
void InputFilter::triggerFunc (lua_State *L, const std::string &bind, const LuaPtr &func)
{
    ensureAlive();

    APP_ASSERT(!func.isNil());

    STACK_BASE;
    //stack is empty

    // error handler in case there is a problem during 
    // the callback
    push_cfunction(L, my_lua_error_handler);
    int error_handler = lua_gettop(L);

    //stack: err

    // get the function
    func.push(L);
    //stack: err, callback

    STACK_CHECK_N(2);

    // call (1 arg), pops function too
    int status = lua_pcall(L, 0, 0, error_handler);
    if (status) {
        STACK_CHECK_N(2);
        //stack: err, error
        // pop the error message since the error handler will
        // have already printed it out
        lua_pop(L, 2);
        STACK_CHECK;
        CERR << "InputFilter \"" << description << "\" "
             << "raised an error on bind "<<bind<<"." << std::endl;
        //stack is empty
    } else {
        //stack: err
        STACK_CHECK_N(1);
        lua_pop(L, 1);
        //stack is empty
    }

    //stack is empty
    STACK_CHECK;
}
// searching for the i such that cT[i-1].top < top && cT[i].top >= top, or 0 if cT[0] >= top
unsigned long GfxTextBuffer::binaryChopTop (unsigned long begin, unsigned long end, unsigned long top)
{
    unsigned long middle = (end + begin + 1) / 2;
    if (middle == 0) return middle;
    if (middle == colouredText.size() - 1) return middle+1;
    const ColouredChar &c = colouredText[middle];
    const ColouredChar &b = colouredText[middle-1];
    if (c.top < top) {
        // too close to the beginning of the text, look right
        APP_ASSERT(begin != middle); // this leads to infinite recursion
        return binaryChopTop(middle, end, top);
    } else if (b.top < top) {
        // found it
        return middle;
    } else {
        // too close to the end of the text, look left
        return binaryChopTop(begin, middle-1, top);
    }
}
Example #25
0
int
GGI_kgi_setPalette(struct ggi_visual *vis, size_t start, size_t len, const ggi_color *colormap)
{
	kgic_ilut_set_request_t ilut;
	size_t nocols = 1 << GT_DEPTH(LIBGGI_GT(vis));

	APP_ASSERT(colormap != NULL,
			 "GGI_kgi_setPalette() - colormap == NULL");

	DPRINT_COLOR("display-kgi: SetPalVec(%d,%d)\n", start, len);
	
	if (start == (size_t)GGI_PALETTE_DONTCARE) {
		start = 0;
	}

	if ((start < 0) || (len < 0) || (start+len > nocols)) {
		return GGI_ENOSPACE;
	}

	memcpy(LIBGGI_PAL(vis)->clut.data, colormap, len*sizeof(ggi_color));

	ilut.image = 0;
	ilut.resource = 0;
	ilut.lut = 0;
	ilut.idx = start;
	ilut.cnt = len;
	ilut.am = KGI_AM_COLORS;
	ilut.data = (kgi_u16_t *)KGI_PRIV(vis);

	for (start = 0; len > 0; start++, colormap++, len--) {
		ilut.data[start*3]     = colormap->r;
		ilut.data[start*3 + 1] = colormap->g;
		ilut.data[start*3 + 2] = colormap->b;
	}

	if(kgiSetIlut(&KGI_CTX(vis), &ilut) != KGI_EOK) {
		DPRINT_COLOR("display-kgi: PUTCMAP failed.");
		return -1;
	}

	return 0;
}
Example #26
0
void InputFilter::bind (lua_State *L, const std::string &button)
{
    ensureAlive();

    Callback &c = buttonCallbacks[button];
    c.down.setNil(L);
    c.up.setNil(L);
    c.repeat.setNil(L);
    APP_ASSERT(lua_gettop(L) >= 3);
    // DOWN
    if (!lua_isnil(L, -3)) {
        if (!lua_isfunction(L, -3)) {
            EXCEPT << "Expected a function for down binding of " << button << ENDL;
        }
        c.down.setNoPop(L, -3);
    }
    // UP
    if (!lua_isnil(L, -2)) {
        if (!lua_isfunction(L, -2)) {
            EXCEPT << "Expected a function for up binding of " << button << ENDL;
        }
        c.up.setNoPop(L, -2);
    }
    // REPEAT
    if (!lua_isnil(L, -1)) {
        if (lua_isboolean(L, -1)) {
            if (lua_toboolean(L, -1)) {
                if (lua_isnil(L, -3)) {
                    c.repeat.setNoPop(L, -3);
                }
            }
            // it's false, treat the same as nil
        } else {
            if (!lua_isfunction(L, -1)) {
                EXCEPT << "Expected a function or true for repeat binding of " << button << ENDL;
            }
            c.repeat.setNoPop(L, -1);
        }
    }
}
Example #27
0
void GfxBody::reinitialise (void)
{
    APP_ASSERT(mesh->isLoaded());

    destroyGraphics();

    for (unsigned short i = 0; i < mesh->getNumSubMeshes(); ++i) {
        Ogre::SubMesh *sm = mesh->getSubMesh(i);
        Sub* sub = new Sub(this, sm);
        subList.push_back(sub);
        GFX_MAT_SYNC;
        std::string matname = apply_map(initialMaterialMap, sm->getMaterialName());
        if (!gfx_material_has(matname)) {
            CERR << "Mesh \"/"<<mesh->getName()<<"\" references non-existing material "
                 << "\""<<matname<<"\""<<std::endl;
            matname = "/system/FallbackMaterial";
        }
        sub->material = gfx_material_get(matname);
    }


    if (!mesh->getSkeleton().isNull()) {
        skeleton = OGRE_NEW Ogre::SkeletonInstance(mesh->getSkeleton());
        skeleton->load();
        numBoneMatrixes = skeleton->getNumBones();
        boneMatrixes      = static_cast<Ogre::Matrix4*>(OGRE_MALLOC_SIMD(sizeof(Ogre::Matrix4) * numBoneMatrixes, Ogre::MEMCATEGORY_ANIMATION));
        boneWorldMatrixes = static_cast<Ogre::Matrix4*>(OGRE_MALLOC_SIMD(sizeof(Ogre::Matrix4) * numBoneMatrixes, Ogre::MEMCATEGORY_ANIMATION));

        mesh->_initAnimationState(&animationState);
    } else {
        skeleton = NULL;
        numBoneMatrixes = 0;
        boneMatrixes      = NULL;
        boneWorldMatrixes = NULL;
    }

    updateBones();
}
Example #28
0
void Img::init (std::istream &f, std::string name_)
{
        name = name_;
        unsigned long version = ios_read_u32(f);
        APP_ASSERT(version==0x32524556);

        numFiles = ios_read_u32(f);
        names.resize(numFiles);
        offsets.resize(numFiles);
        sizes.resize(numFiles);

        for (size_t i=0 ; i<numFiles ; i++) {
                offsets[i] = ios_read_u32(f) * BLK_SZ;
                sizes[i]= ios_read_u32(f) * BLK_SZ;
                names[i] = ios_read_fixedstr(f,24);
                strlower(names[i]);
        }

        if (dir.size()==numFiles) return;
        for (unsigned long i=0 ; i<numFiles ; ++i) {
                dir[names[i]] = i;
        }
}
void * flash_cmd(struct ifreq* ifr, void * handle, char * filename)
{
  
   static int host_flash_active = 0;

   int data_index;
   int vendor;
   int sector;
   int message_id;
   struct nanoioctl* nr = (struct nanoioctl*) ifr->ifr_data;

   message_id = nr->data[ID_INDEX];
   data_index = nr->data[HEADER_PAD_INDEX] + 4; 
 
   APP_DEBUG("flash message id: %d\n",message_id);
    
   switch(message_id) {
 
   case HIC_MAC_START_PRG_REQ:
      //start a flash write
      vendor = nr->data[data_index];
      sector = nr->data[data_index+1];
 
      if(vendor == HOST_FLASH_VENDOR)
         {
            APP_DEBUG("host flash command \n");
            host_flash_active = 1;
            handle = host_flash_open(filename,HOST_FLASH_WRITE_FLAG);
            if (handle) nr->data[data_index] = 0;
            else nr->data[data_index] = 1;
            //reply
            nr->data[ID_INDEX] = HIC_MAC_START_PRG_CFM;
         }
      else return NULL;

      break;

   case HIC_MAC_WRITE_FLASH_REQ:

      if(host_flash_active) 
         {
            //start to write flash data	                                    	
            nr->data[data_index] = host_flash_write(&nr->data[data_index],nr->length - data_index,handle);
            //reply
            nr->data[ID_INDEX] = HIC_MAC_WRITE_FLASH_CFM;;
         }
      else return NULL;
      break; 
                                    
   case HIC_MAC_END_PRG_REQ:
     
      if(host_flash_active)
         {
            //stop write to flash                               
            //reply
            nr->data[ID_INDEX] = HIC_MAC_END_PRG_CFM;
            nr->data[data_index] =  host_flash_close(handle);
            
            host_flash_active = 0;
         }
      else return NULL;
      break;
   case HIC_MAC_START_READ_REQ:
     
      //start a flash read cmd
      vendor = nr->data[data_index];
      sector = nr->data[data_index+1];

      if(vendor == HOST_FLASH_VENDOR)
         {
            host_flash_active = 1;
            //reply
            nr->data[ID_INDEX] = HIC_MAC_START_READ_CFM;
            
            handle = host_flash_open(filename,HOST_FLASH_READ_FLAG);
            if (handle) nr->data[data_index] = 0;
            else nr->data[data_index] = 1;
         }
      else return NULL;

      break;

   case HIC_MAC_READ_FLASH_REQ:
      //start to read flash data
        			  
      if(host_flash_active)
         {
            nr->data[ID_INDEX] = HIC_MAC_READ_FLASH_CFM;
            nr->data[TYPE_INDEX] = HIC_MESSAGE_TYPE_FLASH_PRG;
            nr->data[PAYLOAD_PAD_INDEX] = 0; 
            { 
               int i;
               i = host_flash_read(&nr->data[data_index],HOST_FLASH_MAX_READ_SIZE,handle);      
               APP_ASSERT(i);
               nr->length = data_index + i;
               *(uint16_t*)nr->data = (nr->length - 2);
            }
         }
      else return NULL;
      break; 
      
   case HIC_MAC_END_READ_REQ:
      
      if(host_flash_active)
         {
            host_flash_active = 0;
            //stop read from flash                             
            //reply
            nr->data[ID_INDEX] = HIC_MAC_END_READ_CFM;
            nr->data[data_index] =  host_flash_close(handle);
         }
      else return NULL;
      break;
   default:
      APP_ASSERT(0);
      break;
   }

   if (message_id != HIC_MAC_READ_FLASH_REQ) {
      //Common reply data
      *(uint16_t*)nr->data = (data_index - 1);
      nr->data[TYPE_INDEX] = HIC_MESSAGE_TYPE_FLASH_PRG;
      nr->data[PAYLOAD_PAD_INDEX] = 0; 
      nr->length = (*(uint16_t*)nr->data) + 2;
   }

   return handle;    
}
int poll_host(int host_fd, struct ifreq *ifr)
{
   int status;
   int message_type;
   size_t num_read = 0, len;
   char buf[1024];
   struct nanoioctl* nr = (struct nanoioctl*) ifr->ifr_data;
   int host_fd_flags;
   int flags;

   status = read(host_fd, buf, 2);
    
   if(status == 0)
     return 0;
     
   if(status < 0) 
     {
       if (errno == EAGAIN)
	 return 0;
       else
	 err(1,"read");
     }

   num_read += status;
    
   while(num_read < 2) {
      status = read(host_fd, buf + num_read, 2 - num_read);
      if(status < 0) 
	{
	  if(errno != EAGAIN)  
	    err(1, "read");
	}
      else
	num_read += status;
   }
            
   /* Ok, we got 2 bytes from nanoloader */
   len = *((uint16_t*) buf);
   APP_ASSERT((len > 0 && len < 1022));
   
   APP_DEBUG("Packet size is %d\n", len);

   /*  Read the rest of the packet */
   while(num_read < len + 2) {
     status = read(host_fd, buf + num_read, (len + 2 ) - num_read);
     if(status < 0) 
	{
	  if(errno != EAGAIN)  
	    err(1, "read");
	}
     else
       {
	 num_read += status;
       }
   }		 
   APP_DEBUG("Packet recieved\n"); 
   
   memcpy(nr->data, buf, num_read);
    
   nr->length = num_read;
   return num_read;
}