Beispiel #1
0
void CloseConsole(void)
{
	if(!(CheckIO((struct IORequest *)conreadreq))) {
		AbortIO((struct IORequest *)conreadreq);
		WaitIO((struct IORequest *)conreadreq);
	}
	if(!(CheckIO((struct IORequest *)conwritereq))) {
		AbortIO((struct IORequest *)conwritereq);
		WaitIO((struct IORequest *)conwritereq);
	}
	CloseDevice((struct IORequest *)conwritereq);
}
Beispiel #2
0
/* Waits for a signal or a timeout */
ULONG ata_WaitTO(struct IORequest* tmr, ULONG secs, ULONG micro, ULONG sigs)
{
    ULONG sig = 1 << tmr->io_Message.mn_ReplyPort->mp_SigBit;

    D(struct Node *t = (struct Node *)FindTask(NULL));
    D(bug("[ATA  ] Timed wait %lds %ldu (task='%s')\n", secs, micro,
        t->ln_Name));

    tmr->io_Command = TR_ADDREQUEST;
    ((struct timerequest*)tmr)->tr_time.tv_secs = secs;
    ((struct timerequest*)tmr)->tr_time.tv_micro = micro;

    SendIO(tmr);
    D(bug("[ATA  ] Preset signals: %lx ('%s')\n", SetSignal(0, 0), t->ln_Name));
    D(bug("[ATA  ] Signals requested: %lx ('%s')\n", sigs, t->ln_Name));
    D(bug("[ATA  ] Timer signal: %lx ('%s')\n", sig, t->ln_Name));
    sigs = Wait(sigs | sig);
    D(bug("[ATA  ] Signals received: %lx ('%s')\n", sigs, t->ln_Name));
    if (0 == (sigs & sig))
    {
	if (!CheckIO(tmr))
	    AbortIO(tmr);
    }
    WaitIO(tmr);

    SetSignal(0, sig);

    return sigs & ~sig;
}
Beispiel #3
0
void CloseTimer(struct timerequest *treq) {
	if(!(CheckIO((struct IORequest *)timerreq))) {
		AbortIO((struct IORequest *)timerreq);
		WaitIO((struct IORequest *)timerreq);
	}
	CloseDevice((struct IORequest *)treq);
}
Beispiel #4
0
int lib_exec_f_CheckIO_2(emumsg_syscall_t *msg)
{
	/* Make real syscall */
	msg->arg[0]._aptr = CheckIO((struct IORequest *)msg->arg[0]._aptr);

	return HOOK_DONE;
}
Beispiel #5
0
void
ti_Cleanup(Global_T *g)
{
#ifndef DISABLED
    SyncTimer *st = &g->g_SyncTimer;

    if(st->st_Pkt)
    {
	if(st->st_Req)
	{
	    if(st->st_Flags & STF_TIMER_USED)
	    {
    		if(!CheckIO(&st->st_Req->Request))
		      AbortIO(&st->st_Req->Request);

    		WaitIO(&st->st_Req->Request);
	    }

      if(st->st_Flags & STF_DEVICE_OPEN)
		    CloseDevice(&st->st_Req->Request);
	}
    }

    if(st->st_Pkt)
    	FreeVec(st->st_Pkt);

    if(st->st_Req)
	    DeleteIORequest(st->st_Req);
    
    memset(st, 0, sizeof(*st));
#endif
}
void static AHI_WaitAudio(_THIS)
{
	if(!CheckIO((struct IORequest *)audio_req[current_buffer]))
	{
		WaitIO((struct IORequest *)audio_req[current_buffer]);
//		AbortIO((struct IORequest *)audio_req[current_buffer]);
	}
}
Beispiel #7
0
long __saveds __regargs nik_sread(char *databuffer,long size,long timeout) {
    ULONG signals,sersig=1L << serreadport->mp_SigBit,
                  timersig=1L << timerport->mp_SigBit;
    if(timeout) {
        serreadreq->IOSer.io_Command=CMD_READ;
        serreadreq->IOSer.io_Length=size;
        serreadreq->IOSer.io_Data=(APTR)databuffer;
        SendIO((struct IORequest *)serreadreq);
        timerreq->tr_node.io_Command=TR_ADDREQUEST;
        timerreq->tr_time.tv_secs=timeout/1000000;
        timerreq->tr_time.tv_micro=timeout%1000000;
        timerreq->tr_node.io_Message.mn_ReplyPort=timerport;
        SendIO((struct IORequest *)timerreq);
        for(;;) {
            signals=Wait(sersig | timersig);
            if((signals & sersig) && CheckIO((struct IORequest *)serreadreq)) {
                WaitIO((struct IORequest *)serreadreq);
                AbortIO((struct IORequest *)timerreq);
                WaitIO((struct IORequest *)timerreq);
                if(serreadreq->IOSer.io_Error || carrierdropped()) return(-1L);
                return((long)serreadreq->IOSer.io_Actual);
            }
            if((signals & timersig) && CheckIO((struct IORequest *)timerreq)) {
                WaitIO((struct IORequest *)timerreq);
                AbortIO((struct IORequest *)serreadreq);
                WaitIO((struct IORequest *)serreadreq);
                /* printf("Timeout! Size=%d Timeout=%d Actual=%d",size,timeout,serreadreq->IOSer.io_Actual); */
                return((long)serreadreq->IOSer.io_Actual);
            }
        }
    } else {
        serreadreq->IOSer.io_Command=SDCMD_QUERY;
        DoIO((struct IORequest *)serreadreq);
        serreadreq->IOSer.io_Command=CMD_READ;
        if(serreadreq->IOSer.io_Actual > size) serreadreq->IOSer.io_Length=size;
        else serreadreq->IOSer.io_Length=serreadreq->IOSer.io_Actual;
        serreadreq->IOSer.io_Data=(APTR)databuffer;
        DoIO((struct IORequest *)serreadreq);
        return((long)serreadreq->IOSer.io_Actual);
    }
}
Beispiel #8
0
void ami_remove_timer_event(struct nscallback *nscb)
{
	if(!nscb) return;

	if(nscb->treq)
	{
		if(CheckIO((struct IORequest *)nscb->treq)==NULL)
   			AbortIO((struct IORequest *)nscb->treq);

		WaitIO((struct IORequest *)nscb->treq);
		FreeVec(nscb->treq);
	}
}
Beispiel #9
0
void closetimer()
{
	if (TimerIO)
	{
		/* Delete any pending timer requests */
		if (!(CheckIO((struct IORequest *)TimerIO))) AbortIO((struct IORequest *)TimerIO);

		CloseDevice((struct IORequest *) TimerIO);
		DeleteExtIO((struct IORequest *) TimerIO);
	}

	if (TimerMP)
	{
		DeletePort(TimerMP);
	}
}
Beispiel #10
0
ULONG sdcard_WaitTO(struct IORequest* tmr, ULONG secs, ULONG micro, ULONG sigs)
{
    ULONG sig = 1 << tmr->io_Message.mn_ReplyPort->mp_SigBit;

    tmr->io_Command = TR_ADDREQUEST;
    ((struct timerequest*)tmr)->tr_time.tv_secs = secs;
    ((struct timerequest*)tmr)->tr_time.tv_micro = micro;

    SendIO(tmr);
    sigs = Wait(sigs | sig);
    if (0 == (sigs & sig))
    {
	if (!CheckIO(tmr))
	    AbortIO(tmr);
    }
    WaitIO(tmr);

    SetSignal(0, sig);

    return sigs &~ sig;
}
Beispiel #11
0
int getfifoevent(struct MsgPort *fifoport, char *puthere)
{
	struct IntuiMessage *mymess;
	struct NiKMess *nikmess;
	ULONG signals,conreadsig=1L << conreadport->mp_SigBit,windsig=1L << NiKwind->UserPort->mp_SigBit,
		fifosig=1L << fifoport->mp_SigBit, nikomnodesig = 1L << nikomnodeport->mp_SigBit;
	int event=0;
	while(!event) {
		signals = Wait(conreadsig | windsig | fifosig | nikomnodesig | SIGBREAKF_CTRL_C);
		if((signals & conreadsig) && CheckIO((struct IORequest *)conreadreq)) {
			*puthere=congettkn();
			event|=FIFOEVENT_FROMUSER;
		}
		if(signals & windsig) {
			mymess=(struct IntuiMessage *)GetMsg(NiKwind->UserPort);
			ReplyMsg((struct Message *)mymess);
			AbortIO((struct IORequest *)conreadreq);
			WaitIO((struct IORequest *)conreadreq);
			event|=FIFOEVENT_CLOSEW;
		}
		if(signals & SIGBREAKF_CTRL_C) {
			AbortIO((struct IORequest *)conreadreq);
			WaitIO((struct IORequest *)conreadreq);
			event|=FIFOEVENT_CLOSEW;
		}
		if(signals & fifosig) {
			event|=FIFOEVENT_FROMFIFO;
		}
		if(signals & nikomnodesig) {
			while(nikmess = (struct NiKMess *) GetMsg(nikomnodeport)) {
				handleservermess(nikmess);
				ReplyMsg((struct Message *)nikmess);
			}
			if(carrierdropped()) event |= FIFOEVENT_NOCARRIER;
		}
	}
	return(event);
}
Beispiel #12
0
/*
 *******************************************************************
 * Function: CKERROR BGWrapperCB(const CKBehaviorContext& behContext)
 *
 * Description : The Behavior Callback function is called by Virtools 
 *               when various events happen in the life of a BuildingBlock.
 *
 * Parameters :
 *    behaviourContext	      Behavior context reference, which gives access to 
 *                            frequently used global objects ( context, level, manager, etc... )
 *
 * Returns : CKERROR
 *
 *******************************************************************
 */
CKERROR GBLCOBGWrapper::BGWrapperCB(const CKBehaviorContext& behContext)
{
	CKERROR	result = CKBR_GENERICERROR; 

	// Initialize common pointers.	
	CKBehavior *behaviour   = behContext.Behavior;
	CKContext  *context   = behContext.Context;
	CKLevel    *level = behContext.CurrentLevel;
	CKBeObject *owner = behContext.Behavior->GetOwner();
	
	char*name = behaviour->GetName();
	
	if ( behaviour == NULL || context == NULL || level == NULL /*|| owner == NULL*/ )
		return CKBR_OK;
	
	//Get The BG Script Object if exists
	CKBehavior* newBG = NULL;
	CKBehavior* curBG = (CKBehavior*)behaviour->GetLocalParameterObject(EGBLCOBGWRAPPERPARAM_PARAMETER_SCRIPT);

	// Get the BG nms file path. GetStringValue doesn't work with setting...
	char fileName[_MAX_PATH+1];
	memset(fileName,0,_MAX_PATH+1);
	CKParameter* scriptPath  = behaviour->GetLocalParameter(EGBLCOBGWRAPPERPARAM_PARAMETER_NAME);
	if ( scriptPath == NULL )
		return CKBR_OK;
	
	int lenPath  = scriptPath->GetDataSize();
	if ( lenPath >= _MAX_PATH )
		return CKBR_OK;
	
	void*ptrPath = scriptPath->GetReadDataPtr(TRUE);
	if ( ptrPath == NULL )
		return CKBR_OK;
	
	memcpy(fileName,ptrPath,lenPath);

	CKDWORD message = behContext.CallbackMessage;

	switch (message)
		{
		case CKM_BEHAVIORLOAD :				// when the behavior is loaded
		case CKM_BEHAVIORRESET:				// when the behavior is reseted
		case CKM_BEHAVIORSETTINGSEDITED :	// when the settings are edited
			{
				if ( curBG != NULL )
				{
					DestroyCurrentBG(level,behaviour,curBG);
					curBG = NULL;
				}

				newBG = BGLoader( fileName, behContext );
				if ( newBG == NULL )
					return CKBR_OK;
				
				if ( message == CKM_BEHAVIORLOAD || message == CKM_BEHAVIORRESET )
				{
					//context->OutputToConsoleExBeep("%s : LOADED %s",behaviour->GetName(), fileName);
					if ( CheckIO(behaviour, newBG) == TRUE )
						result = CKBR_OK;
					else	
						context->OutputToConsoleExBeep("%s : Too many inputs/outputs changes in %s\r\nPlease reconstruct the wrapper.",behaviour->GetName(), fileName);
				}
				else if ( message == CKM_BEHAVIORSETTINGSEDITED )
				{
					if ( CheckIO(behaviour, newBG) == TRUE )
					{					
						result = CKBR_OK;
					}
					else if (DeleteIO(behaviour) == TRUE)
					{
						if ( CreateIO(behaviour, newBG ) == TRUE )
							result = CKBR_OK;
						else	
							context->OutputToConsoleExBeep("%s : Cannot Create Inputs/Outputs %s",behaviour->GetName(), fileName);
					}
					else
						context->OutputToConsoleExBeep("%s : Cannot Delete Inputs/Outputs %s",behaviour->GetName(), fileName);
				}

				if ( result == CKBR_OK && newBG != NULL )
					SetNewBG(behaviour,newBG);
			}
			break;
	
		case CKM_BEHAVIORDEACTIVATESCRIPT:
			{
				if ( curBG != NULL )
					DesactivateSubBB(curBG);
				result = CKBR_OK;
			}
			break;
		
		case CKM_BEHAVIORDETACH : // when the behavior is deleted
			{
				if (curBG != NULL)
				{
					DestroyCurrentBG(level,behaviour,curBG);
					curBG = NULL;
				}
				result = CKBR_OK;
			}
			break;				
		
		default: 
			{
				result = CKBR_OK;
			}
			break;

		}
		
	if (result != CKBR_OK)
		context->OutputToConsoleExBeep("%s : Problem while manipulating",behaviour->GetName());



	return result;
	}
Beispiel #13
0
long HandleServerMsg(void)
{
	unsigned long PubScreenModes;
	BlankMsg *CurMsg;
	
	while(CurMsg = (BlankMsg *)GetMsg(ServerPort))
	{
		long Type = CurMsg->bm_Type;
		long Flags = CurMsg->bm_Flags;

		if(Flags & BF_REPLY)
		{
			if(!(Flags & BF_INTERNAL))
				FreeVec(CurMsg);
		}
		else
		{
			CurMsg->bm_Flags |= BF_REPLY;
			ReplyMsg((struct Message *)CurMsg);
		}
		
		switch(Type)
		{
		case BM_DOBLANK:
			if(Flags & BF_REPLY)
			{
				if(!CheckIO((struct IORequest *)TimeOutIO))
				{
					AbortIO((struct IORequest *)TimeOutIO);
					WaitIO((struct IORequest *)TimeOutIO);
					SetSignal(0L, SIG_TIMER);
				}
				if(ServerScr)
				{
					UnblankMousePointer(Wnd);
					CloseScreen(ServerScr);
					ServerScr = 0L;
				}
				if(!PingTask)
					PingTask = CreateTask("GarshnePing", -5, PingFunc, 4096);
				Blanking = TRUE;
			}
			break;
		case BM_DOTESTBLANK:
			if(Flags & BF_REPLY)
			{
				if(!PingTask)
					PingTask = CreateTask("GarshnePing", -5, PingFunc, 4096);
				Blanking = TRUE;
			}
			break;
		case BM_INITMSG:
			if(BlankAfterInit)
			{
				BlankAfterInit = FALSE;
				MessageModule("GarshneClient", BM_DOBLANK);
			}
			break;
		case BM_FAILED:
			if(PingTask)
			{
				Signal(PingTask, SIGBREAKF_CTRL_C);
				PingTask = 0L;
			}
			InternalBlank();
			break;
		case BM_SENDBLANK:
			if((Flags & BF_REPLY)|| BlankingDisabled)
				break;
			if(ServerScr &&(UsagePercent() > 40))
				break;
			PubScreenModes = SetPubScreenModes(0L);
			if(Stricmp(Prefs->bp_Blanker, "Random"))
			{
				if(!Blanking || ServerScr)
					MessageModule("GarshneClient", BM_DOBLANK);
			}
			else
			{
				if(!Blanking || Prefs->bp_Flags & BF_REPLACE)
				{
					MessageModule("GarshneClient", BM_DELAYEDQUIT);
					BlankAfterInit = TRUE;
					LoadModule(Prefs->bp_Dir, Prefs->bp_Blanker);
				}
				else if(ServerScr)
					MessageModule("GarshneClient", BM_DOBLANK);
			}
			SetPubScreenModes(PubScreenModes);
			break;
		case BM_SENDTEST:
			if((Flags & BF_REPLY)|| BlankingDisabled)
				break;
			PubScreenModes = SetPubScreenModes(0L);
			MessageModule("GarshneClient", BM_DOTESTBLANK);
			SetPubScreenModes(PubScreenModes);
			break;
		case BM_SENDUNBLANK:
			if(Flags & BF_REPLY)
				break;
			if(ServerScr)
			{
				UnblankMousePointer(Wnd);
				CloseScreen(ServerScr);
				ServerScr = 0L;
			}
			Blanking = FALSE;
			MessageModule("GarshneClient", BM_UNBLANK);
			if(PingTask)
			{
				Signal(PingTask, SIGBREAKF_CTRL_C);
				PingTask = 0L;
			}
			break;
		default:
			break;
		}
	}

	return OK;
}
Beispiel #14
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 #15
0
int sendbinfile(void) {
    struct TransferFiles *tf;
    int xprreturkod,cnt=0;
    if(!(XProtocolBase=(struct Library *)OpenLibrary("xprzmodem.library",0L)))
    {
        puttekn("\r\n\nKunde inte öppna xprzmodem.library!\r\n",-1);
        return(2);
    }
    if(!(xio=(struct XPR_IO *)AllocMem(sizeof(struct XPR_IO),MEMF_PUBLIC | MEMF_CLEAR))) {
        puttekn("\r\n\nKunde inte allokera en io-struktur\r\n",-1);
        CloseLibrary(XProtocolBase);
        return(2);
    }
    puttekn("\r\nDu kan börja ta emot med Zmodem.\r\n",-1);
    puttekn("Tryck Ctrl-X några gånger för att avbryta.\r\n",-1);
    AbortIO((struct IORequest *)serreadreq);
    WaitIO((struct IORequest *)serreadreq);
    if(!CheckIO((struct IORequest *)inactivereq)) {
        AbortIO((struct IORequest *)inactivereq);
        WaitIO((struct IORequest *)inactivereq);
    }

    xpr_setup(xio);
    xio->xpr_filename=zinitstring;
    XProtocolSetup(xio);
    xio->xpr_filename="Hejhopp";
    xprreturkod=XProtocolSend(xio);
    Delay(30);
    XProtocolCleanup(xio);
    CloseLibrary(XProtocolBase);
    if(!CheckIO((struct IORequest *)serreadreq)) {
        AbortIO((struct IORequest *)serreadreq);
        WaitIO((struct IORequest *)serreadreq);
        printf("Serreadreq avbruten!!\n");
    }
    if(!CheckIO((struct IORequest *)timerreq)) {
        AbortIO((struct IORequest *)timerreq);
        WaitIO((struct IORequest *)timerreq);
        printf("Timerreq avbruten!!\n");
    }
    FreeMem(xio,sizeof(struct XPR_IO));
    Delay(100);
    serchangereq->IOSer.io_Command=CMD_CLEAR;
    DoIO((struct IORequest *)serchangereq);
    serchangereq->IOSer.io_Command=CMD_FLUSH;
    DoIO((struct IORequest *)serchangereq);
    serreqtkn();
    updateinactive();
    if(Servermem->cfg.logmask & LOG_SENDFILE) {
        for(tf=(struct TransferFiles *)tf_list.mlh_Head; tf->node.mln_Succ; tf=(struct TransferFiles *)tf->node.mln_Succ)
            if(tf->sucess) {
                LogEvent(USAGE_LOG, INFO, "Skickar filen %s till %s",
                         tf->path, getusername(inloggad));
            }
    }
    for(tf=(struct TransferFiles *)tf_list.mlh_Head; tf->node.mln_Succ; tf=(struct TransferFiles *)tf->node.mln_Succ)
        if(tf->sucess) cnt++;
    if(cnt==1) strcpy(outbuffer,"\n\n\rFörde över 1 fil.\n\n\r");
    else sprintf(outbuffer,"\n\n\rFörde över %d filer.\n\n\r",cnt);
    puttekn(outbuffer,-1);
    return(0);
}
Beispiel #16
0
int recbinfile(char *dir) {
    int xprreturkod;
    char zmodeminit[100];

    ulfiles = 0;
    if(access(dir,0)) {
        puttekn("\r\nDirectoryt finns inte!\r\n",-1);
        return 2;
    }

    if(Servermem->cfg.diskfree != 0
            && !HasPartitionEnoughFreeSpace(dir, Servermem->cfg.diskfree)) {
        puttekn("\r\nTyvärr, gränsen för hur full disken får bli har överskridits!\r\n",-1);
        return 2;
    }

    if(Servermem->cfg.ar.preup2) {
        sendautorexx(Servermem->cfg.ar.preup2);
    }
    sprintf(zmodeminit,"%s%s",zinitstring,dir);
    if(!(XProtocolBase = (struct Library *) OpenLibrary("xprzmodem.library", 0L))) {
        puttekn("\r\n\nKunde inte öppna xprzmodem.library!\r\n",-1);
        return 2;
    }
    if(!(xio = (struct XPR_IO *)
               AllocMem(sizeof(struct XPR_IO), MEMF_PUBLIC | MEMF_CLEAR))) {
        puttekn("\r\n\nKunde inte allokera en io-struktur\r\n",-1);
        CloseLibrary(XProtocolBase);
        return 2;
    }
    NewList((struct List *)&tf_list);

    puttekn("\r\nDu kan börja sända med Zmodem. Du kan nu skicka fler filer!",-1);
    puttekn("\r\nTryck Ctrl-X några gånger för att avbryta.\r\n",-1);
    AbortIO((struct IORequest *)serreadreq);
    WaitIO((struct IORequest *)serreadreq);
    if(!CheckIO((struct IORequest *)inactivereq)) {
        AbortIO((struct IORequest *)inactivereq);
        WaitIO((struct IORequest *)inactivereq);
    }
    xpr_setup(xio);
    xio->xpr_filename = zmodeminit;
    XProtocolSetup(xio);
    xprreturkod = XProtocolReceive(xio);
    Delay(30);
    XProtocolCleanup(xio);
    CloseLibrary(XProtocolBase);
    if(!CheckIO((struct IORequest *)serreadreq)) {
        AbortIO((struct IORequest *)serreadreq);
        WaitIO((struct IORequest *)serreadreq);
        printf("Serreadreq avbruten!!\n");
    }
    if(!CheckIO((struct IORequest *)timerreq)) {
        AbortIO((struct IORequest *)timerreq);
        WaitIO((struct IORequest *)timerreq);
        printf("Timerreq avbruten!!\n");
    }
    FreeMem(xio,sizeof(struct XPR_IO));
    Delay(100);
    serchangereq->IOSer.io_Command=CMD_CLEAR;
    DoIO((struct IORequest *)serchangereq);
    serchangereq->IOSer.io_Command=CMD_FLUSH;
    DoIO((struct IORequest *)serchangereq);
    serreqtkn();
    updateinactive();
    if(Servermem->cfg.ar.postup2) {
        sendautorexx(Servermem->cfg.ar.postup2);
    }

    if(ulfiles > 0) {
        puttekn("\r\n\nÖverföringen lyckades.\r\n",-1);
        return 0;
    }
    else {
        puttekn("\r\n\nÖverföringen misslyckades.\r\n",-1);
        return 2;
    }
}
Beispiel #17
0
int SerialPort::ReadPort()
{ 
	return CheckIO(portfd, 0, 0, buf, &bytesRead);
}
Beispiel #18
0
int recbinfile(char *dir) {
	int xprreturkod,bytesfree;
	char zmodeminit[100];
	struct InfoData *id;
	BPTR lock;

	ulfiles = 0;
	if(access(dir,0)) {
		puttekn("\r\nDirectoryt finns inte!\r\n",-1);
		return(2);
	}
	if(!(id=AllocMem(sizeof(struct InfoData),MEMF_CLEAR))) {
		puttekn("\r\nKunde inte allokera en InfoData-struktur!\r\n",-1);
		return(2);
	}
	if(!(lock=Lock(dir,ACCESS_READ))) {
		puttekn("\r\nKunde inte få ett Lock för directoryt!\r\n",-1);
		FreeMem(id,sizeof(struct InfoData));
		return(2);
	}
	if(!Info(lock,id)) {
		puttekn("\r\nKunde inte få info om devicet!\r\n",-1);
		UnLock(lock);
		FreeMem(id,sizeof(struct InfoData));
		return(2);
	}
	bytesfree=(id->id_NumBlocks - id->id_NumBlocksUsed)*id->id_BytesPerBlock;
	UnLock(lock);
	FreeMem(id,sizeof(struct InfoData));
	if(bytesfree < Servermem->cfg.diskfree) {
		puttekn("\r\nTyvärr, gränsen för hur full disken får bli har överskridits!\r\n",-1);
		return(2);
	}
	if(Servermem->cfg.ar.preup2) sendrexx(Servermem->cfg.ar.preup2);
	sprintf(zmodeminit,"%s%s",zinitstring,dir);
	if(!(XProtocolBase=(struct Library *)OpenLibrary("xprzmodem.library",0L))) {
		puttekn("\r\n\nKunde inte öppna xprzmodem.library!\r\n",-1);
		return(2);
	}
	if(!(xio=(struct XPR_IO *)AllocMem(sizeof(struct XPR_IO),MEMF_PUBLIC | MEMF_CLEAR))) {
		puttekn("\r\n\nKunde inte allokera en io-struktur\r\n",-1);
		CloseLibrary(XProtocolBase);
		return(2);
	}
	NewList((struct List *)&tf_list);

	puttekn("\r\nDu kan börja sända med Zmodem. Du kan nu skicka fler filer!",-1);
	puttekn("\r\nTryck Ctrl-X några gånger för att avbryta.\r\n",-1);
	AbortIO((struct IORequest *)serreadreq);
	WaitIO((struct IORequest *)serreadreq);
	if(!CheckIO((struct IORequest *)inactivereq)) {
		AbortIO((struct IORequest *)inactivereq);
		WaitIO((struct IORequest *)inactivereq);
	}
	xpr_setup(xio);
	xio->xpr_filename=zmodeminit;
	XProtocolSetup(xio);
	xprreturkod=XProtocolReceive(xio);
	Delay(30);
	XProtocolCleanup(xio);
	CloseLibrary(XProtocolBase);
	if(!CheckIO((struct IORequest *)serreadreq)) {
		AbortIO((struct IORequest *)serreadreq);
		WaitIO((struct IORequest *)serreadreq);
		printf("Serreadreq avbruten!!\n");
	}
	if(!CheckIO((struct IORequest *)timerreq)) {
		AbortIO((struct IORequest *)timerreq);
		WaitIO((struct IORequest *)timerreq);
		printf("Timerreq avbruten!!\n");
	}
	FreeMem(xio,sizeof(struct XPR_IO));
	Delay(100);
	serchangereq->IOSer.io_Command=CMD_CLEAR;
	DoIO((struct IORequest *)serchangereq);
	serchangereq->IOSer.io_Command=CMD_FLUSH;
	DoIO((struct IORequest *)serchangereq);
	serreqtkn();
	updateinactive();
	if(Servermem->cfg.ar.postup2) sendrexx(Servermem->cfg.ar.postup2);
/*	if(Servermem->cfg.logmask & LOG_RECFILE) {
		sprintf(outbuffer,"Tar emot filen %s från %s",xprfilnamn,getusername(inloggad));
		logevent(outbuffer);
	}
	if(xprreturkod) {
		puttekn("\r\n\nÖverföringen lyckades.\r\n",-1);
		sprintf(outbuffer,"Hastighet: %d cps\n\r",cps);
		puttekn(outbuffer,-1);
		return(0);
	} else {
		puttekn("\r\n\nÖverföringen misslyckades.\r\n",-1);
		return(2);
	} Removed by Tomas Kärki 22/1 1996 */

	if(ulfiles > 0) {
		puttekn("\r\n\nÖverföringen lyckades.\r\n",-1);
		return(0);
	}
	else {
		puttekn("\r\n\nÖverföringen misslyckades.\r\n",-1);
		return(2);
	}
}
Beispiel #19
0
void checkinterrupt(void)
{
  CheckIO();
  interruptcount = interruptfreq;
  if(interrupted) systemerror(1);
}
Beispiel #20
0
__saveds void ASERDPort::serial_func(void)
{
	struct ASERDPort *obj = (ASERDPort *)proc_arg;
	struct MsgPort *proc_port = NULL, *io_port = NULL, *control_port = NULL;
	struct IOExtSer *read_io = NULL, *write_io = NULL, *control_io = NULL;
	uint8 orig_params[sizeof(struct IOExtSer)];
	bool opened = false;
	ULONG io_mask = 0, proc_port_mask = 0;

	// Default: error occured
	obj->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 serial.device I/O
	io_port = CreateMsgPort();
	if (io_port == NULL)
		goto quit;
	io_mask = 1 << io_port->mp_SigBit;
	control_port = CreateMsgPort();
	if (control_port == NULL)
		goto quit;

	// Create IORequests
	read_io = (struct IOExtSer *)CreateIORequest(io_port, sizeof(struct IOExtSer));
	write_io = (struct IOExtSer *)CreateIORequest(io_port, sizeof(struct IOExtSer));
	control_io = (struct IOExtSer *)CreateIORequest(control_port, sizeof(struct IOExtSer));
	if (read_io == NULL || write_io == NULL || control_io == NULL)
		goto quit;
	read_io->IOSer.io_Message.mn_Node.ln_Type = 0;	// Avoid CheckIO() bug
	write_io->IOSer.io_Message.mn_Node.ln_Type = 0;
	control_io->IOSer.io_Message.mn_Node.ln_Type = 0;

	// Parse device name
	char dev_name[256];
	ULONG dev_unit;
	if (sscanf(obj->device_name, "%[^/]/%ld", dev_name, &dev_unit) < 2)
		goto quit;

	// Open device
	if (obj->is_parallel)
		((IOExtPar *)read_io)->io_ParFlags = PARF_SHARED;
	else
		read_io->io_SerFlags = SERF_SHARED | SERF_7WIRE;
	if (OpenDevice((UBYTE *) dev_name, dev_unit, (struct IORequest *)read_io, 0) || read_io->IOSer.io_Device == NULL)
		goto quit;
	opened = true;

	// Copy IORequests
	memcpy(write_io, read_io, sizeof(struct IOExtSer));
	memcpy(control_io, read_io, sizeof(struct IOExtSer));

	// Attach control_io to control_port and set default values
	control_io->IOSer.io_Message.mn_ReplyPort = control_port;
	if (!obj->is_parallel) {
		control_io->io_CtlChar = SER_DEFAULT_CTLCHAR;
		control_io->io_RBufLen = 64;
		control_io->io_ExtFlags = 0;
		control_io->io_Baud = 9600;
		control_io->io_BrkTime = 250000;
		control_io->io_ReadLen = control_io->io_WriteLen = 8;
		control_io->io_StopBits = 1;
		control_io->io_SerFlags = SERF_SHARED;
		control_io->IOSer.io_Command = SDCMD_SETPARAMS;
		DoIO((struct IORequest *)control_io);
		memcpy(orig_params, &(control_io->io_CtlChar), (uint8 *)&(control_io->io_Status) - (uint8 *)&(control_io->io_CtlChar));
	}

	// Initialization went well, inform main task
	obj->proc_port = proc_port;
	obj->control_io = control_io;
	obj->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 | io_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 SerMessage *msg;
			while (msg = (SerMessage *)GetMsg(proc_port)) {
				D(bug("serial_proc received %08lx\n", msg->what));
				switch (msg->what) {
					case MSG_QUERY:
						control_io->IOSer.io_Command = SDCMD_QUERY;
						DoIO((struct IORequest *)control_io);
						D(bug(" query returned %08lx, actual %08lx\n", control_io->IOSer.io_Error, control_io->IOSer.io_Actual));
						break;

					case MSG_SET_PARAMS:
						// Only send SDCMD_SETPARAMS when configuration has changed
						if (memcmp(orig_params, &(control_io->io_CtlChar), (uint8 *)&(control_io->io_Status) - (uint8 *)&(control_io->io_CtlChar))) {
							memcpy(orig_params, &(control_io->io_CtlChar), (uint8 *)&(control_io->io_Status) - (uint8 *)&(control_io->io_CtlChar));
							memcpy(&(read_io->io_CtlChar), &(control_io->io_CtlChar), (uint8 *)&(control_io->io_Status) - (uint8 *)&(control_io->io_CtlChar));
							memcpy(&(write_io->io_CtlChar), &(control_io->io_CtlChar), (uint8 *)&(control_io->io_Status) - (uint8 *)&(control_io->io_CtlChar));
							control_io->IOSer.io_Command = SDCMD_SETPARAMS;
							D(bug(" params %08lx %08lx %08lx %08lx %08lx %08lx\n", control_io->io_CtlChar, control_io->io_RBufLen, control_io->io_ExtFlags, control_io->io_Baud, control_io->io_BrkTime, *(uint32 *)((uint8 *)control_io + 76)));
							DoIO((struct IORequest *)control_io);
							D(bug(" set_parms returned %08lx\n", control_io->IOSer.io_Error));
						}
						break;

					case MSG_SET_PAR_PARAMS:
						control_io->IOSer.io_Command = PDCMD_SETPARAMS;
						DoIO((struct IORequest *)control_io);
						D(bug(" set_par_parms returned %08lx\n", control_io->IOSer.io_Error));
						break;

					case MSG_BREAK:
						control_io->IOSer.io_Command = SDCMD_BREAK;
						DoIO((struct IORequest *)control_io);
						D(bug(" break returned %08lx\n", control_io->IOSer.io_Error));
						break;

					case MSG_RESET:
						control_io->IOSer.io_Command = CMD_RESET;
						DoIO((struct IORequest *)control_io);
						D(bug(" reset returned %08lx\n", control_io->IOSer.io_Error));
						break;

					case MSG_KILL_IO:
						AbortIO((struct IORequest *)read_io);
						AbortIO((struct IORequest *)write_io);
						WaitIO((struct IORequest *)read_io);
						WaitIO((struct IORequest *)write_io);
						obj->read_pending = obj->write_pending = false;
						obj->read_done = obj->write_done = false;
						break;

					case MSG_PRIME_IN:
						read_io->IOSer.io_Message.mn_Node.ln_Name = (char *)msg->pb;
						read_io->IOSer.io_Data = Mac2HostAddr(ReadMacInt32(msg->pb + ioBuffer));
						read_io->IOSer.io_Length = ReadMacInt32(msg->pb + ioReqCount);
						read_io->IOSer.io_Actual = 0;
						read_io->IOSer.io_Command = CMD_READ;
						D(bug("serial_proc receiving %ld bytes from %08lx\n", read_io->IOSer.io_Length, read_io->IOSer.io_Data));
						SendIO((struct IORequest *)read_io);
						break;

					case MSG_PRIME_OUT: {
						write_io->IOSer.io_Message.mn_Node.ln_Name = (char *)msg->pb;
						write_io->IOSer.io_Data = Mac2HostAddr(ReadMacInt32(msg->pb + ioBuffer));
						write_io->IOSer.io_Length = ReadMacInt32(msg->pb + ioReqCount);
						write_io->IOSer.io_Actual = 0;
						write_io->IOSer.io_Command = CMD_WRITE;
						D(bug("serial_proc transmitting %ld bytes from %08lx\n", write_io->IOSer.io_Length, write_io->IOSer.io_Data));
#if MONITOR
						bug("Sending serial data:\n");
						uint8 *adr = Mac2HostAddr(ReadMacInt32(msg->pb + ioBuffer));
						for (int i=0; i<len; i++) {
							bug("%02lx ", adr[i]);
						}
						bug("\n");
#endif
						SendIO((struct IORequest *)write_io);
						break;
					}
				}
				D(bug(" serial_proc replying\n"));
				ReplyMsg(msg);
			}
		}

		// I/O operation completed
		if (sig & io_mask) {
			struct IOExtSer *io;
			while (io = (struct IOExtSer *)GetMsg(io_port)) {
				if (io == read_io) {
					D(bug("read_io complete, %ld bytes received, error %ld\n", read_io->IOSer.io_Actual, read_io->IOSer.io_Error));
					uint32 pb = (uint32)read_io->IOSer.io_Message.mn_Node.ln_Name;
#if MONITOR
					bug("Receiving serial data:\n");
					uint8 *adr = Mac2HostAddr(ReadMacInt32(msg->pb + ioBuffer));
					for (int i=0; i<read_io->IOSer.io_Actual; i++) {
						bug("%02lx ", adr[i]);
					}
					bug("\n");
#endif
					WriteMacInt32(pb + ioActCount, read_io->IOSer.io_Actual);
					obj->conv_error(read_io, obj->input_dt);
					obj->read_done = true;
					SetInterruptFlag(INTFLAG_SERIAL);
					TriggerInterrupt();
				} else if (io == write_io) {
					D(bug("write_io complete, %ld bytes sent, error %ld\n", write_io->IOSer.io_Actual, write_io->IOSer.io_Error));
					uint32 pb = (uint32)write_io->IOSer.io_Message.mn_Node.ln_Name;
					WriteMacInt32(pb + ioActCount, write_io->IOSer.io_Actual);
					obj->conv_error(write_io, obj->output_dt);
					obj->write_done = true;
					SetInterruptFlag(INTFLAG_SERIAL);
					TriggerInterrupt();
				}
			}
		}
	}
quit:

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

	// Send signal to main task to confirm termination
	Forbid();
	Signal(MainTask, SIGF_SINGLE);
}
Beispiel #21
0
int main(int argc, const char ** argv)
{
    struct IntuiMessage *winmsg;
    ULONG signals, conreadsig, windowsig;
    LONG lch;
    WORD InControl = 0;
    BOOL Done = FALSE;
    UBYTE ch, ibuf;
    UBYTE obuf[200];
    BYTE error;

    FromWb = (argc==0L) ? TRUE : FALSE;

    if(!(IntuitionBase=OpenLibrary("intuition.library",0)))
         cleanexit("Can't open intuition\n",RETURN_FAIL);

    /* Create reply port and io block for writing to console */
    if(!(writePort = CreatePort("RKM.console.write",0)))
         cleanexit("Can't create write port\n",RETURN_FAIL);

    if(!(writeReq = (struct IOStdReq *)
                    CreateExtIO(writePort,(LONG)sizeof(struct IOStdReq))))
         cleanexit("Can't create write request\n",RETURN_FAIL);

    /* Create reply port and io block for reading from console */
    if(!(readPort = CreatePort("RKM.console.read",0)))
         cleanexit("Can't create read port\n",RETURN_FAIL);

    if(!(readReq = (struct IOStdReq *)
                   CreateExtIO(readPort,(LONG)sizeof(struct IOStdReq))))
         cleanexit("Can't create read request\n",RETURN_FAIL);

    /* Open a window */
    if(!(win = OpenWindow(&nw)))
         cleanexit("Can't open window\n",RETURN_FAIL);

    /* Now, attach a console to the window */
    if(error = OpenConsole(writeReq,readReq,win))
         cleanexit("Can't open console.device\n",RETURN_FAIL);
    else OpenedConsole = TRUE;

    /* Demonstrate some console escape sequences */
    ConPuts(writeReq,"Here's some normal text\n");
    sprintf(obuf,"%s%sHere's text in color 3 & italics\n",COLOR03,ITALICS);
    ConPuts(writeReq,obuf);
    ConPuts(writeReq,NORMAL);
    Delay(50);      /* Delay for dramatic demo effect */
    ConPuts(writeReq,"We will now delete this asterisk =*=");
    Delay(50);
    ConPuts(writeReq,"\b\b");  /* backspace twice */
    Delay(50);
    ConPuts(writeReq,DELCHAR); /* delete the character */
    Delay(50);

    QueueRead(readReq,&ibuf); /* send the first console read request */

    ConPuts(writeReq,"\n\nNow reading console\n");
    ConPuts(writeReq,"Type some keys.  Close window when done.\n\n");

    conreadsig = 1 << readPort->mp_SigBit;
    windowsig = 1 << win->UserPort->mp_SigBit;

    while(!Done)
        {
        /* A character, or an IDCMP msg, or both could wake us up */
        signals = Wait(conreadsig|windowsig);

        /* If a console signal was received, get the character */
        if (signals & conreadsig)
            {
            if((lch = ConMayGetChar(readPort,&ibuf)) != -1)
                {
                ch = lch;
                /* Show hex and ascii (if printable) for char we got.
                 * If you want to parse received control sequences, such as
                 * function or Help keys,you would buffer control sequences
                 * as you receive them, starting to buffer whenever you
                 * receive 0x9B (or 0x1B[ for user-typed sequences) and
                 * ending when you receive a valid terminating character
                 * for the type of control sequence you are receiving.
                 * For CSI sequences, valid terminating characters
                 * are generally 0x40 through 0x7E.
                 * In our example, InControl has the following values:
                 * 0 = no, 1 = have 0x1B, 2 = have 0x9B OR 0x1B and [,
                 * 3 = now inside control sequence, -1 = normal end esc,
                 * -2 = non-CSI(no [) 0x1B end esc
                 * NOTE - a more complex parser is required to recognize
                 *  other types of control sequences.
                 */

                /* 0x1B ESC not followed by '[', is not CSI seq */
                if (InControl==1)
                    {
                    if(ch=='[') InControl = 2;
                    else InControl = -2;
                    }

                if ((ch==0x9B)||(ch==0x1B))  /* Control seq starting */
                    {
                    InControl = (ch==0x1B) ? 1 : 2;
                    ConPuts(writeReq,"=== Control Seq ===\n");
                    }

                /* We'll show value of this char we received */
                if (((ch >= 0x1F)&&(ch <= 0x7E))||(ch >= 0xA0))
                   sprintf(obuf,"Received: hex %02x = %c\n",ch,ch);
                else sprintf(obuf,"Received: hex %02x\n",ch);
                ConPuts(writeReq,obuf);

                /* Valid ESC sequence terminator ends an ESC seq */
                if ((InControl==3)&&((ch >= 0x40) && (ch <= 0x7E)))
                    {
                    InControl = -1;
                    }
                if (InControl==2) InControl = 3;
                /* ESC sequence finished (-1 if OK, -2 if bogus) */
                if (InControl < 0)
                    {
                    InControl = 0;
                    ConPuts(writeReq,"=== End Control ===\n");
                    }
                }
            }

        /* If IDCMP messages received, handle them */
        if (signals & windowsig)
            {
            /* We have to ReplyMsg these when done with them */
            while (winmsg = (struct IntuiMessage *)GetMsg(win->UserPort))
                {
                switch(winmsg->Class)
                    {
                    case IDCMP_CLOSEWINDOW:
                      Done = TRUE;
                      break;
                    default:
                      break;
                     }
                ReplyMsg((struct Message *)winmsg);
                }
            }
        }

    /* We always have an outstanding queued read request
     * so we must abort it if it hasn't completed,
     * and we must remove it.
     */
    if(!(CheckIO(readReq)))  AbortIO(readReq);
    WaitIO(readReq);     /* clear it from our replyport */

    cleanup();
    exit(RETURN_OK);
    }