/* * File Name: pthread_dht11.c * Workflow: periodically rw from coordinator, get TH data, push * it to shared memory * Return Value: NULL always */ /* Header files */ #include #include #include #include #include #include #include #include #include #include #include "debug.h" #include "proto.h" /* external variables */ extern pthread_mutex_t mutex_zigbee_coordinator; extern volatile sig_atomic_t should_exit; /* thread start routine function*/ void *pthread_dht11(void *args) { ARG_STRUCT *p_resource_struct = malloc(sizeof(ARG_STRUCT)); SHM_STRUCT *p_shm_struct = malloc(sizeof(SHM_STRUCT)); char tmp[7]; ssize_t rwRetCount; // get resources from main p_resource_struct = args; DebugLog("[DEBUG-INFO %s:%d]: Get read/write fd: %d.\n", __FUNCTION__, __LINE__, p_resource_struct->rw_fd); DebugLog("[DEBUG-INFO %s:%d]: Get shared memory ID: %d.\n", __FUNCTION__, __LINE__, p_resource_struct->shm_id); // attach shared memory to local p_shm_struct = shmat(p_resource_struct->shm_id, NULL, 0); // prepare buffer to get TH data memset(tmp, '\0', 7); // modify shared memory while (!should_exit) { pthread_mutex_lock(&mutex_zigbee_coordinator); rwRetCount = write(p_resource_struct->rw_fd, "TH", sizeof("TH")); // write failure retry if (rwRetCount == -1) { pthread_mutex_unlock(&mutex_zigbee_coordinator); continue; } DebugLog("[DEBUG-INFO %s:%d]: write(\"TH\") to coordinator, %zd Byte(s) " "written.\n", __FUNCTION__, __LINE__, rwRetCount); // zigbee end-device reaction time wait sleep(3); rwRetCount = read(p_resource_struct->rw_fd, tmp, 7); DebugLog("[DEBUG-INFO %s:%d]: read() from coordinator, %zd Byte(s) read.\n", __FUNCTION__, __LINE__, rwRetCount); if (rwRetCount == -1) { p_shm_struct->tempNow = 0; DebugLog("[DEBUG-INFO %s:%d]: Nothing read, set temperature to 0.\n", __FUNCTION__, __LINE__); p_shm_struct->humiNow = 0; DebugLog("[DEBUG-INFO %s:%d]: Nothing read, set humidity to 0.\n", __FUNCTION__, __LINE__); } else { p_shm_struct->tempNow = ((int)(tmp[0] - '0')) * 10 + ((int)(tmp[1] - '0')) * 1; DebugLog("[DEBUG-INFO %s:%d]: Current temperature: %d.\n", __FUNCTION__, __LINE__, p_shm_struct->tempNow); p_shm_struct->humiNow = ((int)(tmp[4] - '0')) * 10 + ((int)(tmp[5] - '0')) * 1; DebugLog("[DEBUG-INFO %s:%d]: Current humidity: %d.\n", __FUNCTION__, __LINE__, p_shm_struct->humiNow); } pthread_mutex_unlock(&mutex_zigbee_coordinator); } pthread_exit(NULL); }