real sig2_gsp(gsprof *tgsp, gsprof *mgsp, real beta_a, real *sig2, real r) { int n = tgsp->npoint - 1; real r0, rn, gamma, m0, c0; r0 = tgsp->radius[0]; rn = tgsp->radius[n]; if (r < r0) { gamma = 2 * beta_a + mgsp->alpha + tgsp->alpha + 2; m0 = mass_gsp(mgsp, r0); if (gamma != 0.0) { c0 = sig2[0] + m0 / (gamma * r0); return (- (m0 / r0) * rpow(r / r0, 2 + mgsp->alpha) / gamma + c0 * rpow(r0 / r, 2 * beta_a + tgsp->alpha)); } else { c0 = sig2[0] + rlog(r0) * m0 / r0; return (- rlog(r) * m0 / rpow(r0, 3 + mgsp->alpha) / rpow(r, 2 * beta_a + tgsp->alpha) + c0 * rpow(r0 / r, 2 * beta_a + tgsp->alpha)); } } else if (r > rn) { if (tgsp->density[n] > 0) { gamma = 2 * beta_a + mgsp->beta + tgsp->beta + 2; return (- mgsp->mtot / ((2*beta_a + tgsp->beta - 1) * r) + (mgsp->mtot - mass_gsp(mgsp, r)) / (gamma * r)); } else return (0.0); } else return (seval(r, tgsp->radius, sig2, sig2 + n + 1, n + 1)); }
void RemoteConnection_close() { if (RemoteConnection_connected()) { rlog(R_INFO, "closing client socket %d\n", s_socket); closesocket(s_socket); s_socket = INVALID_SOCKET; } rlog(R_INFO, "closing socket %d\n", s_serverSocket); closesocket(s_serverSocket); s_serverSocket = INVALID_SOCKET; }
void polymodel1(void) { bodyptr p; real r, x, v; for (p = btab; p < NthBody(btab, nbody); p = NextBody(p)) { Mass(p) = 1.0 / nbody; r = xrandom(0.0, 2.0); pickshell(Pos(p), 3, r); x = SQRT2 * rcos(PI * (2.0 - xrandom(0.0, 1.0)) / 4.0); v = (xrandom(-1.0, 1.0) < 0.0 ? -1.0 : 1.0) * (1 - x*x) * rsqrt(rlog(2 / r)); MULVS(Vel(p), Pos(p), v/r); Phi(p) = 0.5 * rlog(r / 2.0) - 0.5; } bodyfields[4] = NULL; // don't output Aux data }
bool RemoteConnection_createListner() { struct sockaddr_in sin; int yes = 1; #if defined(_WIN32) WSADATA wsaData; if (WSAStartup(MAKEWORD(2,0),&wsaData) != 0) return false; #endif s_serverSocket = socket(AF_INET, SOCK_STREAM, 0); if (s_serverSocket == INVALID_SOCKET) return false; memset(&sin, 0, sizeof sin); sin.sin_family = AF_INET; sin.sin_addr.s_addr = INADDR_ANY; sin.sin_port = htons(1338); if (setsockopt(s_serverSocket, SOL_SOCKET, SO_REUSEADDR, (const char*)&yes, sizeof(int)) == -1) { perror("setsockopt"); return false; } if (-1 == bind(s_serverSocket, (struct sockaddr *)&sin, sizeof(sin))) { perror("bind"); rlog(R_ERROR, "Unable to bind server socket\n"); return false; } while (listen(s_serverSocket, SOMAXCONN) == -1) ; rlog(R_INFO, "Created listner\n"); return true; }
int init(const char *appTitle, int flags) { flags |= SDL_WINDOW_SHOWN; rlog("Creating Window."); win = SDL_CreateWindow(appTitle, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, screenWidth, screenHeight, flags); if(!win) { rerror("SDL_CreateWindow: %s", SDL_GetError()); return 0; } ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if(!ren) { rerror("SDL_CreateRenderer: %s", SDL_GetError()); return 0; } SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, filter); rlog("Window Created."); if(SDL_ShowCursor(show_cursor) < 0) { rerror("SDL_ShowCursor: %s", SDL_GetError()); } bmp = bm_create(virt_width, virt_height); tex = SDL_CreateTexture(ren, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, bmp->w, bmp->h); if(!tex) { rerror("SDL_CreateTexture: %s", SDL_GetError()); return 0; } rlog("Texture Created."); reset_keys(); return 1; }
void RemoteConnection_disconnect() { #if defined(_WIN32) closesocket(s_socket); #else close(s_socket); #endif s_socket = INVALID_SOCKET; rlog(R_INFO, "disconnect!\n"); s_paused = true; memset(s_nameLookup.ids, -1, sizeof(int) * s_nameLookup.count); s_nameLookup.count = 0; }
int handleSpecialKeys(SDL_Scancode key) { if(key == SDL_SCANCODE_ESCAPE && (keys[SDL_SCANCODE_LSHIFT] || keys[SDL_SCANCODE_RSHIFT])) { quit = 1; return 1; } else if (key == SDL_SCANCODE_F11) { if(!(SDL_GetWindowFlags(win) & SDL_WINDOW_FULLSCREEN_DESKTOP)) { if(SDL_SetWindowFullscreen(win, SDL_WINDOW_FULLSCREEN_DESKTOP) < 0) rerror("Unable to set window to fullscreen: %s", SDL_GetError()); } else if(SDL_SetWindowFullscreen(win, 0) < 0) { rerror("Unable to set window to windowed: %s", SDL_GetError()); } return 1; } else if(key == SDL_SCANCODE_F12) { char filename[256]; snprintf(filename, sizeof filename, "%s/save.png", initial_dir); bm_save(bmp, filename); rlog("Screenshot saved as %s", filename); return 1; } return 0; }
void RemoteConnection_updateListner(int currentRow) { struct timeval timeout; struct sockaddr_in client; SOCKET clientSocket = INVALID_SOCKET; fd_set fds; FD_ZERO(&fds); FD_SET(s_serverSocket, &fds); timeout.tv_sec = 0; timeout.tv_usec = 0; if (RemoteConnection_connected()) return; // look for new clients if (select(s_serverSocket + 1, &fds, NULL, NULL, &timeout) > 0) { clientSocket = clientConnect(s_serverSocket, &client); if (INVALID_SOCKET != clientSocket) { snprintf(s_connectionName, sizeof(s_connectionName), "Connected to %s", inet_ntoa(client.sin_addr)); rlog(R_INFO, "%s\n", s_connectionName); s_socket = clientSocket; s_clientIndex = 0; RemoteConnection_sendPauseCommand(true); RemoteConnection_sendSetRowCommand(currentRow); } else { // } } }
real ratanh(real x) { return (0.5 * rlog((1.0 + x) / (1.0 - x))); }
void * samr_restore(void* jobid) { node_t *destp; node_t *pathp; node_t *oldpathp; node_t *copyp; int rval; argbuf_t *arg; char mountpt[BUFFSIZ]; dumpspec_t *dsp; char msgbuf[MAX_MSGBUF_SIZE] = {0}; char catmsg[MAX_MSGBUF_SIZE] = {0}; int fd; sqm_lst_t *filelst = NULL; char *ptr; size_t end; arg = samr_get_args((char *)jobid); if (arg == NULL) { pthread_mutex_lock(&search_mutex); search_active = 0; /* Indicate search/restore is done */ pthread_mutex_unlock(&search_mutex); end_this_activity((char *)jobid); return (NULL); } Trace(TR_MISC, "restoring from %s %s", arg->r.fsname, arg->r.dumpname); /* * cleanup handler ends activity and frees arg but * jobid was malloced in the function that called * pthread_create and must be freed here. */ free(jobid); pthread_cleanup_push(&restorecleanup, arg); dsp = arg->r.dsp; rval = getfsmountpt(arg->r.fsname, mountpt, sizeof (mountpt)); if (rval == 0) { /* Pick up pointers to starts of these lists */ destp = arg->r.dest->head; copyp = arg->r.copies->head; } else { Trace(TR_MISC, "Restore init failed %s", samerrmsg); goto done; } /* Open log file */ if ((fd = open64(RESTORELOG, O_WRONLY|O_APPEND|O_CREAT, 0644)) != -1) { dsp->logfil = fdopen(fd, "a"); /* Open logfile for append */ } if (dsp->logfil == NULL) { /* must return or a crash will follow on rlog */ rval = samrerr(SE_NOTAFILE, RESTORELOG); goto done; } /* Log the fact that we are starting a restore */ strlcpy(catmsg, GetCustMsg(SE_START_RESTORE), sizeof (catmsg)); snprintf(msgbuf, sizeof (msgbuf), catmsg, destp->data, samerrmsg); rlog(dsp->logfil, catmsg, destp->data, samerrmsg); /* strip off any trailing slashes on the destinations */ for (pathp = destp; pathp != NULL; pathp = pathp->next) { ptr = (char *)pathp->data; if (ptr == NULL) { continue; } end = strlen(ptr) - 1; while ((ptr[end] == '/') || (ptr[end] == '.')) { ptr[end] = '\0'; } } /* * if we're restoring the whole filesystem, don't restore the * root node, just call into the restore_children func. */ if (strcmp((char *)(arg->r.filepaths->head->data), ".") == 0) { restore_children(".", copyp->data, destp->data, mountpt, dsp, arg->r.replace, FALSE); goto done; } /* get the details for the requested files */ rval = collect_file_details_restore(dsp->fsname, dsp->snapname, "", arg->r.filepaths, 0, &filelst); if (rval != 0) { /* we could probably do a better error */ strlcpy(catmsg, GetCustMsg(SE_RESTORE_FAILED), sizeof (catmsg)); snprintf(msgbuf, sizeof (msgbuf), catmsg, samerrmsg); strlcat(msgbuf, " ", sizeof (msgbuf)); strlcat(msgbuf, destp->data, sizeof (msgbuf)); rlog(dsp->logfil, msgbuf, NULL, NULL); PostEvent(DUMP_CLASS, DUMP_INTERRUPTED_SUBCLASS, SE_RESTORE_FAILED, LOG_ERR, msgbuf, NOTIFY_AS_FAULT); Trace(TR_MISC, "Restore init failed %s", samerrmsg); goto done; } /* Push a cleanup handler for the filelst */ pthread_cleanup_push(&free_file_details_lst, filelst); for (pathp = filelst->head, oldpathp = arg->r.filepaths->head; (pathp != NULL) && (oldpathp != NULL); pathp = pathp->next, oldpathp = oldpathp->next) { filedetails_t *details = (filedetails_t *)pathp->data; /* * Restore this file/directory/link/whatever. * If it's a directory, also restore children */ rval = restore_node( details, copyp->data, destp->data, mountpt, dsp, arg->r.replace); if (rval) { /* * file already exists isn't fatal reset rval for * later */ if (samerrno == SE_FILE_ALREADY_EXISTS) { rval = 0; } strlcpy(catmsg, GetCustMsg(SE_RESTORE_FAILED), sizeof (catmsg)); snprintf(msgbuf, sizeof (msgbuf), catmsg, samerrmsg); rlog(dsp->logfil, msgbuf, NULL, NULL); PostEvent(DUMP_CLASS, DUMP_INTERRUPTED_SUBCLASS, SE_RESTORE_FAILED, LOG_ERR, msgbuf, NOTIFY_AS_FAULT); } /* Restore any children */ if ((rval == 0) && (S_ISDIR(details->prot))) { restore_children((char *)oldpathp->data, copyp->data, destp->data, mountpt, dsp, arg->r.replace, FALSE); } strlcpy(catmsg, GetCustMsg(SE_FINISH_RESTORE), sizeof (catmsg)); snprintf(msgbuf, sizeof (msgbuf), catmsg, " ", samerrmsg); strlcat(msgbuf, destp->data, sizeof (msgbuf)); rlog(dsp->logfil, msgbuf, NULL, NULL); destp = destp->next; copyp = copyp->next; } /* pop file list free handler */ pthread_cleanup_pop(1); done: /* pop the cleanup handler */ pthread_cleanup_pop(1); return (NULL); }
/* Restore child nodes. Recursive. */ static int restore_children(char *dir_name, int *copy, char *dest, char *mountpt, dumpspec_t *dsp, replace_t replace, boolean_t count_only) { int st; char childdest[MAXPATHLEN + 1]; char msgbuf[MAX_MSGBUF_SIZE] = {0}; char catmsg[MAX_MSGBUF_SIZE] = {0}; sqm_lst_t *lstp = NULL; sqm_lst_t *dirlist = NULL; uint32_t morefiles = 0; restrict_t filter; filedetails_t *details; char *ptr; char startFrom[MAXPATHLEN + 1]; node_t *node; char *lastFile = NULL; char *startp; char *destp; dirlist = lst_create(); if (dirlist == NULL) { return (-1); } memset(&filter, 0, sizeof (restrict_t)); /* TODO: Add testcancel points and cleanup function */ startFrom[0] = '\0'; /* * get file info from the database in chunks so as not to * overwhelm ourselves if we're restoring a huge directory */ do { lstp = lst_create(); if (lstp == NULL) { goto done; } st = list_snapshot_files(dsp->fsname, dsp->snapname, dir_name, startFrom, filter, 0, 2048, FALSE, &morefiles, lstp); if (st != 0) { /* list_snapshot_files doesn't set samerrmsg */ snprintf(msgbuf, sizeof (msgbuf), GetCustMsg(SE_RESTORE_FAILED), ""); snprintf(catmsg, sizeof (catmsg), "%d %s ", st, strerror(st)); strlcat(msgbuf, catmsg, sizeof (msgbuf)); strlcat(msgbuf, dir_name, sizeof (msgbuf)); rlog(dsp->logfil, msgbuf, NULL, NULL); PostEvent(DUMP_CLASS, DUMP_INTERRUPTED_SUBCLASS, SE_RESTORE_FAILED, LOG_ERR, msgbuf, NOTIFY_AS_FAULT); goto done; } /* * Create new destination path - add filename with * strlcat to avoid possible problems with % in * the pathname. */ strlcpy(childdest, dest, MAXPATHLEN + 1); strlcat(childdest, "/", MAXPATHLEN + 1); destp = childdest + strlen(childdest); for (node = lstp->head; node != NULL; node = node->next) { details = node->data; if (details == NULL) { continue; } /* * save the path name in case we need it to get * more files */ lastFile = details->file_name; *destp = '\0'; strlcat(childdest, details->file_name, MAXPATHLEN + 1); /* if we're only counting, don't call restore_node */ /* Restore the child node */ if (!count_only) { st = restore_node(details, copy, childdest, mountpt, dsp, replace); if (st != 0) { strlcpy(catmsg, GetCustMsg(SE_RESTORE_FAILED), sizeof (catmsg)); snprintf(msgbuf, sizeof (msgbuf), catmsg, samerrmsg); rlog(dsp->logfil, msgbuf, NULL, NULL); PostEvent(DUMP_CLASS, DUMP_INTERRUPTED_SUBCLASS, SE_RESTORE_FAILED, LOG_ERR, msgbuf, NOTIFY_AS_FAULT); /* file already exists isn't fatal */ if (samerrno == SE_FILE_ALREADY_EXISTS) { st = 0; } } } if (S_ISDIR(details->prot)) { lst_append(dirlist, details->file_name); /* ensure not doubly deleted */ details->file_name = NULL; } } if (count_only) { restore_max += lstp->length; } if (lastFile) { strlcpy(startFrom, lastFile, sizeof (startFrom)); } lst_free_deep_typed(lstp, FREEFUNCCAST(free_file_details)); lstp = NULL; } while (morefiles > 0); /* restore any directories we found along the way */ strlcpy(startFrom, dir_name, sizeof (startFrom)); strlcat(startFrom, "/", sizeof (startFrom)); startp = startFrom + strlen(startFrom); for (node = dirlist->head; node != NULL; node = node->next) { ptr = (char *)node->data; *startp = '\0'; /* Create new source path */ strlcat(startp, ptr, sizeof (startFrom)); /* Create new destination path */ snprintf(childdest, MAXPATHLEN + 1, "%s/%s", dest, ptr); /* this will log individual errors for failure */ (void) restore_children(startFrom, copy, childdest, mountpt, dsp, replace, count_only); } done: if (lstp != NULL) { lst_free_deep_typed(lstp, FREEFUNCCAST(free_file_details)); } if (dirlist != NULL) { lst_free_deep(dirlist); } return (st); }
int main(int argc, char *argv[]) { int opt; int fullscreen = 0, resizable = 0, borderless = 0; const char *appTitle = DEFAULT_APP_TITLE; const char *game_dir = NULL; const char *pak_filename = "game.pak"; const char *rlog_filename = "rengine.log"; const char *startstate; struct game_state *gs = NULL; int demo = 0; SDL_version compiled, linked; log_init(rlog_filename); json_error = rerror; if(SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_AUDIO) < 0) { rerror("SDL_Init: %s", SDL_GetError()); return 1; } atexit(SDL_Quit); while((opt = getopt(argc, argv, "p:g:l:d?")) != -1) { switch(opt) { case 'p': { pak_filename = optarg; } break; case 'g' : { game_dir = optarg; pak_filename = NULL; } break; case 'l': { rlog_filename = optarg; } break; case 'd': { demo = 1; } break; case '?' : { usage(argv[0]); return 1; } } } if(!getcwd(initial_dir, sizeof initial_dir)) { rerror("error in getcwd(): %s", strerror(errno)); return 1; } rlog("Running engine from %s", initial_dir); if(!gdb_new()) { rerror("Unable to create Game Database"); return 1; } re_initialize(); states_initialize(); if(!snd_init()) { rerror("Terminating because of audio problem."); return 1; } /* Don't quite know how to use this in Windows yet. */ SDL_LogSetAllPriority(SDL_LOG_PRIORITY_WARN); SDL_Log("Testing Log capability."); SDL_VERSION(&compiled); SDL_GetVersion(&linked); rlog("SDL version %d.%d.%d (compile)", compiled.major, compiled.minor, compiled.patch); rlog("SDL version %d.%d.%d (link)", linked.major, linked.minor, linked.patch); if(!demo) { if(pak_filename) { rlog("Loading game PAK file: %s", pak_filename); if(!rs_read_pak(pak_filename)) { rerror("Unable to open PAK file '%s'; Playing demo mode.", pak_filename); goto start_demo; } } else { rlog("Not using a PAK file. Using '%s' instead.", game_dir); if(chdir(game_dir)) { rerror("Unable to change to '%s': %s", game_dir, strerror(errno)); return 1; } } game_ini = re_get_ini(GAME_INI); if(game_ini) { appTitle = ini_get(game_ini, "init", "appTitle", "Rengine"); screenWidth = atoi(ini_get(game_ini, "screen", "width", PARAM(SCREEN_WIDTH))); screenHeight = atoi(ini_get(game_ini, "screen", "height", PARAM(SCREEN_HEIGHT))); resizable = atoi(ini_get(game_ini, "screen", "resizable", "0")) ? SDL_WINDOW_RESIZABLE : 0; borderless = atoi(ini_get(game_ini, "screen", "borderless", "0")) ? SDL_WINDOW_BORDERLESS : 0; fullscreen = atoi(ini_get(game_ini, "screen", "fullscreen", "0")) ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0; fps = atoi(ini_get(game_ini, "screen", "fps", PARAM(DEFAULT_FPS))); if(fps <= 0) fps = DEFAULT_FPS; filter = !my_stricmp(ini_get(game_ini, "screen", "filter", "nearest"), "linear")? "1": "0"; virt_width = atoi(ini_get(game_ini, "virtual", "width", PARAM(VIRT_WIDTH))); virt_height = atoi(ini_get(game_ini, "virtual", "height", PARAM(VIRT_HEIGHT))); show_cursor = atoi(ini_get(game_ini, "mouse", "show-cursor", PARAM(1)))? 1 : 0; startstate = ini_get(game_ini, "init", "startstate", NULL); if(startstate) { gs = get_state(startstate); if(!gs) { rerror("Unable to get initial state: %s", startstate); return 1; } } else { rerror("No initial state in %s", GAME_INI); return 1; } } else { rerror("Unable to load %s", GAME_INI); return 1; } } else { start_demo: rlog("Starting demo mode"); gs = get_demo_state("demo"); } rlog("Initialising..."); if(!init(appTitle, fullscreen | borderless | resizable)) { return 1; } if(!bmf_init()){ rlog("Quiting; Unable to start FreeType font library"); return 1; } assert(gs); rlog("Entering initial state..."); if(!change_state(gs)) { rlog("Quiting, because of earlier problems with the initial state"); return 1; } frameStart = SDL_GetTicks(); rlog("Event loop starting..."); while(!quit) { gs = current_state(); if(!gs) { break; } if(gs->update) gs->update(gs, bmp); advanceFrame(); } rlog("Event loop stopped."); gs = current_state(); if(gs && gs->deinit) gs->deinit(gs); bm_free(bmp); SDL_DestroyTexture(tex); SDL_DestroyRenderer(ren); SDL_DestroyWindow(win); SDL_Quit(); ini_free(game_ini); re_clean_up(); bmf_deinit(); gdb_save("dump.db"); /* For testing the game database functionality. Remove later. */ gdb_close(); snd_deinit(); rlog("Engine shut down."); return 0; }
/* advanceFrame() is kept separate so that it * can be exposed to the scripting system later */ void advanceFrame() { SDL_Event event; Uint32 end; int new_btns, cursor; frame_counter++; render(); end = SDL_GetTicks(); assert(end > frameStart); if(end - frameStart < 1000/fps) SDL_Delay(1000/fps - (end - frameStart)); frameStart = SDL_GetTicks(); cursor = SDL_ShowCursor(-1); if(cursor < 0) { rerror("SDL_ShowCursor: %s", SDL_GetError()); cursor = 0; } if(cursor > 0) { int mx, my; new_btns = SDL_GetMouseState(&mx, &my); /* clicked = buttons that were down in the previous frame and aren't down anymore */ mouse_clck = mouse_btns & ~new_btns; mouse_btns = new_btns; mouse_x = screen_to_virt_x(mx); mouse_y = screen_to_virt_y(my); } else { /* Ignore the mouse if the cursor is gone */ new_btns = 0; mouse_clck = 0; mouse_btns = 0; mouse_x = -1; mouse_y = -1; } last_key = SDL_SCANCODE_UNKNOWN; while(SDL_PollEvent(&event)) { if(event.type == SDL_QUIT) { quit = 1; } else if(event.type == SDL_KEYDOWN) { /* FIXME: Descision whether to stick with scancodes or keycodes? */ int index = event.key.keysym.scancode; /* Special Keys: F11, F12 and Esc */ if(!handleSpecialKeys(event.key.keysym.scancode)) { /* Not a special key: */ assert(index < SDL_NUM_SCANCODES); keys[index] = 1; last_key = index; } } else if(event.type == SDL_KEYUP) { int index = event.key.keysym.scancode; assert(index < SDL_NUM_SCANCODES); keys[index] = 0; /*} else if(event.type == SDL_MOUSEBUTTONDOWN) { } else if(event.type == SDL_MOUSEMOTION) { mouse_x = screen_to_virt_x(event.motion.x); mouse_y = screen_to_virt_y(event.motion.y);*/ } else if(event.type == SDL_WINDOWEVENT) { switch(event.window.event) { case SDL_WINDOWEVENT_RESIZED: screenWidth = event.window.data1; screenHeight = event.window.data2; rlog("Window resized to %dx%d", screenWidth, screenHeight); break; default: break; } } } }
static int processCommands() { int strLen, newRow, serverIndex; unsigned char cmd = 0; int ret = 0; TrackViewInfo* viewInfo = getTrackViewInfo(); if (RemoteConnection_recv((char*)&cmd, 1, 0)) { switch (cmd) { case GET_TRACK: { char trackName[4096]; reset_tracks = true; memset(trackName, 0, sizeof(trackName)); RemoteConnection_recv((char *)&strLen, sizeof(int), 0); strLen = ntohl(strLen); if (!RemoteConnection_connected()) return 0; if (!RemoteConnection_recv(trackName, strLen, 0)) return 0; rlog(R_INFO, "Got trackname %s (%d) from demo\n", trackName, strLen); // find track serverIndex = TrackData_createGetTrack(&s_editorData.trackData, trackName); // if it's the first one we get, select it too if (serverIndex == 0) setActiveTrack(0); // setup remap and send the keyframes to the demo RemoteConnection_mapTrackName(trackName); RemoteConnection_sendKeyFrames(trackName, s_editorData.trackData.syncData.tracks[serverIndex]); TrackData_linkTrack(serverIndex, trackName, &s_editorData.trackData); s_editorData.trackData.tracks[serverIndex].active = true; ret = 1; break; } case SET_ROW: { //int i = 0; ret = RemoteConnection_recv((char*)&newRow, sizeof(int), 0); if (ret) { viewInfo->rowPos = htonl(newRow); viewInfo->selectStartRow = viewInfo->selectStopRow = viewInfo->rowPos; rlog(R_INFO, "row from demo %d\n", s_editorData.trackViewInfo.rowPos); } ret = 1; break; } } } return ret; }
static unsigned int remnode_send(remnode_item *remnode, pwr_sClass_RemTrans *remtrans, char *buf, int buf_size) { unsigned int sts, i; unsigned int size_of_telegram, datasize; unsigned int number_of_DLE = 0; unsigned int delta_pos = 0; unsigned int pos_counter = 0; unsigned int follow_on = FALSE; unsigned int A_telegram = FALSE; unsigned char ch, cpu_number, CPU; unsigned char BCC = DLE ^ ETX; unsigned char datasize_low_byte, datasize_high_byte; unsigned char received_char = '\0'; unsigned char response_buffer[RESP_MESSAGE_SIZE]; unsigned char *restore_buf_ptr = (unsigned char *)buf; static unsigned char sstx[2] = {STX, '\0'}; static unsigned char sdle[2] = {DLE, '\0'}; static unsigned char snak[2] = {NAK, '\0'}; fd_set read_fd; struct timeval tv; /* Define complete telegrams for sending */ struct{ unsigned char telegram_header[HEADER_SIZE]; unsigned char telegram[MAX_SIZE_DATA_BLOCK*2 + NUMBER_OF_STOP_CHAR]; }sendbuffer; struct{ unsigned char telegram_header[FOLLOW_ON_HEADER_SIZE]; unsigned char telegram[MAX_SIZE_DATA_BLOCK*2 + NUMBER_OF_STOP_CHAR]; }follow_on_sendbuffer; do /* Send 128 byte telegrams until message is finished */ { if ( !follow_on ) { A_telegram = TRUE; /*************************************************************************/ /** Send A-telegram. **/ /*************************************************************************/ /** Check if follow on telegrams are needed. **/ /*************************************************************************/ if ( buf_size - pos_counter > MAX_SIZE_DATA_BLOCK ) { delta_pos = MAX_SIZE_DATA_BLOCK; follow_on = TRUE; } else { delta_pos = buf_size - pos_counter; } /*************************************************************************/ /** Calculate the size of the A-telegram. **/ /*************************************************************************/ /* Count DLE characters */ for ( i=0 ; i<delta_pos ; i++ ) { if ( *buf++ == DLE ) number_of_DLE += 1; } size_of_telegram = HEADER_SIZE+ delta_pos+number_of_DLE+NUMBER_OF_STOP_CHAR; /*************************************************************************/ /** Fill in the telegram header and calculate BCC. **/ /*************************************************************************/ /* Size have to be expressed in number of 16 bits words. */ /* If odd number of bytes add one. */ datasize = buf_size/2 + buf_size%2; datasize_low_byte = (unsigned char)(BYTE_MASK & datasize); datasize = datasize >> 8; datasize_high_byte = (unsigned char)(BYTE_MASK & datasize); cpu_number = (unsigned char)remtrans->Address[2]; CPU = '\xFF'; CPU = CPU_NR_MASK & cpu_number; sendbuffer.telegram_header[0] = '\0'; sendbuffer.telegram_header[1] = '\0'; sendbuffer.telegram_header[2] = 'A'; sendbuffer.telegram_header[3] = 'D'; sendbuffer.telegram_header[4] = (unsigned char)remtrans->Address[0]; sendbuffer.telegram_header[5] = (unsigned char)remtrans->Address[1]; sendbuffer.telegram_header[6] = datasize_high_byte; sendbuffer.telegram_header[7] = datasize_low_byte; sendbuffer.telegram_header[8] = '\xFF'; sendbuffer.telegram_header[9] = CPU; /* Calculate checksum for the header */ for ( i=0 ; i<HEADER_SIZE ; i++ ) { BCC ^= sendbuffer.telegram_header[i]; } /*************************************************************************/ /** Fill up A-telegram with contents of message and calculate BCC **/ /*************************************************************************/ buf = (char *)restore_buf_ptr; for ( i=0 ; i<(delta_pos+number_of_DLE) ; i++ ) { ch = sendbuffer.telegram[i] = *buf++; BCC ^= ch; if ( ch == DLE ) { sendbuffer.telegram[++i] = DLE; BCC ^= ch; } } if ( delta_pos%2 ) { /* Ensure that a even number of bytes is treated */ sendbuffer.telegram[i++] = '\0'; size_of_telegram += 1; } sendbuffer.telegram[i++] = DLE; sendbuffer.telegram[i++] = ETX; sendbuffer.telegram[i] = BCC; pos_counter = delta_pos; } else /* follow on telegram */ { /*************************************************************************/ /** Send follow on telegram. **/ /*************************************************************************/ /** Check if more follow on telegrams are needed. **/ /*************************************************************************/ if ( buf_size - pos_counter > MAX_SIZE_DATA_BLOCK ) { delta_pos = MAX_SIZE_DATA_BLOCK; follow_on = TRUE; } else { delta_pos = buf_size - pos_counter; follow_on = FALSE; } /*************************************************************************/ /** Calculate the size of the follow on telegram. **/ /*************************************************************************/ /* Count DLE characters */ restore_buf_ptr = (unsigned char *)buf; number_of_DLE = 0; for ( i=0 ; i<delta_pos ; i++ ) { if ( *buf++ == DLE ) number_of_DLE += 1; } size_of_telegram = FOLLOW_ON_HEADER_SIZE+ delta_pos+number_of_DLE+NUMBER_OF_STOP_CHAR; /*************************************************************************/ /** Fill in the follow on telegram header and calculate BCC. **/ /*************************************************************************/ follow_on_sendbuffer.telegram_header[0] = '\xFF'; follow_on_sendbuffer.telegram_header[1] = '\0'; follow_on_sendbuffer.telegram_header[2] = 'A'; follow_on_sendbuffer.telegram_header[3] = 'D'; /* Calculate checksum for the header */ BCC = DLE ^ ETX; for ( i=0 ; i<FOLLOW_ON_HEADER_SIZE ; i++ ) { BCC ^= follow_on_sendbuffer.telegram_header[i]; } /*************************************************************************/ /* Fill up follow on telegram with contents of message and calculate BCC */ /*************************************************************************/ buf = (char *)restore_buf_ptr; for ( i = 0 ; i < (delta_pos+number_of_DLE) ; i++ ) { ch = follow_on_sendbuffer.telegram[i] = *buf++; BCC ^= ch; if ( ch == DLE ) { follow_on_sendbuffer.telegram[++i] = DLE; BCC ^= ch; } } if ( delta_pos%2 ) { /* Ensure that a even number of bytes is treated */ follow_on_sendbuffer.telegram[i++] = '\0'; size_of_telegram += 1; } follow_on_sendbuffer.telegram[i++] = DLE; follow_on_sendbuffer.telegram[i++] = ETX; follow_on_sendbuffer.telegram[i] = BCC; pos_counter += delta_pos; } /*************************************************************************/ /** Execute the send procedure **/ /*************************************************************************/ /* Send STX and wait for answer */ sts = write(ser_fd, sstx, 1); rlog("snd STX", 0); if ( sts > 0) { load_timeval(&tv, rn_RK512->CharTimeout); FD_ZERO(&read_fd); FD_SET(ser_fd, &read_fd); select(ser_fd+1, &read_fd, NULL, NULL, &tv); sts = read(ser_fd, &received_char, 1); } if ( sts > 0) { //om det inte var timeout if ( received_char == STX ) { rlog("snd STX received", 0); /* Both nodes is in sending mode. */ /* Cancel this send operation and wait for next timeout or receive */ write(ser_fd, snak, 1); return(FALSE); } if ( received_char == DLE ) { /* Contact is established. Send telegram */ rlog("snd DLE received, contact", 0); if ( A_telegram ) { sts = write(ser_fd, &sendbuffer, size_of_telegram); rlog("snd message sent", size_of_telegram); A_telegram = FALSE; } else { sts = write(ser_fd, &follow_on_sendbuffer, size_of_telegram); rlog("snd message sent", size_of_telegram); } if ( sts > 0 ) { /* wait for break character or timeout */ load_timeval(&tv, rn_RK512->CharTimeout); FD_ZERO(&read_fd); FD_SET(ser_fd, &read_fd); select(ser_fd+1, &read_fd, NULL, NULL, &tv); sts = read(ser_fd, &received_char, 1); if ( sts > 0 &&(received_char == DLE) ) { /*************************************************************************/ /** The sending was a SUCCESS. Take care of the response message **/ /*************************************************************************/ rlog("snd DLE received, success", 0); load_timeval(&tv, rn_RK512->CharTimeout); FD_ZERO(&read_fd); FD_SET(ser_fd, &read_fd); select(ser_fd+1, &read_fd, NULL, NULL, &tv); sts = read(ser_fd, &received_char, 1); if ( sts > 0 &&(received_char == STX) ) { /* Send DLE acknowledge and wait for response data */ sts = write(ser_fd, sdle, 1); if ( sts > 0 ) { BCC = '\0'; for (i=0 ; i < RESP_MESSAGE_SIZE && sts > 0; i++ ) { load_timeval(&tv, rn_RK512->CharTimeout); FD_ZERO(&read_fd); FD_SET(ser_fd, &read_fd); select(ser_fd+1, &read_fd, NULL, NULL, &tv); sts = read(ser_fd, &received_char, 1); response_buffer[i] = received_char; BCC ^= received_char; } /* endfor */ if ( sts > 0 && (response_buffer[2] == '\0') ) { /* Compare received BCC with calculated */ load_timeval(&tv, rn_RK512->CharTimeout); FD_ZERO(&read_fd); FD_SET(ser_fd, &read_fd); select(ser_fd+1, &read_fd, NULL, NULL, &tv); sts = read(ser_fd, &received_char, 1); if ( sts > 0 && ( BCC == received_char ) ) { /* Response telegram received OK */ sts = write(ser_fd, sdle, 1); if ( response_buffer[3] != 0 ) { /* This response contains a error code */ errh_CErrLog(REM__SIEMENSERROR, errh_ErrArgL(response_buffer[3]) ); } } else { /* Wrong checksum. */ sts = FALSE; } } else { /* This is not a response message as expected */ sts = write(ser_fd, snak, 1); sts = FALSE; } } /* ENDIF. DLE acknowledge failed */ } else { /* STX character in response message was expected. */ /* Ensure that error status is returned */ sts = FALSE; } } else { /* DLE ack. after sending telegram was expected. */ /* Ensure that error status is returned */ rlog("snd DLE missing", 0); sts = FALSE; } } /* ENDIF. Contact established but tty_write failed */ } else { /* Failed in making contact. Wrong response character. */ /* Ensure that error status is returned */ sts = FALSE; } } /* ENDIF. tty_write or tty_read failed */ /*************************************************************************/ /** Check final status. **/ /*************************************************************************/ if ( EVEN(sts)) { /* The send procedure has failed */ sts = write(ser_fd, snak, 1); rlog("snd failed, NAK sent", 0); follow_on = FALSE; /* Ensure that error status is returned */ sts = FALSE; } }while( follow_on );