int AtRcv(int lMsgId, struct stAtRcvMsg *pstAtRcvMsg, int lMsgType) { /* BEGIN: Modified by y67514, 2008/6/20 问题单号:优化AT收发机制*/ int iRetryTimes = 0; struct stAtRcvMsg AtRcvMsg; memset(pstAtRcvMsg, 0, sizeof(*pstAtRcvMsg)); memset(&AtRcvMsg, 0, sizeof(AtRcvMsg)); /* 若接收消息失败,重试10次 */ while (-1 == msgrcv(lMsgId,(void*)pstAtRcvMsg, AT_RCV_MSG_LENGTH, lMsgType, IPC_NOWAIT)) { iRetryTimes++; if (15 <= iRetryTimes) { printf("\n! ! !NO RESPONSE FOR AT TYPE %d ! ! !\n",lMsgType); return -1; } __msleep(1000); } while (-1 != msgrcv(lMsgId,(void*)&AtRcvMsg, AT_RCV_MSG_LENGTH, lMsgType, IPC_NOWAIT)) { memcpy(pstAtRcvMsg,&AtRcvMsg,sizeof(*pstAtRcvMsg)); __msleep(1000); } return 0; /* END: Modified by y67514, 2008/6/20 */ }
/* * busywait() * Wait and sleep for a location to return to zero */ static void busywait(volatile uint *ptr) { while (*ptr) { __msleep(10); } }
/*------------------------------------------------------------ 函数原型 : int at_sm_submit_at(int at_num, void* res, int* is_report_err,char* parameters) 描述 : 通过pcui口下发一条AT命令 输入 : at_num AT命令号;parameters AT命令需要用到的参数 输出 : res : 接受AT上报的结果; is_report_err: 返回cm500端是否上报了error消息或上报格式错误 返回值 : 1 : 表示超时; 0 : AT命令下发成功 -------------------------------------------------------------*/ int at_sm_submit_at(int at_num, int* is_report_err,char* param) { struct stAtSndMsg AtSndMsg; struct stAtRcvMsg AtRcvMsg; char atbuf[AT_SND_MSG_LENGTH]; int ret = 1; int iRetryTimes = 0; //char buf[64];//存放AT命令 g_i_is_sm_active = 1; g_i_is_report_ok = AT_REPORT_OK; memset(atbuf,0,AT_SND_MSG_LENGTH); if (g_at_handles[at_num].create_at_cmd == NULL) { /*AT生成函数为空,表明AT命令为一般形式*/ strcpy(atbuf, g_at_handles[at_num].at_cmd_str); //, strlen(g_at_handles[at_num].at_cmd_str)); } else { /*AT生成函数不为空,表明AT命令格式特殊,需要特殊函数生成*/ g_at_handles[at_num].create_at_cmd(atbuf, param); } AtSndMsgId = msgget(MSG_AT_QUEUE, 0666); while(-1 == AtSndMsgId) { VDF_DBG("VDF:%s:%s:%d:can't get the AtSndMsgId***\n",__FILE__,__FUNCTION__,__LINE__); __msleep(5*1000); AtSndMsgId = msgget(MSG_AT_QUEUE, 0666); } while(-1 ==AtSend(AtSndMsgId,&AtSndMsg,MODEM_MODULE,g_at_handles[at_num].at_cmd_id,atbuf)) { VDF_DBG("VDF:%s:%s:%d:AtSend ERRO:msgid=%d,atnum=%d,param=%s***\n",__FILE__,__FUNCTION__,__LINE__,AtSndMsgId,g_at_handles[at_num].at_cmd_id,atbuf); //g_i_is_sm_active = 0; //return AT_TIMEOUT; __msleep(5*1000); } //g_i_cur_at_num = at_num; //ret = __sleep_wait(&g_st_submit_at_wait, 7 * 1000); if (g_main_thread_killed) { ret = 0; } AtRcvMsgId = msgget(MSG_MODEM_QUEUE, 0666); while(-1 == AtRcvMsgId) { VDF_DBG("VDF:%s:%s:%d:Can't get the AtRcvMsgId***\n",__FILE__,__FUNCTION__,__LINE__); __msleep(5*1000); AtRcvMsgId = msgget(MSG_MODEM_QUEUE, 0666); } VDF_DBG("VDF:%s:%s:%d:AtRcvMsgId=%d***\n",__FILE__,__FUNCTION__,__LINE__,AtRcvMsgId); __msleep(200); /* BEGIN: Modified by y67514, 2008/6/20 问题单号:优化AT收发机制*/ if(-1 == AtRcv(AtRcvMsgId,&AtRcvMsg,g_at_handles[at_num].at_cmd_id)) { g_i_is_sm_active = 0; return AT_TIMEOUT; } /* END: Modified by y67514, 2008/6/20 */ if(PARSE_ERROR == g_at_handles[at_num].at_cmd_report_handler(&AtRcvMsg)) { *is_report_err = 1; } else { *is_report_err = 0; } // 与上报接收线程同步,避免当前线程返回后,上报线程使用g_at_result,造成堆栈错误; //__p(&g_st_cur_at_num_mutex); //g_i_cur_at_num = -1; //g_at_result = NULL; //__v(&g_st_cur_at_num_mutex); g_i_is_sm_active = 0; return (ret > 0) ? AT_OK : AT_TIMEOUT; }
void loop(void) { // Read the current command from the user std::string command; std::getline(std::cin, command); std::cerr << "Got '" << command << "'.\n"; // Split the command on spaces std::stringstream ss("0 "); ss << command; ss << " 0"; unsigned char bytes[PAYLOAD]; int buf = 0; // Read each space-separated value into an integer and put it into bytes int used = 0; for (int i = 0; i < PAYLOAD && ss >> buf; i++) { bytes[i] = (unsigned char)buf; used = i; } std::cerr << "Read " << used << " bytes from stdin." << std::endl; // Stop listening so we can talk. radio.stopListening(); // Send the bytes std::cerr << "Sending bytes: "; for (int i = 0; i < used; i++) { std::cerr << (int)bytes[i] << " "; } std::cerr << std::endl; bool ok = radio.write( bytes, used ); if (ok) { std::cerr << "ok..." << std::endl; } else { std::cerr << "failed..." << std::endl; // TODO: retry! } // Now, continue listening radio.startListening(); // Wait here until we get a response, or timeout (500ms) unsigned long started_waiting_at = __millis(); bool timeout = false; while ( !radio.available() && ! timeout ) { __msleep(5); //add a small delay to let radio.available to check payload timeout = ((__millis() - started_waiting_at) > TIMEOUT); } // Describe the results if (timeout) { std::cerr << "response timed out..." << std::endl; // TODO: retry! } else { // Grab the response, compare, and send to debugging spew radio.read( bytes, PAYLOAD ); // TODO: replace PAYLOAD // Print the bytes for (int i = 0; i < PAYLOAD; i++) { std::cout << (unsigned int)bytes[i] << " "; } std::cout << std::endl; } }
/***************************************************************************** Function Name : ftp_upload_file Description : upload file into location specified by url. Returns : status indicate download result, 0 indicate success , other no-zero value indicate fault error code. Fault is classified in the following case: 9001, Request denied 9002, Internal error (Such as malloc failed,etc.) 9011, Upload failure (network error) 9012, File transfer server authentication failure Parameter : @url: file server path indicating a file location @username: used to authenticate with ftp server @password: used to authenticate with ftp server @filesize: fileContent length @fileContent: buffer contained file content need be uploaded. It's allocated and released by caller ******************************************************************************/ PAL_INT32_T ftp_upload_file(IN char *fileType , IN char *url , IN char *username , IN char *password , IN char *fileContent , IN PAL_UINT32_T filesize) { PAL_INT32_T retval; PAL_INT32_T n, left; PAL_INT32_T optval; char *p, *beginWith; char _filename[FILENAME_MAX]; PAL_INT32_T _len; PAL_INT32_T sockCtrlFd; PAL_INT32_T sockDataFd; struct sockaddr_in ftpServerSockAddr; struct sockaddr_in ftpServerDataAddr; PAL_INT32_T nsent; char timestr[TIME_STR_LENGTH]; //pal_set_logger(LOG_FTP_MODULE, T_LOG_INFO, LOG_CONSOLE, 0, NULL); /* parse ftp server ip/port */ if (ftp_parse_url(url) == INTERNAL_ERROR) { return INTERNAL_ERROR; } /* use default value if filename is not specified in url */ if (url[strlen(url)-1] == '/') { if (strcmp(fileType, UPLOAD_CONFIG_TYPE) == 0) { strcat(gFilename, DEFAULT_CONFIG_NAME); } else if (strcmp(fileType, UPLOAD_LOG_TYPE) == 0) { strcat(gFilename, DEFAULT_LOG_NAME); } else { pal_logger(T_LOG_ERROR, __FILE__, __LINE__, LOG_FTP_MODULE, __func__ , "unknown file type\n"); return INTERNAL_ERROR; } //pal_datetime(timestr);//use time to diff name //strcat(gFilename,timestr); } pal_logger(T_LOG_INFO, __FILE__, __LINE__, LOG_FTP_MODULE, __func__ , "gFilename: %s\n", gFilename); /* initiate socket */ if ((sockCtrlFd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { pal_logger(T_LOG_ERROR, __FILE__, __LINE__, LOG_FTP_MODULE, __func__ , "%s\n", strerror(errno)); return INTERNAL_ERROR; } optval = 1; retval = setsockopt(sockCtrlFd, SOL_SOCKET, SO_REUSEADDR , (void *) & optval, sizeof(optval)); if (retval == -1) { pal_logger(T_LOG_ERROR, __FILE__, __LINE__, LOG_FTP_MODULE, __func__ , "%s\n", strerror(errno)); return INTERNAL_ERROR; } memset(&ftpServerSockAddr, 0, sizeof(struct sockaddr)); ftpServerSockAddr.sin_family = AF_INET; ftpServerSockAddr.sin_port = htons(gFtpServerPort); inet_aton(gFtpServerStrIP, &ftpServerSockAddr.sin_addr); retval = connect(sockCtrlFd, (struct sockaddr *) & ftpServerSockAddr , sizeof(struct sockaddr)); if (retval == -1) { pal_logger(T_LOG_ERROR, __FILE__, __LINE__, LOG_FTP_MODULE, __func__ , "%s\n", strerror(errno)); return INTERNAL_ERROR; } /* ftp login */ if (username == NULL && password == NULL) { /* user anonymous login */ if (ftp_sock_auth(sockCtrlFd, "anonymous", "anonymous") == FILE_TRANSFER_AUTHFAILURE) { pal_logger(T_LOG_WARNING, __FILE__, __LINE__, LOG_FTP_MODULE, __func__ , "authentication failed\n"); return FILE_TRANSFER_AUTHFAILURE; } } else if (username == NULL || password == NULL) { pal_logger(T_LOG_WARNING, __FILE__, __LINE__, LOG_FTP_MODULE, __func__ , "username or password needed\n"); return FILE_TRANSFER_AUTHFAILURE; } else { retval = ftp_sock_auth(sockCtrlFd, username, password); if (retval == FILE_TRANSFER_AUTHFAILURE) { pal_logger(T_LOG_WARNING, __FILE__, __LINE__, LOG_FTP_MODULE, __func__ , "authentication failed\n"); return FILE_TRANSFER_AUTHFAILURE; } } /* create the directory structure if it does not exist */ /* gFilename may looks like '/upload/hook/doc/TR-111.pdf' */ beginWith = gFilename + 1; gFilenameLen = strlen(gFilename); while (1) { char dirname[64]; PAL_INT32_T dirlen; char *slash; slash = strchr(beginWith, '/'); if (slash == NULL) { break; } dirlen = slash - beginWith; memcpy(dirname, beginWith, dirlen); dirname[dirlen] = '\0'; ftp_commit_cmd(sockCtrlFd, FTP_CMD_CWD, dirname); retval = ftp_handle_cmd_resp(sockCtrlFd, FTP_CMD_CWD , FTP_RCV_RESP_TIMEOUT, '2', NULL, NULL); if (retval == FTP_ERR_ERROR_RESP) { /* directory does no exist, create it */ ftp_commit_cmd(sockCtrlFd, FTP_CMD_MKD, dirname); retval = ftp_handle_cmd_resp(sockCtrlFd, FTP_CMD_MKD , FTP_RCV_RESP_TIMEOUT, '2', NULL, NULL); if (retval == FTP_ERR_ERROR_RESP) { /* unable to mkdir */ return REQUEST_DENIED ; } /* change directory */ ftp_commit_cmd(sockCtrlFd, FTP_CMD_CWD, dirname); retval = ftp_handle_cmd_resp(sockCtrlFd, FTP_CMD_CWD , FTP_RCV_RESP_TIMEOUT, '2', NULL, NULL); if (retval == FTP_ERR_ERROR_RESP) { /* unable to change dir */ return REQUEST_DENIED ; } } beginWith = beginWith + strlen(dirname) + 1; } /* end of while(1) */ /* PASV */ ftp_commit_cmd(sockCtrlFd, FTP_CMD_PASV, NULL); retval = ftp_handle_cmd_resp(sockCtrlFd, FTP_CMD_PASV , FTP_RCV_RESP_TIMEOUT, '2', NULL, NULL); if (retval == FTP_ERR_ERROR_RESP) { /* ftp 4xx or 5xx error response */ return REQUEST_DENIED ; } /* TYPE I */ ftp_commit_cmd(sockCtrlFd, FTP_CMD_TYPE, NULL); retval = ftp_handle_cmd_resp(sockCtrlFd, FTP_CMD_TYPE , FTP_RCV_RESP_TIMEOUT, '2', NULL, NULL); if (retval == FTP_ERR_ERROR_RESP) { /* ftp 4xx or 5xx error response */ return REQUEST_DENIED ; } /* initiate data socket */ if ((sockDataFd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { pal_logger(T_LOG_ERROR, __FILE__, __LINE__, LOG_FTP_MODULE, __func__ , "%s\n", strerror(errno)); return INTERNAL_ERROR; } /* reuse ip/port */ optval = 1; retval = setsockopt(sockCtrlFd, SOL_SOCKET, SO_REUSEADDR , (void *) & optval, sizeof(optval)); if (retval == -1) { return INTERNAL_ERROR; } memset(&ftpServerDataAddr, 0, sizeof(struct sockaddr)); ftpServerDataAddr.sin_family = AF_INET; ftpServerDataAddr.sin_port = htons(gPasvPort); inet_aton((char *)gPasvIPAddr, &ftpServerDataAddr.sin_addr); retval = connect(sockDataFd, (struct sockaddr *) & ftpServerDataAddr , sizeof(struct sockaddr)); if (retval == -1) { pal_logger(T_LOG_ERROR, __FILE__, __LINE__, LOG_FTP_MODULE, __func__ , "%s\n", strerror(errno)); return INTERNAL_ERROR; } /* get absolute filename without path */ p = strrchr(gFilename, '/'); _len = strlen(gFilename) - (p - gFilename); memcpy(_filename, p + 1, _len); _filename[_len] = '\0'; /* STOR */ ftp_commit_cmd(sockCtrlFd, FTP_CMD_STOR, _filename); retval = ftp_handle_cmd_resp(sockCtrlFd, FTP_CMD_STOR , FTP_RCV_RESP_TIMEOUT, '1', NULL, NULL); if (retval == FTP_ERR_ERROR_RESP) { /* ftp 4xx or 5xx error response */ return REQUEST_DENIED ; } p = fileContent; left = filesize; nsent = 0; while (left > 0) { PAL_INT32_T bufsize; bufsize = (left > 1460) ? 1460 : left; n = write(sockDataFd, p, bufsize); __msleep(100); if (n == -1) { pal_logger(T_LOG_ERROR, __FILE__, __LINE__, LOG_FTP_MODULE, __func__ , "%s\n", strerror(errno)); close(sockDataFd); close(sockCtrlFd); return -1; } else if (n == 0) { break; } else if (n > 0) { left -= n; p += n; nsent += n; } } pal_logger(T_LOG_INFO, __FILE__, __LINE__, LOG_FTP_MODULE, __func__ , "filesize: %d, sent: %d\n", filesize, nsent); shutdown(sockDataFd, SHUT_RDWR); shutdown(sockCtrlFd, SHUT_RDWR); return (left == 0) ? TCMAGENT_OK : UPLOAD_FAILURE; }
static ssize_t max14688_adc_refresh_store (struct device *dev, struct device_attribute *devattr, const char *buf, size_t count) { struct max14688 *me = dev_get_drvdata(dev); unsigned long timeout; unsigned int delay; u8 adcstatus, adccontrol_save, adccontrol; int rc; __lock(me); adccontrol = 0; rc = max14688_read(me, ADCCONTROL, &adccontrol); if (unlikely(rc)) { log_err("ADCCONTROL read error [%d]\n", rc); goto out; } /* Save original ADCCONTROL value */ adccontrol_save = adccontrol; delay = (unsigned int)simple_strtoul(buf, NULL, 10); if (likely(delay > 0)) { __msleep(delay); } adccontrol |= ADCCONTROL_FORCEADC; adccontrol |= ADCCONTROL_MANUALADC; rc = max14688_write(me, ADCCONTROL, adccontrol); if (unlikely(rc)) { log_err("ADCCONTROL write error [%d]\n", rc); goto out; } timeout = jiffies + usecs_to_jiffies(MAX14688_IDETIN_RISE_TIME) + usecs_to_jiffies(MAX14688_IDETIN_FALL_TIME) + usecs_to_jiffies(MAX14688_IDETIN_ON_TIME); do { if (unlikely(time_after(jiffies, timeout))) { log_err("AD conversion timed out\n"); goto out; } __msleep(1); adcstatus = 0; max14688_read(me, ADCSTATUS, &adcstatus); } while (likely(!BITS_GET(adcstatus, ADCSTATUS_EOC))); /* Restore ADCCONTROL value and make sure FORCEADC bit cleared */ adccontrol_save &= ~ADCCONTROL_FORCEADC; rc = max14688_write(me, ADCCONTROL, adccontrol_save); if (unlikely(rc)) { log_err("ADCCONTROL write error [%d]\n", rc); goto out; } out: __unlock(me); return (ssize_t)count; }
/* * rename() * Request rename of object within a server */ int rename(const char *src, const char *dest) { int err, tries = 0; char *p; port_name srcname, destname; /* * Explode src/dest paths into needed elements */ if (getpath(src, &srcfd, &srcname, &srcent)) { return(-1); } if (getpath(dest, &destfd, &destname, &destent)) { err = -1; goto out; } /* * Can't do this across two distinct servers */ if (srcname != destname) { err = -1; __seterr(EXDEV); goto out; } /* * Launch a thread to start the request. We will do the * matching rename. */ again: if (tfork(request, 0) < 0) { return(-1); } else { __msleep(20); /* Let'em get set */ } /* * Now connect with the destination */ if (msg(destfd, FS_RENAME, 1, destent)) { /* * If it's a transient failure (usually, the server * needs to flush a reference from the page cache), * wait a bit and try, try again. */ if (!strcmp(strerror(), EAGAIN) && (tries++ < 10)) { __msleep(20); goto again; } err = -1; goto out; } /* * Success */ err = 0; out: if (srcfd != -1) { close(srcfd); } if (destfd != -1) { close(destfd); } return(err); }
bool loop() { const char msg[10] = ""; // // Ping out role. Repeatedly send the current time // if (role == role_ping_out) { // First, stop listening so we can talk. radio.stopListening(); // Take the time, and send it. This will block until complete // unsigned long time = __millis(); // char msg[9] = "lamp1_on"; // printf("Now sending %s...",msg); bool ok = radio.write( msg, 10 ); if (ok) printf("ok..."); else printf("failed.\n\r"); // Now, continue listening radio.startListening(); // Wait here until we get a response, or timeout (250ms) unsigned long started_waiting_at = __millis(); bool timeout = false; while ( ! radio.available() && ! timeout ) { // by bcatalin » Thu Feb 14, 2013 11:26 am __msleep(5); //add a small delay to let radio.available to check payload if (__millis() - started_waiting_at > 200 ) timeout = true; } // Describe the results if ( timeout ) { printf("Failed, response timed out.\n\r"); return false; } else { // Grab the response, compare, and send to debugging spew char got[10]; radio.read( &got, 10 ); // Spew it printf("Got response %s\n",got); return true; } // Try again 1s later // delay(1000); //sleep(1); } // // Pong back role. Receive each packet, dump it out, and send it back // if ( role == role_pong_back ) { // if there is data ready if ( radio.available() ) { // Dump the payloads until we've gotten everything unsigned long got_time = 0; bool done = false; while (!done) { // Fetch the payload, and see if this was the last one. // done = radio.read( &got_time, sizeof(unsigned long) ); float celsius; // done = radio.read( &celsius, sizeof(float)); char tempC[100]; char len[2]; std::string recievedStr; // int i = 0; // while(i<16) // { // done = radio.read( &len, 2); // cout << len << endl; // i++; // } // printf("Payload length: %s... ",len); int payloadSize = radio.getPayloadSize(); // printf("Payload size: %d", payloadSize); done = radio.read( &tempC, payloadSize); cout << "Received from radio: " << tempC << endl; // Spew it printf("Got payload %s... ",tempC); stringstream ss; string received; ss << tempC; ss >> received; // char mark[] = "mark,a,b"; char *test[sizeof(strtok(tempC, ","))]; test[0] = strtok(tempC, ","); for(int i = 1; i < sizeof(strtok(tempC, ",")); i++) { test[i] = strtok (NULL, ","); // printf ("%s\n",test[i]); // Writes "is" } cout << "App:" << test[0] << "append" << strcmp(test[0],"temp") << endl; if(strcmp(test[0],"temp") == 0) { printf("Got data from temperature sensor, sending to temp server\n"); try { ClientSocket client_socket ( "localhost", 5656 ); std::string reply; try { cout << "received: " << received << endl; client_socket << received; client_socket >> reply; } catch ( SocketException& ) {} std::cout << "We received this response from the server:\n\"" << reply << "\"\n";; } catch ( SocketException& e ) { std::cout << "Exception was caught:" << e.description() << "\n"; } } // Delay just a little bit to let the other unit // make the transition to receiver delay(20); } // First, stop listening so we can talk radio.stopListening(); // Send the final one back. printf("Sent response.\n\r"); radio.write( &got_time, sizeof(unsigned long) ); // Now, resume listening so we catch the next packets. radio.startListening(); }