Exemple #1
0
void handler(state_t *state){
	state->io_tick += 1;
	if(state->io_tick >= IO_DELAY){
		state->io_tick = 0;
		load(state);
	}


	if(state->cycle_ticks >= 6000){
		state->cycle_ticks = 0;
//		state->ticks = 0;
	}

	if(state->cycle_ticks == 1){
		send_port(LPT_DATA, 0);
	}


	if(state->cycle_ticks == 0
	&& state->enable){
		state->enable = false;
		send_port(LPT_DATA, 1);
	}

	if(state->echo){
		debug_sent_signals += 1;
	}

	state->cycle_ticks += 1;
}
Exemple #2
0
pid_t
sampling_fork ()
{
    kern_return_t       err;
    mach_port_t         parent_recv_port = MACH_PORT_NULL;
    mach_port_t         child_recv_port = MACH_PORT_NULL;

    if (setup_recv_port (&parent_recv_port) != 0)
        return -1;
    err = task_set_bootstrap_port (mach_task_self (), parent_recv_port);
    CHECK_MACH_ERROR (err, "task_set_bootstrap_port failed:");

    pid_t               pid;
    switch (pid = fork ()) {
    case -1:
        err = mach_port_deallocate (mach_task_self(), parent_recv_port);
        CHECK_MACH_ERROR (err, "mach_port_deallocate failed:");
        return pid;
    case 0: /* child */
        err = task_get_bootstrap_port (mach_task_self (), &parent_recv_port);
        CHECK_MACH_ERROR (err, "task_get_bootstrap_port failed:");
        if (setup_recv_port (&child_recv_port) != 0)
            return -1;
        if (send_port (parent_recv_port, mach_task_self ()) != 0)
            return -1;
        if (send_port (parent_recv_port, child_recv_port) != 0)
            return -1;
        if (recv_port (child_recv_port, &bootstrap_port) != 0)
            return -1;
        err = task_set_bootstrap_port (mach_task_self (), bootstrap_port);
        CHECK_MACH_ERROR (err, "task_set_bootstrap_port failed:");
        break;
    default: /* parent */
        err = task_set_bootstrap_port (mach_task_self (), bootstrap_port);
        CHECK_MACH_ERROR (err, "task_set_bootstrap_port failed:");
        if (recv_port (parent_recv_port, &child_task) != 0)
            return -1;
        if (recv_port (parent_recv_port, &child_recv_port) != 0)
            return -1;
        if (send_port (child_recv_port, bootstrap_port) != 0)
            return -1;
        err = mach_port_deallocate (mach_task_self(), parent_recv_port);
        CHECK_MACH_ERROR (err, "mach_port_deallocate failed:");
        break;
    }

    return pid;
}
Exemple #3
0
static void handle_update (CcnetProcessor *processor,
                           char *code, char *code_msg,
                           char *content, int clen)
{
    USE_PRIV;

    switch (priv->tdata->state) {
    case PREPARE:
        if (memcmp (code, SC_BLOCKLIST, 3) == 0) {
            process_block_list (processor, content, clen);
            return;
        } else if (memcmp (code, SC_GET_PORT, 3) == 0) {
            send_port (processor);
            return;
        }
        break;
    case READY:
        if (memcmp (code, SC_GET_BLOCK, 3) == 0) {
            process_get_block (processor, content, clen);
            return;
        }
        break;
    }

    g_warning ("Bad code: %s %s\n", code, code_msg);
    ccnet_processor_send_response (processor, SC_BAD_UPDATE_CODE, 
                                   SS_BAD_UPDATE_CODE, NULL, 0);
    ccnet_processor_done (processor, FALSE);
}
Exemple #4
0
void deinit_ack(){
	asm cli

	send_port(LPT_CONTROL, 0);
	setvect(0x0f, old_ack7);

	asm sti
}
Exemple #5
0
void init_ack(){
	asm cli

	send_port(LPT_CONTROL, 16);

	old_ack7 = getvect(0x0f);
	setvect(0x0f, ack_int_7);

	asm sti
}
Exemple #6
0
int main(int argc, char **argv){
	int begin = time(NULL)
		,	pin
		,	offset;

	if(argc < 2){
		printf("Ze ktory pin?\n");
		return -1;
	}
	pin = atoi(argv[1]);
	if(pin < 0
	|| pin > 7){
		printf("Zly numer pinu pajacu\n");
		return -2;
	}

	if(argc < 3){
		offset = 0;
	}else{
		offset = atoi(argv[2]);
	}
	if(offset < 0
	|| offset > 2){
		printf("Wyjezdzasz za LPT jebany idioto!\n");
		offset = 0;
	}

	send_port(LPT_DATA + offset, (1 << pin));
//	send_port(LPT_DATA + 1, 255);
	send_port(LPT_DATA + 1, 0);
//	delay(2000);
// 	while( time(NULL) - begin < 2 ){
// 		; // wait
// 	}

 //	send_port(LPT_DATA, 0);

	return 0;
}
// Timer
gboolean timeout_callback(gpointer data)
{
  static unsigned char dispatch = 0;

  // Only do the settings if in xbee mode
  if ((power_level >= 0) && (handle_api() == 0))
    return TRUE;

  // Every Time
  read_port();

  // One out of 4
  if (dispatch > 2)
  {
    send_port();
    dispatch = 0;
  }
  else
  {
    dispatch ++;
  }
  return TRUE;
}
Exemple #8
0
void chat(int sockfd){

    // recv name
    int count;
    char bufferFST[4];
    count = recv(sockfd, bufferFST, 4, MSG_PEEK);
    if(count == -1)
        perror("Recv with error");

    google::protobuf::uint32 pkg_size = readHdr(bufferFST);
    int byteCount;
    online::OnlinePerson person;
    char buffer[pkg_size + HDR_SIZE];
    if( ( byteCount = recv(sockfd, (void *)buffer, pkg_size + HDR_SIZE, MSG_WAITALL) ) == -1 ){
        perror("Error recviving data");
    }
    google::protobuf::io::ArrayInputStream ais(buffer, pkg_size + HDR_SIZE);
    google::protobuf::io::CodedInputStream coded_input(&ais);
    coded_input.ReadVarint32(&pkg_size);
    google::protobuf::io::CodedInputStream::Limit msgLimit = coded_input.PushLimit(pkg_size);
    person.ParseFromCodedStream(&coded_input);

    // check whether online
    for(int i=0; i<loginData.logindata_size(); ++i){
        if( loginData.logindata(i).online() == true ){
            if( loginData.logindata(i).id() != "" &&
                loginData.logindata(i).id() == person.name() ){
                sendCheck(sockfd, true);
                send_port(sockfd, loginData.logindata(i).port(), loginData.logindata(i).ip());
                return;
            }
        }
    }
    sendCheck(sockfd, false);
    printf("!ok\n");

}
Exemple #9
0
void update_data(){
	send_port(LPT_DATA, state.data);
}
Exemple #10
0
int main(int argc, char *argv[]) {

    if(argc != 7) {
        printf("usage: host port R stream_id window_size filename\n");
        exit(0);
    }

    char *endptr;
    long R = strtol(argv[3], &endptr, 10);
    char *stream_id = argv[4];
    int window_size = strtol(argv[5], NULL, 10);

    if(endptr != (argv[3] + strlen(argv[3]))) {
        fprintf(stderr, "R must be an integer (milliseconds).\n");
        exit(1);
    }


    struct addrinfo* p;
    int send_sock = send_port(argv[1], argv[2], &p);
    int recv_sock = recv_port(NULL, argv[2]);// TODO fix


    printf("Stream id = %s\n", stream_id);
    ee122_packet pkt;
    pkt.R = R;
    pkt.stream = *stream_id;
    printf("pkt.stream = %c\n", pkt.stream);
    pkt.avg_len = 0;
    pkt.window_size = window_size;

    int read_count;
    char fbuff[sizeof(pkt.payload)];
    memset(fbuff,0,sizeof(fbuff));
    FILE *fd = fopen(argv[6], "rb");
    if(NULL == fd) {
        fprintf(stderr, "fopen() error\n");
        return 1;
    }

    ee122_packet rcv_pkt;

    struct timespec sleep_spec;
    sleep_spec.tv_sec = 0;

    struct timeval curr_time, start_time, last_generated, diff_time;
    gettimeofday(&start_time, NULL);
    gettimeofday(&last_generated, NULL);

    int seq_no = 0;
    int available_window = window_size;

    struct timeval timeouts[window_size+1];
    ee122_packet packets[window_size+1];

    int i;
    struct timeval zero_timeout;
    zero_timeout.tv_usec = 0;
    zero_timeout.tv_sec = 0;

    for(i = 0; i < window_size+1; i++) {
        memcpy(&timeouts[i], &zero_timeout, sizeof(zero_timeout));
    }

    bytequeue q;
    bytequeue_init(&q, sizeof(ee122_packet), window_size);

    float rtt = 400*1000;
    char buff[sizeof(ee122_packet)];

    float next_wait = rand_poisson(R);
    printf("next wait: %f\n", next_wait);

    int bytes_read;
    struct sockaddr src_addr;
    int src_len = sizeof(src_addr);
    int last_received = -1;
    unsigned total_attempts = 0;
    unsigned seconds = 0;
    unsigned errors = 0;

    while (1) {
        gettimeofday(&curr_time, NULL);

        timeval_subtract(&diff_time, &curr_time, &start_time);

        if (diff_time.tv_sec * 1000000 + diff_time.tv_usec > seconds * 1000000) {
            printf("%f,%d\n", rtt, seconds);
            seconds++;
        }
        // Stop sending after 60 seconds
        if(diff_time.tv_sec * 1000000 + diff_time.tv_usec > 60*1000000) {
            break;
        }

        // Check timeouts. If timeout reached, retransmit that packet and all following.
        int retransmitting = -1;
        int i;
        for(i=0; i < window_size+1; i++) {
            struct timeval timeout = timeouts[i];
            if(timeout.tv_sec == 0 && timeout.tv_usec == 0) continue;

            timeval_subtract(&diff_time, &curr_time, &timeouts[i]);
            if(diff_time.tv_sec * 1000000 + diff_time.tv_usec > rtt) {
                retransmitting = i;
                break;
            }
        }

        if(retransmitting != -1) {
            i = retransmitting;
            do {
                struct timeval timeout = timeouts[i];
                if(timeout.tv_sec == 0 && timeout.tv_usec == 0) {
                    i = (i + 1) % (window_size+1);
                    continue;
                }
                //printf("Retransmitting seq_no == %d, stream == %c, rtt == %f\n", packets[i].seq_number, packets[i].stream, rtt);
                // Reset the timeout for this packet and send.
                gettimeofday(&(timeouts[i]), NULL);
                serialize_packet(buff, packets[i]);
                sendto(send_sock, buff, sizeof(packets[i]), 0, p->ai_addr, p->ai_addrlen);
                i = (i + 1) % (window_size+1);
                total_attempts++;
                errors++;
            } while (i != retransmitting);
        }

        // Check if new packet should be generated by now
        timeval_subtract(&diff_time, &curr_time, &last_generated);
        if(diff_time.tv_sec * 1000000 + diff_time.tv_usec > next_wait * 1000) {
            // Enqueue the packet.
            bytequeue_push(&q, &pkt);
            next_wait = rand_poisson(R);
        }

        // Read from socket. Increase available window for each ack received
        int bytes_read = recvfrom(recv_sock, buff, sizeof(ee122_packet), 0, &src_addr, &src_len);
        if(bytes_read > 0) {
            rcv_pkt = deserialize_packet(buff);
            if(rcv_pkt.stream == 'Z' && rcv_pkt.seq_number == (last_received + 1) % (window_size+1)) {
                struct timeval timeout_start = rcv_pkt.timestamp;

                // Learn RTT
                timeval_subtract(&diff_time, &curr_time, &timeout_start);
                //printf("RTT difftime, tv_sec == %d, tv_usec == %d\n", diff_time.tv_sec, diff_time.tv_usec);
                rtt = (0.6 * (diff_time.tv_sec * 1000000 + diff_time.tv_usec)) + 0.4*rtt;

                // Reset this timeout
                timeouts[rcv_pkt.seq_number].tv_usec = 0;
                timeouts[rcv_pkt.seq_number].tv_sec = 0;

                available_window += 1;
                last_received = rcv_pkt.seq_number % (window_size+1);
            }
            else {
                //printf("Received ACK with seq = %d, expecting = %d\n", rcv_pkt.seq_number, (last_received + 1) % window_size);
            }
        }

        // Check available window. If available, dequeue and send a packet.
        if(available_window > 0 && q.filled != 0) {
            bytequeue_pop(&q, &pkt);

            total_attempts++;

            pkt.seq_number = (seq_no) % (window_size+1);
            pkt.timestamp = curr_time;
            pkt.total_attempts = total_attempts;
            pkt.timeout = rtt;
            read_count = fread(pkt.payload, sizeof(char), sizeof(pkt.payload), fd);

            //printf("Sending. Seq_no == %d, stream == %c\n", pkt.seq_number, pkt.stream);
            serialize_packet(buff, pkt);

            //Store the packet into the packets buffer for possible transmission
            memcpy(&packets[pkt.seq_number], &pkt, sizeof(pkt));

            sendto(send_sock, buff, sizeof(pkt), 0, p->ai_addr, p->ai_addrlen);
            pkt = deserialize_packet(buff);
            available_window -= 1;

            if (feof(fd)) break;
            if(ferror(fd)) {
                fprintf(stderr, "error: %s\n", strerror(errno));
                exit(3);
            }

            // Set this timeout
            gettimeofday(&timeouts[pkt.seq_number], NULL);

            seq_no++;
        }

    }

    printf("Total errors: %d. Total total:%d\n", errors, total_attempts);

    close(send_sock);
    close(recv_sock);
    exit(0);
}
/**
  \fn uint32_t receive_port(HANDLE fpCom, uint32_t lenRx, char *Rx)
   
  \brief receive data via comm port
  
  \param[in]  fpCom   handle to comm port
  \param[in]  lenRx   number of bytes to receive
  \param[out] Rx      array containing bytes received
  
  \return number of received bytes
  
  receive data via comm port. Use this function to facilitate serial communication
  on different platforms, e.g. Win32 and Posix
  If g_UARTmode==2 (UART reply mode with 2-wire interface), reply each byte from STM8 -> SLOW
*/
uint32_t receive_port(HANDLE fpCom, uint32_t lenRx, char *Rx) {

  
/////////
// Win32
/////////
#ifdef WIN32

  DWORD     numChars, numTmp;
  uint32_t  i, numRx;
  
  // for UART reply mode with 2-wire interface echo each received bytes -> SLOW
  if (g_UARTmode==2) {
    
    // echo each byte as it is received
    numChars = 0;
    for (i=0; i<lenRx; i++) {
      ReadFile(fpCom, Rx+i, 1, &numTmp, NULL);
      if (numTmp == 1) {
        numChars++;
        send_port(fpCom, 1, Rx+i);
      }
      else
        break;
    } // loop i
  
  } // g_UARTmode==2
  
  
  // UART duplex mode or 1-wire interface -> receive all bytes in single block -> fast
  else {
    ReadFile(fpCom, Rx, lenRx, &numChars, NULL);
  }
  
  // return number of bytes received
  return((uint32_t) numChars);

#endif // WIN32


/////////
// Posix
/////////
#if defined(__APPLE__) || defined(__unix__) 

  char            *dest = Rx;
  uint32_t        remaining = lenRx, got = 0, received = 0;
  struct          timeval tv;
  fd_set          fdr;
  struct termios  toptions;
  uint32_t        timeout;
  
  // get terminal attributes
  if (tcgetattr(fpCom, &toptions) < 0) {
    setConsoleColor(PRM_COLOR_RED);
    fprintf(stderr, "\n\nerror in 'receive_port': get port attributes failed, exit!\n\n");
    Exit(1, g_pauseOnExit);
  }
  
  // get terminal timeout (see: http://unixwiz.net/techtips/termios-vmin-vtime.html)
  timeout = toptions.c_cc[VTIME] * 100;        // convert 0.1s to ms
  
  // while there are bytes left to read...
  while (remaining != 0) {
   
    // reinit timeval structure each time through loop
    tv.tv_sec  = (timeout / 1000L);
    tv.tv_usec = (timeout % 1000L) * 1000L;

    // wait for data to come in using select
    FD_ZERO(&fdr);
    FD_SET(fpCom, &fdr);
    if (select(fpCom + 1, &fdr, NULL, NULL, &tv) != 1) {
      return(received);
    }

    // read a response, we know there's data waiting
    got = read(fpCom, dest, remaining);
    
    // handle errors. retry on EAGAIN, fail on anything else, ignore if no bytes read
    if (got == -1) {
      if (errno == EAGAIN)
        continue;
      else
        return(received);
    } 
    else if (got > 0) {
      
      // for UART reply mode with 2-wire interface echo each byte
      if (g_UARTmode==2) {
        //fprintf(stderr,"sent echo %dB 0x%02x\n", (int) lenRx, Rx[0]);
        send_port(fpCom, 1, dest);
      }
      
      // figure out how many bytes are left and increment dest pointer through buffer
      dest += got;
      remaining -= got;
      received += got;
      
    } // received bytes

  } // while (remaining != 0)

  // return number of received bytes
  return(received);
  
#endif // __APPLE__ || __unix__

} // receive_port
Exemple #12
0
int main(int argc, char *argv[]){

  if(argc != 5){
    printf("usage: port sender_hostname ack_port filename\n");
    exit(0);
  }

  srand(time(0)); // init random

  int status;
  int sockfd;

  struct addrinfo hints;
  memset(&hints, 0, sizeof hints);
  hints.ai_family = AF_INET;
  hints.ai_socktype = SOCK_DGRAM;
  hints.ai_flags = AI_PASSIVE;

  struct addrinfo *res, *p;

  if ((status = getaddrinfo(NULL, argv[1], &hints, &res)) != 0) {
    fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
    exit(1);
  }

  for(p = res; p != NULL; p = p->ai_next) {
    if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) {
        perror("listener: socket");
        continue;
    }

    if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
      close(sockfd);
      perror("listener: bind");
      continue;
    }

    break;
  }

  if (p == NULL) {
    fprintf(stderr, "listener: failed to bind socket\n");
    return 2;
  }

	struct addrinfo* send_p;
  int outsock = send_port(argv[2], argv[3], &send_p);

  struct timeval timeout;

  timeout.tv_sec = 4;
  timeout.tv_usec = 0;
  setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO,(struct timeval *)&timeout, sizeof(struct timeval));

  struct sockaddr src_addr;
  int src_len = sizeof src_addr;
  ee122_packet pkt;

  int write_count;
  char fbuff[sizeof(pkt.payload)];
  memset(fbuff,0,sizeof(fbuff));
  FILE *fd = fopen(argv[4], "wb");
  if(NULL == fd) {
    fprintf(stderr, "fopen() error\n");
    return 1;
  }

  int num_rcv = 0;
  int bytes_read = 0;
  unsigned long attempted = 0;
  float avg_len ;

  unsigned char buff[sizeof(ee122_packet)];
  long R;

  int delay;
  struct timespec sleep_spec;
  sleep_spec.tv_sec = 0;

  struct timeval last_time, curr_time, diff_time, last_print;
  gettimeofday(&last_print, NULL);

  double sum = 0.0;

  int seq_expected = 0;
  int gotten = 0;

  float efficiency = 0;

  while(bytes_read = recvfrom(sockfd, buff, sizeof(ee122_packet), 0, &src_addr, &src_len)){
    if(bytes_read == -1){
      if(num_rcv > 0){
        break;
      }
    } else {
      if(bytes_read == 0){
        break;
      }

      pkt = deserialize_packet(buff);

      //printf("Received packet with seq no: %d\n", ntohl(*((uint32_t*) buff)));
      if(num_rcv == 0) {
        R = pkt.R;
      } else {
      }

      if (flip_state) {
        delay = rand() % 15;
      }
      else {
        delay = rand() % 5;
      }

      sleep_spec.tv_nsec = delay * 1000000;
      nanosleep(&sleep_spec, &sleep_spec);
      if(pkt.seq_number == seq_expected){
        write_count = fwrite(pkt.payload, sizeof(char), sizeof(pkt.payload), fd);
        if (ferror(fd)) {
          fprintf(stderr, "error: %s\n", strerror(errno));
          exit(3);
        }
        seq_expected = (seq_expected + 1) % (MAX_WINDOW + 1);

        // Do the calcs
        num_rcv++;
        attempted = pkt.total_attempts;
        avg_len = pkt.avg_len;
        gettimeofday(&curr_time, NULL);
        last_time = pkt.timestamp;
        timeval_subtract(&diff_time, &curr_time, &last_time);
        sum += ((double)(diff_time.tv_sec)) + (diff_time.tv_usec / 1000000.0);

        timeval_subtract(&diff_time, &curr_time, &last_print);
        if (diff_time.tv_sec * 1000000 + diff_time.tv_usec > 1000000) {
          printf("%f\n", ((float) num_rcv)/attempted);
          gettimeofday(&last_print, NULL);
        }
      }

      gotten = pkt.total_attempts;

      // Send ACK
      ee122_packet ack;
      ack = pkt;
      ack.stream = 'Z';

      unsigned char buff[sizeof(ack)];
      serialize_packet(buff, ack);
			sendto(outsock, buff, sizeof(ack), 0, send_p->ai_addr, send_p->ai_addrlen);
    }
  }

  printf("%d,%f,%lf\n", pkt.R, ((float) num_rcv)/attempted, avg_len);

  freeaddrinfo(res);
  close(sockfd);
  exit(0);
}
Exemple #13
0
/**
   \fn int main(int argc, char *argv[])
   
   \brief main routine
   
   \param argc      number of commandline arguments + 1
   \param argv      string array containing commandline arguments (argv[0] contains name of executable)
   
   \return dummy return code (not used)
   
   Main routine for import, programming, and check routines
*/
int main(int argc, char ** argv) {
 
  char      *appname;             // name of application without path
  char      portname[STRLEN];     // name of communication port
  int       baudrate;             // communication baudrate [Baud]
  uint8_t   resetSTM8;            // 0=no reset; 1=HW reset via DTR (RS232/USB) or GPIO18 (Raspi); 2=SW reset by sending 0x55+0xAA
  uint8_t   enableBSL;            // don't enable ROM bootloader after upload (caution!)
  uint8_t   jumpFlash;            // jump to flash after upload
  uint8_t   pauseOnLaunch;        // prompt for <return> prior to upload
  int       flashsize;            // size of flash (kB) for w/e routines
  uint8_t   versBSL;              // BSL version for w/e routines
  char      hexfile[STRLEN];      // name of file to flash
  HANDLE    ptrPort;              // handle to communication port
  char      buf[BUFSIZE];         // buffer for hexfiles
  char      image[BUFSIZE];       // memory image buffer
  uint32_t  imageStart;           // starting address of image
  uint32_t  numBytes;             // number of bytes in image
  char      *ptr=NULL;            // pointer to memory
  int       i, j;                 // generic variables  
  //char      Tx[100], Rx[100];     // debug: buffer for tests
  

  // initialize global variables
  g_pauseOnExit = 1;            // wait for <return> before terminating
  g_UARTmode    = 0;            // 2-wire interface with UART duplex mode
  verbose       = false;        // verbose output when requested only
  
  // initialize default arguments
  portname[0] = '\0';           // no default port name
  baudrate   = 230400;          // default baudrate
  resetSTM8  = 0;               // don't automatically reset STM8
  jumpFlash  = 1;               // jump to flash after uploade
  pauseOnLaunch = 1;            // prompt for return prior to upload
  enableBSL  = 1;               // enable bootloader after upload
  hexfile[0] = '\0';            // no default hexfile
  
  // for debugging only
  //sprintf(portname, "/dev/tty.usbserial-A4009I0O");

  // required for strncpy()
  portname[STRLEN-1]  = '\0';
  hexfile[STRLEN-1]   = '\0';
    
    
  // reset console color (needs to be called once for Win32)      
  setConsoleColor(PRM_COLOR_DEFAULT);


  ////////
  // parse commandline arguments
  ////////
  for (i=1; i<argc; i++) {
    
    // debug: print argument
    //printf("arg %d: '%s'\n", (int) i, argv[i]);
    
    // name of communication port
    if (!strcmp(argv[i], "-p"))
      strncpy(portname, argv[++i], STRLEN-1);

    // communication baudrate
    else if (!strcmp(argv[i], "-b"))
      sscanf(argv[++i],"%d",&baudrate);

    // UART mode: 0=duplex, 1=1-wire reply, 2=2-wire reply (default: duplex)\n");
    else if (!strcmp(argv[i], "-u")) {
      sscanf(argv[++i], "%d", &j);
      g_UARTmode = j;
    }

    // name of hexfile
    else if (!strcmp(argv[i], "-f"))
      strncpy(hexfile, argv[++i], STRLEN-1);

    // HW reset STM8 via DTR line (RS232/USB) or GPIO18 (Raspi only)
    else if (!strcmp(argv[i], "-r")) {
      sscanf(argv[++i], "%d", &j);
      resetSTM8 = j;
    }
    
    // don't enable ROM bootloader after upload (caution!)
    else if (!strcmp(argv[i], "-x"))
      enableBSL = 0;

    // don't jump to address after upload
    else if (!strcmp(argv[i], "-j"))
      jumpFlash = 0;

    // don't prompt for <return> prior to upload
    else if (!strcmp(argv[i], "-Q"))
      pauseOnLaunch = 0;

    // don't prompt for <return> prior to exit
    else if (!strcmp(argv[i], "-q"))
      g_pauseOnExit = 0;

    // verbose output
    else if (!strcmp(argv[i], "-v"))
      verbose = true;

    // else print list of commandline arguments and language commands
    else {
      if (strrchr(argv[0],'\\'))
        appname = strrchr(argv[0],'\\')+1;         // windows
      else if (strrchr(argv[0],'/'))
        appname = strrchr(argv[0],'/')+1;          // Posix
      else
        appname = argv[0];
      printf("\n");
      printf("usage: %s [-h] [-p port] [-b rate] [-u mode] [-f file] [-r ch] [-x] [-j] [-Q] [-q] [-v]\n\n", appname);
      printf("  -h        print this help\n");
      printf("  -p port   name of communication port (default: list all ports and query)\n");
      printf("  -b rate   communication baudrate in Baud (default: 230400)\n");
      printf("  -u mode   UART mode: 0=duplex, 1=1-wire reply, 2=2-wire reply (default: duplex)\n");
      printf("  -f file   name of s19 or intel-hex file to flash (default: none)\n");
      #ifdef __ARMEL__
        printf("  -r ch     reset STM8: 1=DTR line (RS232), 2=send 'Re5eT!' @ 115.2kBaud, 3=GPIO18 pin (Raspi) (default: no reset)\n");
      #else
        printf("  -r ch     reset STM8: 1=DTR line (RS232), 2=send 'Re5eT!' @ 115.2kBaud (default: no reset)\n");
      #endif
      printf("  -x        don't enable ROM bootloader after upload (default: enable)\n");
      printf("  -j        don't jump to flash after upload (default: jump to flash)\n");
      printf("  -Q        don't prompt for <return> prior to upload (default: prompt)\n");
      printf("  -q        don't prompt for <return> prior to exit (default: prompt)\n");
      printf("  -v        verbose output\n");
      printf("\n");
      Exit(0, 0);
    }

  } // process commandline arguments
  
  

  ////////
  // print app name & version, and change console title
  ////////
  get_app_name(argv[0], VERSION, buf);
  printf("\n%s\n", buf);
  setConsoleTitle(buf);  
  
  
  ////////
  // if no port name is given, list all available ports and query
  ////////
  if (strlen(portname) == 0) {
    printf("  enter comm port name ( ");
    list_ports();
    printf(" ): ");
    scanf("%s", portname);
    getchar();
  } // if no comm port name

  // If specified import hexfile - do it early here to be able to report file read errors before others
  if (strlen(hexfile)>0) {
    const char *shortname = strrchr(hexfile, '/');
    if (!shortname)
      shortname = hexfile;

    // convert to memory image, depending on file type
    const char *dot = strrchr (hexfile, '.');
    if (dot && !strcmp(dot, ".s19")) {
      if (verbose)
        printf("  Loading Motorola S-record file %s …\n", shortname);
      load_hexfile(hexfile, buf, BUFSIZE);
      convert_s19(buf, &imageStart, &numBytes, image);
      }
    else if (dot && (!strcmp(dot, ".hex") || !strcmp(dot, ".ihx"))) {
      if (verbose)
        printf("  Loading Intel hex file %s …\n", shortname);
      load_hexfile(hexfile, buf, BUFSIZE);
      convert_hex(buf, &imageStart, &numBytes, image);
    }
    else {
      if (verbose)
        printf("  Loading binary file %s …\n", shortname);
      load_binfile(hexfile, image, &imageStart, &numBytes, BUFSIZE);
    }
  }

  ////////
  // put STM8 into bootloader mode
  ////////
  if (pauseOnLaunch) {
    printf("  activate STM8 bootloader and press <return>");
    fflush(stdout);
    fflush(stdin);
    getchar();
  }

  ////////
  // open port with given properties
  ////////
  printf("  open port '%s' with %gkBaud ... ", portname, (float) baudrate / 1000.0);
  fflush(stdout);
  if (g_UARTmode == 0)
    ptrPort = init_port(portname, baudrate, 1000, 8, 2, 1, 0, 0);   // use even parity
  else
    ptrPort = init_port(portname, baudrate, 1000, 8, 0, 1, 0, 0);   // use no parity
  printf("ok\n");
  fflush(stdout);
  
 
  // debug: communication test (echo+1 test-SW on STM8)
  /*
  printf("open: %d\n", ptrPort);
  for (i=0; i<254; i++) {
    Tx[0] = i;
    send_port(ptrPort, 1, Tx);
    receive_port(ptrPort, 1, Rx);
	printf("%d  %d\n", (int) Tx[0], (int) Rx[0]);
  }
  printf("done\n");
  Exit(1,0);
  */
  

  ////////
  // communicate with STM8 bootloader
  ////////

  // HW reset STM8 using DTR line (USB/RS232)
  if (resetSTM8 == 1) {
    printf("  reset via DTR ... ");
    pulse_DTR(ptrPort, 10);
    printf("done\n");
    SLEEP(5);                       // allow BSL to initialize
  }
  
  // SW reset STM8 via command 'Re5eT!' at 115.2kBaud (requires respective STM8 SW)
  else if (resetSTM8 == 2) {
    set_baudrate(ptrPort, 115200);    // expect STM8 SW to receive at 115.2kBaud
    printf("  reset via UART command ... ");
    sprintf(buf, "Re5eT!");           // reset command (same as in STM8 SW!)
    for (i=0; i<6; i++) {
      send_port(ptrPort, 1, buf+i);   // send reset command bytewise to account for slow handling
      SLEEP(10);
    }
    printf("done\n");
    set_baudrate(ptrPort, baudrate);  // restore specified baudrate
  }
  
  // HW reset STM8 using GPIO18 pin (only Raspberry Pi!)
  #ifdef __ARMEL__
    else if (resetSTM8 == 3) {
      printf("  reset via GPIO18 ... ");
      pulse_GPIO(18, 10);
      printf("done\n");
      SLEEP(5);                       // allow BSL to initialize
    }
  #endif // __ARMEL__
  
  // synchronize baudrate
  bsl_sync(ptrPort);
  
  // get bootloader info for selecting flash w/e routines
  bsl_getInfo(ptrPort, &flashsize, &versBSL);

  // select device dependent flash routines for upload
  if ((flashsize==32) && (versBSL==0x10)) {
    ptr = (char*) STM8_Routines_E_W_ROUTINEs_32K_ver_1_0_s19;
    ptr[STM8_Routines_E_W_ROUTINEs_32K_ver_1_0_s19_len]=0;
  }
  else if ((flashsize==32) && (versBSL==0x12)) {
    ptr = (char*) STM8_Routines_E_W_ROUTINEs_32K_ver_1_2_s19;
    ptr[STM8_Routines_E_W_ROUTINEs_32K_ver_1_2_s19_len]=0;
  }
  else if ((flashsize==32) && (versBSL==0x13)) {
    ptr = (char*) STM8_Routines_E_W_ROUTINEs_32K_ver_1_3_s19;
    ptr[STM8_Routines_E_W_ROUTINEs_32K_ver_1_3_s19_len]=0;
  }
  else if ((flashsize==32) && (versBSL==0x14)) {
    ptr = (char*) STM8_Routines_E_W_ROUTINEs_32K_ver_1_4_s19;
    ptr[STM8_Routines_E_W_ROUTINEs_32K_ver_1_4_s19_len]=0;
  }
  else if ((flashsize==128) && (versBSL==0x20)) {
    ptr = (char*) STM8_Routines_E_W_ROUTINEs_128K_ver_2_0_s19;
    ptr[STM8_Routines_E_W_ROUTINEs_128K_ver_2_0_s19_len]=0;
  }
  else if ((flashsize==128) && (versBSL==0x21)) {
    ptr = (char*) STM8_Routines_E_W_ROUTINEs_128K_ver_2_1_s19;
    ptr[STM8_Routines_E_W_ROUTINEs_128K_ver_2_1_s19_len]=0;
  }
  else if ((flashsize==128) && (versBSL==0x22)) {
    ptr = (char*) STM8_Routines_E_W_ROUTINEs_128K_ver_2_2_s19;
    ptr[STM8_Routines_E_W_ROUTINEs_128K_ver_2_2_s19_len]=0;
  }
  else if ((flashsize==128) && (versBSL==0x24)) {
    ptr = (char*) STM8_Routines_E_W_ROUTINEs_128K_ver_2_4_s19;
    ptr[STM8_Routines_E_W_ROUTINEs_128K_ver_2_4_s19_len]=0;
  }
  else if ((flashsize==256) && (versBSL==0x10)) {
    ptr = (char*) STM8_Routines_E_W_ROUTINEs_256K_ver_1_0_s19;
    ptr[STM8_Routines_E_W_ROUTINEs_256K_ver_1_0_s19_len]=0;
  }
  else {
    setConsoleColor(PRM_COLOR_RED);
    fprintf(stderr, "\n\nerror: unsupported device, exit!\n\n");
    Exit(1, g_pauseOnExit);
  }

  {
    char      ramImage[8192];
    uint32_t  ramImageStart;
    uint32_t  numRamBytes;

    convert_s19(ptr, &ramImageStart, &numRamBytes, ramImage);

    if (verbose)
      printf("Uploading RAM routines\n");
    bsl_memWrite(ptrPort, ramImageStart, numRamBytes, ramImage, 0);
  }

  // if specified upload hexfile
  if (strlen(hexfile)>0)
    bsl_memWrite(ptrPort, imageStart, numBytes, image, 1);
  
  // memory read
  //imageStart = 0x8000;  numBytes = 128*1024;   // complete 128kB flash
  //imageStart = 0x00A0;  numBytes = 352;        // RAM
  //bsl_memRead(ptrPort, imageStart, numBytes, image);
  
  
  // enable ROM bootloader after upload (option bytes always on same address)
  if (enableBSL==1) {
    printf("  activate bootloader ... ");
    bsl_memWrite(ptrPort, 0x487E, 2, (char*)"\x55\xAA", 0);
    printf("done\n");
  }
  
  // jump to flash start address after upload (reset vector always on same address)
  if (jumpFlash)
    bsl_jumpTo(ptrPort, 0x8000);
  
  
  ////////
  // clean up and exit
  ////////
  close_port(&ptrPort);
  if (verbose)
    printf("done with program\n");
  Exit(0, g_pauseOnExit);
  
  // avoid compiler warnings
  return(0);
  
} // main
Exemple #14
0
int main(){

	send_port(LPT_DATA, 0);

	return 0;
}