Beispiel #1
0
/*
 * copy a device to a FILE*.
 */
static int raw_copy(char *dev_name, int dev_unit, FILE *dst)
{
    struct MsgPort  *port   = NULL;
    struct IOStdReq *ioreq  = NULL;
    int tracklen            = 512*11;
    int retstatus           = 1;
    int inhibited           = 0;
    char *buffer            = NULL;
    static char name[]      = {'D','F','0','\0'};

    if(!strcmp(dev_name, "trackdisk.device")) {
	inhibited = 1;
	name[2] = '0'+dev_unit;
    }

    /* allocate system stuff */
    if((port   = CreatePort(0, 0)))            {
    if((ioreq  = CreateStdIO(port)))           {
    if((buffer = AllocMem(tracklen, MEMF_CHIP))) {

    /* gain access to the device */
    if(!OpenDevice(dev_name, dev_unit, (struct IORequest*)ioreq, 0)) {

    /* check if a disk is present */
    myDoIO(ioreq, TD_CHANGESTATE, 0, -1, -1, -1);
    if(!ioreq->io_Error && ioreq->io_Actual) {
	fprintf(stderr,"No disk in %s unit %d !\n", dev_name, dev_unit);
	retstatus = 0;
    } else {
	int tr = 0;
	int write_protected = 0;
	/* check if disk is write-protected:
	myDoIO(ioreq, TD_PROTSTATUS, 0, -1, -1, -1);
	if(!ioreq->io_Error && ioreq->io_Actual) write_protected = 1;
	*/

	/* inhibit device */
	if(inhibited) inhibited = dev_inhibit(name,1);

	/* read tracks */
	for(tr = 0; tr < 160; ++tr) {
	    printf("Reading track %2d side %d of %s unit %d  \r",
		   tr/2, tr%2, dev_name, dev_unit);
	    fflush(stdout);
	    myDoIO(ioreq, CMD_READ, -1, tracklen*tr, tracklen, (LONG)buffer);
	    if(ioreq->io_Error) printf("Err. on\n");
	    if(fwrite(buffer, 1, tracklen, dst) != (unsigned int)tracklen) {
	       retstatus = 0;
	       break;
	    }
	}

	/* ok everything done! */
	printf("                                                                        \r");
	fflush(stdout);

	/* stop motor */
	myDoIO(ioreq, TD_MOTOR, 0, -1, 0, -1);

	/* uninhibit */
	if(inhibited) dev_inhibit(name,0);
    }
    CloseDevice((struct IORequest*)ioreq);   } else retstatus = 0;
    FreeMem(buffer,tracklen);                } else retstatus = 0;
    DeleteStdIO(ioreq);                      } else retstatus = 0;
    DeletePort(port);                        } else retstatus = 0;
    return retstatus;
}
Beispiel #2
0
/****************************************************************************
*
*    FUNCTION: LoadDeviceDriver( const TCHAR, const TCHAR, HANDLE *)
*
*    PURPOSE: Registers a driver with the system configuration manager 
*	 and then loads it.
*
****************************************************************************/
BOOL LoadDeviceDriver( const TCHAR * Name, const TCHAR * Path, 
					  HANDLE * lphDevice, PDWORD Error, BOOL extended)
{
	SC_HANDLE	schSCManager;
	BOOL		okay;
	if (extended)
	{
		schSCManager = OpenSCManager( NULL, NULL, SC_MANAGER_ALL_ACCESS );
		if (schSCManager != NULL)
		{
	
			// Remove old instances
			//RemoveDriver( schSCManager, Name );

			// Ignore success of installation: it may already be installed.
			okay = InstallDriver( schSCManager, Name, Path );
/*			if (okay == FALSE)
			{
				if (Error != NULL)
					*Error = GetLastError();
				CloseServiceHandle( schSCManager );
				return FALSE;
			}
*/
			// Ignore success of start: it may already be started.
			okay = StartDriver( schSCManager, Name );
			if (okay == FALSE)
			{
				if (Error != NULL)
				{
					*Error = GetLastError();
					if ((*Error != ERROR_SERVICE_ALREADY_RUNNING))
					{
						CloseServiceHandle( schSCManager );
						return FALSE;
					}
				}
				else
				{
					CloseServiceHandle( schSCManager );
					return FALSE;
				}
			}
		
			CloseServiceHandle( schSCManager );
		}
		else {
			if (Error != NULL)
				*Error = GetLastError();
			return FALSE;
		}
	}
	// Do make sure we can open it.
	okay = OpenDevice( Name, lphDevice );
	if (okay == FALSE)
	{
		if (Error != NULL)
			*Error = GetLastError();
	}
 
	return okay;
}
Beispiel #3
0
int LIBFUNC L_Module_Entry(
	REG(a0, struct List *files),
	REG(a1, struct Screen *screen),
	REG(a2, IPCData *ipc),
	REG(a3, IPCData *main_ipc),
	REG(d0, ULONG mod_id),
	REG(d1, ULONG mod_data))
{
	struct IOAudio audio;
	struct MsgPort *reply_port;

	// Flash only?
	if (mod_id==FLASH)
	{
		DisplayBeep(screen);
		return 1;
	}

	// Create port
	if (!(reply_port=CreateMsgPort()))
		return 0;

	// Fill out audio request
	audio.ioa_Request.io_Message.mn_ReplyPort=reply_port;
	audio.ioa_Request.io_Message.mn_Node.ln_Pri=90;
	audio.ioa_Data=achannels;
	audio.ioa_Length=sizeof(achannels);

	// Open audio device
	if (!(OpenDevice("audio.device",0,(struct IORequest *)&audio,0)))
	{
		// Initialise write command
		audio.ioa_Request.io_Command=CMD_WRITE;
		audio.ioa_Request.io_Flags=ADIOF_PERVOL;
		audio.ioa_Volume=64;
		audio.ioa_Data=(UBYTE *)beepwave;

		// It's an alarm?
		if (mod_id==ALARM)
		{
			short a;

			// Waveform size
			audio.ioa_Length=8;

			// Standard length
			audio.ioa_Cycles=60;

			// Five cycles
			for (a=0;a<5;a++)
			{
				// High tone
				audio.ioa_Period=800;

				// Play sound
				BeginIO((struct IORequest *)&audio);
				WaitIO((struct IORequest *)&audio);

				// Low tone
				audio.ioa_Period=1200;

				// Play sound
				BeginIO((struct IORequest *)&audio);
				WaitIO((struct IORequest *)&audio);
			}
		}

		// Waveform size
		else audio.ioa_Length=sizeof(beepwave);

		// Set note information
		audio.ioa_Period=(mod_id==BEEP)?300:800;
		audio.ioa_Cycles=(mod_id==BEEP)?100:60;

		// Play sound
		BeginIO((struct IORequest *)&audio);
		WaitIO((struct IORequest *)&audio);

		// Close audio device
		CloseDevice((struct IORequest *)&audio);
	}

	// Delete message port
	DeleteMsgPort(reply_port);
	return 1;
}
Beispiel #4
0
int
main(
    int		argc,
    char **	argv)
{
  int loaded;
  int target = -1;
  int oldtarget;
  command com;   /* a little DOS joke */
  
  /*
   * drive_num really should be something from the config file, but..
   * for now, it is set to zero, since most of the common changers
   * used by amanda only have one drive ( until someone wants to 
   * use an EXB60/120, or a Breece Hill Q45.. )
   */
  int    drive_num = 0;
  int need_eject = 0; /* Does the drive need an eject command ? */
  unsigned need_sleep = 0; /* How many seconds to wait for the drive to get ready */
  int clean_slot = -1;
  int maxclean = 0;
  char *clean_file=NULL;
  char *time_file=NULL;

  int use_slots;
  int slot_offset;
  int confnum;

  int fd, slotcnt, drivecnt;
  int endstatus = 0;
  char *changer_dev = NULL;
  char *tape_device = NULL;
  char *changer_file = NULL;
  char *scsitapedevice = NULL;

  /*
   * Configure program for internationalization:
   *   1) Only set the message locale for now.
   *   2) Set textdomain for all amanda related programs to "amanda"
   *      We don't want to be forced to support dozens of message catalogs.
   */  
  setlocale(LC_MESSAGES, "C");
  textdomain("amanda"); 

  set_pname("chg-scsi");

  /* Don't die when child closes pipe */
  signal(SIGPIPE, SIG_IGN);

  dbopen(DBG_SUBDIR_SERVER);
  parse_args(argc,argv,&com);

  changer = alloc(SIZEOF(changer_t));
  config_init(CONFIG_INIT_USE_CWD, NULL);

  if (config_errors(NULL) >= CFGERR_WARNINGS) {
    config_print_errors();
    if (config_errors(NULL) >= CFGERR_ERRORS) {
      g_critical(_("errors processing config file"));
    }
  }

  changer_dev = getconf_str(CNF_CHANGERDEV);
  changer_file = getconf_str(CNF_CHANGERFILE);
  tape_device = getconf_str(CNF_TAPEDEV);

  /* Get the configuration parameters */

  if (strlen(tape_device)==1){
    read_config(changer_file, changer);
    confnum=atoi(tape_device);
    use_slots    = changer->conf[confnum].end-changer->conf[confnum].start+1;
    slot_offset  = changer->conf[confnum].start;
    drive_num    = changer->conf[confnum].drivenum;
    need_eject   = changer->eject;
    need_sleep   = changer->sleep;
    clean_file   = stralloc(changer->conf[confnum].cleanfile);
    clean_slot   = changer->conf[confnum].cleanslot;
    maxclean     = changer->cleanmax;
    if (NULL != changer->conf[confnum].timefile)
      time_file = stralloc(changer->conf[confnum].timefile);
    if (NULL != changer->conf[confnum].slotfile)
      changer_file = stralloc(changer->conf[confnum].slotfile);
    else
      changer_file = NULL;
    if (NULL != changer->conf[confnum].device)
      tape_device  = stralloc(changer->conf[confnum].device);
    if (NULL != changer->device)
      changer_dev  = stralloc(changer->device); 
    if (NULL != changer->conf[confnum].scsitapedev)
      scsitapedevice = stralloc(changer->conf[confnum].scsitapedev);
    if (NULL != changer->conf[confnum].tapestatfile)
      tapestatfile = stralloc(changer->conf[confnum].tapestatfile);
    dump_changer_struct(changer);
    /* get info about the changer */
    fd = OpenDevice(INDEX_CHANGER , changer_dev,
			"changer_dev", changer->conf[confnum].changerident);
    if (fd == -1) {
      int localerr = errno;
      g_fprintf(stderr, _("%s: open: %s: %s\n"), get_pname(), 
              changer_dev, strerror(localerr));
      g_printf(_("%s open: %s: %s\n"), "<none>", changer_dev, strerror(localerr));
      dbprintf(_("open: %s: %s\n"), changer_dev, strerror(localerr));
      return 2;
    }

    if (tape_device == NULL)
      {
        tape_device = stralloc(changer_dev);
      }

    if (scsitapedevice == NULL)
      {
         scsitapedevice = stralloc(tape_device);
      }

    if ((changer->conf[confnum].end == -1) || (changer->conf[confnum].start == -1)){
      slotcnt = get_slot_count(fd);
      use_slots    = slotcnt;
      slot_offset  = 0;
    }
    free_changer_struct(&changer);
  } else {
    /* get info about the changer */
    confnum = 0;
    fd = OpenDevice(INDEX_CHANGER , changer_dev,
			"changer_dev", changer->conf[confnum].changerident);
    if (fd == -1) {
      int localerr = errno;
      g_fprintf(stderr, _("%s: open: %s: %s\n"), get_pname(), 
              changer_dev, strerror(localerr));
      g_printf(_("%s open: %s: %s\n"), _("<none>"), changer_dev, strerror(localerr));
      dbprintf(_("open: %s: %s\n"), changer_dev, strerror(localerr));
      return 2;
    }
    slotcnt = get_slot_count(fd);
    use_slots    = slotcnt;
    slot_offset  = 0;
    drive_num    = 0;
    need_eject   = 0;
    need_sleep   = 0;
  }

  drivecnt = get_drive_count(fd);

  if (drive_num > drivecnt) {
    g_printf(_("%s drive number error (%d > %d)\n"), _("<none>"), 
           drive_num, drivecnt);
    g_fprintf(stderr, _("%s: requested drive number (%d) greater than "
            "number of supported drives (%d)\n"), get_pname(), 
            drive_num, drivecnt);
    dbprintf(_("requested drive number (%d) greater than "
              "number of supported drives (%d)\n"), drive_num, drivecnt);
    CloseDevice("", fd);
    return 2;
  }

  loaded = drive_loaded(fd, drive_num);

  switch(com.command_code) {
  case COM_SLOT:  /* slot changing command */
    if (is_positive_number(com.parameter)) {
      if ((target = atoi(com.parameter))>=use_slots) {
        g_printf(_("<none> no slot `%d'\n"),target);
        close(fd);
        endstatus = 2;
        break;
      } else {
        target = target+slot_offset;
      }
    } else
      target=get_relative_target(fd, use_slots,
                                 com.parameter,
                                 loaded, 
                                 changer_file,slot_offset,slot_offset+use_slots);
    if (loaded) {
      if (changer_file != NULL)
        {
          oldtarget=get_current_slot(changer_file);
        } else {
          oldtarget = GetCurrentSlot(fd, drive_num);
        }
      if ((oldtarget)!=target) {
        if (need_eject)
          eject_tape(scsitapedevice, need_eject);
        (void)unload(fd, drive_num, oldtarget);
        if (ask_clean(scsitapedevice))
          clean_tape(fd,tape_device,clean_file,drive_num,
                     clean_slot,maxclean,time_file);
        loaded=0;
      }
    }
    if (changer_file != NULL)
      {
      put_current_slot(changer_file, target);
    }
    if (!loaded && isempty(fd, target)) {
      g_printf(_("%d slot %d is empty\n"),target-slot_offset,
             target-slot_offset);
      close(fd);
      endstatus = 1;
      break;
    }
    if (!loaded)
      if (load(fd, drive_num, target) != 0) {
        g_printf(_("%d slot %d move failed\n"),target-slot_offset,
               target-slot_offset);  
        close(fd);
        endstatus = 2;
        break;
      }
    if (need_sleep)
      Tape_Ready1(scsitapedevice, need_sleep);
    g_printf(_("%d %s\n"), target-slot_offset, tape_device);
    break;

  case COM_INFO:
    if (changer_file != NULL)
      {
        g_printf("%d ", get_current_slot(changer_file)-slot_offset);
      } else {
        g_printf("%d ", GetCurrentSlot(fd, drive_num)-slot_offset);
      }
    g_printf("%d 1\n", use_slots);
    break;

  case COM_RESET:
    if (changer_file != NULL)
      {
        target=get_current_slot(changer_file);
      } else {
        target = GetCurrentSlot(fd, drive_num);
      }
    if (loaded) {
      if (!isempty(fd, target))
        target=find_empty(fd,0 ,0);
      if (need_eject)
        eject_tape(scsitapedevice, need_eject);
      (void)unload(fd, drive_num, target);
      if (ask_clean(scsitapedevice))
        clean_tape(fd,tape_device,clean_file,drive_num,clean_slot,
                   maxclean,time_file);
    }

    if (isempty(fd, slot_offset)) {
      g_printf(_("0 slot 0 is empty\n"));
      close(fd);
      endstatus = 1;
      break;
    }

    if (load(fd, drive_num, slot_offset) != 0) {
      g_printf(_("%d slot %d move failed\n"),slot_offset,
             slot_offset);  
      close(fd);
      endstatus = 2;
      break;
    }
    if (changer_file != NULL)
    {
      put_current_slot(changer_file, slot_offset);
    }
    if (need_sleep)
      Tape_Ready1(scsitapedevice, need_sleep);
    if (changer_file != NULL)
      {
        g_printf("%d %s\n", get_current_slot(changer_file), tape_device);
      } else {
        g_printf("%d %s\n", GetCurrentSlot(fd, drive_num), tape_device);
      }
    break;

  case COM_EJECT:
    if (loaded) {
      if (changer_file != NULL)
        {
          target=get_current_slot(changer_file);
        } else {
          target = GetCurrentSlot(fd, drive_num);
        }
      if (need_eject)
        eject_tape(scsitapedevice, need_eject);
      (void)unload(fd, drive_num, target);
      if (ask_clean(scsitapedevice))
        clean_tape(fd,tape_device,clean_file,drive_num,clean_slot,
                   maxclean,time_file);
      g_printf("%d %s\n", target, tape_device);
    } else {
      g_printf(_("%d drive was not loaded\n"), target);
      endstatus = 1;
    }
    break;
  case COM_CLEAN:
    if (loaded) {
      if (changer_file  != NULL)
        {
          target=get_current_slot(changer_file);
        } else {
          target = GetCurrentSlot(fd, drive_num);
        }
      if (need_eject)
        eject_tape(scsitapedevice, need_eject);
      (void)unload(fd, drive_num, target);
    } 
    clean_tape(fd,tape_device,clean_file,drive_num,clean_slot,
               maxclean,time_file);
    g_printf(_("%s cleaned\n"), tape_device);
    break;
  };

  CloseDevice("", 0);
  dbclose();
  return endstatus;
}
Beispiel #5
0
int cd_opendevice (int unit, void *ioreq, uint32 flags)
{
	struct FSReq *fsreq = ioreq;
	struct CDSB *cdsb;
	struct MountEnviron *me;
	struct BlkReq blkreq;
	
	
	KPRINTF ("cd_opendevice ()");
	
	
	if ((cdsb = KMalloc (sizeof (struct CDSB))) != NULL)
	{
		me = fsreq->me;
		
		
		if (OpenDevice (me->device_name, me->device_unit, &blkreq, me->device_flags) == 0)
		{	
			/* FIXME:  Shouldn't need it (also in fat handler) */
			MemSet (cdsb, 0, sizeof (struct CDSB)); /* Need it as cdsb->validated isn't initialized */
			
			cdsb->device = blkreq.device;
			cdsb->unitp = blkreq.unitp;
			cdsb->me = fsreq->me;
			cdsb->reference_cnt = 0;
							
			LIST_INIT (&cdsb->node_list);
			LIST_INIT (&cdsb->active_filp_list);
			LIST_INIT (&cdsb->invalid_filp_list);
			
			cdsb->root_node.flags = ISO_DIRECTORY;
			cdsb->root_node.cdsb = cdsb;
			cdsb->root_node.reference_cnt = 0;
			
			if ((cdsb->buf = CreateBuf (cdsb->device, cdsb->unitp,
							me->buffer_cnt, me->block_size,
							me->partition_start, me->partition_end,
							me->writethru_critical, me->writeback_delay,
							me->max_transfer)) != NULL)
			{
				if (KSpawn (CDTask, cdsb, 10, "cd.handler") != -1)
				{		
					KWait (SIGF_INIT);
					
					RWWriteLock (&mountlist_rwlock);
					cd_device.reference_cnt ++;
					
					cdsb->device_mount = MakeMount (cdsb->me, &cd_device, cdsb);
					AddMount (cdsb->device_mount);
					
					RWUnlock (&mountlist_rwlock);

					fsreq->unitp = cdsb;
					fsreq->error = 0;
					fsreq->rc = 0;
					return 0;
				}
			}
		
			CloseDevice (&blkreq);
		}
		
		KFree (cdsb);
	}
	
	fsreq->error = IOERR_OPENFAIL;
	fsreq->rc = -1;
	
	KPANIC ("CD OpenDevice FAIL");
	return -1;
}
Beispiel #6
0
void SCSIInit(void)
{
	int id, lun;

	int memtype = PrefsFindInt32("scsimemtype");
	switch (memtype) {
		case 1:
			buffer_memf = MEMF_24BITDMA | MEMF_PUBLIC;
			break;
		case 2:
			buffer_memf = MEMF_ANY | MEMF_PUBLIC;
			direct_transfers_supported = true;
			break;
		default:
			buffer_memf = MEMF_CHIP | MEMF_PUBLIC;
			break;
	}

	// Create port and buffers
	the_port = CreateMsgPort();
	buffer = (UBYTE *)AllocMem(buffer_size = 0x10000, buffer_memf);
	sense_buffer = (UBYTE *)AllocMem(SENSE_LENGTH, MEMF_CHIP | MEMF_PUBLIC);
	if (the_port == NULL || buffer == NULL || sense_buffer == NULL) {
		ErrorAlert(STR_NO_MEM_ERR);
		QuitEmulator();
	}

	// Create and open IORequests for all 8 units (and all 8 LUNs)
	for (id=0; id<8; id++) {
		for (lun=0; lun<8; lun++)
			ios[id*8+lun] = NULL;
		char prefs_name[16];
		sprintf(prefs_name, "scsi%d", id);
		const char *str = PrefsFindString(prefs_name);
		if (str) {
			char dev_name[256];
			ULONG dev_unit = 0;
			if (sscanf(str, "%[^/]/%ld", dev_name, &dev_unit) == 2) {
				for (lun=0; lun<8; lun++) {
					struct IOStdReq *io = (struct IOStdReq *)CreateIORequest(the_port, sizeof(struct IOStdReq));
					if (io == NULL)
						continue;
					if (OpenDevice((UBYTE *) dev_name, dev_unit + lun * 10, (struct IORequest *)io, 0)) {
						DeleteIORequest(io);
						continue;
					}
					io->io_Data = &scsi;
					io->io_Length = sizeof(scsi);
					io->io_Command = HD_SCSICMD;
					ios[id*8+lun] = io;
				}
			}
		}
	}

	// Reset SCSI bus
	SCSIReset();

	// Init SCSICmd
	memset(&scsi, 0, sizeof(scsi));
	scsi.scsi_Command = cmd_buffer;
	scsi.scsi_SenseData = sense_buffer;
	scsi.scsi_SenseLength = SENSE_LENGTH;
}
Beispiel #7
0
int main(int argc, char **argv) {
	if( argc != 2 && argc != 3 ) {
		printf( "Usage: c64 <command> [filename]\n" );
		printf( "Commands:\n" );
		printf( "     upload <filename>      - Uploads CRT image to C64FC\n" );
		printf( "     download <filename>    - Downloads image from C64FC (not implemented)\n");
		printf( "     reset                  - Resets the C64\n" );
		printf( "     clear                  - Clears the entire C64FC, writes 0x0 to every address\n");
		printf( "     hexdump                - Prints a hexdump of the entire cart\n");
		printf( "     bootloader             - Enters bootloader mode on cart\n");
		printf( "     ramsize                - Prints your EEPROM size\n");
		printf( "     chardump <fps>         - Takes stdout from pipe and dump it on screen\n");
		return( 1 );
	}

	if( OpenDevice() ) {
		printf( "C64FC not found\n" );
		return( 1 );
	}





	if( (strcasecmp( argv[1], "reset" ) == 0) && (argc == 2) ) {
		/* 
		 * Issues a Reset of the C64 
		 */
		Reset();


	} else 	if( (strcasecmp( argv[1], "bootloader" ) == 0) && (argc == 2) ) {
		/*
		 * Makes the cart enter bootloader mode, this mode needs a power cycle of the cart to exit from
		 */
		EnterBootloader();	


	} else if( (strcasecmp( argv[1], "upload" ) == 0) && (argc == 3) ) {
		/*
		 * Uploads data to the cart
		 */
		int skip = 0;
		FILE *fp = fopen( argv[2], "rb" );
		if( !fp ) {
			printf( "Can't open input file for reading\n" );
			return( 1 );
		}
		fseek( fp, 0L, SEEK_END );
		int len = ftell( fp );
		fseek( fp, 0L, SEEK_SET );
		unsigned char *array = malloc( len );
		fread( array, len, 1, fp );
		fclose( fp );
		if( array[0] == 'C' && array[1] == '6' && array[2] == '4' ) {
			skip = 80;
		}
		printf( "Sending data (%d bytes)..\n", len-skip );
		WriteData( 0, array+skip, len-skip );
		if( len-skip >= 8192 ) {
			Set16KMode();
		} else {
			Set8KMode();
		}
		printf( "Issuing reset..\n" );
		Reset();


	} else 	if( (strcasecmp( argv[1], "clear" ) == 0) && (argc == 2) ) {
		/*
		 * Clears the content of the entire C64FC
		 */



	} else if ((strcasecmp( argv[1], "fubar" ) == 0) && (argc == 2)) {
		/* 
		 * Runars test function
		 * Actually.. does nothing more than return fubar in hex to the user... :)
		 */
		char buff[10];
		int len = getFubar(buff);
		printf("getFubar: %s(%d)\n", buff, len);
		hexdump(0, buff, 10);

	} else if ((strcasecmp( argv[1], "hexdump" ) == 0) && (argc == 2)) {
		/* 
		 * Make a hexdump of the current register in the cart
		 */
		char buff[128];
		printf("Hexdump of cart:\n");
		int i;
		for (i = 0; i < 0x3FFF; i += 128) {
			memset(buff, 0x0, 128);
			int len = getData(i, buff,128);
			//printf("getData: %d(%d)\n", i, len);
			hexdump(i, buff, 128);
			//printf("\n");
		}

	} else if ((strcasecmp( argv[1], "ramsize" ) == 0) && (argc == 2)) {
		/* 
		 * Check if your cart is 8k or 16k..
		 * .. Thats it.. :) 
		 */
		unsigned int size = GetRamSize();
		printf("Your RAM is a %dkb chip\n", size);


	} else {
		/* 
		 * Command not understood... yea yea... 
		 */
		printf( "WHAT? WHAT\n" );
		return( 1 );
	}


	CloseDevice();
	return( 0 );

}
Beispiel #8
0
NTSTATUS
InsertAudioDevice(
    IN PDEVICE_OBJECT DeviceObject,
    IN PUNICODE_STRING DeviceName)
{
    NTSTATUS Status = STATUS_SUCCESS;
    PSYSAUDIODEVEXT DeviceExtension;
    PKSAUDIO_DEVICE_ENTRY DeviceEntry = NULL;

    /* a new device has arrived */
    DeviceEntry = AllocateItem(NonPagedPool, sizeof(KSAUDIO_DEVICE_ENTRY));
    if (!DeviceEntry)
    {
        /* no memory */
        return STATUS_INSUFFICIENT_RESOURCES;
    }

    /* initialize audio device entry */
    RtlZeroMemory(DeviceEntry, sizeof(KSAUDIO_DEVICE_ENTRY));

    /* set device name */
    DeviceEntry->DeviceName.Length = 0;
    DeviceEntry->DeviceName.MaximumLength = DeviceName->MaximumLength + 10 * sizeof(WCHAR);

    DeviceEntry->DeviceName.Buffer = AllocateItem(NonPagedPool, DeviceEntry->DeviceName.MaximumLength);

    if (!DeviceEntry->DeviceName.Buffer)
    {
        Status = STATUS_INSUFFICIENT_RESOURCES;
        goto cleanup;
    }

    /* open device */
    Status = OpenDevice(DeviceName, &DeviceEntry->Handle, &DeviceEntry->FileObject);
    if (NT_SUCCESS(Status))
    {
        /* copy device name */
        RtlAppendUnicodeStringToString(&DeviceEntry->DeviceName, DeviceName);
    }
    else
    {
        /* the device name needs to be prefixed */
        RtlAppendUnicodeToString(&DeviceEntry->DeviceName, L"\\??\\");
        RtlAppendUnicodeStringToString(&DeviceEntry->DeviceName, DeviceName);

        /* open device */
        Status = OpenDevice(&DeviceEntry->DeviceName, &DeviceEntry->Handle, &DeviceEntry->FileObject);
    }

    if (!NT_SUCCESS(Status))
    {
        goto cleanup;
    }

    /* fetch device extension */
    DeviceExtension = (PSYSAUDIODEVEXT)DeviceObject->DeviceExtension;
    /* insert new audio device */
    ExInterlockedInsertTailList(&DeviceExtension->KsAudioDeviceList, &DeviceEntry->Entry, &DeviceExtension->Lock);
    InterlockedIncrement((PLONG)&DeviceExtension->NumberOfKsAudioDevices);

    DPRINT("Successfully opened audio device %u Device %S\n", DeviceExtension->NumberOfKsAudioDevices, DeviceEntry->DeviceName.Buffer);
    return Status;

cleanup:
    if (DeviceEntry)
    {
        if (DeviceEntry->DeviceName.Buffer)
            FreeItem(DeviceEntry->DeviceName.Buffer);

        FreeItem(DeviceEntry);
    }

    return Status;

}
Beispiel #9
0
// Open a disk for IO
DiskHandle *LIBFUNC L_OpenDisk(
    REG(a0, char *disk),
    REG(a1, struct MsgPort *port))
{
    DiskHandle *handle;
    struct DosList *dl;
    unsigned long blocks;
    char *ptr;

    // Allocate handle
    if (!(handle=AllocVec(sizeof(DiskHandle),MEMF_CLEAR)))
        return 0;

    // Copy name, strip colon
    stccpy(handle->dh_name,disk,31);
    if ((ptr=strchr(handle->dh_name,':'))) *ptr=0;

    // Lock DOS list
    dl=LockDosList(LDF_DEVICES|LDF_READ);

    // Find entry
    if (!(dl=FindDosEntry(dl,handle->dh_name,LDF_DEVICES)))
    {
        // Not found
        UnLockDosList(LDF_DEVICES|LDF_READ);
        FreeVec(handle);
        return 0;
    }

    // Add colon back on
    strcat(handle->dh_name,":");

    // Get pointer to startup message and geometry
    handle->dh_startup=(struct FileSysStartupMsg *)BADDR(dl->dol_misc.dol_handler.dol_Startup);
    handle->dh_geo=(struct DosEnvec *)BADDR(handle->dh_startup->fssm_Environ);

    // Shortcuts to root block and blocksize
    blocks=handle->dh_geo->de_BlocksPerTrack*
           handle->dh_geo->de_Surfaces*
           (handle->dh_geo->de_HighCyl-handle->dh_geo->de_LowCyl+1);
    handle->dh_root=(blocks-1+handle->dh_geo->de_Reserved)>>1;
    handle->dh_blocksize=handle->dh_geo->de_SizeBlock<<2;

    // Get real device name
    L_BtoCStr((BPTR)handle->dh_startup->fssm_Device,handle->dh_device,32);

    // Get information
#ifdef __AROS__
    if (((struct Library *)DOSBase)->lib_Version<50)
    {
        //handle->dh_result=Info(dl->dol_Lock,&handle->dh_info);
        BPTR lock;
        handle->dh_result=0;
        if ((lock=Lock(handle->dh_name,SHARED_LOCK)))
        {
            handle->dh_result=Info(lock,&handle->dh_info);
            UnLock(lock);
        }
    }
    else
#endif
        handle->dh_result=DoPkt(dl->dol_Task,ACTION_DISK_INFO,MKBADDR(&handle->dh_info),0,0,0,0);

    // Unlock dos list
    UnLockDosList(LDF_DEVICES|LDF_READ);

    // Create message port if needed
    if (!port)
    {
        if (!(handle->dh_port=CreateMsgPort()))
        {
            FreeVec(handle);
            return 0;
        }
        port=handle->dh_port;
    }

    // Create IO request
    if (!(handle->dh_io=(struct IOExtTD *)CreateIORequest(port,sizeof(struct IOExtTD))))
    {
        if (handle->dh_port) DeleteMsgPort(handle->dh_port);
        FreeVec(handle);
        return 0;
    }

    // Open device
    if (OpenDevice(
                handle->dh_device,
                handle->dh_startup->fssm_Unit,
                (struct IORequest *)handle->dh_io,
                handle->dh_startup->fssm_Flags))
    {
        // Failed to open
        L_CloseDisk(handle);
        return 0;
    }

    return handle;
}
Beispiel #10
0
// Open libraries
void startup_open_libraries()
{
    BPTR file;
    long seed=0;

    // Open the other libraries that we need
    if (!(GfxBase=(struct GfxBase *)main_open_library("graphics.library",37)) ||
            !(IntuitionBase=(struct IntuitionBase *)main_open_library("intuition.library",37)) ||
            !(LayersBase=main_open_library("layers.library",37)) ||
            !(DiskfontBase=main_open_library("diskfont.library",36)) ||
            !(IconBase=main_open_library("icon.library",37)) ||
            !(WorkbenchBase=main_open_library("workbench.library",37)) ||
            !(CxBase=main_open_library("commodities.library",37)) ||
            !(UtilityBase=(struct UtilityBase *)main_open_library("utility.library",37)) ||
            !(GadToolsBase=main_open_library("gadtools.library",37)) ||
            !(RexxSysBase=main_open_library("rexxsyslib.library",0)) ||
            !(AslBase=main_open_library("asl.library",37))) quit(0);

#ifdef __amigaos4__
    // obtain ifaces
    if (!(IGraphics=(struct GraphicsIFace *)GetInterface((struct Library *)GfxBase,"main",1,NULL)) ||
            !(IIntuition=(struct IntuitionIFace *)GetInterface((struct Library *)IntuitionBase,"main",1,NULL)) ||
            !(ILayers=(struct LayersIFace *)GetInterface(LayersBase,"main",1,NULL)) ||
            !(IDiskfont=(struct DiskfontIFace *)GetInterface(DiskfontBase,"main",1,NULL)) ||
            !(IIcon=(struct IconIFace *)GetInterface(IconBase,"main",1,NULL)) ||
            !(IWorkbench=(struct WorkbenchIFace *)GetInterface(WorkbenchBase,"main",1,NULL)) ||
            !(ICommodities=(struct CommoditiesIFace *)GetInterface(CxBase,"main",1,NULL)) ||
            !(IUtility=(struct UtilityIFace *)GetInterface((struct Library *)UtilityBase,"main",1,NULL)) ||
            !(IGadTools=(struct GadToolsIFace *)GetInterface(GadToolsBase,"main",1,NULL)) ||
            !(IRexxSys=(struct RexxSysIFace *)GetInterface(RexxSysBase,"main",1,NULL)) ||
            !(IAsl=(struct AslIFace *)GetInterface(AslBase,"main",1,NULL))) quit(0);
#endif


    // Some other useful libraries
    DataTypesBase=OpenLibrary("datatypes.library",0);
    AmigaGuideBase=OpenLibrary("amigaguide.library",0);
    NewIconBase=OpenLibrary("newicon.library",0);
#ifdef __amigaos4__
    IDataTypes=(struct DataTypesIFace *)GetInterface(DataTypesBase,"main",1,NULL);
    IAmigaGuide=(struct AmigaGuideIFace *)GetInterface(AmigaGuideBase,"main",1,NULL);
    INewIcon=(struct NewIconIFace *)GetInterface(NewIconBase,"main",1,NULL);
#endif


    // Is CyberGfx library already in system? If so, open it for ourselves
    if (FindName(&SysBase->LibList,"cybergraphics.library")) {
        CyberGfxBase=OpenLibrary("cybergraphics.library",0);
#ifdef __amigaos4__
        ICyberGfx=(struct CyberGfxIFace *)GetInterface(CyberGfxBase,"main",1,NULL);
#endif
    }

    // Get input.device base
#ifdef __AROS__
    input_req.io_Message.mn_Length = sizeof(input_req);
#endif
    if (!OpenDevice("input.device",0,(struct IORequest *)&input_req,0)) {
        InputBase=(struct Library *)input_req.io_Device;
#ifdef __amigaos4__
        IInput = (struct InputIFace *)GetInterface(InputBase,"main",1,NULL);
#endif
    }

    // Get timer.device base
    if (!OpenDevice("timer.device",0,(struct IORequest *)&timer_req,0)) {
        TimerBase=(APTR)timer_req.io_Device;
#ifdef __amigaos4__
        ITimer = (struct TimerIFace *)GetInterface((struct Library *)TimerBase,"main",1,NULL);
#endif
    }
    else {
        quit(0);
    }

    // Get console.device base
    if (!OpenDevice("console.device",-1,(struct IORequest *)&console_req,0)) {
        ConsoleDevice=(APTR)console_req.io_Device;
#ifdef __amigaos4__
        IConsole = (struct ConsoleIFace *)GetInterface((struct Library *)ConsoleDevice,"main",1,NULL);
#endif
    }
    else {
        quit(0);
    };

    // Seed random number with something interesting
    if ((file=Open("dopus5:system/seed",MODE_OLDFILE)))
    {
        char buf[20];
        Read(file,buf,20);
        Close(file);
        seed=atoi((buf[0]=='-'?buf+1:buf));
    }
    seed+=(long)IntuitionBase+(long)AslBase*(long)WorkbenchBase*IntuitionBase->Micros;
    Seed(seed);
}
Beispiel #11
0
static int SynoddOne(char *szDev, BOOL blRead)
{
	int err = -1;
	int fd = -1;
	int counts = 0;
	ssize_t lProgressBytes = 0;
	unsigned long long ullProgTotalBytes = 0;
	unsigned long long ullTotalBytes = 0;
	FILE *fp = NULL;

	if (!szDev) {
		return -1;
	}
	
	if (0 > (fd = OpenDevice(szDev, blRead, 0))){
		err = errno;
		goto END;
	}

	if (0 > CheckDevice(fd, &ullTotalBytes)){
		err = errno;
		syslog(LOG_ERR, "%s(%d) failed to check [%s].", __FILE__, __LINE__, szDev);
		goto END;
	}

	//Open Progress File
	if (NULL == (fp = OpenProgress(szDev))) {
		goto END;
	}

	err = 0;
	while(1) {
		if (COUNTS_TO_CHECK == counts) {
			counts = 0;
			
			if (fd >= 0) {
				close(fd);
			}
			if (0 > (fd = OpenDevice(szDev, blRead, ullProgTotalBytes))){
				err = errno;
				goto END;
			}
		}
		if (blRead) {
			lProgressBytes = read(fd, gszBuf, sizeof(gszBuf));
		} else {
			lProgressBytes = write(fd, gszBuf, sizeof(gszBuf));
		}
		if (0 > lProgressBytes) {
			if (ENOSPC != errno) {
				syslog(LOG_ERR, "(%s/%d) %s [%s] failed, errno=%m"
					   ,__FILE__ ,__LINE__ , blRead?"read":"write", szDev);
				err = errno;
			}
			goto END;
		}
		ullProgTotalBytes += lProgressBytes;

		WriteProgress(fp, ullProgTotalBytes, ullTotalBytes);
		if (ullTotalBytes <= ullProgTotalBytes) {
			break;
		}

		counts++;
	}
END:
	if (0 <= fd) close(fd);
	if (NULL != fp) fclose(fp);
	return err;
}
Beispiel #12
0
void CDiskImageStream::Open(LPCWSTR name, TOpenMode mode)
{ 
  PARTITION_INFORMATION_EX partInfo;
  DISK_GEOMETRY diskGeometry;
  NTFS_VOLUME_DATA_BUFFER ntfsVolData;
  GET_LENGTH_INFORMATION lengthInfo;
  DWORD dummy, res;
  long ntStatus;
  bool isRawDisk;
  DWORD shareMode, options;
  
  fName = name;
  fOpenMode = mode;
  isRawDisk = fName.find(L"Partition0") != std::string::npos;
  options = FILE_SYNCHRONOUS_IO_NONALERT | FILE_RANDOM_ACCESS | FILE_NON_DIRECTORY_FILE;
  if (isRawDisk) {
    shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
    ntStatus = OpenDevice(shareMode);
    CHECK_KERNEL_EX_HANDLE_PARAM1(ntStatus, EWinException::volumeOpenError, fName.c_str());
    ATLTRACE("Opened raw disk device: %S with handle %u\n", name, fHandle);
    if (fContainedVolumeCount > 0) {
      std::wstring rootName = fName.substr(0, fName.length() - 1);
      fSubVolumeLocker = new CSubVolumeLocker(rootName.c_str(), fContainedVolumeCount);
    }
    ReadDriveLayout();
  } else {    
    shareMode = FILE_SHARE_DELETE | FILE_SHARE_WRITE | FILE_SHARE_READ;
    ntStatus = OpenDevice(shareMode);
    CHECK_KERNEL_EX_HANDLE_PARAM1(ntStatus, EWinException::volumeOpenError, fName.c_str());
  }
  
  if (fOpenMode == forReading) {
    memset(&partInfo, 0, sizeof(partInfo));
    memset(&diskGeometry, 0, sizeof(diskGeometry));
    memset(&lengthInfo, 0, sizeof(lengthInfo));
    memset(&ntfsVolData, 0, sizeof(ntfsVolData));
    res = DeviceIoControl(fHandle, IOCTL_DISK_GET_PARTITION_INFO_EX, NULL, 0, &partInfo, sizeof(partInfo), &dummy, NULL);
    //CHECK_OS_EX_PARAM1(res, EWinException::ioControlError, L"IOCTL_DISK_GET_PARTITION_INFO_EX");
    // on some disks this might fail try PARTITION_INFORMATION then
    if (res==0) {
      PARTITION_INFORMATION partInfo2;
      memset(&partInfo, 0, sizeof(partInfo));
      res = DeviceIoControl(fHandle, IOCTL_DISK_GET_PARTITION_INFO, NULL, 0, &partInfo2, sizeof(partInfo2), &dummy, NULL);
      CHECK_OS_EX_PARAM1(res, EWinException::ioControlError, L"IOCTL_DISK_GET_PARTITION_INFO_EX and IOCTL_DISK_GET_PARTITION_INFO");
      fPartitionType = partInfo2.PartitionType;
    }
    else {
      CHECK_OS_EX_PARAM1(res, EWinException::ioControlError, L"IOCTL_DISK_GET_DRIVE_GEOMETRY");
      fPartitionType = partInfo.Mbr.PartitionType;
    }
    fIsMounted = DeviceIoControl(fHandle, FSCTL_IS_VOLUME_MOUNTED, NULL, 0, NULL, 0, &dummy, NULL) != FALSE;  
    res = DeviceIoControl(fHandle, IOCTL_DISK_GET_LENGTH_INFO, NULL, 0, &lengthInfo, sizeof(lengthInfo), &dummy, NULL);
    if (res == FALSE)
      fSize = partInfo.PartitionLength.QuadPart; // IOCTL_DISK_GET_LENGTH_INFO not available on some older windows versions
    else
      fSize = lengthInfo.Length.QuadPart;

    CHECK_OS_EX_PARAM1(res, EWinException::ioControlError, L"IOCTL_DISK_GET_LENGTH_INFO");
    res = DeviceIoControl(fHandle, IOCTL_DISK_GET_DRIVE_GEOMETRY	, NULL, 0, &diskGeometry, sizeof(diskGeometry), &dummy, NULL);
    
    ATLTRACE("Size of volume %S is %u\n", fName.c_str(), (DWORD)fSize);
    fBytesPerSector = diskGeometry.BytesPerSector;
    // Note: for NTFS use: FSCTL_GET_NTFS_VOLUME_DATA to get cluster size
    //       for FAT use getDiskFreeSpaceEx (see KB 231497,http://support.microsoft.com/?scid=kb%3Ben-us%3B231497&x=21&y=17)
    res = DeviceIoControl(fHandle, FSCTL_GET_NTFS_VOLUME_DATA, NULL, 0, &ntfsVolData, sizeof(ntfsVolData), &dummy, NULL);
    if (res != 0) {
      // we have an NTFSVolume
      fBytesPerCluster = ntfsVolData.BytesPerCluster;
    }

    CalculateFATExtraOffset(); // FAT has some sectors before the bitmap starts counting

  // note: under Vista/Server2008 there are new limitations in the direct access of disks
  // there are reserved areas that can not be written to even with admin rights, see
  // http://support.microsoft.com/kb/942448 for details. Therefore we unmount volume
  //http://msdn.microsoft.com/newsgroups/default.aspx?dg=microsoft.public.win32.programmer.kernel&tid=d0ff3e7a-e32c-49dc-b3e6-6cbdd1da67ac&cat=en-us-msdn-windev-winsdk&lang=en&cr=US&sloc=en-us&m=1&p=1
  } else { // (fOpenMode==forWriting) 
    res = DeviceIoControl(fHandle, FSCTL_LOCK_VOLUME, NULL, 0, NULL, 0, &dummy, NULL);
    if (res == 0)
      DismountAndLockVolume();
        // see: http://www.eggheadcafe.com/software/aspnet/31520519/direct-disk-access-write-to-system-areas.aspx
        // In order to achieve that you need to lock the volume by sending FSCTL_LOCK_VOLUME. This has to
        // be issued on the same volume handle performing the actual writes. This
        // request can fail if there are open file handles. In that case application
        // can force dismount the file system by issuing FSCTL_DISMOUNT_VOLUME.
    
    fWasLocked = true;
    if (!isRawDisk) { // does not work for raw disks in Win XP, no problem in Vista
      res = DeviceIoControl(fHandle, FSCTL_ALLOW_EXTENDED_DASD_IO, NULL, 0, NULL, 0, &dummy, NULL);
      if (res == 0)
        ATLTRACE("Warning: DeviceIoControl with FSCTL_ALLOW_EXTENDED_DASD_IO failed.\n");
    }
  }
}
Beispiel #13
0
SAVEDS void CamdTimerProc(void){
	struct timerequest *TimerIO;
	struct MsgPort  *TimerMP;
	ULONG sig;
	int error;

	D(bug("camdtimerproc1\n"));
	camdwaitsig=AllocSignal(-1);
	if(camdwaitsig==-1){
		camdwaitprocstatus=2;
		return;
	}
	D(bug("camdtimerproc2\n"));
	camdwaitsig2=AllocSignal(-1);
	if(camdwaitsig2==-1){
		FreeSignal(1L<<camdwaitsig);
		camdwaitprocstatus=2;
		return;
	}

	D(bug("camdtimerproc3\n"));
	TimerMP=CreateMsgPort();
	if(TimerMP==NULL){
		FreeSignal(1L<<camdwaitsig2);
		FreeSignal(1L<<camdwaitsig);
		camdwaitprocstatus=2;
		return;
	}
	D(bug("camdtimerproc4\n"));

	TimerIO=(struct timerequest *)AllocMem(sizeof(struct timerequest),MEMF_ANY|MEMF_CLEAR|MEMF_PUBLIC);
	D(bug("camdtimerproc5\n"));

	if(TimerIO==NULL){
		FreeSignal(1L<<camdwaitsig2);
		FreeSignal(1L<<camdwaitsig);
		DeleteMsgPort(TimerMP);
		camdwaitprocstatus=2;
		return;
	}
	D(bug("camdtimerproc6\n"));

	TimerIO->tr_node.io_Message.mn_Node.ln_Type=NT_MESSAGE;
	TimerIO->tr_node.io_Message.mn_ReplyPort=TimerMP;
	TimerIO->tr_node.io_Message.mn_Length=sizeof(struct timerequest);

	/* No support for eclock in AROS. */
#ifndef _AROS
	if((error=OpenDevice(
			TIMERNAME,UNIT_ECLOCK,(struct IORequest *)TimerIO,0L
	))!=0){
#else
	D(bug("camdtimerproc7\n"));
	if((error=OpenDevice(
			TIMERNAME,UNIT_VBLANK,(struct IORequest *)TimerIO,0L
	))!=0){
#endif
	  D(bug("camdtimerproc7.1\n"));
		FreeSignal(1L<<camdwaitsig2);
		FreeSignal(1L<<camdwaitsig);
		TimerIO->tr_node.io_Message.mn_Node.ln_Type=(UBYTE)-1;
		TimerIO->tr_node.io_Device=(struct Device *)-1L;
		TimerIO->tr_node.io_Unit=(struct Unit *)-1L;
		FreeMem(TimerIO,sizeof(struct timerequest));
		DeleteMsgPort(TimerMP);
		D(bug("failed camdtimerproc11, error: %ld\n",error));
		camdwaitprocstatus=2;
		return;
	}

	D(bug("camdtimerproc8\n"));
	ObtainSemaphore(&camdwaitsemaphore);

	D(bug("camdtimerproc9\n"));
	camdwaittask=FindTask(0L);

	camdwaitprocstatus=1;

	for(;;){
		sig=Wait(
			1L<<camdwaitsig |
			SIGBREAKF_CTRL_C
		);
		if(sig&SIGBREAKF_CTRL_C) break;

		if(sig & 1L<<camdwaitsig){				// Someone wants to obtain the semaphore?
			TimerIO->tr_node.io_Command=TR_ADDREQUEST;
			TimerIO->tr_time.tv_secs=0;
			TimerIO->tr_time.tv_micro=10;
			DoIO((struct IORequest *)TimerIO);	// ..Better let them wait.

			ReleaseSemaphore(&camdwaitsemaphore);		// Well, okey then.

			Wait(1L<<camdwaitsig2);					// Finished soon?

			ObtainSemaphore(&camdwaitsemaphore);		// But I want it back!
		}

	}

	ReleaseSemaphore(&camdwaitsemaphore);

	FreeSignal(1L<<camdwaitsig2);
	FreeSignal(1L<<camdwaitsig);
	CloseDevice((struct IORequest *)TimerIO);
	TimerIO->tr_node.io_Message.mn_Node.ln_Type=(UBYTE)-1;
	TimerIO->tr_node.io_Device=(struct Device *)-1L;
	TimerIO->tr_node.io_Unit=(struct Unit *)-1L;
	FreeMem(TimerIO,sizeof(struct timerequest));

	DeleteMsgPort(TimerMP);

	camdwaitprocstatus=3;

	return;
}

BOOL InitCamdTimer(void){
	struct Process *process;

	InitSemaphore(&camdwaitsemaphore);
	InitSemaphore(&camdwaitsemaphore2);

	process=CreateNewProcTags(
		NP_Entry,CamdTimerProc,
		NP_Name,"Camd Wait Proc",
		NP_Priority,5,
		TAG_END
	);
	if(process==NULL) return FALSE;

	D(bug("4.7\n"));
	while(camdwaitprocstatus==0) Delay(1);
	D(bug("4.8\n"));

	if(camdwaitprocstatus==2) return FALSE;

	return TRUE;
}

void UninitCamdTimer(void){

  if(camdwaitprocstatus==2) return;

  Signal(camdwaittask,SIGBREAKF_CTRL_C);
  while(camdwaitprocstatus!=3) Delay(1);
}



/*
 * When a hardware-sender buffer is full, or we are sending a sysex-message
 * to hardware, we need to wait for small amounts of time. That is what
 * this function tries to do.
 *
 */

void CamdWait(void){

	static BOOL iswaiting=FALSE;
	BOOL imjustgoingtoreturnsoon=iswaiting;

	ObtainSemaphore(&camdwaitsemaphore2);

		if(imjustgoingtoreturnsoon==TRUE){			// No big point having more than one visitor to wait.
			ReleaseSemaphore(&camdwaitsemaphore2);
			return;
		}

		iswaiting=TRUE;

		Signal(camdwaittask,1L<<camdwaitsig);		// Give me the semaphore!
		ObtainSemaphore(&camdwaitsemaphore);			// This should take some time.
			Signal(camdwaittask,1L<<camdwaitsig2);	// Okey, I've got it.
		ReleaseSemaphore(&camdwaitsemaphore);		// You're welcome.

		iswaiting=FALSE;

	ReleaseSemaphore(&camdwaitsemaphore2);

	return;
}
static void
Slave( struct ExecBase* SysBase )
{
  struct AHIAudioCtrlDrv* AudioCtrl;
  struct DriverBase*      AHIsubBase;
  struct DeviceBase* DeviceBase;
  BOOL                    running;
  ULONG                   signals;

  AudioCtrl  = (struct AHIAudioCtrlDrv*) FindTask( NULL )->tc_UserData;
  AHIsubBase = (struct DriverBase*) dd->ahisubbase;
  DeviceBase = (struct DeviceBase*) AHIsubBase;

  dd->slavesignal = AllocSignal( -1 );

  if( dd->slavesignal != -1 )
  {
    struct MsgPort*    ahi_mp           = NULL;
    struct AHIRequest* ahi_iorequest    = NULL;
    APTR               ahi_iocopy       = NULL;
    BYTE               ahi_device       = -1;

    struct AHIRequest* ahi_io[ 2 ]      = { NULL,  NULL };
    BOOL               ahi_io_used[ 2 ] = { FALSE, FALSE };

    ULONG              frame_length     = 0;

    ahi_mp = CreateMsgPort();

    if( ahi_mp != NULL )
    {
      ahi_iorequest = CreateIORequest( ahi_mp, sizeof( struct AHIRequest ) );

      if( ahi_iorequest != NULL )
      {
	ahi_iorequest->ahir_Version = 4;

	ahi_device = OpenDevice( AHINAME, dd->unit,
				 (struct IORequest*) ahi_iorequest, 0 );

	if( ahi_device == 0 )
	{
	  struct Library* AHIBase = (struct Library*) ahi_iorequest->ahir_Std.io_Device;

	  ahi_iocopy = AllocVec( sizeof( *ahi_iorequest ), MEMF_ANY );

	  if( ahi_iocopy != NULL )
	  {
	    bcopy( ahi_iorequest, ahi_iocopy, sizeof( *ahi_iorequest ) );

	    ahi_io[ 0 ] = ahi_iorequest;
	    ahi_io[ 1 ] = ahi_iocopy;
    
	    // Everything set up. Tell Master we're alive and healthy.

	    Signal( (struct Task*) dd->mastertask,
		    1L << dd->mastersignal );

	    running = TRUE;

	    // The main playback loop follow

	    while( running )
	    {
	      int skip_mix;
	      APTR tmp_buff;
	      struct AHIRequest* tmp_io;
	      
	      if( ahi_io_used[ 0 ] )
	      {
		LONG  err;
		ULONG mask = ( SIGBREAKF_CTRL_C |
			       (1L << dd->slavesignal) |
			       (1L << ahi_mp->mp_SigBit) );
	      
		signals = Wait( mask );

		if( signals & ( SIGBREAKF_CTRL_C |
				(1L << dd->slavesignal) ) ) 
		{
		  running = FALSE;
		  break;
		}

		err = WaitIO( (struct IORequest*) ahi_io[ 0 ] );

		if( err != 0 )
		{
		  KPrintF( DRIVER ": AHI device error %ld\n", err );
//		  running = FALSE;
		  break;
		}
	      }

	      skip_mix = CallHookPkt( AudioCtrl->ahiac_PreTimerFunc,
				      (Object*) AudioCtrl, 0 );

	      CallHookPkt( AudioCtrl->ahiac_PlayerFunc, AudioCtrl, NULL );
		
	      if( ! skip_mix )
	      {
		CallHookPkt( AudioCtrl->ahiac_MixerFunc, AudioCtrl,
			     dd->mixbuffers[ 0 ] );
	      }
		
	      CallHookPkt( AudioCtrl->ahiac_PostTimerFunc, (Object*) AudioCtrl, 0 );

	      if( frame_length == 0 )
	      {
		frame_length = AHI_SampleFrameSize( AudioCtrl->ahiac_BuffType );
	      }
	      
	      ahi_io[ 0 ]->ahir_Std.io_Command = CMD_WRITE;
	      ahi_io[ 0 ]->ahir_Std.io_Data    = dd->mixbuffers[ 0 ];
	      ahi_io[ 0 ]->ahir_Std.io_Length  = ( AudioCtrl->ahiac_BuffSamples *
						   frame_length );
	      ahi_io[ 0 ]->ahir_Std.io_Offset  = 0;
	      ahi_io[ 0 ]->ahir_Frequency      = AudioCtrl->ahiac_MixFreq;
	      ahi_io[ 0 ]->ahir_Type           = AudioCtrl->ahiac_BuffType;
	      ahi_io[ 0 ]->ahir_Volume         = 0x10000;
	      ahi_io[ 0 ]->ahir_Position       = 0x08000;
	      ahi_io[ 0 ]->ahir_Link           = ( ahi_io_used[ 1 ] ?
						   ahi_io[ 1 ] : NULL );

	      SendIO( (struct IORequest*) ahi_io[ 0 ] );
    
	      tmp_io = ahi_io[ 0 ];
	      ahi_io[ 0 ] = ahi_io[ 1 ];
	      ahi_io[ 1 ] = tmp_io;

	      tmp_buff = dd->mixbuffers[ 0 ];
	      dd->mixbuffers[ 0 ] = dd->mixbuffers[ 1 ];
	      dd->mixbuffers[ 1 ] = tmp_buff;
	      
	      ahi_io_used[ 0 ] = ahi_io_used[ 1 ];
	      ahi_io_used[ 1 ] = TRUE;
	    }

	    
	    if( ahi_io_used[ 0 ] )
	    {
	      AbortIO( (struct IORequest*) ahi_io[ 0 ] );
	      WaitIO( (struct IORequest*) ahi_io[ 0 ] );
	    }

	    if( ahi_io_used[ 1 ] )
	    {
	      AbortIO( (struct IORequest*) ahi_io[ 1 ] );
	      WaitIO( (struct IORequest*) ahi_io[ 1 ] );
	    }
	    
	    FreeVec( ahi_iocopy );
	  }

	  CloseDevice( (struct IORequest*) ahi_iorequest );
	}

	DeleteIORequest( (struct IORequest*) ahi_iorequest );
      }

      DeleteMsgPort( ahi_mp );
    }
  }

  FreeSignal( dd->slavesignal );
  dd->slavesignal = -1;

  Forbid();

  // Tell the Master we're dying

  Signal( (struct Task*) dd->mastertask,
          1L << dd->mastersignal );

  dd->slavetask = NULL;

  // Multitaking will resume when we are dead.
}
XnStatus SimKinect::Init(const char* filename) {
	XnStatus nRetVal = XN_STATUS_OK;
	xn::EnumerationErrors errors;
	if ( filename ) { //read data from files
		record_file = new char[255];
		strcpy(record_file,filename);
		xnSetPlayerRepeat(player,FALSE);
		char skeleton_data_file_name[1024];
		sprintf(skeleton_data_file_name,"%s.txt",filename);
		ReadUsers(skeleton_data_file_name,users,frame_ids);
	}

	nRetVal = OpenDevice(XML_CONFIG, errors);
	
	if (nRetVal == XN_STATUS_NO_NODE_PRESENT)
	{
		XnChar strError[1024];
		errors.ToString(strError, 1024);
		printf("%s\n", strError);
		return (nRetVal);
	}
	else if (nRetVal != XN_STATUS_OK)
	{
		printf("Open failed: %s\n", xnGetStatusString(nRetVal));
		return (nRetVal);
	}
	if ( bIsDepthOn ) {
		depth_frame = new unsigned char[video_size_width*video_size_height*3];
		depth_map = new int[video_size_width*video_size_height];
	}
	if ( bIsImageOn ) {
		color_frame = new unsigned char[video_size_width*video_size_height*3];
	}
	
	XnCallbackHandle hUserCallbacks, hCalibrationStart, hCalibrationComplete, hPoseDetected, hCalibrationInProgress, hPoseInProgress;
	if (!user_generator.IsCapabilitySupported(XN_CAPABILITY_SKELETON))
	{
		printf("Supplied user generator doesn't support skeleton\n");
		if ( record_file )
			return 0;
		else 
			return 1;
	}

	nRetVal = user_generator.RegisterUserCallbacks(User_NewUser, User_LostUser, NULL, hUserCallbacks);
	CHECK_RC(nRetVal, "Register to user callbacks");
	nRetVal = user_generator.GetSkeletonCap().RegisterToCalibrationStart(UserCalibration_CalibrationStart, NULL, hCalibrationStart);
	CHECK_RC(nRetVal, "Register to calibration start");
	nRetVal = user_generator.GetSkeletonCap().RegisterToCalibrationComplete(UserCalibration_CalibrationComplete, NULL, hCalibrationComplete);
	CHECK_RC(nRetVal, "Register to calibration complete");

	if (user_generator.GetSkeletonCap().NeedPoseForCalibration())
	{
		bNeedPose = TRUE;
		if (!user_generator.IsCapabilitySupported(XN_CAPABILITY_POSE_DETECTION))
		{
			printf("Pose required, but not supported\n");
			return 1;
		}
		nRetVal = user_generator.GetPoseDetectionCap().RegisterToPoseDetected(UserPose_PoseDetected, NULL, hPoseDetected);
		CHECK_RC(nRetVal, "Register to Pose Detected");
		user_generator.GetSkeletonCap().GetCalibrationPose(strPose);
	}

	user_generator.GetSkeletonCap().SetSkeletonProfile(XN_SKEL_PROFILE_ALL);

	nRetVal = user_generator.GetSkeletonCap().RegisterToCalibrationInProgress(MyCalibrationInProgress, NULL, hCalibrationInProgress);
	CHECK_RC(nRetVal, "Register to calibration in progress");

	nRetVal = user_generator.GetPoseDetectionCap().RegisterToPoseInProgress(MyPoseInProgress, NULL, hPoseInProgress);
	CHECK_RC(nRetVal, "Register to pose in progress");

	nRetVal = context.StartGeneratingAll();
	CHECK_RC(nRetVal, "StartGenerating");
	return 0;
}
Beispiel #16
0
static dc1394error_t
windows_capture_setup (platform_camera_t * craw, uint32_t num_dma_buffers, uint32_t flags)
{
    int i;

    free_resources(craw);

    ULARGE_INTEGER dma_buffer_size;
    const char * device_path = craw->device->device_path;
    t1394_GetHostDmaCapabilities (device_path, NULL, &dma_buffer_size);

    const dc1394video_frame_t * frame = &craw->capture.frames[0];
    int max_buffer_size = frame->total_bytes; //number of bytes needed
    int max_bytes = frame->packet_size / 2;

    PACQUISITION_BUFFER acquisition_buffer =
        dc1394BuildAcquisitonBuffer(max_buffer_size,
                                    (unsigned long)dma_buffer_size.QuadPart,
                                    max_bytes, 0);

    ISOCH_STREAM_PARAMS stream_params;
    if (acquisition_buffer) {
        stream_params.nMaxBufferSize = acquisition_buffer->subBuffers[0].ulSize;
        stream_params.nNumberOfBuffers = (num_dma_buffers * acquisition_buffer->nSubBuffers) + 1;

        // free the buffer: this wouldn't be necessary if this were merged into StartImageAcquisitionEx
        dc1394FreeAcquisitionBuffer(acquisition_buffer);
        acquisition_buffer = NULL;
    } else {
        dc1394_log_error("windows_capture_setup: failed to determine required buffer size and count!");
        return DC1394_FAILURE;
    }

    dc1394speed_t speed;
    if (dc1394_video_get_iso_speed(craw->camera, &speed) != DC1394_SUCCESS) {
        dc1394_log_error("windows_capture_setup: failed to get iso speed!");
        return DC1394_FAILURE;
    }

    uint32_t channel = -1;
    stream_params.fulSpeed = 1 << speed;
    stream_params.nChannel = channel;
    stream_params.nMaxBytesPerFrame = max_bytes;

    DWORD ret = t1394IsochSetupStream(craw->device->device_path,
                                      &stream_params);
    craw->allocated_channel = stream_params.nChannel;
    if (ret != ERROR_SUCCESS) {
        dc1394_log_error("windows_capture_setup: Error on IsochSetupStream: %d\n", ret);
        return DC1394_FAILURE;
    }

#if 1
    // allocate channel/bandwidth if requested
    if (flags & DC1394_CAPTURE_FLAGS_CHANNEL_ALLOC) {
        if (dc1394_iso_allocate_channel (craw->camera, 0, &craw->allocated_channel)
            != DC1394_SUCCESS) {
            return DC1394_FAILURE;
        }
        if (dc1394_video_set_iso_channel (craw->camera, craw->allocated_channel)
            != DC1394_SUCCESS) {
            return DC1394_FAILURE;
        }
    }
#endif
#if 1
    if (flags & DC1394_CAPTURE_FLAGS_BANDWIDTH_ALLOC) {
        unsigned int bandwidth_usage;
        if (dc1394_video_get_bandwidth_usage (craw->camera, &bandwidth_usage)
            != DC1394_SUCCESS) {
            return DC1394_FAILURE;
        }
        if (dc1394_iso_allocate_bandwidth (craw->camera, bandwidth_usage)
            != DC1394_SUCCESS) {
            return DC1394_FAILURE;
        }
        craw->allocated_bandwidth = bandwidth_usage;
    }
#endif

    /* QUEUE the buffers */
    for (i = 0; i < num_dma_buffers; ++i) {
        PACQUISITION_BUFFER buffer =
            dc1394BuildAcquisitonBuffer(max_buffer_size,
                                        dma_buffer_size.QuadPart, max_bytes, i);
        if(!buffer) {
            dc1394_log_error("windows_capture_setup: Error Allocating AcqBuffer %d\n", i);
            return DC1394_FAILURE;
        }

        // add it to our list of buffers
        if (i == 0) {
            craw->pLastBuffer = craw->pFirstBuffer = buffer;
            craw->pLastBuffer->pNextBuffer = craw->pCurrentBuffer = NULL;
        } else {
            craw->pFirstBuffer->pNextBuffer = buffer;
            craw->pFirstBuffer = buffer;
        }
    }

    // all done making buffers
    // open our long term device handle
    HANDLE device;
    if((device = OpenDevice(device_path, TRUE)) == INVALID_HANDLE_VALUE) {
        dc1394_log_error("windows_capture_setup error opening device (%s)\n", craw->device->device_path);
        return DC1394_FAILURE;
    }

    // all done making buffers
    // open our long term device handle
    PACQUISITION_BUFFER buffer;
    for (buffer = craw->pLastBuffer;
         buffer != NULL; buffer = buffer->pNextBuffer) {
        DWORD ret = dc1394AttachAcquisitionBuffer(device, buffer);
        if (ret != ERROR_SUCCESS) {
            dc1394_log_error("windows_capture_setup: Failed to attach buffer %u/%u", buffer->index, num_dma_buffers);
            return DC1394_FAILURE;
        }
    }

    // new: sleep a little while and verify that the buffers were
    // successfully attached this basically catches "Parameter is Incorrect"
    // here instead of confusing users at AcquireImageEx()
    // 50 ms is all it should take for completion routines to fire and
    // propagate in the kernel
    Sleep(50);

    for (buffer = craw->pLastBuffer;
         buffer != NULL; buffer = buffer->pNextBuffer) {
        DWORD dwBytesRet = 0;
        for (unsigned int bb = 0; bb < buffer->nSubBuffers; ++bb) {
            if (!GetOverlappedResult(device,
                                     &(buffer->subBuffers[bb].overLapped),
                                     &dwBytesRet, FALSE)) {
                if (GetLastError() != ERROR_IO_INCOMPLETE) {
                    dc1394_log_error("Buffer validation failed for buffer %u\n", buffer->index,bb);
                    return DC1394_FAILURE;
                }
                // else: this is the actual success case
            } else {
                dc1394_log_error("Buffer %u is unexpectedly ready during pre-listen validation\n", buffer->index, bb);
                return DC1394_FAILURE;
            }
        }
    }

    ret = t1394IsochListen(craw->device->device_path);
    if (ret != ERROR_SUCCESS) {
        dc1394_log_error("Error %08lx on IOCTL_ISOCH_LISTEN\n", ret);
        return DC1394_FAILURE;
    }

    // starting from here we use the ISO channel so we set the flag
    // in the camera struct:
    craw->capture_is_set = 1;

    for (i = 1; i < num_dma_buffers; ++i) {
        memcpy(&craw->capture.frames[i], frame, sizeof (dc1394video_frame_t));
    }
    craw->capture.frames_last_index = num_dma_buffers - 1;

    craw->device_acquisition = device;
    return DC1394_SUCCESS;
}
Beispiel #17
0
void hidd_demo(struct ExecBase * SysBase)
{
    D(bug("graphics.hidd = %08.8lx\n",OpenLibrary("graphics.hidd",0)));
    D(bug("display.hidd = %08.8lx\n",OpenLibrary("display.hidd",0)));

    OpenLibrary("hidd.gfx.display",0);
    {
	struct GfxBase *GfxBase;
	BOOL success = FALSE;
    
        D(bug("init_gfx(hiddbase=%s)\n", "hidd.gfx.display"));

        GfxBase = (struct GfxBase *)OpenLibrary("graphics.library", 37);
        if (GfxBase)
        {

	    /*  Call private gfx.library call to init the HIDD.
	        Gfx library is responsable for closing the HIDD
	        library (although it will probably not be neccesary).
	    */

	    D(bug("calling private gfx LateGfxInit()\n"));
	    if (LateGfxInit("hidd.gfx.display"))
	    {
	        struct IntuitionBase *IntuitionBase;

    	    	D(bug("lategfxinit okay\n"));
 
	        /* Now that gfx. is guaranteed to be up & working, let intuition open WB screen */
	        IntuitionBase = (struct IntuitionBase *)OpenLibrary("intuition.library", 37);
		D(bug("ibase = %lx\n", IntuitionBase));
	        if (IntuitionBase)
	        {
	    	    if (LateIntuiInit(NULL))
	    	    {
			success = TRUE;
		    }
		    CloseLibrary((struct Library *)IntuitionBase);
		}
	    }
	    D(bug("Closing gfx\n"));
	
	    CloseLibrary((struct Library *)GfxBase);

	    if (success == FALSE)
	    {
	    	D(bug("There is something wrong with hidd subsystem..."));
		while(1) {};
	    }
	
	}
    }

#if 0
    {
	struct IORequest *io;
	struct MsgPort *mp;

	mp=CreateMsgPort();
	io=CreateIORequest(mp,sizeof(struct IOStdReq));
	D(bug("Result of opening device %d\n",
	    OpenDevice("gameport.device",0,io,0)));
	D(bug("Doing CMD_HIDDINIT...\n"));
	{
	    UBYTE *data;
	    data = AllocMem(100, MEMF_PUBLIC);
	    strcpy(data, "hidd.bus.mouse");
	    ioStd(io)->io_Command=32000;
	    ioStd(io)->io_Data=data;
	    ioStd(io)->io_Length=strlen(data);
	    DoIO(io);
	    D(bug("Got io_ERROR=%d",io->io_Error));
	}
    }
#endif
    {
        struct IntuitionBase *IntuitionBase;
        struct GfxBase *GfxBase;
        struct Window * win = NULL;
#define XSTART 50
#define YSTART 50
        int x = XSTART;
        int y = YSTART;


	IntuitionBase = (struct IntuitionBase *)OpenLibrary("intuition.library", 37);
        GfxBase = (struct GfxBase *)OpenLibrary("graphics.library", 37);
	if (IntuitionBase)
	{

	    struct TagItem tags[] = {
		{WA_Width,			100},
		{WA_Height,			100},
		{WA_Left,			x},
		{WA_Top,			y},
		{WA_MinWidth,                   100},
		{WA_MinHeight,                  100},
		{WA_MaxWidth,                   120},
		{WA_MaxHeight,                  120},
		{WA_Title,  (ULONG)"AROS Dream :-)"},
		{WA_Activate,			  1},
		{WA_SizeGadget,                TRUE},
		{WA_DepthGadget,               TRUE},
		{TAG_DONE,			  0}};
	    win = OpenWindowTagList(0, tags);
	}

        DrawEllipse(win->RPort,160/2-35,120/2-4,80/2,80/2);
        DrawEllipse(win->RPort,185/2-35,90/2-4,15/2,15/2);
        DrawEllipse(win->RPort,135/2-35,90/2-4,15/2,15/2);
        
        Move(win->RPort,125/2-35,140/2-4);
        Draw(win->RPort,140/2-35,150/2-4);
        Draw(win->RPort,180/2-35,150/2-4);
        Draw(win->RPort,195/2-35,140/2-4);

#if 0
	if (win)
	{
	  while (x < 100)
	  {
	    MoveWindow(win,1,0);
	    x++;
	  }
	  while (y < 100)
	  {
	    MoveWindow(win,0,1);
	    y++;
	  }
	  while (x > XSTART)
	  {
	    MoveWindow(win,-1,0);
	    x--;
	  }
	  while (y > YSTART)
	  {
	    MoveWindow(win,0,-1);
	    y--;
	  }
	}
#endif
#if 0
	if (IntuitionBase)
	{
	  struct Screen	 *screen;
	  struct Window	 *win2;
	  struct IntuiMessage *msg;
	  char ScreenInfo[40];

	  if ((screen = LockPubScreen(NULL)))
	  {
	      struct TagItem tags[] = {
		{WA_Width,			640},
		{WA_Height,			100},
		{WA_Left,			  0},
		{WA_Top,			 79},
		{WA_MinWidth,                   200},
		{WA_MinHeight,                  100},
		{WA_MaxWidth,                   640},
		{WA_MaxHeight,                  480},
		{WA_Title,  (ULONG)"AROS !ext"     },
		{WA_Activate,			  1},
		{WA_CloseGadget,               TRUE},
		{WA_SizeGadget,                TRUE},
		{WA_DepthGadget,               TRUE},
		{WA_IDCMP, IDCMP_CLOSEWINDOW | IDCMP_MOUSEMOVE | IDCMP_RAWKEY},
		{WA_ReportMouse,	       TRUE},
		{TAG_DONE,			 0}};
	      win2 = OpenWindowTagList(0, tags);

	      sprintf(ScreenInfo,"ScreenWidth: %d, ScreenHeight: %d", screen->Width, screen->Height);

	      if (win2)
	      {
		BlackPrint(win2->RPort, ScreenInfo, 40, GfxBase);

		for(;;)
		{
		  BOOL quitme = FALSE;
		  
		  WaitPort(win2->UserPort);
		  while((msg = ((struct IntuiMessage *)GetMsg(win2->UserPort))))
		  {
		    switch(msg->Class)
		    {
		      case IDCMP_RAWKEY:
		        {
			  static char hex[] = "0123456789ABCDEF";
			  char s[9];
			  
			  s[0] = 'K';
			  s[1] = 'e';
			  s[2] = 'y';
			  s[3] = ' ';
			  s[4] = hex[(msg->Code >> 12) & 0xF];
			  s[5] = hex[(msg->Code >> 8) & 0xF];
			  s[6] = hex[(msg->Code >> 4) & 0xF];
			  s[7] = hex[(msg->Code >> 0) & 0xF];
			  s[8] = '\0';
			  
			  BlackPrint(win2->RPort, s, 60, GfxBase);
			  
			  if (msg->Code == 0x45) quitme = TRUE;
			}
			break;
			
		      case IDCMP_MOUSEMOVE:
		        {
			  WORD mx = win2->WScreen->MouseX;
			  WORD my = win2->WScreen->MouseY;

			  char s[20];

			  sprintf(s, "Mouse: %4d, %4d", mx, my);

			  WhitePrint(win2->RPort, s, 80, GfxBase);
#if 0
			  mx &= 511;
			  my &= 255;
			  
			  SetAPen(&win2->WScreen->RastPort, 1);
			  SetDrMd(&win2->WScreen->RastPort, JAM2);
			  WritePixel(&win2->WScreen->RastPort, mx, my);
#endif
			}
			break;
			
		      case IDCMP_CLOSEWINDOW:
		        {
			  quitme = TRUE;
			}
			break;
					      
		    }
		    ReplyMsg((struct Message *)msg);
		  }
		  
		  if (quitme) break;
		}
		CloseWindow(win2);
	    }
	    UnlockPubScreen(NULL,screen);
	  }
	}
#endif
    }
}
Beispiel #18
0
	bool OpenAL::Initialize(bool openDevice)
	{
		if (IsInitialized())
			return true;

		#if defined(NAZARA_PLATFORM_WINDOWS)
		///FIXME: Is OpenAL Soft a better implementation than Creative ?
		/// If we could use OpenAL Soft everytime, this would allow us to use sonorous extensions
		/// and give us more technical possibilities  with audio
		const char* libs[] = {
			"soft_oal.dll",
			"wrap_oal.dll",
			"openal32.dll"
		};
		#elif defined(NAZARA_PLATFORM_LINUX)
		const char* libs[] = {
			"libopenal.so.1",
			"libopenal.so.0",
			"libopenal.so"
		};
		//#elif defined(NAZARA_PLATFORM_MACOSX)
		#else
		NazaraError("Unknown OS");
		return false;
		#endif

		bool succeeded = false;
		for (const char* path : libs)
		{
			String libPath(path);
			if (!s_library.Load(libPath))
				continue;

			try
			{
				// al
				alBuffer3f = reinterpret_cast<OpenALDetail::LPALBUFFER3F>(LoadEntry("alBuffer3f"));
				alBuffer3i = reinterpret_cast<OpenALDetail::LPALBUFFER3I>(LoadEntry("alBuffer3i"));
				alBufferData = reinterpret_cast<OpenALDetail::LPALBUFFERDATA>(LoadEntry("alBufferData"));
				alBufferf = reinterpret_cast<OpenALDetail::LPALBUFFERF>(LoadEntry("alBufferf"));
				alBufferfv = reinterpret_cast<OpenALDetail::LPALBUFFERFV>(LoadEntry("alBufferfv"));
				alBufferi = reinterpret_cast<OpenALDetail::LPALBUFFERI>(LoadEntry("alBufferi"));
				alBufferiv = reinterpret_cast<OpenALDetail::LPALBUFFERIV>(LoadEntry("alBufferiv"));
				alDeleteBuffers = reinterpret_cast<OpenALDetail::LPALDELETEBUFFERS>(LoadEntry("alDeleteBuffers"));
				alDeleteSources = reinterpret_cast<OpenALDetail::LPALDELETESOURCES>(LoadEntry("alDeleteSources"));
				alDisable = reinterpret_cast<OpenALDetail::LPALDISABLE>(LoadEntry("alDisable"));
				alDistanceModel = reinterpret_cast<OpenALDetail::LPALDISTANCEMODEL>(LoadEntry("alDistanceModel"));
				alDopplerFactor = reinterpret_cast<OpenALDetail::LPALDOPPLERFACTOR>(LoadEntry("alDopplerFactor"));
				alDopplerVelocity = reinterpret_cast<OpenALDetail::LPALDOPPLERVELOCITY>(LoadEntry("alDopplerVelocity"));
				alEnable = reinterpret_cast<OpenALDetail::LPALENABLE>(LoadEntry("alEnable"));
				alGenBuffers = reinterpret_cast<OpenALDetail::LPALGENBUFFERS>(LoadEntry("alGenBuffers"));
				alGenSources = reinterpret_cast<OpenALDetail::LPALGENSOURCES>(LoadEntry("alGenSources"));
				alGetBoolean = reinterpret_cast<OpenALDetail::LPALGETBOOLEAN>(LoadEntry("alGetBoolean"));
				alGetBooleanv = reinterpret_cast<OpenALDetail::LPALGETBOOLEANV>(LoadEntry("alGetBooleanv"));
				alGetBuffer3f = reinterpret_cast<OpenALDetail::LPALGETBUFFER3F>(LoadEntry("alGetBuffer3f"));
				alGetBuffer3i = reinterpret_cast<OpenALDetail::LPALGETBUFFER3I>(LoadEntry("alGetBuffer3i"));
				alGetBufferf = reinterpret_cast<OpenALDetail::LPALGETBUFFERF>(LoadEntry("alGetBufferf"));
				alGetBufferfv = reinterpret_cast<OpenALDetail::LPALGETBUFFERFV>(LoadEntry("alGetBufferfv"));
				alGetBufferi = reinterpret_cast<OpenALDetail::LPALGETBUFFERI>(LoadEntry("alGetBufferi"));
				alGetBufferiv = reinterpret_cast<OpenALDetail::LPALGETBUFFERIV>(LoadEntry("alGetBufferiv"));
				alGetDouble = reinterpret_cast<OpenALDetail::LPALGETDOUBLE>(LoadEntry("alGetDouble"));
				alGetDoublev = reinterpret_cast<OpenALDetail::LPALGETDOUBLEV>(LoadEntry("alGetDoublev"));
				alGetEnumValue = reinterpret_cast<OpenALDetail::LPALGETENUMVALUE>(LoadEntry("alGetEnumValue"));
				alGetError = reinterpret_cast<OpenALDetail::LPALGETERROR>(LoadEntry("alGetError"));
				alGetFloat = reinterpret_cast<OpenALDetail::LPALGETFLOAT>(LoadEntry("alGetFloat"));
				alGetFloatv = reinterpret_cast<OpenALDetail::LPALGETFLOATV>(LoadEntry("alGetFloatv"));
				alGetInteger = reinterpret_cast<OpenALDetail::LPALGETINTEGER>(LoadEntry("alGetInteger"));
				alGetIntegerv = reinterpret_cast<OpenALDetail::LPALGETINTEGERV>(LoadEntry("alGetIntegerv"));
				alGetListener3f = reinterpret_cast<OpenALDetail::LPALGETLISTENER3F>(LoadEntry("alGetListener3f"));
				alGetListener3i = reinterpret_cast<OpenALDetail::LPALGETLISTENER3I>(LoadEntry("alGetListener3i"));
				alGetListenerf = reinterpret_cast<OpenALDetail::LPALGETLISTENERF>(LoadEntry("alGetListenerf"));
				alGetListenerfv = reinterpret_cast<OpenALDetail::LPALGETLISTENERFV>(LoadEntry("alGetListenerfv"));
				alGetListeneri = reinterpret_cast<OpenALDetail::LPALGETLISTENERI>(LoadEntry("alGetListeneri"));
				alGetListeneriv = reinterpret_cast<OpenALDetail::LPALGETLISTENERIV>(LoadEntry("alGetListeneriv"));
				alGetProcAddress = reinterpret_cast<OpenALDetail::LPALGETPROCADDRESS>(LoadEntry("alGetProcAddress"));
				alGetSource3f = reinterpret_cast<OpenALDetail::LPALGETSOURCE3F>(LoadEntry("alGetSource3f"));
				alGetSource3i = reinterpret_cast<OpenALDetail::LPALGETSOURCE3I>(LoadEntry("alGetSource3i"));
				alGetSourcef = reinterpret_cast<OpenALDetail::LPALGETSOURCEF>(LoadEntry("alGetSourcef"));
				alGetSourcefv = reinterpret_cast<OpenALDetail::LPALGETSOURCEFV>(LoadEntry("alGetSourcefv"));
				alGetSourcei = reinterpret_cast<OpenALDetail::LPALGETSOURCEI>(LoadEntry("alGetSourcei"));
				alGetSourceiv = reinterpret_cast<OpenALDetail::LPALGETSOURCEIV>(LoadEntry("alGetSourceiv"));
				alGetString = reinterpret_cast<OpenALDetail::LPALGETSTRING>(LoadEntry("alGetString"));
				alIsBuffer = reinterpret_cast<OpenALDetail::LPALISBUFFER>(LoadEntry("alIsBuffer"));
				alIsEnabled = reinterpret_cast<OpenALDetail::LPALISENABLED>(LoadEntry("alIsEnabled"));
				alIsExtensionPresent = reinterpret_cast<OpenALDetail::LPALISEXTENSIONPRESENT>(LoadEntry("alIsExtensionPresent"));
				alIsSource = reinterpret_cast<OpenALDetail::LPALISSOURCE>(LoadEntry("alIsSource"));
				alListener3f = reinterpret_cast<OpenALDetail::LPALLISTENER3F>(LoadEntry("alListener3f"));
				alListener3i = reinterpret_cast<OpenALDetail::LPALLISTENER3I>(LoadEntry("alListener3i"));
				alListenerf = reinterpret_cast<OpenALDetail::LPALLISTENERF>(LoadEntry("alListenerf"));
				alListenerfv = reinterpret_cast<OpenALDetail::LPALLISTENERFV>(LoadEntry("alListenerfv"));
				alListeneri = reinterpret_cast<OpenALDetail::LPALLISTENERI>(LoadEntry("alListeneri"));
				alListeneriv = reinterpret_cast<OpenALDetail::LPALLISTENERIV>(LoadEntry("alListeneriv"));
				alSource3f = reinterpret_cast<OpenALDetail::LPALSOURCE3F>(LoadEntry("alSource3f"));
				alSource3i = reinterpret_cast<OpenALDetail::LPALSOURCE3I>(LoadEntry("alSource3i"));
				alSourcef = reinterpret_cast<OpenALDetail::LPALSOURCEF>(LoadEntry("alSourcef"));
				alSourcefv = reinterpret_cast<OpenALDetail::LPALSOURCEFV>(LoadEntry("alSourcefv"));
				alSourcei = reinterpret_cast<OpenALDetail::LPALSOURCEI>(LoadEntry("alSourcei"));
				alSourceiv = reinterpret_cast<OpenALDetail::LPALSOURCEIV>(LoadEntry("alSourceiv"));
				alSourcePause = reinterpret_cast<OpenALDetail::LPALSOURCEPAUSE>(LoadEntry("alSourcePause"));
				alSourcePausev = reinterpret_cast<OpenALDetail::LPALSOURCEPAUSEV>(LoadEntry("alSourcePausev"));
				alSourcePlay = reinterpret_cast<OpenALDetail::LPALSOURCEPLAY>(LoadEntry("alSourcePlay"));
				alSourcePlayv = reinterpret_cast<OpenALDetail::LPALSOURCEPLAYV>(LoadEntry("alSourcePlayv"));
				alSourceQueueBuffers = reinterpret_cast<OpenALDetail::LPALSOURCEQUEUEBUFFERS>(LoadEntry("alSourceQueueBuffers"));
				alSourceRewind = reinterpret_cast<OpenALDetail::LPALSOURCEREWIND>(LoadEntry("alSourceRewind"));
				alSourceRewindv = reinterpret_cast<OpenALDetail::LPALSOURCEREWINDV>(LoadEntry("alSourceRewindv"));
				alSourceStop = reinterpret_cast<OpenALDetail::LPALSOURCESTOP>(LoadEntry("alSourceStop"));
				alSourceStopv = reinterpret_cast<OpenALDetail::LPALSOURCESTOPV>(LoadEntry("alSourceStopv"));
				alSourceUnqueueBuffers = reinterpret_cast<OpenALDetail::LPALSOURCEUNQUEUEBUFFERS>(LoadEntry("alSourceUnqueueBuffers"));
				alSpeedOfSound = reinterpret_cast<OpenALDetail::LPALSPEEDOFSOUND>(LoadEntry("alSpeedOfSound"));

				// alc
				alcCaptureCloseDevice = reinterpret_cast<OpenALDetail::LPALCCAPTURECLOSEDEVICE>(LoadEntry("alcCaptureCloseDevice"));
				alcCaptureOpenDevice = reinterpret_cast<OpenALDetail::LPALCCAPTUREOPENDEVICE>(LoadEntry("alcCaptureOpenDevice"));
				alcCaptureSamples = reinterpret_cast<OpenALDetail::LPALCCAPTURESAMPLES>(LoadEntry("alcCaptureSamples"));
				alcCaptureStart = reinterpret_cast<OpenALDetail::LPALCCAPTURESTART>(LoadEntry("alcCaptureStart"));
				alcCaptureStop = reinterpret_cast<OpenALDetail::LPALCCAPTURESTOP>(LoadEntry("alcCaptureStop"));
				alcCloseDevice = reinterpret_cast<OpenALDetail::LPALCCLOSEDEVICE>(LoadEntry("alcCloseDevice"));
				alcCreateContext = reinterpret_cast<OpenALDetail::LPALCCREATECONTEXT>(LoadEntry("alcCreateContext"));
				alcDestroyContext = reinterpret_cast<OpenALDetail::LPALCDESTROYCONTEXT>(LoadEntry("alcDestroyContext"));
				alcGetContextsDevice = reinterpret_cast<OpenALDetail::LPALCGETCONTEXTSDEVICE>(LoadEntry("alcGetContextsDevice"));
				alcGetCurrentContext = reinterpret_cast<OpenALDetail::LPALCGETCURRENTCONTEXT>(LoadEntry("alcGetCurrentContext"));
				alcGetEnumValue = reinterpret_cast<OpenALDetail::LPALCGETENUMVALUE>(LoadEntry("alcGetEnumValue"));
				alcGetError = reinterpret_cast<OpenALDetail::LPALCGETERROR>(LoadEntry("alcGetError"));
				alcGetIntegerv = reinterpret_cast<OpenALDetail::LPALCGETINTEGERV>(LoadEntry("alcGetIntegerv"));
				alcGetProcAddress = reinterpret_cast<OpenALDetail::LPALCGETPROCADDRESS>(LoadEntry("alcGetProcAddress"));
				alcGetString = reinterpret_cast<OpenALDetail::LPALCGETSTRING>(LoadEntry("alcGetString"));
				alcIsExtensionPresent = reinterpret_cast<OpenALDetail::LPALCISEXTENSIONPRESENT>(LoadEntry("alcIsExtensionPresent"));
				alcMakeContextCurrent = reinterpret_cast<OpenALDetail::LPALCMAKECONTEXTCURRENT>(LoadEntry("alcMakeContextCurrent"));
				alcOpenDevice = reinterpret_cast<OpenALDetail::LPALCOPENDEVICE>(LoadEntry("alcOpenDevice"));
				alcProcessContext = reinterpret_cast<OpenALDetail::LPALCPROCESSCONTEXT>(LoadEntry("alcProcessContext"));
				alcSuspendContext = reinterpret_cast<OpenALDetail::LPALCSUSPENDCONTEXT>(LoadEntry("alcSuspendContext"));

				succeeded = true;
				break;
			}
			catch (const std::exception& e)
			{
				NazaraWarning(libPath + " loading failed: " + String(e.what()));
				continue;
			}
		}

		if (!succeeded)
		{
			NazaraError("Failed to load OpenAL");
			Uninitialize();

			return false;
		}

		if (openDevice)
			OpenDevice();

		return true;
	}
Beispiel #19
0
BOOL
OpenLibs ( void )
{

  /* DOS Library */

  DOSBase = (struct DosLibrary *) OpenLibrary("dos.library", 37);

  if( DOSBase == NULL)
  {
    Alert(AN_Unknown|AG_OpenLib|AO_DOSLib);
    return FALSE;
  }

  /* Graphics Library */

  GfxBase = (struct GfxBase *) OpenLibrary("graphics.library", 37);

  if( GfxBase == NULL)
  {
    Alert(AN_Unknown|AG_OpenLib|AO_GraphicsLib);
    return FALSE;
  }

  /* GadTools Library */

  GadToolsBase = OpenLibrary("gadtools.library", 37);

  if( GadToolsBase == NULL)
  {
    Alert(AN_Unknown|AG_OpenLib|AO_GadTools);
    return FALSE;
  }

  /* IFFParse Library */

  IFFParseBase = OpenLibrary("iffparse.library", 37);

  if( IFFParseBase == NULL)
  {
    Alert(AN_Unknown|AG_OpenLib|AO_Unknown);
    return FALSE;
  }

  /* Intuition Library */

  IntuitionBase = (struct IntuitionBase *) OpenLibrary("intuition.library", 37);

  if( IntuitionBase == NULL)
  {
    Alert(AN_Unknown|AG_OpenLib|AO_Intuition);
    return FALSE;
  }

  /* Locale Library */

  LocaleBase = (struct LocaleBase*) OpenLibrary("locale.library", 38);

  /* Timer Device */

  TimerIO = (struct timerequest *) AllocVec( sizeof(struct timerequest),
                                             MEMF_PUBLIC | MEMF_CLEAR );

  if( TimerIO == NULL)
  {
    Alert(AN_Unknown|AG_NoMemory);
    return FALSE;
  }

  timeval = (struct timeval *) AllocVec( sizeof(struct timeval),
                                         MEMF_PUBLIC | MEMF_CLEAR);

  if( timeval == NULL)
  {
    Alert(AN_Unknown|AG_NoMemory);
    return FALSE;
  }

  if( OpenDevice( "timer.device",
                  UNIT_MICROHZ,
                  (struct IORequest *)
                  TimerIO,
                  0) != 0 )
  {
    Alert(AN_Unknown|AG_OpenDev|AO_TimerDev);
    return FALSE;
  }

  TimerBase = (struct Device *) TimerIO->tr_node.io_Device;

  /* Utility Library */

  UtilityBase = (struct UtilityBase *) OpenLibrary("utility.library", 37);

  if( UtilityBase == NULL)
  {
    Alert(AN_Unknown|AG_OpenLib|AO_UtilityLib);
    return FALSE;
  }

  OpenahiCatalog(NULL, NULL);

  return TRUE;
}
Beispiel #20
0
struct DiskIO *DIO_Setup(CONST_STRPTR name, const struct TagItem *tags) {
	DEBUGF("DIO_Setup('%s', %#p)\n", name, tags);

	if (name == NULL || name[0] == '\0' || name[0] == ':') {
		DEBUGF("DIO_Setup: No valid name argument specified.\n");
		return NULL;
	}

	struct DiskIO *dio;
	struct TagItem *tstate;
	const struct TagItem *tag;
#ifndef DISABLE_DOSTYPE_CHECK
	ULONG check_dostype = 0;
	ULONG dostype_mask = ~0;
#endif
	struct DosList *dol;
	struct DeviceNode *dn = NULL;
	struct FileSysStartupMsg *fssm = NULL;
	struct DosEnvec *de = NULL;
	struct MsgPort *mp = NULL;
	struct IOExtTD *iotd = NULL;
	char devname[256];
	struct NSDeviceQueryResult nsdqr;
	int error = DIO_ERROR_UNSPECIFIED;
	int *error_storage;

	dio = AllocMem(sizeof(*dio), MEMF_PUBLIC|MEMF_CLEAR);
	if (dio == NULL) {
		error = DIO_ERROR_NOMEM;
		goto cleanup;
	}

	tstate = (struct TagItem *)tags;
	while ((tag = NextTagItem(&tstate)) != NULL) {
		switch (tag->ti_Tag) {
#ifndef DISABLE_BLOCK_CACHE
			case DIOS_Cache:
				dio->no_cache = !tag->ti_Data;
				break;
			case DIOS_WriteCache:
				dio->no_write_cache = !tag->ti_Data;
				break;
#endif
			case DIOS_Inhibit:
				dio->inhibit = !!tag->ti_Data;
				break;
#ifndef DISABLE_DOSTYPE_CHECK
			case DIOS_DOSType:
				check_dostype = tag->ti_Data;
				break;
			case DIOS_DOSTypeMask:
				dostype_mask = tag->ti_Data;
				break;
#endif
			case DIOS_ReadOnly:
				dio->read_only = !!tag->ti_Data;
				break;
		}
	}

	/* Remove possible colon from name and anything else that might follow it */
	SplitName(name, ':', dio->devname, 0, sizeof(dio->devname));

	/* Find device node */
	dol = LockDosList(LDF_DEVICES|LDF_READ);
	if (dol != NULL) {
		dn = (struct DeviceNode *)FindDosEntry(dol, dio->devname, LDF_DEVICES|LDF_READ);
		UnLockDosList(LDF_DEVICES|LDF_READ);
	}
	if (dn == NULL) {
		error = DIO_ERROR_GETFSD;
		goto cleanup;
	}

	/* Add back trailing colon for Inhibit() */
	strlcat((char *)dio->devname, ":", sizeof(dio->devname));

	/* Check that device node has the necessary data */
	if ((fssm = BADDR(dn->dn_Startup)) == NULL ||
		(de = BADDR(fssm->fssm_Environ)) == NULL ||
		de->de_TableSize < DE_UPPERCYL)
	{
		error = DIO_ERROR_GETFSD;
		goto cleanup;
	}

	if (dio->inhibit) {
		if (!Inhibit(dio->devname, TRUE)) {
			error = DIO_ERROR_INHIBIT;
			goto cleanup;
		}

		dio->uninhibit = TRUE; /* So Cleanup() knows that it should uninhibit */
	}

	dio->diskmp = mp = CreateMsgPort();
	dio->diskiotd = iotd = CreateIORequest(dio->diskmp, sizeof(*iotd));
	if (iotd == NULL) {
		error = DIO_ERROR_NOMEM;
		goto cleanup;
	}

	FbxCopyStringBSTRToC(fssm->fssm_Device, (STRPTR)devname, sizeof(devname));
	if (OpenDevice((CONST_STRPTR)devname, fssm->fssm_Unit,
		(struct IORequest *)iotd, fssm->fssm_Flags) != 0)
	{
		DEBUGF("DIO_Setup: Failed to open %s unit %u using flags 0x%x.\n",
			fssm->fssm_Device,
			(unsigned int)fssm->fssm_Unit,
			(unsigned int)fssm->fssm_Flags);
		error = DIO_ERROR_OPENDEVICE;
		goto cleanup;
	}

	dio->disk_device = iotd->iotd_Req.io_Device;

	if (de->de_LowCyl == 0) {
		dio->use_full_disk = TRUE;
		DEBUGF("de_LowCyl == 0 => using full disk\n");
	} else {
		UQUAD sector_size = de->de_SizeBlock * sizeof(ULONG);
		UQUAD cylinder_size = (UQUAD)de->de_BlocksPerTrack * (UQUAD)de->de_Surfaces * sector_size;
		dio->use_full_disk = FALSE;
		SetSectorSize(dio, sector_size);
		dio->partition_start = (UQUAD)de->de_LowCyl * cylinder_size;
		dio->partition_size = (UQUAD)(de->de_HighCyl - de->de_LowCyl + 1) * cylinder_size;
		dio->total_sectors = dio->partition_size / dio->sector_size;
		DEBUGF("partiton start: %llu partition size: %llu cylinder size: %llu sector size: %lu total sectors: %llu\n",
			dio->partition_start, dio->partition_size, cylinder_size, dio->sector_size, dio->total_sectors);
	}

	DEBUGF("Trying NSD query command\n");
	iotd->iotd_Req.io_Command = NSCMD_DEVICEQUERY;
	iotd->iotd_Req.io_Data = &nsdqr;
	iotd->iotd_Req.io_Length = sizeof(nsdqr);
	bzero(&nsdqr, sizeof(nsdqr)); /* Required for usbscsi.device */
	if (DoIO((struct IORequest *)iotd) == 0) {
		if (nsdqr.DeviceType != NSDEVTYPE_TRACKDISK) {
			DEBUGF("Not a trackdisk device\n");
			error = DIO_ERROR_NSDQUERY;
			goto cleanup;
		}

		if (nsdqr.SupportedCommands != NULL) {
			UWORD cmd;
			int i = 0;
			while ((cmd = nsdqr.SupportedCommands[i++]) != CMD_INVALID) {
				if (cmd == CMD_READ)
					dio->cmd_support |= CMDSF_TD32;
				else if (cmd == ETD_READ)
					dio->cmd_support |= CMDSF_ETD32;
				else if (cmd == TD_READ64)
					dio->cmd_support |= CMDSF_TD64;
				else if (cmd == NSCMD_TD_READ64)
					dio->cmd_support |= CMDSF_NSD_TD64;
				else if (cmd == NSCMD_ETD_READ64)
					dio->cmd_support |= CMDSF_NSD_ETD64;
				else if (cmd == CMD_UPDATE)
					dio->cmd_support |= CMDSF_CMD_UPDATE;
				else if (cmd == ETD_UPDATE)
					dio->cmd_support |= CMDSF_ETD_UPDATE;
			}
		}
	} else if (iotd->iotd_Req.io_Error == IOERR_NOCMD) {
		DEBUGF("Not an NSD device\n");
		dio->cmd_support = CMDSF_TD32|CMDSF_CMD_UPDATE;

		DEBUGF("Checking for TD64 support\n");
		iotd->iotd_Req.io_Command = TD_READ64;
		iotd->iotd_Req.io_Data = NULL;
		iotd->iotd_Req.io_Actual = 0;
		iotd->iotd_Req.io_Offset = 0;
		iotd->iotd_Req.io_Length = 0;
		if (DoIO((struct IORequest *)iotd) != IOERR_NOCMD)
			dio->cmd_support |= CMDSF_TD64;
	} else {
		DEBUGF("NSD query command failed (error: %d)\n", (int)iotd->iotd_Req.io_Error);
		error = DIO_ERROR_NSDQUERY;
		goto cleanup;
	}

	if ((dio->cmd_support & (CMDSF_TD32|CMDSF_ETD32|CMDSF_TD64|CMDSF_NSD_TD64|CMDSF_NSD_ETD64)) == 0) {
		DEBUGF("No I/O commands supported\n");
		error = DIO_ERROR_NSDQUERY;
		goto cleanup;
	}

	if (dio->cmd_support & CMDSF_ETD_UPDATE)
		dio->update_cmd = ETD_UPDATE;
	else if (dio->cmd_support & CMDSF_CMD_UPDATE)
		dio->update_cmd = CMD_UPDATE;
	else
		dio->update_cmd = CMD_INVALID;

	dio->mempool = CreatePool(MEMF_PUBLIC, 4096, 1024);
	if (dio->mempool == NULL) {
		error = DIO_ERROR_NOMEM;
		goto cleanup;
	}

	DIO_Update(dio);

	DEBUGF("DIO_Setup: %#p\n", dio);
	return dio;

cleanup:
	if (dio != NULL) DIO_Cleanup(dio);

	error_storage = (int *)GetTagData(DIOS_Error, (Tag)NULL, tags);
	if (error_storage != NULL) *error_storage = error;

	DEBUGF("DIO_Setup failed (error: %d)\n", error);
	return NULL;
}
Beispiel #21
0
int main (int argc, const char * argv[]) {
    UInt32 addr = 0;
    UInt8 config = 0;
    USBDevice device;
    USBInterface iface;
    dload_action action = kDLoadNone;
    
    printf("Starting DLOADTool\n");
    if(argc >= 1) {
        if(strcmp(argv[1], "-c") == 0) {
            // Send custom packets
            action = kDLoadSend;
            
        } else if(strcmp(argv[1], "-f") == 0) {
            // Upload firmware file
            action = kDLoadUpload;
            
        } else {
            // Upload dbl
            action = kDLoadNone;
        }
    } else {
        printf("Usage: %s [-f firmware] [-c command1 command2 ... commandN]\n", argv[0]);
        return -1;
    }
    
    //Vendor ID: 0x5c6
    //Product ID: 0x9008
    device = OpenDevice(0x5c6, 0x9008);
    if(device) {
        printf("Device Opened\n");
        config = SetConfiguration(device, 1);
        if(config == 1) {
            printf("Configuration %hhx set\n", config);
            iface = OpenInterface(device, 0, 0);
            if(iface) {
                printf("Interface Opened\n");
                
                if(action == kDLoadSend && argc >= 3) {
                    int i = 0;
                    int v = 0;
                    unsigned char input[0x200];
                    unsigned char output[0x200];
                    for(v = 2; v < argc; v++) {
                        const char* arg = (const char*) argv[v];
                        unsigned int size = strlen(arg) / 2;
                        memset(output,'\0', sizeof(output));
                        memset(input, '\0', sizeof(input));
                        for(i = 0; i < size; i++) {
                            unsigned int byte = 0;
                            sscanf(arg, "%02x", &byte);
                            output[i] = byte;
                            arg += 2;
                        }
                        dload_write(iface, output, size);
                        dload_read(iface, input, sizeof(input));
                    }
                }
                
                if(action == kDLoadUpload && argc == 3) {
                    addr = 0x20012000;
                    dload_get_params(iface);
                    dload_get_sw_version(iface);
                    dload_upload_firmware(iface, addr, argv[2]);
                    dload_send_execute(iface, addr);
                }
                
                if(action == kDLoadNone && argc == 1) {
                    addr = 0x20012000;
                    dload_get_params(iface);
                    dload_get_sw_version(iface);
                    dload_upload_firmware(iface, addr, "/usr/local/standalone/firmware/Trek/dbl.mbn");
                    dload_send_execute(iface, addr);
                }
                
                printf("Closing Interface\n");
                CloseInterface(iface);
                
            } else {
                fprintf(stderr, "Couldn't open device interface\n");
            }
        }
        
        
        CloseDevice(device);
    }

    return 0;
}
Beispiel #22
0
int
consinit(void *consptr) {
	struct Console *mc;

	if (consptr != NULL) {
		/* Check magic? */
		ConsoleBase = consptr;		/* Use existing console */
		return (0);
	}

	mc = &myConsole;
	IntuitionBase = OpenLibrary("intuition.library", 36L);
	if (IntuitionBase == 0)
		goto err;

	mc->s = OpenScreenTagList(0, screentags);
	if (!mc->s)
		goto err;

	windowtags[1] = (u_int32_t)mc->s;
	mc->w = OpenWindowTagList(0, windowtags);
	if (!mc->w)
		goto err;

	mc->cnmp = CreateMsgPort();

	if (!mc->cnmp)
		goto err;

	mc->cnior = (struct AmigaIO *)CreateIORequest(mc->cnmp, sizeof(struct AmigaIO));
	if (!mc->cnior)
		goto err;

	mc->cnior->buf = (void *)mc->w;
	if (OpenDevice("console.device", 0, mc->cnior, 0))
		goto err;

	mc->tmior = (struct TimerIO *)CreateIORequest(mc->cnmp, sizeof(struct TimerIO));
	if (!mc->tmior)
		goto err;

	if (OpenDevice("timer.device", 0, (struct AmigaIO*)mc->tmior, 0))
		goto err;

#ifdef SERCONSOLE
	conspreinit();
	if (use_serconsole)
		RawIOInit();
#endif

	ConsoleBase = mc;
	return 0;

err:
#ifdef notyet
	if (mc->tmior)
		DeleteIORequest(mc->tmior);

	if (mc->cnior)
		DeleteIORequest(mc->cnior);

	if (mc->cnmp)
		DeleteMsgPort(mc->cnmp);

	if (mc->w)
		CloseWindow(mc->w);

	if (mc->s)
		CloseScreen(mc->s);
	if (IntuitionBase)
		CloseLibrary(IntuitionBase);
#endif

	return 1;
}
Beispiel #23
0
//----------------------------------------------------------------------------
//!	\brief	this is main work loop function for any GUI's entry, 
// param  index is for GUI's index id
//----------------------------------------------------------------------------
void CReturnDlg::WorkLoop(int index)
{
	TCHAR buf[10] = { L"" };
	m_strMsg.m_nFormat = DT_LEFT;
	m_strMsg2.m_nFormat = DT_RIGHT;
	m_Bt.ShowWindow(SW_HIDE);
	m_Bt1.ShowWindow(SW_HIDE);
	m_strMsg.SetColor(RGB(0, 0, 0),RGB( 255,255,255));
	m_strMsg1.SetColor(RGB(0, 0, 0),RGB( 255,255,255));

	CString str = L"";
	CString str1 = L"";
	int i = 0;
	switch(index)
	{
	case PASSWORD_INPUT: //Password Input
		m_bGoBackFlag = FALSE;
		for(i = 0;i<m_strPassword.GetLength();i++)
			str += L"*";

		ShowText(L"Enter Password", L"", str);
		break;
	case AMOUNT_INPUT: //Amout Input
		m_bGoBackFlag = FALSE;
		ShowText(L"Enter Amount", L"", m_strAmount);
		break;
	case CLERK_INPUT:  //Clerk ID input
		if (CDataFile::Read(L"CLERK ID", buf) && CString(buf) == L"Off")
		{
			m_bGoBackFlag?GoBack():GoNext();
		}
		else
		{
			m_bGoBackFlag = FALSE;
			ShowText(L"Enter Clerk", L"Id", L"");
			break;
		}
	case RECEIP_TINPUT:  //Receipt input
		if (CDataFile::Read(L"RECEIPT", buf) && CString(buf) == L"Off")
		{
			m_bGoBackFlag?GoBack():GoNext();
		}
		else
		{
			m_bGoBackFlag = FALSE;
			ShowText(L"Enter Receipt", L"Number", L"");
		}
		break;
	case ENTERCARD_INPUT:  //Card enter and manual Entry
		m_bGoBackFlag = FALSE;
		if (!OpenDevice())
		{
			m_strErr1 = L"fail open device";
			PostMessage(ERROR_MESSAGE, 2, 1);
			break;
		}
		m_strMsg.m_nFormat = DT_RIGHT;
		m_strMsg2.m_nFormat = DT_LEFT;
		ShowText(m_strAmount, L"Insert/Swipe/Tap", L"or Key Card #");
		SetTimer(1, 30000, NULL);
		break;

// debit card 
	case DEBITCARDENTRY:
		m_bCancelPrint = TRUE;
		m_bGoBackFlag = FALSE;
		ShowText(L"Pass to", L"Customer", L"");
		SetTimer(1, 3000, NULL);
		m_bCancelInCustomer = TRUE;
		break;
	case DEBITCASHBACK: //CASHBACK
		if (m_bReturnFlag)
		{
			m_bGoBackFlag?GoBack():GoNext();
			break;
		}
		
		if (CDataFile::Read(L"CASHBACK", buf) && CString(buf) == L"Off")
		{
			m_bGoBackFlag?GoBack():GoNext();
		}
		else
		{
			m_bGoBackFlag = FALSE;
			str = L"Enter Cashback";
			str1 = L"Amount";
			CString str2 = L"$0.00";
			ShowText(str, str1, str2);
		}
		break;
	case DEBITSURCHARGEFEE: //surcharge fee
		if (m_bReturnFlag)
		{
			m_bGoBackFlag?GoBack():GoNext();
			break;
		}
		if (!CDataFile::Read(L"SURCHARGE", buf))
		{
			m_bGoBackFlag?GoBack():GoNext();
			return;
		}
		if (CString(buf) == L"$0.00" || CString(buf) == L"")
		{
			m_bGoBackFlag?GoBack():GoNext();
		}
		else
		{
			m_bGoBackFlag = FALSE;
			m_Bt.SetValue(1, L"  Cancel", IDB_CANCEL);
			m_Bt.ShowWindow(SW_SHOW);
			m_Bt1.SetValue(3, L"  OK", IDB_OK);
			m_Bt1.ShowWindow(SW_SHOW);
			str.Format(L"        %s  OK?", CString(buf));
			ShowText(L"Fee", str, L"");
			m_strSurcharge = CString(buf);
			break;
		}
	case DEBITTIPSELECT: //TipSelect
		if (m_bReturnFlag)
		{
			m_bGoBackFlag?GoBack():GoNext();
			break;
		}
		GetTipValue();
		break;
	case DEBITTOTALCOMFIRM: // TotalComfirm
		m_bGoBackFlag = FALSE;
		if (DoConfirm(m_bReturnFlag))
			GoNext();
		else
			OnCancel();
		break;
	case DEBITSELECTACCOUNT: // SelectAccount
		m_bGoBackFlag = FALSE;
		m_Bt.SetValue(1, L"  CHEQUE");
		m_Bt1.SetValue(3, L"  SAVING");
		m_Bt.ShowWindow(SW_SHOW);
		m_Bt1.ShowWindow(SW_SHOW);
		ShowText(L"Select Account", L"", L"");
		break;
	case DEBITONLINEPIN: //OnlinePin
		if (!EnterOnlinePin())
		{
			m_strErr1 = L"EnterOnlinePin";
			PostMessage(ERROR_MESSAGE, 2, 1);
		}
		else
		{
			ShowText(L"Please Wait...", L"", L"");
			GoToLevel(DOTRANSACTION);
		}
		break;
	case DEBITMERCHANTCOPY: // for merchant copy of the receipt
		if (m_TRREC.ComStatus == ST_OK  &&
				m_TRREC.TranStatus == ST_APPROVED)
			str = L"APPROVED";
		else
			str = L"Unsuccessful";
		m_strMsg2.m_nFormat = DT_LEFT;
		ShowText(str, L"Retrieve Card", L"Pass to Clerk");
		Print();
		break;
	case DEBITCUSTOMERCOPY: // for Customer copy of the receipt
		ShowText(L"Press OK for", L"customer copy", L"");
		SetTimer(1, 30000, NULL);
		break;
	case DEBITWAITCOPYEND: // waiting for Customer copy of the receipt ending...
		if (m_TRREC.ComStatus == ST_OK  &&
				m_TRREC.TranStatus == ST_APPROVED)
		{
			str.Format(L"AUTH : %s", CString(m_TRREC.AuthCode));
			m_strMsg2.m_nFormat = DT_LEFT;
			str1.Format(L"Inv.#: %s", CString(m_TRREC.InvoiceNo));
			ShowText(L"APPROVED", str, str1);
		}
		else
		{
			str.Format(L"Declined %s", CString(m_TRREC.RespCode));
			ShowText(L"Unsuccessful", str, L"");
		}
		break;
	case DEBITEND: // ending...
		CDialog::OnCancel();
		break;
// == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == 
	case MANUALENTRYY: //Manual Entry enter expiry
		m_strMsg.SetCaption(L"Enter Expiry");
		m_strMsg1.SetCaption(L"Date           MMYY");
		m_strMsg2.SetCaption(L"");
		break;
	case MANUAL_IMPRINT_CARD:  //imprint card
		m_strMsg.SetCaption(L"Imprint Card");
		m_strMsg1.SetCaption(L"Press OK");
		m_strMsg2.SetCaption(L"");
		break;

// == == == == == == == == == == == == == = EMV Chip Card Debit Sale :C chip page 122 == == == == == == == == == == == == == = 
	case CHIPENTRYY:
		m_bCancelPrint = TRUE;
		m_bGoBackFlag = FALSE;
		ShowText(L"Pass to", L"Customer", L"");
		SetTimer(1, 3000, NULL);
		m_bCancelInCustomer = TRUE;
		break;
	case SELECT_LANGUAGE:
		if (SupportEnglishOrFrench())
		{
			// get first language found will be selected
			// EMVSelectLanguage(???);
			m_bGoBackFlag?GoBack():GoNext();
		}
		else
		{
			m_bGoBackFlag = FALSE;
			m_Bt.SetValue(1, L" English");
			m_Bt.ShowWindow(SW_SHOW);
			m_Bt1.SetValue(3, L" Francais");
			m_Bt1.ShowWindow(SW_SHOW);
			str.Format(L"        %s  OK?", CString(buf));
			ShowText(L"Select language", L"Choisir langue", L"");
		}
		break;
	case SELECT_APPLICATIION:
/*		if (!IsEMVMultiApplication())
		{
			//Select this single Application
			m_bGoBackFlag?GoBack():GoNext();
		}
		else
		{
			m_bGoBackFlag = FALSE;
			m_Bt.SetValue(1, L"   No");
			m_Bt.ShowWindow(SW_SHOW);
			m_Bt1.SetValue(3, L"   Yes");
			m_Bt1.ShowWindow(SW_SHOW);
			str = GetNextEMVApplicationLabel();
			ShowText(L"Select", str, L"");
		}
	*/	break;
	case APPLICATION_CONFIRM:
		m_bGoBackFlag = FALSE;
		m_Bt.SetValue(1, L"   No");
		m_Bt.ShowWindow(SW_SHOW);
		m_Bt1.SetValue(3, L"   Yes");
		m_Bt1.ShowWindow(SW_SHOW);
		ShowText(m_strCurrentApplicationLabel, L"OK?", L"");
		break;

	case CHIP_DEBITCASHBACK: //CASHBACK
		m_bCancelPrint = TRUE;
		if (m_TRREC.CardType == CARD_CREDIT)
		{
			m_bGoBackFlag?GoBack():GoNext();
			return;
		}

		if (CDataFile::Read(L"CASHBACK", buf) && CString(buf) == L"Off")
		{
			m_bGoBackFlag?GoBack():GoNext();
		}
		else
		{
			m_bGoBackFlag = FALSE;
			str = L"Enter Cashback";
			str1 = L"Amount";
			CString str2 = m_strCashback;//L"$0.00";
			ShowText(str, str1, str2);
		}
		break;
	case CHIP_DEBITSURCHARGEFEE: //surcharge fee
		if (m_TRREC.CardType == CARD_CREDIT)
		{
			m_bGoBackFlag?GoBack():GoNext();
			return;
		}

		if (!CDataFile::Read(L"SURCHARGE", buf))
		{
			m_bGoBackFlag?GoBack():GoNext();
			return;
		}
		if (CString(buf) == L"$0.00" || CString(buf) == L"")
		{
			m_bGoBackFlag?GoBack():GoNext();
		}
		else
		{
			m_bGoBackFlag = FALSE;
			m_Bt.SetValue(1, L"  Cancel", IDB_CANCEL);
			m_Bt.ShowWindow(SW_SHOW);
			m_Bt1.SetValue(3, L"  OK", IDB_OK);
			m_Bt1.ShowWindow(SW_SHOW);
			str.Format(L"        %s  OK?", CString(buf));
			ShowText(L"Fee", str, L"");
			m_strSurcharge = CString(buf);
			break;
		}
	case CHIP_DEBITTIPSELECT: //TipSelect
		GetTipValue();
		break;
	case CHIP_DEBITTOTALCOMFIRM: // TotalComfirm
		m_bGoBackFlag = FALSE;
		if (DoConfirm(m_bReturnFlag))
			GoNext();
		else
			OnCancel();
		break;
	case CHIP_DEBITSELECTACCOUNT: // SelectAccount
		if (m_TRREC.CardType == CARD_CREDIT)
		{
//			m_bGoBackFlag?GoBack():GoNext();
			m_strMsg2.m_nFormat = DT_LEFT;
			ShowText(L"Please Wait...", L"Do not remove", L"Card!");
			m_iLevel = EMV_WAIT;
			SetKeyReturn(KEY_ENTER);
			return;
		}

		m_bGoBackFlag = FALSE;
		m_Bt.SetValue(1, L"  CHEQUE");
		m_Bt1.SetValue(3, L"  SAVING");
		m_Bt.ShowWindow(SW_SHOW);
		m_Bt1.ShowWindow(SW_SHOW);
		ShowText(L"Select Account", L"", L"");
		break;
	case CHIP_DEBITENTERPIN: //EnterPin
		if (!EMVEnterPin())//Fix me later
		{
			m_strErr1 = L"EMVEnterPin";
			PostMessage(ERROR_MESSAGE, 2, 1);
		}
		else
		{
			if (m_TRREC.CardType == CARD_CREDIT)
			{
				GoNext();
			}
			else
			{
				ShowText(L"Please Wait...", L"", L"");
				GoToLevel(DOTRANSACTION);
			}
		}
		break;
	case CHIP_PASSTOCLERK: //Pass to clerk
		ShowText(L"Pass to clerk", L"Do not remove card", L"");
		SetTimer(1, 3000, NULL);
		break;

	case CHIP_DEBITMERCHANTCOPY: // for merchant copy of the receipt
		if (m_TRREC.ComStatus == ST_OK  &&
				m_TRREC.TranStatus == ST_APPROVED)
			str = L"APPROVED";
		else
			str = L"Unsuccessful";
		m_strMsg2.m_nFormat = DT_LEFT;
		ShowText(str, L"Remove card", L"Pass to clerk");
		Print();
		break;
	case CHIP_DEBITCUSTOMERCOPY: // for Customer copy of the receipt
		ShowText(L"Press OK for", L"customer copy", L"");
		SetTimer(1, 30000, NULL);
		break;
	case CHIP_DEBITWAITCOPYEND: // waiting for Customer copy of the receipt ending...
		if (m_TRREC.ComStatus == ST_OK  &&
				m_TRREC.TranStatus == ST_APPROVED)
		{
			str.Format(L"AUTH : %s", CString(m_TRREC.AuthCode));
			m_strMsg2.m_nFormat = DT_LEFT;
			str1.Format(L"Inv.#: %s", CString(m_TRREC.InvoiceNo));
			ShowText(L"APPROVED", str, str1);
		}
		else
		{
			str.Format(L"Declined %s", CString(m_TRREC.RespCode));
			ShowText(L"Unsuccessful", str, L"");
		}
		break;
	case CHIP_DEBITEND: // ending...
		if (GetScrStatus() == SCR_POWER_ON)	
			ShowText(L"Please",L"Remove Card",L"");
		else
			CDialog::OnCancel();
		break;
// == == == == == == == == == == == == == = Credit Card Sale :C Swiped page 75 == == == == == == == == == == == == == == == == == = 
	case CREDITSWIPEENTRYY://FRAUD CHECK
		m_bCancelPrint = TRUE;
		m_bGoBackFlag = FALSE;
	    if (CDataFile::Read(L"FRAUD CHECK", buf) && CString(buf) == L"Off")
		{
			if (m_bReturnFlag)
				GoToLevel(DOTRANSACTION);
			else
				m_bGoBackFlag?GoBack():GoNext();
		}
		else
		{
			ShowText(L"Enter Last", L"4 Digits", L"");
		}
		break;
	case CREDITSWIPETOCUSTOMER:
	case MANUAL_SWIPETOCUSTOMER:
		if (m_bReturnFlag)
		{
			m_bGoBackFlag?GoBack():GoNext();
			break;
		}
		if (CDataFile::Read(L"TIP PROMPT", buf) && CString(buf) == L"Off")
		{
			m_iLevel = DOTRANSACTION;
			GoToLevel(m_iLevel);
		}
		else
		{
			ShowText(L"Pass to", L"Customer", L"");
			SetTimer(1, 3000, NULL);
			m_bCancelInCustomer = TRUE;
			m_bGoBackFlag = FALSE;
		}
		break;
	case CREDITSWIPETIPSELECT: //TipSelect
	case MANUAL_SWIPETIPSELECT: //TipSelect
		if (m_bReturnFlag)
		{
			m_bGoBackFlag?GoBack():GoNext();
			break;
		}
		GetTipValue();
		break;
	case CREDITSWIPETOTALCOMFIRM: // TotalComfirm
	case MANUAL_SWIPETOTALCOMFIRM: // TotalComfirm
		m_bGoBackFlag = FALSE;
		if (m_bReturnFlag)
		{
			m_bGoBackFlag?GoBack():GoNext();
			break;
		}
		if (DoConfirm(m_bReturnFlag))
			GoNext();
		else
			OnCancel();
		break;
	case CREDITSWIPETOCLERK:  //Pass to clerk
	case MANUAL_SWIPETOCLERK:  //Pass to clerk
		ShowText(L"Pass to", L"clerk", L"");
		SetTimer(1, 3000, NULL);
		break;
	case CREDITMERCHANTCOPY: // for merchant copy of the receipt
		m_strMsg2.m_nFormat = DT_LEFT;
		if (m_TRREC.ComStatus == ST_OK  &&
				m_TRREC.TranStatus == ST_APPROVED)
		{
			str.Format(L"AUTH : %s", CString(m_TRREC.AuthCode));
			m_strMsg2.m_nFormat = DT_LEFT;
			str1.Format(L"Inv.#: %s", CString(m_TRREC.InvoiceNo));
			ShowText(L"APPROVED", str, str1);
		}
		else
		{
			if (strlen(m_TRREC.HostRespText)  > 0)
				str = CString(m_TRREC.HostRespText);
			else
				str.Format(L"Declined %s", CString(m_TRREC.RespCode));
			ShowText(L"Unsuccessful", str, L"");
		}
		Print();
		break;
	case CREDITCUSTOMERCOPY: // for Customer copy of the receipt
		ShowText(L"Press OK for", L"customer copy", L"");
		SetTimer(1, 30000, NULL);
		break;
	case CREDITWAITCOPYEND: // waiting for Customer copy of the receipt ending...
		if (m_TRREC.ComStatus == ST_OK  &&
				m_TRREC.TranStatus == ST_APPROVED)
		{
			str.Format(L"AUTH : %s", CString(m_TRREC.AuthCode));
			m_strMsg2.m_nFormat = DT_LEFT;
			str1.Format(L"Inv.#: %s", CString(m_TRREC.InvoiceNo));
			ShowText(L"APPROVED", str, str1);
		}
		else
		{
			str.Format(L"Declined %s", CString(m_TRREC.RespCode));
			ShowText(L"Unsuccessful", str, L"");
		}
		break;
	case CREDITEND: // ending...
//	case MANUAL_END: // ending...
		CDialog::OnCancel();
		break;

// == == == == == == == == == == == == == == Do transaction (connect to host) == == == == == == == = 
	case DOTRANSACTION:
		DoTransaction();
		break;
	case CANCELENTRY:
		m_bCancelFlag = TRUE;
		ShowText(L"Transaction", L"Cancelled", L"");
		SetTimer(1, 30000, NULL);
		if (m_TRREC.CardError == CARD_NO_ERROR
			&& m_bCancelPrint)
			Print(0);
		break;
	case CANCELTOCLERK:
		if(m_TRREC.bEmvTransaction)
		{
			GoToLevel(EMV_REMOVE_CARD);
			break;
		}
		if (m_bCancelInCustomer)
		{
			ShowText(L"Pass to", L"Clerk", L"");
			SetTimer(1, 3000, NULL);
		}
		else
			CDialog::OnCancel();
		break;

// == == == == == == == Display Window == == == == == 
	case DISPLAY_WINDOW:
		m_strMsg2.m_nFormat = DT_LEFT;
		str = CDisplay::GetLine(1);
		if (str.GetLength() > 0)
			m_strTitle.SetCaption(str);

		str = CDisplay::GetLine(2);
		ShowText(str, CDisplay::GetLine(3), CDisplay::GetLine(4));
		SetDisplayButton();
		break;

	case EMV_SELECT_LANGUAGE: //EMV Select language
		m_Bt.SetValue(1, L" English");
		m_Bt.ShowWindow(SW_SHOW);
		m_Bt1.SetValue(3, L" Francais");
		m_Bt1.ShowWindow(SW_SHOW);
		ShowText(L"Select language", L"Choisir langue", L"");
		break;
	
	case EMV_CONFIRM_AMOUNT: //EMV confirm amount
		str.Format(L"     $ %s  OK?", DealAmountStr(m_TRREC.TotalAmount));
		m_strMsg2.m_nFormat = DT_LEFT;
		ShowText(L"Total :", str, L"Press OK to confirm");
		break;

	case EMV_SELECT_ACCOUNT: //EMV select account
		m_Bt.SetValue(1, L"  CHEQUE");
		m_Bt1.SetValue(3, L"  SAVING");
		m_Bt.ShowWindow(SW_SHOW);
		m_Bt1.ShowWindow(SW_SHOW);
		ShowText(L"Select Account", L"", L"");
		break;
	
	case EMV_REMOVE_CARD: //EMV Remove Card
		if (GetScrStatus() == SCR_POWER_ON)
			ShowText(L"Please",L"Remove Card",L"");
		else
			CDialog::OnCancel();
		break;
	
	case EMV_PASS_COUSTOMER: //EMV Remove Card
		ShowText(L"Pass to", L"Customer", L"");
		break;
	
	case EMV_START: //EMV Remove Card
		StartEMV();
		break;
	}
}
Beispiel #24
0
    int GpibDevice::Open( const char* devname, int address )
    {
	   m_dcs.m_address1 = address;

	   return OpenDevice( devname, &m_dcs );
    }
Beispiel #25
0
struct ifnet *
iface_make(struct ssconfig *ifc)
{
	register struct sana_softc *ssc = NULL;
	register struct IOSana2Req *req;
	struct Sana2DeviceQuery devicequery;

	/* Allocate the request for opening the device */
	if ((req = CreateIOSana2Req(NULL)) == NULL) 
	{
		__log(LOG_ERR, "iface_find(): CreateIOSana2Req failed\n");
	}
	else
	{
		req->ios2_BufferManagement = buffermanagement;

		DSANA(__log(LOG_DEBUG,"Opening device %s unit %ld", ifc->args->a_dev, *ifc->args->a_unit);)
		if (OpenDevice(ifc->args->a_dev, *ifc->args->a_unit, 
			(struct IORequest *)req, 0L))
		{
			sana2perror("OpenDevice", req);
			
			/* Allocate the interface structure */
			ssc = (struct sana_softc *)
			bsd_malloc(sizeof(*ssc) + strlen(ifc->args->a_dev) + 1,
							M_IFNET, M_WAITOK);
  
			if (!ssc)
			{
				__log(LOG_ERR, "iface_find: out of memory\n");
			}
			else
			{
				aligned_bzero_const(ssc, sizeof(*ssc));
			
				/* Save request pointers */
				ssc->ss_dev     = req->ios2_Req.io_Device;
				ssc->ss_unit    = req->ios2_Req.io_Unit;

				ssc->ss_if.if_type = IFT_OTHER;
				ssc->ss_if.if_flags &= ~(IFF_RUNNING|IFF_UP);

				/* Initialize */ 

D(bug("[AROSTCP] if_sana.c: iface_make: Current IP from config = %s\n", ifc->args[0].a_ip));
				ifc->args[0].a_ip = "0.0.0.0";
D(bug("[AROSTCP] if_sana.c: iface_make: IP set to 0.0.0.0\n"));

				ssconfig(ssc, ifc);
	
				NewList((struct List*)&ssc->ss_freereq);

				if_attach((struct ifnet*)ssc);
				ifinit();
	
				ssc->ss_next = ssq;
				ssq = ssc;
			}
		}
		else
		{
			/* Ask for our type, address length, MTU
			* Obl. bitch: nobody tells, WHO is supplying
			* DevQueryFormat and DeviceLevel
			*/
			req->ios2_Req.io_Command   = S2_DEVICEQUERY;
			req->ios2_StatData         = &devicequery;
			devicequery.SizeAvailable  = sizeof(devicequery);
			devicequery.DevQueryFormat = 0L;

			DoIO((struct IORequest *)req);
			if (req->ios2_Req.io_Error)
			{
				sana2perror("S2_DEVICEQUERY", req);
			}
			else
			{
				/* Get Our Station address */
				req->ios2_StatData = NULL;
				req->ios2_Req.io_Command = S2_GETSTATIONADDRESS;
				DoIO((struct IORequest *)req);
		
				if (req->ios2_Req.io_Error)
				{
					sana2perror("S2_GETSTATIONADDRESS", req);
				}
				else
				{
					req->ios2_Req.io_Command = 0;
		  
					/* Allocate the interface structure */
					ssc = (struct sana_softc *)
					bsd_malloc(sizeof(*ssc) + strlen(ifc->args->a_dev) + 1,
									M_IFNET, M_WAITOK);
		  
					if (!ssc)
					{
						__log(LOG_ERR, "iface_find: out of memory\n");
					}
					else
					{
						aligned_bzero_const(ssc, sizeof(*ssc));
			
						/* Save request pointers */
						ssc->ss_dev     = req->ios2_Req.io_Device;
						ssc->ss_unit    = req->ios2_Req.io_Unit;
						ssc->ss_bufmgnt = req->ios2_BufferManagement;
						
						/* Address must be full bytes */
						ssc->ss_if.if_addrlen  = (devicequery.AddrFieldSize + 7) >> 3;
						bcopy(req->ios2_DstAddr, ssc->ss_hwaddr, ssc->ss_if.if_addrlen);
						ssc->ss_if.if_mtu      = devicequery.MTU;
						ssc->ss_maxmtu         = devicequery.MTU;
						ssc->ss_if.if_baudrate = devicequery.BPS;
						ssc->ss_hwtype         = devicequery.HardwareType;	
						
						/* These might be different on different hwtypes */
						ssc->ss_if.if_output = sana_output;
						ssc->ss_if.if_ioctl  = sana_ioctl;
						ssc->ss_if.if_query  = sana_query;

						/* Map SANA-II hardware types to RFC1573 standard */
						switch (ssc->ss_hwtype) 
						{
						case S2WireType_Ethernet:
							ssc->ss_if.if_type = IFT_ETHER;
							break;
						case S2WireType_IEEE802:
							ssc->ss_if.if_type = IFT_IEEE80211;
							break;
						case S2WireType_Arcnet:
							ssc->ss_if.if_type = IFT_ARCNET;
							break;
						case S2WireType_LocalTalk:
							ssc->ss_if.if_type = IFT_LOCALTALK;
							break;
						case S2WireType_PPP:
							ssc->ss_if.if_type = IFT_PPP;
							break;
						case S2WireType_SLIP:
						case S2WireType_CSLIP:
							ssc->ss_if.if_type = IFT_SLIP;
							break;
						case S2WireType_PLIP:
							ssc->ss_if.if_type = IFT_PARA;
							break;
						default:
							ssc->ss_if.if_type = IFT_OTHER;
						}

						/* Initialize */ 
						ssconfig(ssc, ifc);
			
						NewList((struct List*)&ssc->ss_freereq);

						if_attach((struct ifnet*)ssc);
						ifinit();
			
						ssc->ss_next = ssq;
						ssq = ssc;
					}
				}
			}
			if (!ssc)
				CloseDevice((struct IORequest *)req);
		}    
		DeleteIOSana2Req(req);
	}
Beispiel #26
0
int
main(int argc, char *argv[])
{
   struct MsgPort *AROSTCP_Port = NULL;
   
   wait_time = 0;
   
   if ((WFP_rda = ReadArgs(WaitForPort_ArgTemplate, WaitForPort_Arguments, NULL)))
   {
 
      if (WaitForPort_Arguments[0])
      {
D(bug("[WaitForPort] Waiting for '%s' port\n",WaitForPort_Arguments[0]));
      }
      
      timerport = CreateMsgPort();
      if (timerport != NULL)
      {
         /* allocate and initialize the template message structure */
         timerIORequest = (struct timerequest *) CreateIORequest(timerport, sizeof(struct timerequest));

         if (timerIORequest != NULL)
         {
            if (!(OpenDevice(TIMERNAME, UNIT_VBLANK, 
			                      (struct IORequest *)timerIORequest, 0)))
            {
            	/* Make sure that we got at least V36 timer, since we use some
            	 * functions defined only in V36 and later. */

            	if ((timerIORequest->tr_node.io_Device)->dd_Library.lib_Version >= 36)
            	{
            	   /* initialize TimerBase from timerIORequest */
                  TimerBase = timerIORequest->tr_node.io_Device;

            	   /* Initialize some fields of the IO request to common values */
            	   timerIORequest->tr_node.io_Command = TR_ADDREQUEST;

            	   /* NT_UNKNOWN means unused, too (see note on exec/nodes.h) */
            	   timerIORequest->tr_node.io_Message.mn_Node.ln_Type = NT_UNKNOWN;

                  timerIORequest->tr_time.tv_micro = 1000000;
                  wait_limit = timerIORequest->tr_time.tv_micro * 10; /* Default to a 10 second wait */

                  BeginIO((struct IORequest *)timerIORequest);

/* MAIN LOOP */
                  while(1)
                  {
D(bug("[WaitForPort] In Wait Loop ..\n"));
                     ULONG mask = SIGBREAKF_CTRL_C | SIGBREAKF_CTRL_D | (1 << timerport->mp_SigBit);
      					mask = Wait(mask);
                     if (mask & SIGBREAKF_CTRL_C) break;
			         	if (mask & SIGBREAKF_CTRL_D) break;
                     if (mask & (1 << timerport->mp_SigBit))
                     {
D(bug("[WaitForPort] Recieved timer signal? ..\n"));
                        timerIORequest = (struct timerequest *)GetMsg(timerport);
                        if (timerIORequest)
                        {
                           AROSTCP_Port = FindPort((char *)WaitForPort_Arguments[0]);
                           wait_time += 1000000;
                           if (!(AROSTCP_Port))
                           {
                              if (wait_time > wait_limit)
                              {
D(bug("[WaitForPort] Timeout Reached\n"));
                                  break;
                              }
D(bug("[WaitForPort] Port not found .. secs=%d\n",wait_time/1000000));
                           }
                           else
                           {
D(bug("[WaitForPort] Port found ... escaping from wait loop\n"));
                              break;
                           }
                     	   timerIORequest->tr_node.io_Command = TR_ADDREQUEST;
                           timerIORequest->tr_time.tv_micro = 1000000;
                           BeginIO((struct IORequest *)timerIORequest);
                        }
                     }
                  }
               }
            }
         }

/* CLEANUP */

         if (timerIORequest)
         {
            TimerBase = NULL;

            if (timerIORequest->tr_node.io_Device != NULL) CloseDevice((struct IORequest *)timerIORequest);

            DeleteIORequest((struct IORequest *)timerIORequest);
            timerIORequest = NULL;
         }

         if (timerport)
         {
            DeleteMsgPort(timerport);
            timerport = NULL;
         }
      }

      FreeArgs(WFP_rda);
   }
   else
   {
      printf("WaitForPort: Bad Arguments .. Use 'WaitForPort ?' for correct useage\n");
   }

   if (AROSTCP_Port) return RETURN_OK;

   return RETURN_WARN;
}
Beispiel #27
0
static DWORD OpenMidiDevice(UINT DeviceType, DWORD ID, DWORD User, DWORD Param1, DWORD Param2)
{
    PMIDIALLOC pClient = NULL;
    MMRESULT Result = MMSYSERR_NOERROR;
    
    // Check ID?
    DPRINT("OpenMidiDevice()\n");
    
    switch(DeviceType)
    {
        case MidiOutDevice :
            pClient = (PMIDIALLOC) HeapAlloc(Heap, 0, sizeof(MIDIALLOC));
            if ( pClient ) memset(pClient, 0, sizeof(MIDIALLOC));
            break;
        
        case MidiInDevice :
            pClient = (PMIDIALLOC) HeapAlloc(Heap, 0, sizeof(MIDIALLOC) + sizeof(LOCALMIDIDATA));
			if ( pClient ) memset(pClient, 0, sizeof(MIDIALLOC) + sizeof(LOCALMIDIDATA));
            break;
    };
    
    if ( !pClient )
        return MMSYSERR_NOMEM;
    
	if (DeviceType == MidiInDevice) 
	{
        int i;
        pClient->Mid = (PLOCALMIDIDATA)(pClient + 1);
        for (i = 0 ;i < LOCAL_MIDI_BUFFERS ; i++) 
		{
            pClient->Mid->Bufs[i].pClient = pClient;
        }
    }

    pClient->DeviceType = DeviceType;
    pClient->dwCallback = ((LPMIDIOPENDESC)Param1)->dwCallback;
    pClient->dwInstance = ((LPMIDIOPENDESC)Param1)->dwInstance;
    pClient->hMidi = ((LPMIDIOPENDESC)Param1)->hMidi;
    pClient->dwFlags = Param2;
    
    Result = OpenDevice(DeviceType, ID, &pClient->DeviceHandle, (GENERIC_READ | GENERIC_WRITE));
    
    if ( Result != MMSYSERR_NOERROR )
    {
        // cleanup
        return Result;
    }
    
    pClient->Event = CreateEvent(NULL, FALSE, FALSE, NULL);
    
    if ( !pClient->Event )
    {
        // cleanup
        return MMSYSERR_NOMEM;
    }

	if (DeviceType == MidiInDevice) 
	{

        pClient->AuxEvent1 = CreateEvent(NULL, FALSE, FALSE, NULL);
        if (pClient->AuxEvent1 == NULL) 
		{
            // cleanup
            return MMSYSERR_NOMEM;
        }
        
		pClient->AuxEvent2 = CreateEvent(NULL, FALSE, FALSE, NULL);
        if (pClient->AuxEvent2 == NULL) 
		{
            // cleanup
            return MMSYSERR_NOMEM;
        }

        
        // TaskCreate
        
        
       WaitForSingleObject(pClient->AuxEvent2, INFINITE);
    }

    PMIDIALLOC *pUserHandle;
    pUserHandle = (PMIDIALLOC*) User;
    *pUserHandle = pClient;
    
    // callback    

    return MMSYSERR_NOERROR;
}
Beispiel #28
0
static __saveds void net_func(void)
{
	const char *str;
	BYTE od_error;
	struct MsgPort *write_port = NULL, *control_port = NULL;
	struct IOSana2Req *write_io = NULL, *control_io = NULL;
	bool opened = false;
	ULONG read_mask = 0, write_mask = 0, proc_port_mask = 0;
	struct Sana2DeviceQuery query_data = {sizeof(Sana2DeviceQuery)};
	ULONG buffer_tags[] = {
		S2_CopyToBuff, (uint32)copy_to_buff,
		S2_CopyFromBuff, (uint32)copy_from_buff,
		TAG_END
	};

	// Default: error occured
	proc_error = true;

	// Create message port for communication with main task
	proc_port = CreateMsgPort();
	if (proc_port == NULL)
		goto quit;
	proc_port_mask = 1 << proc_port->mp_SigBit;

	// Create message ports for device I/O
	read_port = CreateMsgPort();
	if (read_port == NULL)
		goto quit;
	read_mask = 1 << read_port->mp_SigBit;
	write_port = CreateMsgPort();
	if (write_port == NULL)
		goto quit;
	write_mask = 1 << write_port->mp_SigBit;
	control_port = CreateMsgPort();
	if (control_port == NULL)
		goto quit;

	// Create control IORequest
	control_io = (struct IOSana2Req *)CreateIORequest(control_port, sizeof(struct IOSana2Req));
	if (control_io == NULL)
		goto quit;
	control_io->ios2_Req.io_Message.mn_Node.ln_Type = 0;	// Avoid CheckIO() bug

	// Parse device name
	char dev_name[256];
	ULONG dev_unit;

	str = PrefsFindString("ether");
	if (str) {
		const char *FirstSlash = strchr(str, '/');
		const char *LastSlash = strrchr(str, '/');

		if (FirstSlash && FirstSlash && FirstSlash != LastSlash) {

			// Device name contains path, i.e. "Networks/xyzzy.device"
			const char *lp = str;
			char *dp = dev_name;

			while (lp != LastSlash)
				*dp++ = *lp++;
			*dp = '\0';

			if (strlen(dev_name) < 1)
				goto quit;

			if (sscanf(LastSlash, "/%ld", &dev_unit) != 1)
				goto quit;
		} else {
			if (sscanf(str, "%[^/]/%ld", dev_name, &dev_unit) != 2)
				goto quit;
		}
	} else
		goto quit;

	// Open device
	control_io->ios2_BufferManagement = buffer_tags;
	od_error = OpenDevice((UBYTE *) dev_name, dev_unit, (struct IORequest *)control_io, 0);
	if (od_error != 0 || control_io->ios2_Req.io_Device == 0) {
		printf("WARNING: OpenDevice(<%s>, unit=%d) returned error %d)\n", (UBYTE *)dev_name, dev_unit, od_error);
		goto quit;
	}
	opened = true;

	// Is it Ethernet?
	control_io->ios2_Req.io_Command = S2_DEVICEQUERY;
	control_io->ios2_StatData = (void *)&query_data;
	DoIO((struct IORequest *)control_io);
	if (control_io->ios2_Req.io_Error)
		goto quit;
	if (query_data.HardwareType != S2WireType_Ethernet) {
		WarningAlert(GetString(STR_NOT_ETHERNET_WARN));
		goto quit;
	}

	// Yes, create IORequest for writing
	write_io = (struct IOSana2Req *)CreateIORequest(write_port, sizeof(struct IOSana2Req));
	if (write_io == NULL)
		goto quit;
	memcpy(write_io, control_io, sizeof(struct IOSana2Req));
	write_io->ios2_Req.io_Message.mn_Node.ln_Type = 0;	// Avoid CheckIO() bug
	write_io->ios2_Req.io_Message.mn_ReplyPort = write_port;

	// Configure Ethernet
	control_io->ios2_Req.io_Command = S2_GETSTATIONADDRESS;
	DoIO((struct IORequest *)control_io);
	memcpy(ether_addr, control_io->ios2_DstAddr, 6);
	memcpy(control_io->ios2_SrcAddr, control_io->ios2_DstAddr, 6);
	control_io->ios2_Req.io_Command = S2_CONFIGINTERFACE;
	DoIO((struct IORequest *)control_io);
	D(bug("Ethernet address %08lx %08lx\n", *(uint32 *)ether_addr, *(uint16 *)(ether_addr + 4)));

	// Initialization went well, inform main task
	proc_error = false;
	Signal(MainTask, SIGF_SINGLE);

	// Main loop
	for (;;) {

		// Wait for I/O and messages (CTRL_C is used for quitting the task)
		ULONG sig = Wait(proc_port_mask | read_mask | write_mask | SIGBREAKF_CTRL_C);

		// Main task wants to quit us
		if (sig & SIGBREAKF_CTRL_C)
			break;

		// Main task sent a command to us
		if (sig & proc_port_mask) {
			struct NetMessage *msg;
			while (msg = (NetMessage *)GetMsg(proc_port)) {
				D(bug("net_proc received %08lx\n", msg->what));
				switch (msg->what) {
					case MSG_CLEANUP:
						remove_all_protocols();
						break;

					case MSG_ADD_MULTI:
						control_io->ios2_Req.io_Command = S2_ADDMULTICASTADDRESS;
						Mac2Host_memcpy(control_io->ios2_SrcAddr, msg->pointer + eMultiAddr, 6);
						DoIO((struct IORequest *)control_io);
						if (control_io->ios2_Req.io_Error == S2ERR_NOT_SUPPORTED) {
							WarningAlert(GetString(STR_NO_MULTICAST_WARN));
							msg->result = noErr;
						} else if (control_io->ios2_Req.io_Error)
							msg->result = eMultiErr;
						else
							msg->result = noErr;
						break;

					case MSG_DEL_MULTI:
						control_io->ios2_Req.io_Command = S2_DELMULTICASTADDRESS;
						Mac2Host_memcpy(control_io->ios2_SrcAddr, msg->pointer + eMultiAddr, 6);
						DoIO((struct IORequest *)control_io);
						if (control_io->ios2_Req.io_Error)
							msg->result = eMultiErr;
						else
							msg->result = noErr;
						break;

					case MSG_ATTACH_PH: {
						uint16 type = msg->type;
						uint32 handler = msg->pointer;

						// Protocol of that type already installed?
						NetProtocol *p = (NetProtocol *)prot_list.lh_Head, *next;
						while ((next = (NetProtocol *)p->ln_Succ) != NULL) {
							if (p->type == type) {
								msg->result = lapProtErr;
								goto reply;
							}
							p = next;
						}

						// Allocate NetProtocol, set type and handler
						p = (NetProtocol *)AllocMem(sizeof(NetProtocol), MEMF_PUBLIC);
						if (p == NULL) {
							msg->result = lapProtErr;
							goto reply;
						}
						p->type = type;
						p->handler = handler;

						// Set up and submit read requests
						for (int i=0; i<NUM_READ_REQUESTS; i++) {
							memcpy(p->read_io + i, control_io, sizeof(struct IOSana2Req));
							p->read_io[i].ios2_Req.io_Message.mn_Node.ln_Name = (char *)p;	// Hide pointer to NetProtocol in node name
							p->read_io[i].ios2_Req.io_Message.mn_Node.ln_Type = 0;			// Avoid CheckIO() bug
							p->read_io[i].ios2_Req.io_Message.mn_ReplyPort = read_port;
							p->read_io[i].ios2_Req.io_Command = CMD_READ;
							p->read_io[i].ios2_PacketType = type;
							p->read_io[i].ios2_Data = p->read_buf[i];
							p->read_io[i].ios2_Req.io_Flags = SANA2IOF_RAW;
							BeginIO((struct IORequest *)(p->read_io + i));
						}

						// Add protocol to list
						AddTail(&prot_list, p);

						// Everything OK
						msg->result = noErr;
						break;
					}

					case MSG_DETACH_PH: {
						uint16 type = msg->type;
						msg->result = lapProtErr;
						NetProtocol *p = (NetProtocol *)prot_list.lh_Head, *next;
						while ((next = (NetProtocol *)p->ln_Succ) != NULL) {
							if (p->type == type) {
								remove_protocol(p);
								msg->result = noErr;
								break;
							}
							p = next;
						}
						break;
					}

					case MSG_WRITE: {
						// Get pointer to Write Data Structure
						uint32 wds = msg->pointer;
						write_io->ios2_Data = (void *)wds;

						// Calculate total packet length
						long len = 0;
						uint32 tmp = wds;
						for (;;) {
							int16 w = ReadMacInt16(tmp);
							if (w == 0)
								break;
							len += w;
							tmp += 6;
						}
						write_io->ios2_DataLength = len;

						// Get destination address
						uint32 hdr = ReadMacInt32(wds + 2);
						Mac2Host_memcpy(write_io->ios2_DstAddr, hdr, 6);

						// Get packet type
						uint32 type = ReadMacInt16(hdr + 12);
						if (type <= 1500)
							type = 0;		// 802.3 packet
						write_io->ios2_PacketType = type;

						// Multicast/broadcard packet?
						if (write_io->ios2_DstAddr[0] & 1) {
							if (*(uint32 *)(write_io->ios2_DstAddr) == 0xffffffff && *(uint16 *)(write_io->ios2_DstAddr + 4) == 0xffff)
								write_io->ios2_Req.io_Command = S2_BROADCAST;
							else
								write_io->ios2_Req.io_Command = S2_MULTICAST;
						} else
							write_io->ios2_Req.io_Command = CMD_WRITE;

						// Send packet
						write_done = false;
						write_io->ios2_Req.io_Flags = SANA2IOF_RAW;
						BeginIO((IORequest *)write_io);
						break;
					}
				}
reply:			D(bug(" net_proc replying\n"));
				ReplyMsg(msg);
			}
		}

		// Packet received
		if (sig & read_mask) {
			D(bug(" packet received, triggering Ethernet interrupt\n"));
			SetInterruptFlag(INTFLAG_ETHER);
			TriggerInterrupt();
		}

		// Packet write completed
		if (sig & write_mask) {
			GetMsg(write_port);
			WriteMacInt32(ether_data + ed_Result, write_io->ios2_Req.io_Error ? excessCollsns : 0);
			write_done = true;
			D(bug(" packet write done, triggering Ethernet interrupt\n"));
			SetInterruptFlag(INTFLAG_ETHER);
			TriggerInterrupt();
		}
	}
quit:

	// Close everything
	remove_all_protocols();
	if (opened) {
		if (CheckIO((struct IORequest *)write_io) == 0) {
			AbortIO((struct IORequest *)write_io);
			WaitIO((struct IORequest *)write_io);
		}
		CloseDevice((struct IORequest *)control_io);
	}
	if (write_io)
		DeleteIORequest(write_io);
	if (control_io)
		DeleteIORequest(control_io);
	if (control_port)
		DeleteMsgPort(control_port);
	if (write_port)
		DeleteMsgPort(write_port);
	if (read_port)
		DeleteMsgPort(read_port);

	// Send signal to main task to confirm termination
	Forbid();
	Signal(MainTask, SIGF_SINGLE);
}
Beispiel #29
0
MMRESULT
FAR PASCAL
modMessage(
    UINT device_id,
    UINT message,
    DWORD_PTR private_data,
    DWORD_PTR parameter1,
    DWORD_PTR parameter2)
{
    switch ( message )
    {
        case MODM_GETNUMDEVS :
        {
            /* Only one internal PC speaker device (and even that's too much) */
            DPRINT("MODM_GETNUMDEVS\n");
            return 1;
        }

        case MODM_GETDEVCAPS :
        {
            DPRINT("MODM_GETDEVCAPS\n");
            return GetDeviceCapabilities((MIDIOUTCAPS*) parameter1);
        }

        case MODM_OPEN :
        {
            DPRINT("MODM_OPEN\n");

            return OpenDevice((DeviceInfo**) private_data,
                              (MIDIOPENDESC*) parameter1,
                              parameter2);
        }

        case MODM_CLOSE :
        {
            DPRINT("MODM_CLOSE\n");
            return CloseDevice((DeviceInfo*) private_data);
        }

        case MODM_DATA :
        {
            return ProcessShortMidiMessage((DeviceInfo*) private_data, parameter1);
        }

        case MODM_PREPARE :
        {
            /* We don't bother with this */
            MIDIHDR* hdr = (MIDIHDR*) parameter1;
            hdr->dwFlags |= MHDR_PREPARED;
            return MMSYSERR_NOERROR;
        }

        case MODM_UNPREPARE :
        {
            MIDIHDR* hdr = (MIDIHDR*) parameter1;
            hdr->dwFlags &= ~MHDR_PREPARED;
            return MMSYSERR_NOERROR;
        }

        case MODM_LONGDATA :
        {
            DPRINT("LONGDATA\n");
            return ProcessLongMidiMessage((DeviceInfo*) private_data, (MIDIHDR*) parameter1);
        }

        case MODM_RESET :
        {
            /* TODO */
            break;
        }
    }

    DPRINT("Not supported %d\n", message);

    return MMSYSERR_NOTSUPPORTED;
}
JNIEXPORT void JNICALL
Java_net_sf_jaer_hardwareinterface_usb_usbaermapper_USBAERatc_nativeUpload(JNIEnv *env, jobject, jstring device, jstring path, jboolean SelMapper, jboolean SelDatalogger, jboolean SelOthers, jlong inicio)//inicio -> 0 normalmente
{
	const char *specifiedDevice, *devicePath;
	specifiedDevice=(*env).GetStringUTFChars(device,NULL);
	devicePath=(*env).GetStringUTFChars(path,NULL);

	if(specifiedDevice==NULL || devicePath==NULL){
		return;
	}

	hDevice = OpenDevice(specifiedDevice);
    FILE *fileinput;
    unsigned long count = 0;
    unsigned long counta = 0;
    unsigned long nWrite;
    unsigned long longitud,longtoload;
    char buf[262144];
    int i;
    unsigned int paso = 262144;

    if (hDevice == INVALID_HANDLE_VALUE)
	{
		return;
	}
	else
	{
        fileinput = fopen(devicePath ,"rb");
        if(fileinput) {

                fseek(fileinput,0,SEEK_END);
                longitud = ftell(fileinput);
                fseek(fileinput,0,SEEK_SET);

                buf[0]='A';
                buf[1]='T';
                buf[2]='C';
                buf[3]= 1;   // comando 1 es grabar RAM
                for(i=4;i<8;i++)
                        buf[i]=(longitud>>(8*(i-4)))&0xff;

                // Los siguientes bytes son los comandos que va a recibir la FPGA
                //if (SelMapper)
                   for(i=8;i<12;i++)
                        buf[i]=(inicio>>(8*(i-8)))&0xff;
                
                /*if (SelDatalogger)
                {  
					buf[8]=4;  // Comando de habilitación de escritura
                    buf[9]=3;  // Subcomando de establec. de la direcc
                    for(i=10;i<14;i++)
                        buf[i]=(inicio>>(8*(i-8)))&0xff;
                }*/

				//temporalmente comentado, desbloquearlo para su futuro uso
                /*if (SelOthers)
                {  
					for(i=8;i<24;i++)
                        buf[i]=commands[i-8];
                }*/

                WriteFile(hDevice, buf,(unsigned long) 64, &nWrite, NULL);

				if(nWrite != 64)
				{
					return;
				}
                else
                {
                    while(!feof(fileinput))
                    {
						count = fread(buf, sizeof( char ), paso, fileinput);
						longtoload=(unsigned long)64*(ceilf((float)count/64));
						counta=counta+count;
						WriteFile(hDevice, buf, (unsigned long)longtoload, &nWrite, NULL);
                    }
                }
         }
         fclose(fileinput);
         CloseHandle(hDevice);
	}
	return;
}