UINT __stdcall IOToElevator2(void *args)
{								
	
	CDataPool	dp2("Ele2", sizeof(struct myDpData)) ;
	struct		myDpData *Ele2DP = (struct myDpData *)(dp2.LinkDataPool()) ;

	while(flag) {
		
		if (ps3.Read()>0) {
			ps3.Wait();
			m1->Wait();
			
			Ele2Status = *Ele2DP;
			
			m1->Signal();
			cs3.Signal();
		}
		
		m1->Wait();

		//FLOOR 9
		MOVE_CURSOR(29,1);
		printf("          |");
		if (Ele2Status.floor == 9) 
			printf("._.");
		else
			printf("   ");
		printf("|   ");
		MOVE_CURSOR(29,2);
		printf("          |");
		if (Ele2Status.floor == 9) {
			printf("|");
			if (Ele2Status.door == OPEN) 
				printf("O");
			else
				printf("-");
			printf("|");
		}
		else
			printf("   ");
		printf("|   ");
		MOVE_CURSOR(29,3);
		printf("          |");
		if (Ele2Status.floor == 9) 
			printf("^-^");
		else
			printf("   ");
		printf("|   ");

		//FLOOR 8
		MOVE_CURSOR(29,5);
		printf("          |");
		if (Ele2Status.floor == 8) 
			printf("._.");
		else
			printf("   ");
		printf("|   ");
		MOVE_CURSOR(29,6);
		printf("          |");
		if (Ele2Status.floor == 8) {
			printf("|");
			if (Ele2Status.door == OPEN) 
				printf("O");
			else
				printf("-");
			printf("|");
		}
		else
			printf("   ");
		printf("|   ");
		MOVE_CURSOR(29,7);
		printf("          |");
		if (Ele2Status.floor == 8) 
			printf("^-^");
		else
			printf("   ");
		printf("|   ");

		//FLOOR 7
		MOVE_CURSOR(29,9);
		printf("          |");
		if (Ele2Status.floor == 7) 
			printf("._.");
		else
			printf("   ");
		printf("|   ");
		MOVE_CURSOR(29,10);
		printf("          |");
		if (Ele2Status.floor == 7) {
			printf("|");
			if (Ele2Status.door == OPEN) 
				printf("O");
			else
				printf("-");
			printf("|");
		}
		else
			printf("   ");
		printf("|   ");
		MOVE_CURSOR(29,11);
		printf("          |");
		if (Ele2Status.floor == 7) 
			printf("^-^");
		else
			printf("   ");
		printf("|   ");

		//FLOOR 6
		MOVE_CURSOR(29,13);
		printf("          |");
		if (Ele2Status.floor == 6) 
			printf("._.");
		else
			printf("   ");
		printf("|   ");
		MOVE_CURSOR(29,14);
		printf("          |");
		if (Ele2Status.floor == 6) {
			printf("|");
			if (Ele2Status.door == OPEN) 
				printf("O");
			else
				printf("-");
			printf("|");
		}
		else
			printf("   ");
		printf("|   ");
		MOVE_CURSOR(29,15);
		printf("          |");
		if (Ele2Status.floor == 6) 
			printf("^-^");
		else
			printf("   ");
		printf("|   ");

		//FLOOR 5
		MOVE_CURSOR(29,17);
		printf("          |");
		if (Ele2Status.floor == 5) 
			printf("._.");
		else
			printf("   ");
		printf("|   ");
		MOVE_CURSOR(29,18);
		printf("          |");
		if (Ele2Status.floor == 5) {
			printf("|");
			if (Ele2Status.door == OPEN) 
				printf("O");
			else
				printf("-");
			printf("|");
		}
		else
			printf("   ");
		printf("|   ");
		MOVE_CURSOR(29,19);
		printf("          |");
		if (Ele2Status.floor == 5) 
			printf("^-^");
		else
			printf("   ");
		printf("|   ");

		//FLOOR 4
		MOVE_CURSOR(29,21);
		printf("          |");
		if (Ele2Status.floor == 4) 
			printf("._.");
		else
			printf("   ");
		printf("|   ");
		MOVE_CURSOR(29,22);
		printf("          |");
		if (Ele2Status.floor == 4) {
			printf("|");
			if (Ele2Status.door == OPEN) 
				printf("O");
			else
				printf("-");
			printf("|");
		}
		else
			printf("   ");
		printf("|   ");
		MOVE_CURSOR(29,23);
		printf("          |");
		if (Ele2Status.floor == 4) 
			printf("^-^");
		else
			printf("   ");
		printf("|   ");

		//FLOOR 3
		MOVE_CURSOR(29,25);
		printf("          |");
		if (Ele2Status.floor == 3) 
			printf("._.");
		else
			printf("   ");
		printf("|   ");
		MOVE_CURSOR(29,26);
		printf("          |");
		if (Ele2Status.floor == 3) {
			printf("|");
			if (Ele2Status.door == OPEN) 
				printf("O");
			else
				printf("-");
			printf("|");
		}
		else
			printf("   ");
		printf("|   ");
		MOVE_CURSOR(29,27);
		printf("          |");
		if (Ele2Status.floor == 3) 
			printf("^-^");
		else
			printf("   ");
		printf("|   ");

		//FLOOR 2
		MOVE_CURSOR(29,29);
		printf("          |");
		if (Ele2Status.floor == 2) 
			printf("._.");
		else
			printf("   ");
		printf("|   ");
		MOVE_CURSOR(29,30);
		printf("          |");
		if (Ele2Status.floor == 2) {
			printf("|");
			if (Ele2Status.door == OPEN) 
				printf("O");
			else
				printf("-");
			printf("|");
		}
		else
			printf("   ");
		printf("|   ");
		MOVE_CURSOR(29,31);
		printf("          |");
		if (Ele2Status.floor == 2) 
			printf("^-^");
		else
			printf("   ");
		printf("|   ");

		//FLOOR 1
		MOVE_CURSOR(29,33);
		printf("          |");
		if (Ele2Status.floor == 1) 
			printf("._.");
		else
			printf("   ");
		printf("|   ");

		MOVE_CURSOR(29,34);
		printf("          |");
		if (Ele2Status.floor == 1) {
			printf("|");
			if (Ele2Status.door == OPEN) 
				printf("O");
			else
				printf("-");
			printf("|");
		}
		else
			printf("   ");
		printf("|   ");

		MOVE_CURSOR(29,35);
		printf("          |");
		if (Ele2Status.floor == 1) 
			printf("^-^");
		else
			printf("   ");
		printf("|   ");

		//FLOOR 0
		MOVE_CURSOR(29,37);
		printf("          |");
		if (Ele2Status.floor == 0) 
			printf("._.");
		else
			printf("   ");
		printf("|   ");
		MOVE_CURSOR(29,38);
		printf("          |");
		if (Ele2Status.floor == 0) {
			printf("|");
			if (Ele2Status.door == OPEN) 
				printf("O");
			else
				printf("-");
			printf("|");
		}
		else
			printf("   ");
		printf("|   ");
		MOVE_CURSOR(29,39);
		printf("          |");
		if (Ele2Status.floor == 0) 
			printf("^-^");
		else
			printf("   ");
		printf("|   ");


		MOVE_CURSOR(29,41);
		printf("           Ele2");
		MOVE_CURSOR(36,42);
		for (int i = 7; i < 10; i++) {
			if (Ele2Status.lights[i] == 1) {
				TEXT_COLOUR(14);
			}
			printf("[%d] ", i);
			TEXT_COLOUR(7);
		}
		MOVE_CURSOR(36,43);
		for (int i = 4; i < 7; i++) {
			if (Ele2Status.lights[i] == 1) {
				TEXT_COLOUR(14);
			}
			printf("[%d] ", i);
			TEXT_COLOUR(7);
		}
		MOVE_CURSOR(36,44);
		for (int i = 1; i < 4; i++) {
			if (Ele2Status.lights[i] == 1) {
				TEXT_COLOUR(14);
			}
			printf("[%d] ", i);
			TEXT_COLOUR(7);
		}
		MOVE_CURSOR(40,45);
		if (Ele2Status.lights[0] == 1) {
			TEXT_COLOUR(14);
		}
		printf("[0]");
		TEXT_COLOUR(7);

		fflush(stdout);
		MOVE_CURSOR(0,50);
		fflush(stdout);
		m1->Signal();


		SLEEP(1);
	}
	return 0 ;									
}
Пример #2
0
/*
 * This test does a simple enroll with SRP using a
 * non-default value for the SRP strength.
 */
static void us1060c_test106 (void)
{
    EST_CTX *ectx;
    EVP_PKEY *new_key;
    int rv;
    int pkcs7_len = 0;

    LOG_FUNC_NM;

    /*
     * We need to restart the EST server using an RSA key
     * None of the SRP cipher suites support ECDSA
     */
    st_stop();
    SLEEP(2);
    rv = us1060c_start_server(US1060C_SERVER_CERTKEY, US1060C_SERVER_CERTKEY, 0, 0, 1);

    /*
     * Create a client context 
     */
    ectx = est_client_init(NULL, 0, EST_CERT_FORMAT_PEM, NULL);
    CU_ASSERT(ectx != NULL);

    /*
     * Set the authentication mode to use a user id/password
     */
    rv = est_client_set_auth(ectx, US1060C_UID, US1060C_PWD, NULL, NULL);
    CU_ASSERT(rv == EST_ERR_NONE);

    /*
     * Set the EST server address/port
     */
    est_client_set_server(ectx, US1060C_SERVER_IP, US1060C_SERVER_PORT, NULL);

    /*
     * Enable SRP on the client
     * Use a strength below the minimum
     */
    rv = est_client_enable_srp(ectx, 1023, US1060C_UID, US1060C_PWD); 
    CU_ASSERT(rv == EST_ERR_SRP_STRENGTH_LOW);

    /*
     * Enable SRP on the client
     * Use a strength slightly larger then the N value in passwd.srpv
     */
    rv = est_client_enable_srp(ectx, 1537, US1060C_UID, US1060C_PWD); 
    CU_ASSERT(rv == EST_ERR_NONE);

    /*
     * generate a new private key
     */
    new_key = generate_private_key();
    CU_ASSERT(new_key != NULL);

    /*
     * Attempt to provision a new cert
     */
    rv = est_client_enroll(ectx, "US1060C_TEST106a", &pkcs7_len, new_key);
    CU_ASSERT(rv == EST_ERR_SSL_CONNECT);

    /*
     * Enable SRP on the client
     * Use a strength the same size as the N value in passwd.srpv
     */
    rv = est_client_enable_srp(ectx, 1536, US1060C_UID, US1060C_PWD); 
    CU_ASSERT(rv == EST_ERR_NONE);

    /*
     * Attempt to provision a new cert
     */
    rv = est_client_enroll(ectx, "US1060C_TEST106b", &pkcs7_len, new_key);
    CU_ASSERT(rv == EST_ERR_NONE);

    /*
     * Cleanup
     */
    EVP_PKEY_free(new_key);
    est_destroy(ectx);
}
Пример #3
0
/*
 * This routine is called when CUnit uninitializes this test
 * suite.  This can be used to deallocate data or close any
 * resources that were used for the test cases.
 */
static int us896_destroy_suite(void) {
    st_stop();
    SLEEP(2);
    return 0;
}
Пример #4
0
static uint8_t moteApp_GoToSleep(void)
{
    uint8_t status = 0;
    while (SWITCH_2_PORT == 0);     // Hold for Button Release
    modemSleep();
    oled_displayOff(true); 
    ADCON0bits.ADON = 0;       // ADC Off
    INTCONbits.GIE = 0;
    GIE = 0;
    PEIE = 0;
    // Prepare USB Detect
    USB_DET_ANSEL = 1;
    // Prepare IOC to wake us up
    USB_DET_EN = 1;      // Enables CMP1 interrupt.
    SWITCH_1_IOC = 1;
    SWITCH_2_IOC = 1;
    MODEM_WAKE_IOC = 1;
    IOC_ENABLE = 1;
    // Dummy Reads to Establish IOC level
    status = SWITCH_1_PORT;
    status = SWITCH_2_PORT;
    status = MODEM_WAKE_PORT;
    if (periodicState)
    {
        //WDTCONbits.SWDTEN = 1;
    }
    IOC_FLAG = 0;
    USB_DET_FLAG = 0;
    NOP();
    SLEEP();
    NOP();
    // Reconfigure Critical peripherals
    //WDTCONbits.SWDTEN = 0;
    EUSART_FlushBuffer();
    // Disable IOC
    IOC_ENABLE = 0;
    SWITCH_1_IOC = 0;
    SWITCH_2_IOC = 0;
    MODEM_WAKE_IOC = 0;
    PIE2bits.C1IE = 0;
    GIE = 1;

    PIN_MANAGER_Initialize();
    EUSART_Initialize();
    // Process Wake Up Event
    if (IOC_FLAG)
    {   // PushButton or Module IOC woke us
        IOC_FLAG = 0;
        status = 1;
    }
// TODO:
//    else if (Comparator)    // USB EVENT
//    {
//        status = 2;
//    }
    else
    {   // Time woke us. Reload; so wake from sleep is short
        secTicker = 10;
        status = 0;
    }
    USB_DET_ANSEL = 0;
    oled_displayOff(false);
    oled_init();         // Dispaly

    modemResync();
    return status;
}
Пример #5
0
int video_output(render_context_type *rc)
{
        show_frame(rc);
        SLEEP(1);
    return 0;
}
Пример #6
0
int suspend_cmd(int argc, char *argv[],char *cmdline)
{
char    *fn = SR_DEFAULT_FILENAME;
SR_FILE *file;
CPU_BITMAP started_mask;
struct   timeval tv;
time_t   tt;
int      i, j, rc;
REGS    *regs;
DEVBLK  *dev;
IOINT   *ioq;
BYTE     psw[16];

    UNREFERENCED(cmdline);

    if (argc > 2)
    {
        // "SR: too many arguments"
        WRMSG(HHC02000, "E");
        return -1;
    }

    if (argc == 2)
        fn = argv[1];

    file = SR_OPEN (fn, "wb");
    if (file == NULL)
    {
        // "SR: error in function '%s': '%s'"
        WRMSG(HHC02001, "E","open()",strerror(errno));
        return -1;
    }

    TRACE("SR: Begin Suspend Processing...\n");

    /* Save CPU state and stop all CPU's */
    TRACE("SR: Stopping All CPUs...\n");
    OBTAIN_INTLOCK(NULL);
    started_mask = sysblk.started_mask;
    while (sysblk.started_mask)
    {
        for (i = 0; i < sysblk.maxcpu; i++)
        {
            if (IS_CPU_ONLINE(i))
            {
                sysblk.regs[i]->cpustate = CPUSTATE_STOPPING;
                ON_IC_INTERRUPT(sysblk.regs[i]);
                signal_condition(&sysblk.regs[i]->intcond);
            }
        }
        RELEASE_INTLOCK(NULL);
        usleep (1000);
        OBTAIN_INTLOCK(NULL);
    }
    RELEASE_INTLOCK(NULL);

    /* Wait for I/O queue to clear out */
    TRACE("SR: Waiting for I/O Queue to clear...\n");
#ifdef OPTION_FISHIO
    SLEEP (2);
#else
    obtain_lock (&sysblk.ioqlock);
    while (sysblk.ioq)
    {
        release_lock (&sysblk.ioqlock);
        usleep (1000);
        obtain_lock (&sysblk.ioqlock);
    }
    release_lock (&sysblk.ioqlock);
#endif

    /* Wait for active I/Os to complete */
    TRACE("SR: Waiting for Active I/Os to Complete...\n");
    for (i = 1; i < 5000; i++)
    {
        dev = sr_active_devices();
        if (dev == NULL) break;
        if (i % 500 == 0)
        {
            // "SR: waiting for device %04X"
            WRMSG(HHC02002, "W", dev->devnum);
        }
        usleep (10000);
    }
    if (dev != NULL)
    {
        // "SR: device %04X still busy, proceeding anyway"
        WRMSG(HHC02003, "W",dev->devnum);
    }

    /* Write header */
    TRACE("SR: Writing File Header...\n");
    SR_WRITE_STRING(file, SR_HDR_ID, SR_ID);
    SR_WRITE_STRING(file, SR_HDR_VERSION, VERSION);
    gettimeofday(&tv, NULL); tt = tv.tv_sec;
    SR_WRITE_STRING(file, SR_HDR_DATE, ctime(&tt));

    /* Write system data */
    TRACE("SR: Saving System Data...\n");
    SR_WRITE_STRING(file,SR_SYS_ARCH_NAME,arch_name[sysblk.arch_mode]);
    SR_WRITE_VALUE (file,SR_SYS_STARTED_MASK,started_mask,sizeof(started_mask));
    SR_WRITE_VALUE (file,SR_SYS_MAINSIZE,sysblk.mainsize,sizeof(sysblk.mainsize));
    TRACE("SR: Saving MAINSTOR...\n");
    SR_WRITE_BUF   (file,SR_SYS_MAINSTOR,sysblk.mainstor,sysblk.mainsize);
    SR_WRITE_VALUE (file,SR_SYS_SKEYSIZE,(sysblk.mainsize/STORAGE_KEY_UNITSIZE),sizeof(U32));
    TRACE("SR: Saving Storage Keys...\n");
    SR_WRITE_BUF   (file,SR_SYS_STORKEYS,sysblk.storkeys,sysblk.mainsize/STORAGE_KEY_UNITSIZE);
    SR_WRITE_VALUE (file,SR_SYS_XPNDSIZE,sysblk.xpndsize,sizeof(sysblk.xpndsize));
    TRACE("SR: Saving Expanded Storage...\n");
    SR_WRITE_BUF   (file,SR_SYS_XPNDSTOR,sysblk.xpndstor,4096*sysblk.xpndsize);
    SR_WRITE_VALUE (file,SR_SYS_CPUID,sysblk.cpuid,sizeof(sysblk.cpuid));
    SR_WRITE_VALUE (file,SR_SYS_IPLDEV,sysblk.ipldev,sizeof(sysblk.ipldev));
    SR_WRITE_VALUE (file,SR_SYS_IPLCPU,sysblk.iplcpu,sizeof(sysblk.iplcpu));
    SR_WRITE_VALUE (file,SR_SYS_MBO,sysblk.mbo,sizeof(sysblk.mbo));
    SR_WRITE_VALUE (file,SR_SYS_MBK,sysblk.mbk,sizeof(sysblk.mbk));
    SR_WRITE_VALUE (file,SR_SYS_MBM,sysblk.mbm,sizeof(sysblk.mbm));
    SR_WRITE_VALUE (file,SR_SYS_MBD,sysblk.mbd,sizeof(sysblk.mbd));

    for (ioq = sysblk.iointq; ioq; ioq = ioq->next)
        if (ioq->pcipending)
        {
            SR_WRITE_VALUE(file,SR_SYS_PCIPENDING_LCSS, SSID_TO_LCSS(ioq->dev->ssid),sizeof(U16));
            SR_WRITE_VALUE(file,SR_SYS_PCIPENDING, ioq->dev->devnum,sizeof(ioq->dev->devnum));
        }
        else if (ioq->attnpending)
        {
            SR_WRITE_VALUE(file,SR_SYS_ATTNPENDING_LCSS, SSID_TO_LCSS(ioq->dev->ssid),sizeof(U16));
            SR_WRITE_VALUE(file,SR_SYS_ATTNPENDING, ioq->dev->devnum,sizeof(ioq->dev->devnum));
        }
        else
        {
            SR_WRITE_VALUE(file,SR_SYS_IOPENDING_LCSS, SSID_TO_LCSS(ioq->dev->ssid),sizeof(U16));
            SR_WRITE_VALUE(file,SR_SYS_IOPENDING, ioq->dev->devnum,sizeof(ioq->dev->devnum));
        }

    for (i = 0; i < 8; i++)
        SR_WRITE_VALUE(file,SR_SYS_CHP_RESET+i,sysblk.chp_reset[i],sizeof(sysblk.chp_reset[0]));

    SR_WRITE_VALUE (file,SR_SYS_SERVPARM,sysblk.servparm,sizeof(sysblk.servparm));
    SR_WRITE_VALUE (file,SR_SYS_SIGINTREQ,sysblk.sigintreq,1);
    SR_WRITE_STRING(file,SR_SYS_LOADPARM,str_loadparm());
    SR_WRITE_VALUE (file,SR_SYS_INTS_STATE,sysblk.ints_state,sizeof(sysblk.ints_state));
    SR_WRITE_HDR(file, SR_DELIMITER, 0);

    /* Save service console state */
    TRACE("SR: Saving Service Console State...\n");
    SR_WRITE_HDR(file, SR_SYS_SERVC, 0);
    servc_hsuspend(file);
    SR_WRITE_HDR(file, SR_DELIMITER, 0);

    /* Save clock state */
    TRACE("SR: Saving Clock State...\n");
    SR_WRITE_HDR(file, SR_SYS_CLOCK, 0);
    clock_hsuspend(file);
    SR_WRITE_HDR(file, SR_DELIMITER, 0);

    /* Write CPU data */
    for (i = 0; i < sysblk.maxcpu; i++)
    {
        if (!IS_CPU_ONLINE(i)) continue;

        TRACE("SR: Saving CPU %d Data...\n", i);

        regs = sysblk.regs[i];
        SR_WRITE_VALUE(file, SR_CPU, i, sizeof(i));
        SR_WRITE_VALUE(file, SR_CPU_ARCHMODE, regs->arch_mode,sizeof(regs->arch_mode));
        SR_WRITE_VALUE(file, SR_CPU_PX, regs->PX_G,sizeof(regs->PX_G));
        copy_psw (regs, psw);
        SR_WRITE_BUF(file, SR_CPU_PSW, psw, 16);
        for (j = 0; j < 16; j++)
            SR_WRITE_VALUE(file, SR_CPU_GR+j, regs->GR_G(j),sizeof(regs->GR_G(0)));
        for (j = 0; j < 16; j++)
            SR_WRITE_VALUE(file, SR_CPU_CR+j, regs->CR_G(j),sizeof(regs->CR_G(0)));
        for (j = 0; j < 16; j++)
            SR_WRITE_VALUE(file, SR_CPU_AR+j, regs->ar[j],sizeof(regs->ar[0]));
        for (j = 0; j < 32; j++)
            SR_WRITE_VALUE(file, SR_CPU_FPR+j, regs->fpr[j],sizeof(regs->fpr[0]));
        SR_WRITE_VALUE(file, SR_CPU_FPC, regs->fpc, sizeof(regs->fpc));
        SR_WRITE_VALUE(file, SR_CPU_DXC, regs->dxc, sizeof(regs->dxc));
        SR_WRITE_VALUE(file, SR_CPU_MC, regs->MC_G, sizeof(regs->MC_G));
        SR_WRITE_VALUE(file, SR_CPU_EA, regs->EA_G, sizeof(regs->EA_G));
        SR_WRITE_VALUE(file, SR_CPU_PTIMER, cpu_timer(regs), sizeof(S64));
        SR_WRITE_VALUE(file, SR_CPU_CLKC, regs->clkc, sizeof(regs->clkc));
        SR_WRITE_VALUE(file, SR_CPU_CHANSET, regs->chanset, sizeof(regs->chanset));
        SR_WRITE_VALUE(file, SR_CPU_TODPR, regs->todpr, sizeof(regs->todpr));
        SR_WRITE_VALUE(file, SR_CPU_MONCLASS, regs->monclass, sizeof(regs->monclass));
        SR_WRITE_VALUE(file, SR_CPU_EXCARID, regs->excarid, sizeof(regs->excarid));
        SR_WRITE_VALUE(file, SR_CPU_BEAR, regs->bear, sizeof(regs->bear));
        SR_WRITE_VALUE(file, SR_CPU_OPNDRID, regs->opndrid, sizeof(regs->opndrid));
        SR_WRITE_VALUE(file, SR_CPU_CHECKSTOP, regs->checkstop, 1);
        SR_WRITE_VALUE(file, SR_CPU_HOSTINT, regs->hostint, 1);
        SR_WRITE_VALUE(file, SR_CPU_EXECFLAG, regs->execflag, 1);
//      SR_WRITE_VALUE(file, SR_CPU_INSTVALID, regs->instvalid, 1);
        SR_WRITE_VALUE(file, SR_CPU_PERMODE, regs->permode, 1);
        SR_WRITE_VALUE(file, SR_CPU_LOADSTATE, regs->loadstate, 1);
        SR_WRITE_VALUE(file, SR_CPU_INVALIDATE, regs->invalidate, 1);
        SR_WRITE_VALUE(file, SR_CPU_SIGPRESET, regs->sigpreset, 1);
        SR_WRITE_VALUE(file, SR_CPU_SIGPIRESET, regs->sigpireset, 1);
        SR_WRITE_VALUE(file, SR_CPU_INTS_STATE, regs->ints_state, sizeof(regs->ints_state));
        SR_WRITE_VALUE(file, SR_CPU_INTS_MASK, regs->ints_mask, sizeof(regs->ints_mask));
        for (j = 0; j < sysblk.maxcpu; j++)
            SR_WRITE_VALUE(file, SR_CPU_MALFCPU+j, regs->malfcpu[j], sizeof(regs->malfcpu[0]));
        for (j = 0; j < sysblk.maxcpu; j++)
            SR_WRITE_VALUE(file, SR_CPU_EMERCPU+j, regs->emercpu[j], sizeof(regs->emercpu[0]));
        SR_WRITE_VALUE(file, SR_CPU_EXTCCPU, regs->extccpu, sizeof(regs->extccpu));
        SR_WRITE_HDR(file, SR_DELIMITER, 0);
    }

    /* Write Device data */
    for (dev = sysblk.firstdev; dev; dev = dev->nextdev)
    {
        if (!(dev->pmcw.flag5 & PMCW5_V)) continue;

        TRACE("SR: Saving Device %4.4X...\n", dev->devnum);

        /* These fields must come first so the device could be attached */
        SR_WRITE_VALUE(file, SR_DEV, dev->devnum, sizeof(dev->devnum));
        SR_WRITE_VALUE(file, SR_DEV_LCSS, SSID_TO_LCSS(dev->ssid), sizeof(U16));
        SR_WRITE_VALUE(file, SR_DEV_ARGC, dev->argc, sizeof(dev->argc));
        for (i = 0; i < dev->argc; i++)
            if (dev->argv[i])
            {
                SR_WRITE_STRING(file, SR_DEV_ARGV, dev->argv[i]);
            }
            else
            {
                SR_WRITE_STRING(file, SR_DEV_ARGV, "");
            }
        SR_WRITE_STRING(file, SR_DEV_TYPNAME, dev->typname);

        /* Common device fields */
        SR_WRITE_BUF  (file, SR_DEV_ORB, &dev->orb, sizeof(ORB));
        SR_WRITE_BUF  (file, SR_DEV_PMCW, &dev->pmcw, sizeof(PMCW));
        SR_WRITE_BUF  (file, SR_DEV_SCSW, &dev->scsw, sizeof(SCSW));
        SR_WRITE_BUF  (file, SR_DEV_PCISCSW, &dev->pciscsw, sizeof(SCSW));
        SR_WRITE_BUF  (file, SR_DEV_ATTNSCSW, &dev->attnscsw, sizeof(SCSW));
        SR_WRITE_BUF  (file, SR_DEV_CSW, dev->csw, 8);
        SR_WRITE_BUF  (file, SR_DEV_PCICSW, dev->pcicsw, 8);
        SR_WRITE_BUF  (file, SR_DEV_ATTNCSW, dev->attncsw, 8);
        SR_WRITE_BUF  (file, SR_DEV_ESW, &dev->esw, sizeof(ESW));
        SR_WRITE_BUF  (file, SR_DEV_ECW, dev->ecw, 32);
        SR_WRITE_BUF  (file, SR_DEV_SENSE, dev->sense, 32);
        SR_WRITE_VALUE(file, SR_DEV_PGSTAT, dev->pgstat, sizeof(dev->pgstat));
        SR_WRITE_BUF  (file, SR_DEV_PGID, dev->pgid, 11);
        /* By Adrian - SR_DEV_DRVPWD */
        SR_WRITE_BUF  (file, SR_DEV_DRVPWD, dev->drvpwd, 11);
        SR_WRITE_VALUE(file, SR_DEV_BUSY, dev->busy, 1);
        SR_WRITE_VALUE(file, SR_DEV_RESERVED, dev->reserved, 1);
        SR_WRITE_VALUE(file, SR_DEV_SUSPENDED, dev->suspended, 1);
        SR_WRITE_VALUE(file, SR_DEV_PCIPENDING, dev->pcipending, 1);
        SR_WRITE_VALUE(file, SR_DEV_ATTNPENDING, dev->attnpending, 1);
        SR_WRITE_VALUE(file, SR_DEV_PENDING, dev->pending, 1);
        SR_WRITE_VALUE(file, SR_DEV_STARTPENDING, dev->startpending, 1);
        SR_WRITE_VALUE(file, SR_DEV_CRWPENDING, dev->crwpending, 1);
        SR_WRITE_VALUE(file, SR_DEV_CCWADDR, dev->ccwaddr, sizeof(dev->ccwaddr));
        SR_WRITE_VALUE(file, SR_DEV_IDAPMASK, dev->idapmask, sizeof(dev->idapmask));
        SR_WRITE_VALUE(file, SR_DEV_IDAWFMT, dev->idawfmt, sizeof(dev->idawfmt));
        SR_WRITE_VALUE(file, SR_DEV_CCWFMT, dev->ccwfmt, sizeof(dev->ccwfmt));
        SR_WRITE_VALUE(file, SR_DEV_CCWKEY, dev->ccwkey, sizeof(dev->ccwkey));

        /* Device type specific data */
        SR_WRITE_VALUE(file, SR_DEV_DEVTYPE, dev->devtype, sizeof(dev->devtype));
        if (dev->hnd->hsuspend)
        {
            rc = (dev->hnd->hsuspend) (dev, file);
            if (rc < 0) goto sr_error_exit;
        }
        SR_WRITE_HDR(file, SR_DELIMITER, 0);
    }

    TRACE("SR: Writing EOF\n");

    SR_WRITE_HDR(file, SR_EOF, 0);
    SR_CLOSE (file);

    TRACE("SR: Suspend Complete; shutting down...\n");

    /* Shutdown */
    do_shutdown();

    return 0;

sr_error_exit:
    // "SR: error processing file '%s'"
    WRMSG(HHC02004, "E", fn);
    SR_CLOSE (file);
    return -1;
}
Пример #7
0
/*
============================================================================
This routine applies the current settings in the dialog box and calls the
remote API functions to setup and teardown the socket interface.  It is
called by the OK button also.
============================================================================
*/
static void cb_sockdlg_apply(Fl_Widget* w, void*)
{
	int		port_num = 0, listen_port;
	int		telnet;
	int		enabled;

	// ==============================================
	// Get Port Number & telnet flag
	// ==============================================
	if (sockdlg_ctrl.pPortNumber->value() != NULL)
		port_num = atoi(sockdlg_ctrl.pPortNumber->value());
	telnet = sockdlg_ctrl.pTelnet->value();
	enabled = sockdlg_ctrl.pEnable->value();

	// Test if the socket is enabled but the port is invalid
	if (enabled && ((port_num <= 0) || (port_num >= 65536)))
	{
		fl_alert("Please provide a port number between 1 and 65535");
		return;
	}

	// Get the remote socket status
	listen_port = get_remote_listen_port();

	// Test if the socket is enabled and the user want's it disabled
	if (!enabled)
	{
		// Check if the socket is currently active and shutdown if it is
		if (listen_port != 0)
			deinit_remote();
	}

	// Test if we are enabling the socket for a different port number
	if (enabled && listen_port && (listen_port != port_num))
		deinit_remote();

	// Set the new port parameters
	set_remote_telnet(telnet);
	if (enabled)
		set_remote_port(port_num);
	else
		set_remote_port(0);
	enable_remote(enabled);

	// Update preferences
	virtualt_prefs.set("SocketPort", port_num);
	virtualt_prefs.set("SocketTelnetMode", telnet);
	virtualt_prefs.set("SocketEnabled", enabled);

	// Now enable the socket if the socket number is different
	if (enabled && (listen_port != port_num))
	{
		init_remote();
	}
	
	// If the apply button was pressed, then wait a bit for the port
	// status to change in the remote thread, then update the 
	// port status
	if (w == sockdlg_ctrl.pApply)
	{
		SLEEP(500);
		update_port_status();
	}
}
Пример #8
0
static inline bool listenerDoStream(tl_state_t *pTLState)
{
	AVB_TRACE_ENTRY(AVB_TRACE_TL);

	if (!pTLState) {
		AVB_LOG_ERROR("Invalid TLState");
		AVB_TRACE_EXIT(AVB_TRACE_TL);
		return FALSE;
	}

	openavb_tl_cfg_t *pCfg = &pTLState->cfg;
	listener_data_t *pListenerData = pTLState->pPvtListenerData;
	bool bRet = FALSE;

	if (pTLState->bStreaming) {
		U64 nowNS;

		pListenerData->nReportCalls++;

		// Try to receive a frame
		if (IS_OPENAVB_SUCCESS(openavbAvtpRx(pListenerData->avtpHandle))) {
			pListenerData->nReportFrames++;
		}

		CLOCK_GETTIME64(OPENAVB_TIMER_CLOCK, &nowNS);

		if (pCfg->report_seconds > 0) {
			if (nowNS > pListenerData->nextReportNS) {
			  
				U64 lost = openavbAvtpLost(pListenerData->avtpHandle);
				U64 bytes = openavbAvtpBytes(pListenerData->avtpHandle);
				U32 rxbuf = openavbAvtpRxBufferLevel(pListenerData->avtpHandle);
				U32 mqbuf = openavbMediaQCountItems(pTLState->pMediaQ, TRUE);
				U32 mqrdy = openavbMediaQCountItems(pTLState->pMediaQ, FALSE);
			
				AVB_LOGRT_INFO(LOG_RT_BEGIN, LOG_RT_ITEM, FALSE, "RX UID:%d, ", LOG_RT_DATATYPE_U16, &pListenerData->streamID.uniqueID);
				AVB_LOGRT_INFO(FALSE, LOG_RT_ITEM, FALSE, "calls=%ld, ", LOG_RT_DATATYPE_U32, &pListenerData->nReportCalls);
				AVB_LOGRT_INFO(FALSE, LOG_RT_ITEM, FALSE, "frames=%ld, ", LOG_RT_DATATYPE_U32, &pListenerData->nReportFrames);
				AVB_LOGRT_INFO(FALSE, LOG_RT_ITEM, FALSE, "lost=%lld, ", LOG_RT_DATATYPE_U64, &lost);
				AVB_LOGRT_INFO(FALSE, LOG_RT_ITEM, FALSE, "bytes=%lld, ", LOG_RT_DATATYPE_U64, &bytes);
				AVB_LOGRT_INFO(FALSE, LOG_RT_ITEM, FALSE, "rxbuf=%d, ", LOG_RT_DATATYPE_U32, &rxbuf);
				AVB_LOGRT_INFO(FALSE, LOG_RT_ITEM, FALSE, "mqbuf=%d, ", LOG_RT_DATATYPE_U32, &mqbuf);
				AVB_LOGRT_INFO(FALSE, LOG_RT_ITEM, LOG_RT_END, "mqrdy=%d", LOG_RT_DATATYPE_U32, &mqrdy);

				openavbListenerAddStat(pTLState, TL_STAT_RX_CALLS, pListenerData->nReportCalls);
				openavbListenerAddStat(pTLState, TL_STAT_RX_FRAMES, pListenerData->nReportFrames);
				openavbListenerAddStat(pTLState, TL_STAT_RX_LOST, lost);
				openavbListenerAddStat(pTLState, TL_STAT_RX_BYTES, bytes);

				pListenerData->nReportCalls = 0;
				pListenerData->nReportFrames = 0;
				pListenerData->nextReportNS += (pCfg->report_seconds * NANOSECONDS_PER_SECOND);  
			}
		}

		if (nowNS > pListenerData->nextSecondNS) {
			pListenerData->nextSecondNS += NANOSECONDS_PER_SECOND;
			bRet = TRUE;
		}
	}
	else {
            SLEEP(1);
            bRet = TRUE;
	}

	AVB_TRACE_EXIT(AVB_TRACE_TL);
	return bRet;
}
Пример #9
0
int main( int argc, char *argv[] )
{
  unsigned int channels, fs, bufferFrames, device = 0, offset = 0;
  double time = 2.0;
  FILE *fd;

  // minimal command-line checking
  if ( argc < 3 || argc > 6 ) usage();

  RtAudio adc;
  if ( adc.getDeviceCount() < 1 ) {
    std::cout << "\nNo audio devices found!\n";
    exit( 1 );
  }

  channels = (unsigned int) atoi( argv[1] );
  fs = (unsigned int) atoi( argv[2] );
  if ( argc > 3 )
    time = (double) atof( argv[3] );
  if ( argc > 4 )
    device = (unsigned int) atoi( argv[4] );
  if ( argc > 5 )
    offset = (unsigned int) atoi( argv[5] );

  // Let RtAudio print messages to stderr.
  adc.showWarnings( true );

  // Set our stream parameters for input only.
  bufferFrames = 512;
  RtAudio::StreamParameters iParams;
  iParams.deviceId = device;
  iParams.nChannels = channels;
  iParams.firstChannel = offset;

  InputData data;
  data.buffer = 0;
  try {
    adc.openStream( NULL, &iParams, FORMAT, fs, &bufferFrames, &input, (void *)&data );
  }
  catch ( RtError& e ) {
    std::cout << '\n' << e.getMessage() << '\n' << std::endl;
    goto cleanup;
  }

  data.bufferBytes = bufferFrames * channels * sizeof( MY_TYPE );
  data.totalFrames = (unsigned long) (fs * time);
  data.frameCounter = 0;
  data.channels = channels;
  unsigned long totalBytes;
  totalBytes = data.totalFrames * channels * sizeof( MY_TYPE );

  // Allocate the entire data buffer before starting stream.
  data.buffer = (MY_TYPE*) malloc( totalBytes );
  if ( data.buffer == 0 ) {
    std::cout << "Memory allocation error ... quitting!\n";
    goto cleanup;
  }

  try {
    adc.startStream();
  }
  catch ( RtError& e ) {
    std::cout << '\n' << e.getMessage() << '\n' << std::endl;
    goto cleanup;
  }

  std::cout << "\nRecording for " << time << " seconds ... writing file 'record.raw' (buffer frames = " << bufferFrames << ")." << std::endl;
  while ( adc.isStreamRunning() ) {
    SLEEP( 100 ); // wake every 100 ms to check if we're done
  }

  // Now write the entire data to the file.
  fd = fopen( "record.raw", "wb" );
  fwrite( data.buffer, sizeof( MY_TYPE ), data.totalFrames * channels, fd );
  fclose( fd );

 cleanup:
  if ( adc.isStreamOpen() ) adc.closeStream();
  if ( data.buffer ) free( data.buffer );

  return 0;
}
Пример #10
0
// This is our botting thread
void *main_thread( void *arg ) {
	
// NPC details
// ModelInfo - Model: 496, Weapon: 85, Shield: 0, Helmet: 0, Color: 0199
// ModelInfo - Model: 496, Weapon: 85, Shield: 0, Helmet: 0, Color: 0344
	uint16 quest_giver = 0;
	uint16 other_guard = 0;


	int xs[] = { 1343, 1338, 1343, 1348, 1354, 1358, 1354, 1354, 1354, 1358, 1354, 1348, 1343, 1338, 1343, 1343 };
	int ys[] = {  888,  884,  888,  888,  888,  884,  888,  893,  899,  904,  899,  899,  899,  904,  899,  893 };

	int total = 0;

	while( !exit_bot ) {
		// Make sure we are logged in before we continue
		while( !loggedin ) {
			SLEEP( 1000 );
		}

		have_quest = false;

		requestLog( player_id );
		SLEEP( 5000 );

		if( !have_quest && lastQL.curquest != 0x57 ) {
			port( player_id, 2 );

			SLEEP( 2000 );

			transXY( player_id, ( 758 + rand()%2 ), ( 2333 + rand()%2 ));

			SLEEP( 1500 );

			/*while( 1 ) {
				for( auto& x: um_units ) {
					printf(  "Player: %i | X,Y: %i,%i | ModelInfo - Model: %i, Weapon: %i, Shield: %i, Helmet: %i, Color: %04X\n", 
						x.second.id, x.second.movement.positionX, x.second.movement.positionY, x.second.models.model, x.second.models.weapon, x.second.models.shield, x.second.models.helmet, x.second.models.colorbits );
				}
				fprintf( out, "\n" );
				SLEEP( 2000 );
			}*/

			other_guard = 0;
			while( other_guard == 0 ) {
				other_guard = locateUnit( 496, 85, 0, 0, 0x0244 );
				SLEEP( 1000 );
			}

			while( um_units.count( other_guard ) == 0 ) {
				SLEEP( 1000 );
			}

			clickUnit( player_id, other_guard, um_units[ other_guard ].movement.positionY );
			SLEEP( 2000 );

			Say( player_id, (char*)"Pix Animus Task", 15 );
			SLEEP( 2000 );
			Say( player_id, (char*)"OK", 2 );
			SLEEP( 2000 );
			Say( player_id, (char*)"-quitquest", 10 );
			SLEEP( 2000 );

			transXY( player_id, ( 762 + rand()%3 ), 2329 );
			SLEEP( 2000 );

			quest_giver = 0;
			while( quest_giver == 0 ) {
				quest_giver = locateUnit( 496, 85, 0, 0, 0x0099 );
				SLEEP( 1000 );
			}

			while( um_units.count( quest_giver ) == 0 ) {
				SLEEP( 1000 );
			}

			clickUnit( player_id, quest_giver, um_units[ quest_giver ].movement.positionY );
			SLEEP( 2000 );

			Say( player_id, (char*)"warlock task", 12 );
			SLEEP( 2000 );

			Say( player_id, (char*)"OK", 2 );
			SLEEP( 2000 );
		} else {
			port( player_id, 8 );
			SLEEP( 2000 );
		}

		port( player_id, 7 );
		SLEEP( 2000 );
		

		finished_quest = false;
		missing_quest  = false;

		createSkelly( player_id, 1346, 896 );
		SLEEP( 1500 );
		createSkelly( player_id, 1348, 896 );
		SLEEP( 1500 );

		Say( player_id, (char*)"-battle", 7 );
		SLEEP( 1500 );

		int index = 0;
		while( !finished_quest ) {
			if( aliveUnitsRadius( 200 )) {
				rotFlesh( player_id );
				SLEEP( 1000 );
			}
			transXY( player_id, xs[ index ], ys[ index ] );
			SLEEP( 1000 );
			if( !CheckRadius(( xs[ index ] * 20 ), ( ys[ index ] * 20 ), player_x, player_y, 200 )) {
				printf( "[%s] Radius check failed. Restart everything: %i/%i %i/%i\n", currentDateTime().c_str(), ( xs[ index ] * 20 ), ( ys[ index ] * 20 ), player_x, player_y );
				Say( player_id, (char*)"-quitquest", 10 );
				SLEEP( 1000 );
				finished_quest = true;
				missing_quest  = true;
			}
			if( index == 15 ) {
				index = 0;
				if(( rand()%5 ) == 3 ) {
					Say( player_id, (char*)"-battle", 7 );
					SLEEP( 500 );
				}

				requestLog( player_id );
				SLEEP( 500 );
			} else {
				index++;
			}
		}

		if( !missing_quest ) {
			Say( player_id, (char*)"-destroy", 8 );
			SLEEP( 2000 );

			port( player_id, 2 );
			SLEEP( 2000 );

			quest_giver = 0;
			while( quest_giver == 0 ) {
				quest_giver = locateUnit( 496, 85, 0, 0, 0x0099 );
				SLEEP( 1000 );
			}

			while( um_units.count( quest_giver ) == 0 ) {
				SLEEP( 1000 );
			}

			clickUnit( player_id, quest_giver, um_units[ quest_giver ].movement.positionY );
			SLEEP( 2000 );

			port( player_id, 8 );
			SLEEP( 10000 );


			total++;

			printf( "[%s] Quest Done. #%i\n", currentDateTime().c_str(), total );
		}
	}

	//SLEEP( 10000 );

}
Пример #11
0
void handleUpdatePacket(uint8* data, int len)
{

	UpdatePacketSelf update = *(UpdatePacketSelf*)&data[1];

	//if( player_x != update.positionX || player_y != update.positionY ) {
		//printf( "X/Y: %i, %i\n", update.positionX, update.positionY );
	//}
	player_x = update.positionX;
	player_y = update.positionY;
	player_health = update.currentHPPct;

	if( player_health <= 25 ) {
		printf( "[%s] Health (%i) < 25. Exiting!\n", currentDateTime().c_str(), player_health );
		logout( player_id );
		SLEEP( 100 );
		exit_bot       = true;
		finished_quest = true;
		missing_quest  = true;
	}

	/*for( int j = 0; j < len; j++ ) {
		fprintf( out, "%02X ", data[j] );
	}
	fprintf( out, "\n" );

	fprintf( out, "Update positionX: %i\n", update.positionX );
	fprintf( out, "Update positionY: %i\n", update.positionY );
	fprintf( out, "Update spellflags: %i\n", update.spellflags );
	fprintf( out, "Update colorbits: %i\n", update.colorbits );
	fprintf( out, "Update numInRangeDynamicObjects: %i\n", update.numInRangeDynamicObjects );
	fprintf( out, "Update numInRangeUnits: %i\n", update.numInRangeUnits );
	fprintf( out, "Update unklol: %i\n", update.unklol );
	fprintf( out, "Update flags: %i\n", update.flags );
	fprintf( out, "Update rotation: %i\n", update.rotation );
	fprintf( out, "Update animation: %i\n", update.animation );
	fprintf( out, "Update spellEffect: %i\n", update.spellEffect );
	fprintf( out, "Update numInRangeSpellEffects: %i\n", update.numInRangeSpellEffects );
	fprintf( out, "Update unklol2: %i\n", update.unklol2 );
	fprintf( out, "Update unklol3: %i\n", update.unklol3 );
	fprintf( out, "Update currentHPPct: %i\n", update.currentHPPct );
	fprintf( out, "Update currentMPPct: %i\n", update.currentMPPct );
	fprintf( out, "Update currentExpPct: %i\n", update.currentExpPct );
	fprintf( out, "\n\n" );*/

	int offset = 23;

	if( update.numInRangeDynamicObjects > 0 )
	{
		for( int i = 0; i < update.numInRangeDynamicObjects; i++ )
		{
			if( data[offset] == 0x01 ) offset += 8;
			else if( data[offset] == 0x02 ) offset += 12;
			else if( data[offset] == 0x03 ) offset += 6;
		}
	}

	if( update.numInRangeSpellEffects > 0 )
	{
		for( int x = 0; x < update.numInRangeSpellEffects; x++ )
		{
			if( data[offset] >= 240 ) offset += 12;
			else offset += 8;
		}
	}

	setAllOoR();

	if( update.numInRangeUnits > 0 )
	{
		for( int i = 0; i < update.numInRangeUnits; i++ )
		{
			uint16 id = ( data[offset+1] << 8 ) + data[offset];
			uint16 trueid = id & 0x7FFF;
			
			// Attempt to find unit in our unitmap
			setInRange( trueid );

			offset += 2;

			if( id & 0x8000 )
				continue;
			else
			{
				uint8 updateflag = data[offset];
				offset += 1;

				if(updateflag & 0x01)
				{
					UpdatePacketUnitMovement movement = *(UpdatePacketUnitMovement*)&data[offset];
					um_units.at( trueid ).movement = movement;
					//fprintf( out, "Player: %i | Movement | X/Y: %i, %i\n", trueid, movement.positionX, movement.positionY );
					//UnitMap::UpdateUnitsMovement(trueid, *(UpdatePacketUnitMovement*)&data[offset]); 
					offset += 5;
				}
				if(updateflag & 0x02)
				{
					UpdatePacketUnitAuras auras = *(UpdatePacketUnitAuras*)&data[offset];
					um_units.at( trueid ).auras = auras;
					//UnitMap::UpdateUnitsAuras(trueid, *(UpdatePacketUnitAuras*)&data[offset]);
					offset += 3;
				}
				if(updateflag & 0x04)
				{
					UpdatePacketUnitModels models = *(UpdatePacketUnitModels*)&data[offset];
					um_units.at( trueid ).models = models;
					//fprintf( out, "Player: %i | ModelInfo | Model: %i, Weapon: %i, Shield: %i, Helmet: %i\n", trueid, models.model, models.weapon, models.shield, models.helmet );
					//UnitMap::UpdateUnitsModel(trueid, *(UpdatePacketUnitModels*)&data[offset]);
					offset += 8;
				}
				if(updateflag & 0x08)
				{
					UpdatePacketUnitAnim anim = *(UpdatePacketUnitAnim*)&data[offset];
					//UnitMap::UpdateUnitsAnim(trueid, *(UpdatePacketUnitAnim*)&data[offset]);
					um_units.at( trueid ).anim = anim; 

					if( anim.anim == 21 || anim.anim == 45 )
					{
						um_units.at( trueid ).dead = true;
					} else {
						um_units.at( trueid ).dead = false;
					}

					offset += 1;
				}
				if(updateflag & 0x10)
				{
					UpdatePacketUnitSpellEffect spellfx = *(UpdatePacketUnitSpellEffect*)&data[offset];
					//UnitMap::UpdateUnitsSpellEffect(trueid, *(UpdatePacketUnitSpellEffect*)&data[offset]);
					um_units.at( trueid ).spelleffect = spellfx;
					offset += 1;
				}
				if(updateflag & 0x20)
				{
					offset += 1 + data[offset];
				}
			}
		}
	}

	clearOoR();

	if( update.flags & 0x01 ) {
		if( data[offset] == 0x31 && data[offset+1] == 0x30 && data[offset+2] == 0x30 ) {
			finished_quest = true;
		}
	}

	//fprintf( out, "\n\n" );
}
Пример #12
0
/*-------------------------------------------------------------------*/
static void* spthread (void* arg)
{
    DEVBLK* dev = (DEVBLK*) arg;
    BYTE byte;
    fd_set readset, errorset;
    struct timeval tv;
    int rc, fd = dev->fd;           // (save original fd)

    /* Fix thread name */
    {
        char thread_name[32];
        thread_name[sizeof(thread_name)-1] = 0;
        snprintf( thread_name, sizeof(thread_name)-1,
            "spthread %1d:%04X", SSID_TO_LCSS(dev->ssid), dev->devnum );
        SET_THREAD_NAME( thread_name );
    }

    // Looooop...  until shutdown or disconnect...

    // PROGRAMMING NOTE: we do our select specifying an immediate
    // timeout to prevent our select from holding up (slowing down)
    // the device thread (which does the actual writing of data to
    // the client). The only purpose for our thread even existing
    // is to detect a severed connection (i.e. to detect when the
    // client disconnects)...

    while ( !sysblk.shutdown && dev->fd == fd )
    {
        if (dev->busy)
        {
            SLEEP(3);
            continue;
        }

        FD_ZERO( &readset );
        FD_ZERO( &errorset );

        FD_SET( fd, &readset );
        FD_SET( fd, &errorset );

        tv.tv_sec = 0;
        tv.tv_usec = 0;

        rc = select( fd+1, &readset, NULL, &errorset, &tv );

        if (rc < 0)
            break;

        if (rc == 0)
        {
            SLEEP(3);
            continue;
        }

        if (FD_ISSET( fd, &errorset ))
            break;

        // Read and ignore any data they send us...
        // Note: recv should complete immediately
        // as we know data is waiting to be read.

        ASSERT( FD_ISSET( fd, &readset ) );

        rc = recv( fd, &byte, sizeof(byte), 0 );

        if (rc <= 0)
            break;
    }

    obtain_lock( &dev->lock );

    // PROGRAMMING NOTE: the following tells us whether we detected
    // the error or if the device thread already did. If the device
    // thread detected it while we were sleeping (and subsequently
    // closed the connection) then we don't need to do anything at
    // all; just exit. If we were the ones that detected the error
    // however, then we need to close the connection so the device
    // thread can learn of it...

    if (dev->fd == fd)
    {
        dev->fd = -1;
        close_socket( fd );
        WRMSG (HHC01100, "I", SSID_TO_LCSS(dev->ssid), dev->devnum,
               dev->bs->clientname, dev->bs->clientip, dev->bs->spec);
    }

    release_lock( &dev->lock );

    return NULL;

} /* end function spthread */
Пример #13
0
/*******************************************************************************************
    Video capture routines

 - set input
 - setup_pixelformat
 - set_geometry

 - set_brightness
 - set_chroma
 - set_contrast
 - set_channelset
 - set_channel
 - set_capture_mode

*/
static unsigned char *v4l_start(struct video_dev *viddev, int width, int height,
                                unsigned input, unsigned norm, unsigned long freq)
{
    int dev_bktr = viddev->fd_bktr;
    struct sigaction act, old;
    //int dev_tunner = viddev->fd_tuner;
    /* to ensure that all device will be support the capture mode
      _TODO_ : Autodected the best capture mode .
    */
    int dummy = 1;
    //    int pixelformat = BSD_VIDFMT_I420;

    void *map;

    /* If we have choose the tuner is needed to setup the frequency. */
    if ((viddev->tuner_device != NULL) && (input == IN_TV)) {
        if (!freq) {
            MOTION_LOG(WRN, TYPE_VIDEO, NO_ERRNO, "%s: Not valid Frequency [%lu] for "
                       "Source input [%i]", freq, input);
            return NULL;
        } else if (set_freq(viddev, freq) == -1) {
            MOTION_LOG(NTC, TYPE_VIDEO, NO_ERRNO, "%s: Frequency [%lu] Source input [%i]",
                       freq, input);
            return NULL;
        }
    }

    /* FIXME if we set as input tuner , we need to set option for tuner not for bktr */
    if ((dummy = set_input(viddev, input)) == -1) {
        MOTION_LOG(NTC, TYPE_VIDEO, NO_ERRNO, "%s: set input [%d]", input);
        return NULL;
    }

    viddev->input = dummy;

    if ((dummy = set_input_format(viddev, norm)) == -1) {
        MOTION_LOG(NTC, TYPE_VIDEO, NO_ERRNO, "%s: set input format [%d]",
                   norm);
        return NULL;
    }

    viddev->norm = dummy;

    if (set_geometry(viddev, width, height) == -1) {
        MOTION_LOG(NTC, TYPE_VIDEO, NO_ERRNO, "%s: set geometry [%d]x[%d]",
                   width, height);
        return NULL;
    }

    /*
    if (ioctl(dev_bktr, METEORSACTPIXFMT, &pixelformat) < 0) {
        MOTION_LOG(ERR, TYPE_VIDEO, SHOW_ERRNO, "%s: set encoding method BSD_VIDFMT_I420");
        return NULL;
    }

    NEEDED !? FIXME

    if (setup_pixelformat(viddev) == -1)
        return NULL;
    */

    if (freq) {
        MOTION_LOG(WRN, TYPE_VIDEO, NO_ERRNO, "%s: Frequency set (no implemented yet");
    /*
     TODO missing implementation
        set_channelset(viddev);
        set_channel(viddev);
        if (set_freq (viddev, freq) == -1)
            return NULL;
    */

    }

    /*
     * Set capture mode and capture buffers
     * That is the buffer size for capture images ,
     * so is dependent of color space of input format / FIXME
     */
    viddev->v4l_bufsize = (((width * height * 3 / 2)) * sizeof(unsigned char));
    viddev->v4l_fmt = VIDEO_PALETTE_YUV420P;


    map = mmap((caddr_t)0, viddev->v4l_bufsize, PROT_READ|PROT_WRITE, MAP_SHARED,
               dev_bktr, (off_t)0);

    if (map == MAP_FAILED) {
        MOTION_LOG(ERR, TYPE_VIDEO, SHOW_ERRNO, "%s: mmap failed");
        return NULL;
    }

    /* FIXME double buffer */
    if (0) {
        viddev->v4l_maxbuffer = 2;
        viddev->v4l_buffers[0] = map;
        viddev->v4l_buffers[1] = (unsigned char *)map + 0; /* 0 is not valid just a test */
        //viddev->v4l_buffers[1] = map+vid_buf.offsets[1];
    } else {
        viddev->v4l_buffers[0] = map;
        viddev->v4l_maxbuffer = 1;
    }

    viddev->v4l_curbuffer = 0;

    /* Clear the buffer */
    if (ioctl(dev_bktr, BT848SCBUF, &dummy) < 0) {
        MOTION_LOG(ERR, TYPE_VIDEO, SHOW_ERRNO, "%s: BT848SCBUF");
        return NULL;
    }

    /* Signal handler to know when data is ready to be read() */
    memset(&act, 0, sizeof(act));
    sigemptyset(&act.sa_mask);
    act.sa_handler = catchsignal;
    sigaction(SIGUSR2, &act, &old);

    dummy = SIGUSR2;

    //viddev->capture_method = METEOR_CAP_CONTINOUS;
    //viddev->capture_method = METEOR_CAP_SINGLE;

    if ((viddev->capture_method == METEOR_CAP_CONTINOUS) &&
        (ioctl(dev_bktr, METEORSSIGNAL, &dummy) < 0)) {
        MOTION_LOG(NTC, TYPE_VIDEO, NO_ERRNO, "%s: METEORSSIGNAL");

        viddev->capture_method = METEOR_CAP_SINGLE;

        if (ioctl(dev_bktr, METEORCAPTUR, &viddev->capture_method) < 0) {
            MOTION_LOG(ERR, TYPE_VIDEO, SHOW_ERRNO, "%s: METEORCAPTUR using single method "
                       "Error capturing");
            MOTION_LOG(NTC, TYPE_VIDEO, NO_ERRNO, "%s: METEORCAPTUR using single method "
                       "Error capturing");
        }
    } else {
        if (ioctl(dev_bktr, METEORCAPTUR, &viddev->capture_method) < 0) {
            viddev->capture_method = METEOR_CAP_SINGLE;

            if (ioctl(dev_bktr, METEORCAPTUR, &viddev->capture_method) < 0) {
                MOTION_LOG(ERR, TYPE_VIDEO, SHOW_ERRNO, "%s: METEORCAPTUR using single method "
                           "Error capturing");
            }
        }
    }

    if (viddev->capture_method == METEOR_CAP_CONTINOUS)
        MOTION_LOG(NTC, TYPE_VIDEO, NO_ERRNO, "%s: METEORCAPTUR METEOR_CAP_CONTINOUS");
    else
        MOTION_LOG(NTC, TYPE_VIDEO, NO_ERRNO, "%s: METEORCAPTUR METEOR_CAP_SINGLE");

    // settle , sleep(1) replaced
    SLEEP(1, 0);

    /* FIXME */
    switch (viddev->v4l_fmt) {
    case VIDEO_PALETTE_YUV420P:
        viddev->v4l_bufsize = (width * height * 3) / 2;
        break;
    case VIDEO_PALETTE_YUV422:
        viddev->v4l_bufsize = (width * height * 2);
        break;
    case VIDEO_PALETTE_RGB24:
        viddev->v4l_bufsize = (width * height * 3);
        break;
    case VIDEO_PALETTE_GREY:
        viddev->v4l_bufsize = width * height;
        break;
    }

    MOTION_LOG(NTC, TYPE_VIDEO, NO_ERRNO, "%s: HUE [%d]",
               get_hue(dev_bktr, &dummy));
    MOTION_LOG(NTC, TYPE_VIDEO, NO_ERRNO, "%s: SATURATION [%d]",
               get_saturation(dev_bktr, &dummy));
    MOTION_LOG(NTC, TYPE_VIDEO, NO_ERRNO, "%s: BRIGHTNESS [%d]",
               get_brightness(dev_bktr, &dummy));
    MOTION_LOG(NTC, TYPE_VIDEO, NO_ERRNO, "%s: CONTRAST [%d]",
               get_contrast(dev_bktr, &dummy));

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

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

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


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

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

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

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

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

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

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

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

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

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

  } // process commandline arguments
  
  

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

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

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

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

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

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

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

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

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

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

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

  // if specified upload hexfile
  if (strlen(hexfile)>0)
    bsl_memWrite(ptrPort, imageStart, numBytes, image, 1);
  
  // memory read
  //imageStart = 0x8000;  numBytes = 128*1024;   // complete 128kB flash
  //imageStart = 0x00A0;  numBytes = 352;        // RAM
  //bsl_memRead(ptrPort, imageStart, numBytes, image);
  
  
  // enable ROM bootloader after upload (option bytes always on same address)
  if (enableBSL==1) {
    printf("  activate bootloader ... ");
    bsl_memWrite(ptrPort, 0x487E, 2, (char*)"\x55\xAA", 0);
    printf("done\n");
  }
  
  // jump to flash start address after upload (reset vector always on same address)
  if (jumpFlash)
    bsl_jumpTo(ptrPort, 0x8000);
  
  
  ////////
  // clean up and exit
  ////////
  close_port(&ptrPort);
  if (verbose)
    printf("done with program\n");
  Exit(0, g_pauseOnExit);
  
  // avoid compiler warnings
  return(0);
  
} // main
Пример #15
0
/*
** Called at initialization time to set PWM frequencies, disable amp, etc...
*/
IMMVIBESPIAPI VibeStatus ImmVibeSPI_ForceOut_Initialize(void)
{
    int cnt = 0;
    unsigned char I2C_data[2];
    int ret = VIBE_S_SUCCESS;

    DbgOut((KERN_DEBUG "ImmVibeSPI_ForceOut_Initialize.\n"));

    SYS_API_VDDP_ON;
    SYS_API_LEN_HIGH;

    SLEEP(200 /*us*/);

    I2C_data[1] = g_nLDO_Voltage; // LDO Voltage
    I2C_data[0]= SCTRL;
    do
    {
        ret = SYS_API__I2C__Write(ISA1200_I2C_ADDRESS,  2 /* data length*/,  I2C_data);
        cnt++;
    }while(VIBE_S_SUCCESS != ret && cnt < RETRY_CNT);
    if( VIBE_S_SUCCESS != ret) DEBUG_MSG("[ImmVibeSPI_ForceOut_Initialize] I2C_Write Error,  Slave Address = [%d], ret = [%d]\n", I2C_data[0], ret);

#ifdef ISA1200_GEN_MODE
    I2C_data[1] = 0x11; //Haptic Drive Disable + PWM generation mode + 44.8Khz mode
    I2C_data[0]= HCTRL0;
    do
    {
        ret = SYS_API__I2C__Write(ISA1200_I2C_ADDRESS,  2 /* data length*/,  I2C_data);
        cnt++;
    }while(VIBE_S_SUCCESS != ret && cnt < RETRY_CNT);
    if( VIBE_S_SUCCESS != ret) DEBUG_MSG("[ImmVibeSPI_ForceOut_Initialize] I2C_Write Error,  Slave Address = [%d], ret = [%d]\n", I2C_data[0], ret);

#ifdef MOTOR_TYPE_LRA
    I2C_data[1] = 0xC0 ; // EXT clock + DAC inversion + LRA
#else
    I2C_data[1] = 0xE0; // EXT clock + DAC inversion + ERM
#endif
    I2C_data[0]= HCTRL1;
    do
    {
        ret = SYS_API__I2C__Write(ISA1200_I2C_ADDRESS,  2 /* data length*/,  I2C_data);
        cnt++;
    }while(VIBE_S_SUCCESS != ret && cnt < RETRY_CNT);
    if( VIBE_S_SUCCESS != ret) DEBUG_MSG("[ImmVibeSPI_ForceOut_Initialize] I2C_Write Error,  Slave Address = [%d], ret = [%d]\n", I2C_data[0], ret);

    I2C_data[1] = 0x00 ; // Disable Software Reset
    I2C_data[0]= HCTRL2;
    do
    {
        ret = SYS_API__I2C__Write(ISA1200_I2C_ADDRESS,  2 /* data length*/,  I2C_data);
        cnt++;
    }while(VIBE_S_SUCCESS != ret && cnt < RETRY_CNT);
    if( VIBE_S_SUCCESS != ret) DEBUG_MSG("[ImmVibeSPI_ForceOut_Initialize] I2C_Write Error,  Slave Address = [%d], ret = [%d]\n", I2C_data[0], ret);

    I2C_data[1] = 0x03 + ( g_nPWM_PLLDiv<<4); // PLLLDIV
    I2C_data[0]= HCTRL3;
    do
    {
        ret = SYS_API__I2C__Write(ISA1200_I2C_ADDRESS,  2 /* data length*/,  I2C_data);
        cnt++;
    }while(VIBE_S_SUCCESS != ret && cnt < RETRY_CNT);
    if( VIBE_S_SUCCESS != ret) DEBUG_MSG("[ImmVibeSPI_ForceOut_Initialize] I2C_Write Error,  Slave Address = [%d], ret = [%d]\n", I2C_data[0], ret);

    I2C_data[1] = g_nPWM_Freq; // PWM control
    I2C_data[0]= HCTRL4;
    do
    {
        ret = SYS_API__I2C__Write(ISA1200_I2C_ADDRESS,  2 /* data length*/,  I2C_data);
        cnt++;
    }while(VIBE_S_SUCCESS != ret && cnt < RETRY_CNT);
    if( VIBE_S_SUCCESS != ret) DEBUG_MSG("[ImmVibeSPI_ForceOut_Initialize] I2C_Write Error,  Slave Address = [%d], ret = [%d]\n", I2C_data[0], ret);

    I2C_data[1] = g_nPWM_Duty; // PWM High Duty
    I2C_data[0]= HCTRL5;
    do
    {
        ret = SYS_API__I2C__Write(ISA1200_I2C_ADDRESS,  2 /* data length*/,  I2C_data);
        cnt++;
    }while(VIBE_S_SUCCESS != ret && cnt < RETRY_CNT);
    if( VIBE_S_SUCCESS != ret) DEBUG_MSG("[ImmVibeSPI_ForceOut_Initialize] I2C_Write Error,  Slave Address = [%d], ret = [%d]\n", I2C_data[0], ret);

    I2C_data[1] = g_nPWM_Period; // PWM Period
    I2C_data[0]= HCTRL6;
    do
    {
        ret = SYS_API__I2C__Write(ISA1200_I2C_ADDRESS,  2 /* data length*/,  I2C_data);
        cnt++;
    }while(VIBE_S_SUCCESS != ret && cnt < RETRY_CNT);
    if( VIBE_S_SUCCESS != ret) DEBUG_MSG("[ImmVibeSPI_ForceOut_Initialize] I2C_Write Error,  Slave Address = [%d], ret = [%d]\n", I2C_data[0], ret);

#else // PWM Input Mode

#ifdef ISA1200_PWM_256DIV_MODE
    I2C_data[1] = 0x09; // Haptic Drive Disable + PWM Input mode + 44.8Khz mode
#else
    I2C_data[1] = 0x08; // Haptic Drive Disable + PWM Input mode + 22.4Khz mode
#endif
    I2C_data[0]= HCTRL0;
    do
    {
        ret = SYS_API__I2C__Write(ISA1200_I2C_ADDRESS,  2 /* data length*/,  I2C_data);
        cnt++;
    }while(VIBE_S_SUCCESS != ret && cnt < RETRY_CNT);
    if( VIBE_S_SUCCESS != ret) DEBUG_MSG("[ImmVibeSPI_ForceOut_Initialize] I2C_Write Error,  Slave Address = [%d], ret = [%d]\n", I2C_data[0], ret);

#ifdef MOTOR_TYPE_LRA
    I2C_data[1] = 0x43; // EXT clock + DAC inversion + LRA
#else
    I2C_data[1] = 0x63; // EXT clock + DAC inversion + ERM
#endif
    I2C_data[0]= HCTRL1;
    do
    {
        ret = SYS_API__I2C__Write(ISA1200_I2C_ADDRESS,  2 /* data length*/,  I2C_data);
        cnt++;
    }while(VIBE_S_SUCCESS != ret && cnt < RETRY_CNT);
    if( VIBE_S_SUCCESS != ret) DEBUG_MSG("[ImmVibeSPI_ForceOut_Initialize] I2C_Write Error,  Slave Address = [%d], ret = [%d]\n", I2C_data[0], ret);

    I2C_data[1] = 0x00; // Disable Software Reset
    I2C_data[0]= HCTRL2;
    do
    {
        ret = SYS_API__I2C__Write(ISA1200_I2C_ADDRESS,  2 /* data length*/,  I2C_data);
        cnt++;
    }while(VIBE_S_SUCCESS != ret && cnt < RETRY_CNT);
    if( VIBE_S_SUCCESS != ret) DEBUG_MSG("[ImmVibeSPI_ForceOut_Initialize] I2C_Write Error,  Slave Address = [%d], ret = [%d]\n", I2C_data[0], ret);

    I2C_data[1] = 0x00; // Default
    I2C_data[0]= HCTRL4;
    do
    {
        ret = SYS_API__I2C__Write(ISA1200_I2C_ADDRESS,  2 /* data length*/,  I2C_data);
        cnt++;
    }while(VIBE_S_SUCCESS != ret && cnt < RETRY_CNT);
    if( VIBE_S_SUCCESS != ret) DEBUG_MSG("[ImmVibeSPI_ForceOut_Initialize] I2C_Write Error,  Slave Address = [%d], ret = [%d]\n", I2C_data[0], ret);
#endif
    return VIBE_S_SUCCESS;
}
Пример #16
0
int
eicon_isa_bootload(eicon_isa_card *card, eicon_isa_codebuf *cb) {
	int	tmp;
	int               timeout;
	eicon_isa_codebuf cbuf;
	unsigned char     *code;
	eicon_isa_boot    *boot;

	if (copy_from_user(&cbuf, cb, sizeof(eicon_isa_codebuf)))
		return -EFAULT;

	/* Allocate code-buffer and copy code from userspace */
	if (cbuf.bootstrap_len > 1024) {
		printk(KERN_WARNING "eicon_isa_boot: Invalid startup-code size %ld\n",
		       cbuf.bootstrap_len);
		return -EINVAL;
	}
	if (!(code = kmalloc(cbuf.bootstrap_len, GFP_KERNEL))) {
		printk(KERN_WARNING "eicon_isa_boot: Couldn't allocate code buffer\n");
		return -ENOMEM;
	}
	if (copy_from_user(code, &cb->code, cbuf.bootstrap_len)) {
		kfree(code);
		return -EFAULT;
	}

	if (card->type == EICON_CTYPE_ISAPRI)
		card->ramsize  = RAMSIZE_P;
	else
		card->ramsize  = RAMSIZE;

	if (check_mem_region(card->physmem, card->ramsize)) {
		printk(KERN_WARNING "eicon_isa_boot: memory at 0x%lx already in use.\n",
			card->physmem);
		kfree(code);
		return -EBUSY;
	}
	request_mem_region(card->physmem, card->ramsize, "Eicon ISA ISDN");
	card->shmem = (eicon_isa_shmem *) ioremap(card->physmem, card->ramsize);
#ifdef EICON_MCA_DEBUG
	printk(KERN_INFO "eicon_isa_boot: card->ramsize = %d.\n", card->ramsize);
#endif
	card->mvalid = 1;

	switch(card->type) {
		case EICON_CTYPE_S:
		case EICON_CTYPE_SX:
		case EICON_CTYPE_SCOM:
		case EICON_CTYPE_QUADRO:
		case EICON_CTYPE_ISABRI:
			card->intack   = (__u8 *)card->shmem + INTACK;
			card->startcpu = (__u8 *)card->shmem + STARTCPU;
			card->stopcpu  = (__u8 *)card->shmem + STOPCPU;
			break;
		case EICON_CTYPE_S2M:
		case EICON_CTYPE_ISAPRI:
			card->intack   = (__u8 *)card->shmem + INTACK_P;
			card->startcpu = (__u8 *)card->shmem + STARTCPU_P;
			card->stopcpu  = (__u8 *)card->shmem + STOPCPU_P;
			break;
		default:
			printk(KERN_WARNING "eicon_isa_boot: Invalid card type %d\n", card->type);
			eicon_isa_release_shmem(card);
			kfree(code);
			return -EINVAL;
	}

	/* clear any pending irq's */
	readb(card->intack);
#ifdef CONFIG_MCA
	if (MCA_bus) {
		if (card->type == EICON_CTYPE_SCOM) {
			outb_p(0,card->io+1);
		}
		else {
			printk(KERN_WARNING "eicon_isa_boot: Card type not supported yet.\n");
			eicon_isa_release_shmem(card);
			return -EINVAL;
		};

#ifdef EICON_MCA_DEBUG
	printk(KERN_INFO "eicon_isa_boot: card->io      = %x.\n", card->io);
	printk(KERN_INFO "eicon_isa_boot: card->irq     = %d.\n", (int)card->irq);
#endif
	}
#else
	/* set reset-line active */
	writeb(0, card->stopcpu); 
#endif  /* CONFIG_MCA */
	/* clear irq-requests */
	writeb(0, card->intack);
	readb(card->intack);

	/* Copy code into card */
	memcpy_toio(&card->shmem->c, code, cbuf.bootstrap_len);

	/* Check for properly loaded code */
	if (!check_signature((unsigned long)&card->shmem->c, code, 1020)) {
		printk(KERN_WARNING "eicon_isa_boot: Could not load startup-code\n");
		eicon_isa_release_shmem(card);
		kfree(code);
		return -EIO;
	}
	/* if 16k-ramsize, duplicate the reset-jump-code */
	if (card->ramsize == RAMSIZE_P)
		memcpy_toio((__u8 *)card->shmem + 0x3ff0, &code[0x3f0], 12);

	kfree(code);
	boot = &card->shmem->boot;

	/* Delay 0.2 sec. */
	SLEEP(HZ / 5);

	/* Start CPU */
	writeb(cbuf.boot_opt, &boot->ctrl);
#ifdef CONFIG_MCA
	if (MCA_bus) {
		outb_p(0, card->io);
	}
#else 
	writeb(0, card->startcpu); 
#endif /* CONFIG_MCA */

	/* Delay 0.2 sec. */
	SLEEP(HZ / 5);

	timeout = jiffies + (HZ * 22);
	while (time_before(jiffies, timeout)) {
		if (readb(&boot->ctrl) == 0)
			break;
		SLEEP(10);
	}
	if (readb(&boot->ctrl) != 0) {
		printk(KERN_WARNING "eicon_isa_boot: CPU test failed.\n");
#ifdef EICON_MCA_DEBUG
		printk(KERN_INFO "eicon_isa_boot: &boot->ctrl = %d.\n",
			readb(&boot->ctrl));
#endif
		eicon_isa_release_shmem(card);
		return -EIO;
	}

	/* Check for memory-test errors */
	if (readw(&boot->ebit)) {
		printk(KERN_WARNING "eicon_isa_boot: memory test failed (bit 0x%04x at 0x%08x)\n",
		       readw(&boot->ebit), readl(&boot->eloc));
		eicon_isa_release_shmem(card);
		return -EIO;
	}

        /* Check card type and memory size */
        tmp = readb(&boot->card);
	if ((tmp < 0) || (tmp > 4)) {
		printk(KERN_WARNING "eicon_isa_boot: Type detect failed\n");
		eicon_isa_release_shmem(card);
		return -EIO;
	}
	card->type = tmp;
	((eicon_card *)card->card)->type = tmp;

        tmp = readb(&boot->msize);
        if (tmp != 8 && tmp != 16 && tmp != 24 &&
            tmp != 32 && tmp != 48 && tmp != 60) {
                printk(KERN_WARNING "eicon_isa_boot: invalid memsize\n");
		eicon_isa_release_shmem(card);
                return -EIO;
        }
	printk(KERN_INFO "%s: startup-code loaded\n", eicon_ctype_name[card->type]); 
	if ((card->type == EICON_CTYPE_QUADRO) && (card->master)) {
		tmp = eicon_addcard(card->type, card->physmem, card->irq, 
				((eicon_card *)card->card)->regname, 0);
		printk(KERN_INFO "Eicon: %d adapters added\n", tmp);
	}
	return 0;
}
void CWE400_Resource_Exhaustion__fscanf_sleep_82_bad::action(int count)
{
    /* POTENTIAL FLAW: Sleep function using count as the parameter with no validation */
    SLEEP(count);
    printLine("Sleep time possibly too long");
}
Пример #18
0
int
eicon_isa_load(eicon_isa_card *card, eicon_isa_codebuf *cb) {
	eicon_isa_boot    *boot;
	int               tmp;
	int               timeout;
	int 		  j;
	eicon_isa_codebuf cbuf;
	unsigned char     *code;
	unsigned char     *p;

	if (copy_from_user(&cbuf, cb, sizeof(eicon_isa_codebuf)))
		return -EFAULT;

	if (!(code = kmalloc(cbuf.firmware_len, GFP_KERNEL))) {
		printk(KERN_WARNING "eicon_isa_load: Couldn't allocate code buffer\n");
		return -ENOMEM;
	}

	if (copy_from_user(code, &cb->code, cbuf.firmware_len)) {
		kfree(code);
		return -EFAULT;
	}

	boot = &card->shmem->boot;

	if ((!card->ivalid) && card->master) {
		card->irqprobe = 1;
		/* Check for valid IRQ */
		if ((card->irq < 0) || (card->irq > 15) || 
		    (!((1 << card->irq) & eicon_isa_valid_irq[card->type & 0x0f]))) {
			printk(KERN_WARNING "eicon_isa_load: illegal irq: %d\n", card->irq);
			eicon_isa_release_shmem(card);
			kfree(code);
			return -EINVAL;
		}
		/* Register irq */
		if (!request_irq(card->irq, &eicon_irq, 0, "Eicon ISA ISDN", card))
			card->ivalid = 1;
		else {
			printk(KERN_WARNING "eicon_isa_load: irq %d already in use.\n",
			       card->irq);
			eicon_isa_release_shmem(card);
			kfree(code);
			return -EBUSY;
		}
	}

        tmp = readb(&boot->msize);
        if (tmp != 8 && tmp != 16 && tmp != 24 &&
            tmp != 32 && tmp != 48 && tmp != 60) {
                printk(KERN_WARNING "eicon_isa_load: invalid memsize\n");
		eicon_isa_release_shmem(card);
                return -EIO;
        }

	eicon_isa_printpar(card);

	/* Download firmware */
	printk(KERN_INFO "%s %dkB, loading firmware ...\n", 
	       eicon_ctype_name[card->type],
	       tmp * 16);
	tmp = cbuf.firmware_len >> 8;
	p = code;
	while (tmp--) {
		memcpy_toio(&boot->b, p, 256);
		writeb(1, &boot->ctrl);
		timeout = jiffies + HZ / 10;
		while (time_before(jiffies, timeout)) {
			if (readb(&boot->ctrl) == 0)
				break;
			SLEEP(2);
		}
		if (readb(&boot->ctrl)) {
			printk(KERN_WARNING "eicon_isa_load: download timeout at 0x%x\n", p-code);
			eicon_isa_release(card);
			kfree(code);
			return -EIO;
		}
		p += 256;
	}
	kfree(code);

	/* Initialize firmware parameters */
	memcpy_toio(&card->shmem->c[8], &cbuf.tei, 14);
	memcpy_toio(&card->shmem->c[32], &cbuf.oad, 96);
	memcpy_toio(&card->shmem->c[128], &cbuf.oad, 96);
	
	/* Start firmware, wait for signature */
	writeb(2, &boot->ctrl);
	timeout = jiffies + (5*HZ);
	while (time_before(jiffies, timeout)) {
		if (readw(&boot->signature) == 0x4447)
			break;
		SLEEP(2);
	}
	if (readw(&boot->signature) != 0x4447) {
		printk(KERN_WARNING "eicon_isa_load: firmware selftest failed %04x\n",
		       readw(&boot->signature));
		eicon_isa_release(card);
		return -EIO;
	}

	card->channels = readb(&card->shmem->c[0x3f6]);

	/* clear irq-requests, reset irq-count */
	readb(card->intack);
	writeb(0, card->intack);

	if (card->master) {
		card->irqprobe = 1;
		/* Trigger an interrupt and check if it is delivered */
		tmp = readb(&card->shmem->com.ReadyInt);
		tmp ++;
		writeb(tmp, &card->shmem->com.ReadyInt);
		timeout = jiffies + HZ / 5;
		while (time_before(jiffies, timeout)) {
			if (card->irqprobe > 1)
				break;
			SLEEP(2);
		}
		if (card->irqprobe == 1) {
			printk(KERN_WARNING "eicon_isa_load: IRQ # %d test failed\n", card->irq);
			eicon_isa_release(card);
			return -EIO;
		}
	}
#ifdef EICON_MCA_DEBUG
	printk(KERN_INFO "eicon_isa_load: IRQ # %d test succeeded.\n", card->irq);
#endif

	writeb(card->irq, &card->shmem->com.Int);

	/* initializing some variables */
	((eicon_card *)card->card)->ReadyInt = 0;
	((eicon_card *)card->card)->ref_in  = 1;
	((eicon_card *)card->card)->ref_out = 1;
	for(j=0; j<256; j++) ((eicon_card *)card->card)->IdTable[j] = NULL;
	for(j=0; j< (card->channels + 1); j++) {
		((eicon_card *)card->card)->bch[j].e.busy = 0;
		((eicon_card *)card->card)->bch[j].e.D3Id = 0;
		((eicon_card *)card->card)->bch[j].e.B2Id = 0;
		((eicon_card *)card->card)->bch[j].e.ref = 0;
		((eicon_card *)card->card)->bch[j].e.Req = 0;
		((eicon_card *)card->card)->bch[j].e.complete = 1;
		((eicon_card *)card->card)->bch[j].fsm_state = EICON_STATE_NULL;
	}

	printk(KERN_INFO "Eicon: Supported channels: %d\n", card->channels); 
	printk(KERN_INFO "%s successfully started\n", eicon_ctype_name[card->type]);

	/* Enable normal IRQ processing */
	card->irqprobe = 0;
	return 0;
}
Пример #19
0
static int
tegra_i2c_transfer(device_t dev, struct iic_msg *msgs, uint32_t nmsgs)
{
    int rv, i;
    struct tegra_i2c_softc *sc;
    enum tegra_i2c_xfer_type xtype;

    sc = device_get_softc(dev);
    LOCK(sc);

    /* Get the bus. */
    while (sc->bus_inuse == 1)
        SLEEP(sc,  0);
    sc->bus_inuse = 1;

    rv = 0;
    for (i = 0; i < nmsgs; i++) {
        sc->msg = &msgs[i];
        sc->msg_idx = 0;
        sc->bus_err = 0;
        sc->done = 0;
        /* Check for valid parameters. */
        if (sc->msg == NULL || sc->msg->buf == NULL ||
                sc->msg->len == 0) {
            rv = EINVAL;
            break;
        }

        /* Get flags for next transfer. */
        if (i == (nmsgs - 1)) {
            if (msgs[i].flags & IIC_M_NOSTOP)
                xtype = XFER_CONTINUE;
            else
                xtype = XFER_STOP;
        } else {
            if (msgs[i + 1].flags & IIC_M_NOSTART)
                xtype = XFER_CONTINUE;
            else
                xtype = XFER_REPEAT_START;
        }
        tegra_i2c_start_msg(sc, sc->msg, xtype);
        if (cold)
            rv = tegra_i2c_poll(sc);
        else
            rv = msleep(&sc->done, &sc->mtx, PZERO, "iic",
                        I2C_REQUEST_TIMEOUT);

        WR4(sc, I2C_INTERRUPT_MASK_REGISTER, 0);
        WR4(sc, I2C_INTERRUPT_STATUS_REGISTER, 0xFFFFFFFF);
        if (rv == 0)
            rv = sc->bus_err;
        if (rv != 0)
            break;
    }

    if (rv != 0) {
        tegra_i2c_hw_init(sc);
        tegra_i2c_flush_fifo(sc);
    }

    sc->msg = NULL;
    sc->msg_idx = 0;
    sc->bus_err = 0;
    sc->done = 0;

    /* Wake up the processes that are waiting for the bus. */
    sc->bus_inuse = 0;
    wakeup(sc);
    UNLOCK(sc);

    return (rv);
}
Пример #20
0
int main()
{
	char	str[128];
	char	compiler[128];
	char	fpath[MAX_PATH+1];
	char*	path = ".";
	char*	glob_pattern = "*wrap*";
	int		i;
	int		ch;
	uint	u;
	time_t	t;
	glob_t	g;
	DIR*	dir;
	DIRENT*	dirent;
	thread_data_t thread_data;
	int	fd;
	int	fd2;
	int	canrelock=0;
	clock_t	ticks;

	/* Show platform details */
	DESCRIBE_COMPILER(compiler);
	printf("%-15s: %s\n","Platform",PLATFORM_DESC);
	printf("%-15s: %s\n","Version",os_version(str));
	printf("%-15s: %s\n","Compiler"	,compiler);
	printf("%-15s: %d\n","Random Number",xp_random(1000));

	for(i=0;i<3;i++) {
		if(_beginthread(
			  sopen_child_thread	/* entry point */
			 ,0  					/* stack size (0=auto) */
			 ,(void*)i				/* data */
			 )==(unsigned long)-1)
			printf("_beginthread failed\n");
		else
			SLEEP(1);
	}
	printf("Waiting for all sopen_child_threads to close...\n");
	SLEEP(5000);	/* wait for all threads to quit */

	/* Exclusive sopen test */
	printf("\nsopen() test\n");
	if((fd=sopen(LOCK_FNAME,O_RDWR|O_CREAT,SH_DENYRW,S_IREAD|S_IWRITE))==-1) {
		perror(LOCK_FNAME);
		return(errno);
	}
	printf("%s is opened with an exclusive (read/write) lock\n",LOCK_FNAME);
	getkey();
	if(_beginthread(
		  sopen_test_thread	/* entry point */
		 ,0  				/* stack size (0=auto) */
		 ,NULL				/* data */
		 )==(unsigned long)-1)
		printf("_beginthread failed\n");
	else
		SLEEP(1000);
	close(fd);

	/* sopen()/lock test */
	printf("\nlock() test\n");
	if((fd=sopen(LOCK_FNAME,O_RDWR|O_CREAT,SH_DENYNO,S_IREAD|S_IWRITE))==-1) {
		perror(LOCK_FNAME);
		return(errno);
	}
	write(fd,"lock testing\n",LOCK_LEN);
	if(lock(fd,LOCK_OFFSET,LOCK_LEN)==0)
		printf("lock() succeeds\n");
	else
		printf("!FAILURE: lock() non-functional (or file already locked)\n");
	if(lock(fd,LOCK_OFFSET,LOCK_LEN)==0)  {
		printf("!FAILURE: Subsequent lock of region was allowed (will skip some tests)\n");
		canrelock=1;
	}
		
	if(_beginthread(
		  lock_test_thread	/* entry point */
		 ,0  				/* stack size (0=auto) */
		 ,NULL				/* data */
		 )==(unsigned long)-1)
		printf("_beginthread failed\n");
	else
		SLEEP(1000);
	if(canrelock)
		printf("?? Skipping some tests due to inability to detect own locks\n");
	else  {
		if(lock(fd,LOCK_OFFSET,LOCK_LEN))
			printf("Locks in first thread survive open()/close() in other thread\n");
		else
			printf("!FAILURE: lock() in first thread lost by open()/close() in other thread\n");
		if(lock(fd,LOCK_OFFSET+LOCK_LEN+1,LOCK_LEN))
			printf("!FAILURE: file locking\n");
		else
			printf("Record locking\n");
	}
	if((fd2=sopen(LOCK_FNAME,O_RDWR,SH_DENYRW))==-1) {
		printf("Cannot reopen SH_DENYRW while lock is held\n");
		close(fd2);
	}
	else  {
		printf("!FAILURE: can reopen SH_DENYRW while lock is held\n");
	}
	if(unlock(fd,LOCK_OFFSET,LOCK_LEN))
		printf("!FAILURE: unlock() non-functional\n");
	if(lock(fd,LOCK_OFFSET+LOCK_LEN+1,LOCK_LEN))
		printf("Cannot re-lock after non-overlapping unlock()\n");
	else
		printf("!FAILURE: can re-lock after non-overlappping unlock()\n");
	if(lock(fd,LOCK_OFFSET,LOCK_LEN))
		printf("!FAILURE: cannot re-lock unlocked area\n");
	close(fd);

	/* getch test */
	printf("\ngetch() test (ESC to continue)\n");
	do {
		ch=getch();
		printf("getch() returned %d\n",ch);
	} while(ch!=ESC);

	/* kbhit test */
	printf("\nkbhit() test (any key to continue)\n");
	while(!kbhit()) {
		printf(".");
		fflush(stdout);
		SLEEP(500);
	}
	getch();	/* remove character from keyboard buffer */

	/* BEEP test */
	printf("\nBEEP() test\n");
	getkey();
	for(i=750;i>250;i-=5)
		BEEP(i,15);
	for(;i<1000;i+=5)
		BEEP(i,15);

	/* SLEEP test */
	printf("\nSLEEP(5 second) test\n");
	getkey();
	t=time(NULL);
	printf("sleeping... ");
	fflush(stdout);
	ticks=msclock();
	SLEEP(5000);
	printf("slept %ld seconds (%ld according to msclock)\n",time(NULL)-t,(msclock()-ticks)/MSCLOCKS_PER_SEC);

	/* Thread SLEEP test */
	printf("\nThread SLEEP(5 second) test\n");
	getkey();
	i=0;
	if(_beginthread(
		  sleep_test_thread	/* entry point */
		 ,0					/* stack size (0=auto) */
		 ,&i				/* data */
		 )==(unsigned long)-1)
		printf("_beginthread failed\n");
	else {
		SLEEP(1);			/* yield to child thread */
		while(i==0) {
			printf(".");
			fflush(stdout);
			SLEEP(1000);
		}
	}

	/* glob test */
	printf("\nglob(%s) test\n",glob_pattern);
	getkey();
	i=glob(glob_pattern,GLOB_MARK,NULL,&g);
	if(i==0) {
		for(u=0;u<g.gl_pathc;u++)
			printf("%s\n",g.gl_pathv[u]);
		globfree(&g);
	} else
		printf("glob(%s) returned %d\n",glob_pattern,i);

	/* opendir (and other directory functions) test */
	printf("\nopendir(%s) test\n",path);
	getkey();
	printf("\nDirectory of %s\n\n",FULLPATH(fpath,path,sizeof(fpath)));
	dir=opendir(path);
	while(dir!=NULL && (dirent=readdir(dir))!=NULL) {
		t=fdate(dirent->d_name);
		printf("%.24s %10lu  %06o  %s%c\n"
			,ctime(&t)
			,flength(dirent->d_name)
			,getfattr(dirent->d_name)
			,dirent->d_name
			,isdir(dirent->d_name) ? '/':0
			);
	}
	if(dir!=NULL)
		closedir(dir);
	printf("\nFree disk space: %lu kbytes\n",getfreediskspace(path,1024));

	/* Thread (and inter-process communication) test */
	printf("\nSemaphore test\n");
	getkey();
	if(sem_init(&thread_data.parent_sem
		,0 /* shared between processes */
		,0 /* initial count */
		)) {
		printf("sem_init failed\n");
	}
	if(sem_init(&thread_data.child_sem
		,0	/* shared between processes */
		,0	/* initial count */
		)) {
		printf("sem_init failed\n");
	}
	if(_beginthread(
		  sem_test_thread	/* entry point */
		 ,0					/* stack size (0=auto) */
		 ,&thread_data		/* data */
		 )==(unsigned long)-1)
		printf("_beginthread failed\n");
	else {
		sem_wait(&thread_data.child_sem);	/* wait for thread to begin */
		for(i=0;i<10;i++) {
			printf("<parent>");
			sem_post(&thread_data.parent_sem);
			sem_wait(&thread_data.child_sem);
		}
		sem_wait(&thread_data.child_sem);	/* wait for thread to end */
	}
	sem_destroy(&thread_data.parent_sem);
	sem_destroy(&thread_data.child_sem);

	printf("\nSemaphore blocking test\n");
	getkey();
	sem_init(&thread_data.parent_sem
		,0 /* shared between processes */
		,0 /* initial count */
		);
	sem_init(&thread_data.child_sem
		,0	/* shared between processes */
		,0	/* initial count */
		);
	if(_beginthread(
		  sem_test_thread_block	/* entry point */
		 ,0					/* stack size (0=auto) */
		 ,&thread_data		/* data */
		 )==(unsigned long)-1)
		printf("_beginthread failed\n");
	else {
		sem_wait(&thread_data.child_sem);	/* wait for thread to begin */
		for(i=0;i<10;i++) {
			printf("<parent>");
			SLEEP(5000);
			sem_post(&thread_data.parent_sem);
			sem_wait(&thread_data.child_sem);
		}
		sem_wait(&thread_data.child_sem);	/* wait for thread to end */
	}
	printf("\nsem_trywait_block test...");
	t=time(NULL);
	sem_trywait_block(&thread_data.parent_sem,5000);
	printf("\ntimed-out after %ld seconds (should be 5 seconds)\n",time(NULL)-t);
	sem_destroy(&thread_data.parent_sem);
	sem_destroy(&thread_data.child_sem);
	printf("\nendian check...");
	memcpy(&i,"\x01\x02\x03\x04",4);
	if(LE_LONG(i)==67305985) {
		printf("OK!\n");
	}
	else {
		printf("FAILED!\n");
	}
	return 0;
}
Пример #21
0
int main (int argc, char** argv)
{
#ifdef LINUX
	struct sigaction sv;
	sigemptyset(&sv.sa_mask);
	sv.sa_flags = 0;
	sv.sa_handler = SignalHandler;
	sigaction(SIGTERM, &sv, NULL);
	sigaction(SIGQUIT, &sv, NULL);
	sigaction(SIGINT, &sv, NULL);
//	sigaction(SIGHUP, &sv, NULL);
	sigaction(SIGUSR1, &sv, NULL);
	sigaction(SIGUSR2, &sv, NULL);
	bool bOutputEnable = false;
#endif

	bool bEnableAnnounce = true;
	int iMaxPlayers	= DEFAULT_MAX_PLAYERS;
	int iListenPort	= DEFAULT_LISTEN_PORT;
	int iRconPort	= DEFAULT_RCON_PORT;
	int iRconMaxAdmins	= DEFAULT_RCON_MAXUSERS;
	bool bLanModeEnable = false;
	bool bEnableTimestamp = true;
	bool bEnableInstagib = false;
	bool bGameMod = false;
	bool bEnableAC = false;
	bool bAllowQuery = true;

	// Open the log file
	LoadLogFile();

	// Create the command line string and process if needed.
	char szCmdLine[1024];
	memset(szCmdLine,0,1024);

	int cmdcnt=1;
	if(argc > 1) {
		while(cmdcnt != argc) {
			strcat(szCmdLine, argv[cmdcnt]);
			strcat(szCmdLine, " ");
			cmdcnt++;
		}
		InitSettingsFromCommandLine(szCmdLine);
	}

	// Write welcome message.
	logprintf("");
	logprintf("SA-MP Dedicated Server");
	logprintf("----------------------");
	logprintf("v" SAMP_VERSION ", (C)2005-2009 SA-MP Team\n");

#ifdef _DEBUG
	logprintf("Debug Build Info:\n   NET_VERSION=%d\n   BUILD_DATE=%s\n   BUILD_TIME=%s\n",
				NETGAME_VERSION, __DATE__, __TIME__);
#endif

	// Create a challenge number for the clients to be able to connect
	srand(time(NULL));
	_uiRndSrvChallenge = (unsigned int)rand();
    
	// Create the Console
	pConsole = new CConsole();

	pConsole->AddVariable("announce",CON_VARTYPE_BOOL, 0, &bEnableAnnounce);
	
	if(gServerSettings.iMaxPlayers) {
		iMaxPlayers = gServerSettings.iMaxPlayers;
		pConsole->AddVariable("maxplayers", CON_VARTYPE_INT, 0, &iMaxPlayers);
		pConsole->ModifyVariableFlags("maxplayers", CON_VARFLAG_READONLY);
	} else {
		pConsole->AddVariable("maxplayers", CON_VARTYPE_INT, 0, &iMaxPlayers, ServerMaxPlayersChanged);
	}

	if(gServerSettings.iPort) {
        iListenPort = gServerSettings.iPort;
		pConsole->AddVariable("port", CON_VARTYPE_INT, 0, &iListenPort);
		pConsole->ModifyVariableFlags("port", CON_VARFLAG_READONLY);
	} else {
		pConsole->AddVariable("port", CON_VARTYPE_INT, 0, &iListenPort);
	}

	if(strlen(gServerSettings.szBindIp)) {
		pConsole->AddStringVariable("bind", 0, gServerSettings.szBindIp);
		pConsole->ModifyVariableFlags("bind", CON_VARFLAG_READONLY);
	} else {
		pConsole->AddStringVariable("bind", 0, NULL);
	}

	pConsole->AddVariable("lanmode",CON_VARTYPE_BOOL,0, &bLanModeEnable);
	pConsole->AddVariable("query",CON_VARTYPE_BOOL, 0, &bAllowQuery);

#ifdef RAKRCON
	pConsole->AddVariable("rcon_port", CON_VARTYPE_INT, 0, &iRconPort);
	pConsole->AddVariable("rcon_maxadmins", CON_VARTYPE_INT, 0, &iRconMaxAdmins);
	pConsole->AddStringVariable("rcon_bind", 0, NULL);
#endif

#ifdef LINUX
	pConsole->AddVariable("output",CON_VARTYPE_BOOL,0,&bOutputEnable);
#endif

	pConsole->AddVariable("timestamp",CON_VARTYPE_BOOL,0,&bEnableTimestamp);
	pConsole->AddStringVariable("password", 0, NULL, ServerPasswordChanged);
	pConsole->AddStringVariable("hostname", 0, "SA:MP Server");
	pConsole->AddStringVariable("mapname", CON_VARFLAG_RULE, "San Andreas");
	pConsole->AddStringVariable("weburl", CON_VARFLAG_RULE, "www.sa-mp.com");
	pConsole->AddStringVariable("rcon_password", 0, "changeme");
	pConsole->AddStringVariable("gravity", CON_VARFLAG_RULE, "0.008");
	pConsole->AddStringVariable("weather", CON_VARFLAG_RULE, "10");
	//pConsole->AddStringVariable("tirepopping", CON_VARFLAG_RULE, "0");
	pConsole->AddStringVariable("gamemodetext", 0, "Unknown");
	pConsole->AddStringVariable("filterscripts", 0, "");
	pConsole->AddStringVariable("plugins", 0, "");
	pConsole->AddStringVariable("nosign", 0, "");
	pConsole->AddVariable("anticheat",CON_VARTYPE_BOOL, /* CON_VARFLAG_RULE */ 0, &bEnableAC);
	pConsole->AddVariable("instagib", CON_VARTYPE_BOOL, CON_VARFLAG_RULE, &bEnableInstagib, ServerInstagibChanged);
	pConsole->AddVariable("myriad", CON_VARTYPE_BOOL, 0, &bGameMod);

	// Add 16 gamemode variables.
	int x=0;
	char t[64];
	while(x!=16) {
		sprintf(t,"gamemode%u",x);
		pConsole->AddStringVariable(t,0,"");
		x++;
	}
	
	// Exec the server config!
	pConsole->Execute("exec server");

	if ( !strcmp( pConsole->GetStringVariable("rcon_password"), "changeme" ) )
	{
		logprintf("Error: Your password must be changed from the default password, please change it.");
		return 0;
	}

	// Change some var flags to read-only (can only be accessed from server.cfg).
	pConsole->ModifyVariableFlags("maxplayers", CON_VARFLAG_READONLY);
	pConsole->ModifyVariableFlags("bind", CON_VARFLAG_READONLY);
	pConsole->ModifyVariableFlags("port", CON_VARFLAG_READONLY);
	pConsole->ModifyVariableFlags("rcon_bind", CON_VARFLAG_READONLY);
	pConsole->ModifyVariableFlags("rcon_port", CON_VARFLAG_READONLY);
	pConsole->ModifyVariableFlags("filterscripts", CON_VARFLAG_READONLY);
	pConsole->ModifyVariableFlags("plugins", CON_VARFLAG_READONLY);
	pConsole->ModifyVariableFlags("anticheat", CON_VARFLAG_READONLY /* | CON_VARFLAG_RULE */);
	pConsole->ModifyVariableFlags("nosign", CON_VARFLAG_READONLY);

	// Add the version as a rule
	pConsole->AddStringVariable("version", CON_VARFLAG_RULE | CON_VARFLAG_READONLY, SAMP_VERSION);

	// If we're running in Windows, allow console input and catch exit messages.
	// TODO: Same thing for Linux.
#ifdef WIN32
	SetConsoleCtrlHandler(CtrlHandler, TRUE);
	hConsoleExecuteEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
	DWORD dwThreadId;
	HANDLE hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ConsoleInputThread, NULL, 0, &dwThreadId);
	
	// Setup the exception handler on windows
	SetUnhandledExceptionFilter(exc_handler);
#endif

	// Load up the plugins
	pPlugins = new CPlugins();
	pPlugins->LoadPlugins("plugins");

	// Create the NetGame.
	pNetGame = new CNetGame();
	pNetGame->Init(true);

	// Start the rcon server
	PCHAR szBindAddress = pConsole->GetStringVariable("rcon_bind");
	if (!szBindAddress || szBindAddress[0] == 0)
		szBindAddress = pConsole->GetStringVariable("bind");
	if (!szBindAddress || szBindAddress[0] == 0)
		szBindAddress = NULL;

#ifdef RAKRCON
	pRcon = new CRcon(pConsole->GetStringVariable("rcon_password"), 
						pConsole->GetIntVariable("rcon_port"), 
						pConsole->GetIntVariable("rcon_maxadmins"),
						szBindAddress);
	pRcon->Process();
#endif

	// While the app is running...
	while (!bQuitApp)
	{
		pNetGame->Process();

#ifdef RAKRCON
		pRcon->Process();
#endif

		if(TRUE == bGameModeFinished) {
			pNetGame->ShutdownForGameModeRestart();
			bGameModeFinished = FALSE;
		}

		#ifdef WIN32
			SetEvent(hConsoleExecuteEvent);
			WaitForSingleObject(hConsoleExecuteEvent, INFINITE);
		#endif

		SLEEP(10);		
	}

#ifdef RAKRCON
	delete pRcon;
#endif

	delete pNetGame;

	delete pPlugins;

	// If WIN32: Kill the input thread.
	#ifdef WIN32
		TerminateThread(hThread, 0);
		CloseHandle(hConsoleExecuteEvent);
	#endif

	delete pConsole;

	fclose(pLogFile);

	return 0;
}
Пример #22
0
int CTest::Run(void)
{
    double e;

    START(1);
    // Forbid zero requests per any time.
    {{
        CRequestRateControl mgr(0, CTimeSpan(0,0), CTimeSpan(1,0),
                                CRequestRateControl::eErrCode);
        assert( !mgr.Approve() );
    }}
    DONE;

    START(2);
    // Allow only 1 request per any period of time.
    {{
        CRequestRateControl mgr(1, CTimeSpan(0,0), CTimeSpan(0,0),
                                CRequestRateControl::eErrCode);
        assert( mgr.Approve() );
        assert( !mgr.Approve() );
    }}
    DONE;

    START(3);
    // Allow any number of requests with frequency 1 request per second
    // The behaviour is the same for both modes.
    {{
        CRequestRateControl mgr(1, CTimeSpan(0,0), CTimeSpan(1,0),
                                CRequestRateControl::eErrCode);
        assert( mgr.Approve() );
        assert( !mgr.Approve() );
        SLEEP(1000);
        assert( mgr.Approve() );
    }}
    DONE;

    START(4);
    // Allow 2 request per second with any frequency.
    // The behaviour is different for eContinuous/eDiscrete modes.
    {{
        {{
            CRequestRateControl mgr(2, CTimeSpan(1,0), CTimeSpan(0,0),
                                    CRequestRateControl::eErrCode);
            assert( mgr.Approve() );
            assert( mgr.Approve() );
            assert( !mgr.Approve() );
            SLEEP(1000);
            assert( mgr.Approve() );
            assert( mgr.Approve() );
            assert( !mgr.Approve() );
            SLEEP(1000);
            // Now, will try to split up time period
            assert( mgr.Approve() );
            SLEEP(500);
            assert( mgr.Approve() );
            assert( !mgr.Approve() );
            SLEEP(500);
            // Time period is float, so only first request will be approved.
            // See difference with eDiscrete mode below.
            assert( mgr.Approve() );
            assert( !mgr.Approve() );
        }}
        {{
            CRequestRateControl mgr(2, CTimeSpan(1,0), CTimeSpan(0,0),
                                    CRequestRateControl::eErrCode,
                                    CRequestRateControl::eDiscrete);
            assert( mgr.Approve() );
            assert( mgr.Approve() );
            assert( !mgr.Approve() );
            SLEEP(1000);
            assert( mgr.Approve() );
            assert( mgr.Approve() );
            assert( !mgr.Approve() );
            SLEEP(1000);
            // Now, will try to split up time period
            assert( mgr.Approve() );
            SLEEP(500);
            assert( mgr.Approve() );
            assert( !mgr.Approve() );
            SLEEP(500);
            // Time period ends, so both request will be approved.
            // See difference with eContinuous mode above
            assert( mgr.Approve() );
            assert( mgr.Approve() );
        }}
    }}
    DONE;

    START(5);
    // Allow 2 request per 3 seconds with frequency 1 request per second.
    // In this test behaviour of eContinuous and eDiscrete modes are the same
    // for 3 second time interval. 
    {{
        {{
            CRequestRateControl mgr(2, CTimeSpan(3,0), CTimeSpan(1,0),
                                    CRequestRateControl::eErrCode);
            assert( mgr.Approve() );
            assert( !mgr.Approve() );
            SLEEP(1000);
            assert( mgr.Approve() );
            assert( !mgr.Approve() );
            SLEEP(1000);
            assert( !mgr.Approve() );
            SLEEP(1000);
            assert( mgr.Approve() );
        }}
        {{
            CRequestRateControl mgr(2, CTimeSpan(3,0), CTimeSpan(1,0),
                                    CRequestRateControl::eErrCode,
                                    CRequestRateControl::eDiscrete);
            assert( mgr.Approve() );
            assert( !mgr.Approve() );
            SLEEP(1000);
            assert( mgr.Approve() );
            assert( !mgr.Approve() );
            SLEEP(1000);
            assert( !mgr.Approve() );
            SLEEP(1000);
            assert( mgr.Approve() );
        }}
    }}
    DONE;

    // eSleep

    START(6);
    // Allow any number of requests with frequency 1 request per second
    // with auto sleep beetween requests.
    // The behaviour is the same for both modes.
    {{
        {{
            CRequestRateControl mgr(1, CTimeSpan(0,0), CTimeSpan(1,0),
                                    CRequestRateControl::eSleep);
            CStopWatch sw(CStopWatch::eStart);
            assert( mgr.Approve() );
            assert( mgr.Approve() );
            assert( mgr.Approve() );
            ELAPSED;
            // The StopWatch is more accurate then Sleep methods.
            assert( e > 1.8);
        }}
        {{
            CRequestRateControl mgr(1, CTimeSpan(0,0), CTimeSpan(1,0),
                                    CRequestRateControl::eSleep,
                                    CRequestRateControl::eDiscrete);
            CStopWatch sw(CStopWatch::eStart);
            assert( mgr.Approve() );
            assert( mgr.Approve() );
            assert( mgr.Approve() );
            ELAPSED;
            // The StopWatch is more accurate then Sleep methods.
            assert( e > 1.8); 
        }}
    }}
    DONE;

    START(7);
    // Allow 2 request per 3 seconds with frequency 1 request per second
    // with auto sleep beetween requests.
    // The behaviour is different for both modes.
    {{
        CStopWatch sw(CStopWatch::eStart);
        {{
            LOG_POST("eContinuous");
            CRequestRateControl mgr(2, CTimeSpan(3,0), CTimeSpan(1,0),
                                    CRequestRateControl::eSleep);
            sw.Restart();
            // sleep 0
            assert( mgr.Approve() );
            ELAPSED;
            assert (e < 0.5);
            // sleep 1
            assert( mgr.Approve() );
            ELAPSED;
            assert (e > 0.8  &&  e < 1.2);
            // sleep 2
            assert( mgr.Approve() );
            ELAPSED;
            assert (e > 1.8  &&  e < 2.2);
            // sleep 1
            // See difference with eDiscrete mode below.
            assert( mgr.Approve() );
            ELAPSED;
            assert (e > 0.8  &&  e < 1.2);
            // sleep 2
            assert( mgr.Approve() );
            ELAPSED;
            assert (e > 1.8  &&  e < 2.2);
        }}
        {{
            LOG_POST("eDiscrete");
            CRequestRateControl mgr(2, CTimeSpan(3,0), CTimeSpan(1,0),
                                    CRequestRateControl::eSleep,
                                    CRequestRateControl::eDiscrete);
            sw.Restart();
            // sleep 0
            assert( mgr.Approve() );
            ELAPSED;
            assert (e < 0.5);
            // sleep 1
            assert( mgr.Approve() );
            ELAPSED;
            assert (e > 0.8  &&  e < 1.2);
            // sleep 2
            assert( mgr.Approve() );
            ELAPSED;
            assert (e > 1.8  &&  e < 2.2);
            // sleep 0
            // See difference with eContinuous mode above
            assert( mgr.Approve() );
            ELAPSED;
            assert (e < 0.5);
            // sleep 1
            assert( mgr.Approve() );
            ELAPSED;
            assert (e > 0.8  &&  e < 1.2);
        }}
    }}
    DONE;

    START(8);
    // Allow any number of requests (throtling is disabled)
    {{
        {{
            CRequestRateControl mgr(CRequestRateControl::kNoLimit);
            CStopWatch sw(CStopWatch::eStart);
            for (int i=0; i<1000; i++) {
                assert( mgr.Approve() );
            }
            ELAPSED;
            assert( e < 0.1); 
        }}
    }}
    DONE;

    START(9);
    // eDiscrete mode test with empty time between requests
    {{
        CRequestRateControl mgr(1000, CTimeSpan(1,0), CTimeSpan(0,0),
                                CRequestRateControl::eErrCode,
                                CRequestRateControl::eDiscrete);
        CStopWatch sw(CStopWatch::eStart);
        for (int i=0; i<1000; i++) {
            assert( mgr.Approve() );
        }
        ELAPSED;
        assert( e < 0.1); 
        assert( !mgr.Approve() );
        SLEEP(1000);
        assert( mgr.Approve() );
    }}

    return 0;
}
Пример #23
0
int main()
{
    int cTotal = 0;
    int cState = STATE_READ;

    char toggleOut = FALSE;

    Signal motor1;
    Signal motor2;
    Signal estop;
    Signal rcMode;

    init_coridium();

	setbaud(0, 17);
	
	
    statusMessage[0] = '#';
	statusMessage[1] = '%';
	statusMessage[2] = 0x82;



    INPUT(RC1); motor1.pin = RC1;
    INPUT(RC2); motor2.pin = RC2;
    INPUT(RC3); estop.pin = RC3;
    INPUT(RC4); rcMode.pin = RC4;


    OUTPUT(TX);
    OUTPUT(ESTOP); LOW(ESTOP);
    OUTPUT(RCMode);
    OUTPUT(FreqPin);
    OUTPUT(LIGHT);

    motor1.state = STATE_WAIT;
    motor1.duty = 0;
    motor1.valid = 0;

    motor2.state = STATE_WAIT;
    motor2.duty = 0;
    motor2.valid = 0;

    estop.state = STATE_WAIT;
    estop.duty = 0;
    estop.valid = 0;

    rcMode.state = STATE_WAIT;
    rcMode.duty = 0;
    rcMode.valid = 0;

    SLEEP(2);

    while (TRUE)
    {
        switch (cState)
        {
        case STATE_READ:
            if (toggleOut)
            {
                toggleOut = FALSE;
                HIGH(FreqPin);
            }
            else
            {
                toggleOut = TRUE;
                LOW(FreqPin);
            }

            cTotal += getDuty(&motor1);
            cTotal += getDuty(&motor2);
            cTotal += getDuty(&estop);
            cTotal += getDuty(&rcMode);

            if (cTotal > 8)
            {
                cState = STATE_SERIAL;
                cTotal = 0;
            }
            break;

        case STATE_SERIAL:
			if (estop.lastVal > 0)
            {
                sendESTOP(0);
                gESTOP = FALSE;
				
                if (rcMode.lastVal > 0)
                {
                    HIGH(LIGHT);
                    HIGH(RCMode);

                    // 11 == Manual (teleop) Mode
                    statusMessage[3] = 0x00;
                    statusMessage[4] = 0xFF;
                    statusMessage[5] = 0xFF;
                    statusMessage[6] = 0xFF;

                    calcSum();
					//statusMessage[7] = 0x84;
                    //SEROUT(TXD0,9600, 1, 3, statusMessage);
					TXD0(statusMessage[0]);
					TXD0(statusMessage[1]);
					TXD0(statusMessage[2]);
					TXD0(statusMessage[3]);
					TXD0(statusMessage[4]);
					TXD0(statusMessage[5]);
					TXD0(statusMessage[6]);
					TXD0(statusMessage[7]);
                }
                else
                {
                    if (flashcount > 0)
                    {
                        HIGH(LIGHT);
                    }
                    else
                    {
                        LOW(LIGHT);
                    }

                    if (flashcount > LIGHTDUTY)
                    {
                        flashcount = -LIGHTDUTY;
                    }

                    LOW(RCMode);

                    // 00 == Autonomous Mode
                    statusMessage[3] = 0x00;
                    statusMessage[4] = 0x00;
                    statusMessage[5] = 0x00;
                    statusMessage[6] = 0x00;

                    calcSum();
					//statusMessage[7] = 0x84;
                    //SEROUT(TXD0,9600, 1, 3, statusMessage);
					
					TXD0(statusMessage[0]);
					TXD0(statusMessage[1]);
					TXD0(statusMessage[2]);
					TXD0(statusMessage[3]);
					TXD0(statusMessage[4]);
					TXD0(statusMessage[5]);
					TXD0(statusMessage[6]);
					TXD0(statusMessage[7]);
                }
            }
            else
            {
                HIGH(LIGHT);
                HIGH(RCMode);
                sendESTOP(1);
                gESTOP = TRUE;
				
				// 11 == Manual (teleop) Mode
				statusMessage[3] = 0x00;
				statusMessage[4] = 0xFF;
				statusMessage[5] = 0xFF;
				statusMessage[6] = 0xFF;

				calcSum();
				//statusMessage[7] = 0x84;
				//SEROUT(TXD0,9600, 1, 3, statusMessage);
				TXD0(statusMessage[0]);
				TXD0(statusMessage[1]);
				TXD0(statusMessage[2]);
				TXD0(statusMessage[3]);
				TXD0(statusMessage[4]);
				TXD0(statusMessage[5]);
				TXD0(statusMessage[6]);
				TXD0(statusMessage[7]);
            }

#ifdef DEBUG
            putchar( binToHexstr((char)((motor1.lastVal >> 4) & 0x0F)) );
            putchar( binToHexstr((char)(motor1.lastVal & 0x0F)) );
            putchar(' ');
                        putchar( binToHexstr((char)((motor2.lastVal >> 4) & 0x0F)) );
            putchar( binToHexstr((char)(motor2.lastVal & 0x0F)) );
            putchar('\n');
            //printf("%d\n", estop.lastVal);
#endif
            // motor1 == forward value
            // motor2 == left/right value

            int left_motor = motor1.lastVal/2 - motor2.lastVal/2;
            int right_motor = motor1.lastVal/2 + motor2.lastVal/2;

            sendSerial(right_motor, 1);
            sendSerial(left_motor, 0);

            cState = STATE_READ;

            break;
        }
        flashcount++;
    }

    return 0;
}
/* goodG2B uses the GoodSource with the BadSink */
static void goodG2BSink(int count)
{
    /* POTENTIAL FLAW: Sleep function using count as the parameter with no validation */
    SLEEP(count);
    printLine("Sleep time possibly too long");
}
Пример #25
0
/*
 * This test will enable a just the SRP-RSA-AES-128-CBC-SHA
 * cipher suite, which forces the server to send a certificate
 * to the client while SRP is used.  Similar to #104, we'll
 * omit configuring the trust anchor on the client context.
 * This should cause the TLS session to fail since the
 * server cert can not be verified without a trust anchor. 
 */
static void us1060c_test105 (void)
{
    EST_CTX *ectx;
    EVP_PKEY *new_key;
    int rv;
    int pkcs7_len = 0;
    struct est_dumb_ctx *ed;

    LOG_FUNC_NM;

    /*
     * We need to restart the EST server using an RSA key
     * None of the SRP cipher suites support ECDSA
     */
    st_stop();
    SLEEP(2);
    us1060c_start_server(US1060C_RSA_CERT, US1060C_RSA_KEY, 0, 0, 1);

    /*
     * Create a client context 
     */
    ectx = est_client_init(NULL, 0, EST_CERT_FORMAT_PEM, NULL);
    CU_ASSERT(ectx != NULL);

    /*
     * Set the authentication mode to use a user id/password
     */
    rv = est_client_set_auth(ectx, US1060C_UID, US1060C_PWD, NULL, NULL);
    CU_ASSERT(rv == EST_ERR_NONE);

    /*
     * Set the EST server address/port
     */
    est_client_set_server(ectx, US1060C_SERVER_IP, US1060C_SERVER_PORT, NULL);

    /*
     * Enable SRP on the client
     */
    rv = est_client_enable_srp(ectx, 1024, US1060C_UID, US1060C_PWD); 

    /*
     * This is not an approved use of the EST API.  We do this
     * here only to increase code coverage for testing
     * purposes only.  If you are looking at this code as
     * an example of how to use the EST API, do not do this!
     */
    ed = (struct est_dumb_ctx*)ectx;
    rv = SSL_CTX_set_cipher_list(ed->ssl_ctx, "SRP-RSA-AES-128-CBC-SHA"); 
    CU_ASSERT(rv == 1);

    /*
     * generate a new private key
     */
    new_key = generate_private_key();
    CU_ASSERT(new_key != NULL);

    /*
     * Attempt to provision a new cert
     */
    rv = est_client_enroll(ectx, "US1060C_TEST105", &pkcs7_len, new_key);
    CU_ASSERT(rv == EST_ERR_SSL_CONNECT);

    /*
     * Cleanup
     */
    EVP_PKEY_free(new_key);
    est_destroy(ectx);
}
Пример #26
0
/*! \brief The main function.
 *
 */
int main(void)
{
  aes_config_t      AesConf;        // AES config structure
  int               i;
  static const gpio_map_t USART_GPIO_MAP =      // USART GPIO map
  {
    {DMACA_AES_EVAL_USART_RX_PIN, DMACA_AES_EVAL_USART_RX_FUNCTION},
    {DMACA_AES_EVAL_USART_TX_PIN, DMACA_AES_EVAL_USART_TX_FUNCTION}
  };
  static const usart_options_t USART_OPTIONS =  // USART options.
  {
    .baudrate     = DMACA_AES_EVAL_USART_BAUDRATE,
    .charlength   = 8,
    .paritytype   = USART_NO_PARITY,
    .stopbits     = USART_1_STOPBIT,
    .channelmode  = USART_NORMAL_CHMODE
  };


#if BOARD == EVK1104
  if( PM_FREQ_STATUS_FAIL==pm_configure_clocks(&pm_freq_param) )
    while(1);
#endif

  init_hmatrix();

  // Assign GPIO to USART.
  gpio_enable_module(USART_GPIO_MAP,
                     sizeof(USART_GPIO_MAP) / sizeof(USART_GPIO_MAP[0]));

  // Initialize USART in RS232 mode.
  usart_init_rs232(DMACA_AES_EVAL_USART, &USART_OPTIONS, DMACA_AES_EVAL_CPU_FREQ);
  print(DMACA_AES_EVAL_USART, "\x1B[2J\x1B[H.: Using the AES with the DMACA at ");
  print_ulong(DMACA_AES_EVAL_USART, DMACA_AES_EVAL_CPU_FREQ);
  print(DMACA_AES_EVAL_USART, "Hz :.\r\n\r\n");

  //****************************************************************************
  //               CIPHER IN DMA MODE: RAM -> AES -> RAM
  //  - 256bit cryptographic key
  //  - CBC cipher mode
  //  - No counter measures
  //****************************************************************************

  // Init the input array.
  for(i=0; i<DMACA_AES_EVAL_BUF_SIZE; i+=DMACA_AES_EVAL_REFBUF_SIZE)
  {
    memcpy(InputData+i, RefInputData, DMACA_AES_EVAL_REFBUF_SIZE*sizeof(unsigned int));
  }

  //====================
  // Configure the AES.
  //====================
  AesConf.ProcessingMode = AES_PMODE_CIPHER;  // Cipher
  AesConf.ProcessingDelay = 0;                // No delay: best performance
  AesConf.StartMode = AES_START_MODE_DMA;     // DMA mode
  AesConf.KeySize = AES_KEY_SIZE_256;         // 256bit cryptographic key
  AesConf.OpMode = AES_CBC_MODE;              // CBC cipher mode
  AesConf.LodMode = 0;                        // LODMODE == 0 : the end of the
  // encryption is notified by the DMACA transfer complete interrupt. The output
  // is available in the OutputData[] buffer.
  AesConf.CFBSize = 0;                        // Don't-care because we're using the CBC mode.
  AesConf.CounterMeasureMask = 0;             // Disable all counter measures.
  aes_configure(&AVR32_AES, &AesConf);


  //****************************************************************************
  //  - input of 16 32bit words in CPUSRAM
  //  - output of 16 32bit words in CPUSRAM
  //****************************************************************************
  print(DMACA_AES_EVAL_USART, "\r\n---------------------------------------------------\r\n");
  print(DMACA_AES_EVAL_USART, "------ Cipher in DMA Mode: CPUSRAM -> AES -> CPUSRAM ------\r\n");
  print(DMACA_AES_EVAL_USART, "       - 256bit cryptographic key\r\n");
  print(DMACA_AES_EVAL_USART, "       - CBC cipher mode\r\n");
  print(DMACA_AES_EVAL_USART, "       - No counter measures\r\n");
  print(DMACA_AES_EVAL_USART, "       - input of 16 32bit words in CPUSRAM\r\n");
  print(DMACA_AES_EVAL_USART, "       - output of 16 32bit words in CPUSRAM\r\n");
  print(DMACA_AES_EVAL_USART, "---------------------------------------------------\r\n");

  test_ram_aes_ram(16, (unsigned int *)InputData, (unsigned int *)OutputData);
  gpio_clr_gpio_pin(DMACA_AES_EVAL_LED1);

  //****************************************************************************
  //  - input of 256 32bit words in CPUSRAM
  //  - output of 256 32bit words in CPUSRAM
  //****************************************************************************
  print(DMACA_AES_EVAL_USART, "\r\n---------------------------------------------------\r\n");
  print(DMACA_AES_EVAL_USART, "------ Cipher in DMA Mode: CPUSRAM -> AES -> CPUSRAM ------\r\n");
  print(DMACA_AES_EVAL_USART, "       - 256bit cryptographic key\r\n");
  print(DMACA_AES_EVAL_USART, "       - CBC cipher mode\r\n");
  print(DMACA_AES_EVAL_USART, "       - No counter measures\r\n");
  print(DMACA_AES_EVAL_USART, "       - input of 256 32bit words in CPUSRAM\r\n");
  print(DMACA_AES_EVAL_USART, "       - output of 256 32bit words in CPUSRAM\r\n");
  print(DMACA_AES_EVAL_USART, "---------------------------------------------------\r\n");

  test_ram_aes_ram(256, (unsigned int *)InputData, (unsigned int *)OutputData);
  gpio_clr_gpio_pin(DMACA_AES_EVAL_LED2);

  //****************************************************************************
  //  - input of 256 32bit words in HSBSRAM0
  //  - output of 256 32bit words in HSBSRAM1
  //****************************************************************************
  print(DMACA_AES_EVAL_USART, "\r\n---------------------------------------------------\r\n");
  print(DMACA_AES_EVAL_USART, "------ Cipher in DMA Mode: HSBSRAM0 -> AES -> HSBSRAM1 ------\r\n");
  print(DMACA_AES_EVAL_USART, "       - 256bit cryptographic key\r\n");
  print(DMACA_AES_EVAL_USART, "       - CBC cipher mode\r\n");
  print(DMACA_AES_EVAL_USART, "       - No counter measures\r\n");
  print(DMACA_AES_EVAL_USART, "       - Input of 256 32bit words in HSBSRAM0\r\n");
  print(DMACA_AES_EVAL_USART, "       - Output of 256 32bit words in HSBSRAM1\r\n");
  print(DMACA_AES_EVAL_USART, "---------------------------------------------------\r\n");

  // Set the Src and Dst array addresses to respectively HSBSRAM0 & HSBRAM1.
  pSrcData_HsbSram = (unsigned int *)AVR32_INTRAM0_ADDRESS;
  pDstData_HsbSram = (unsigned int *)AVR32_INTRAM1_ADDRESS;

  // Init the input array.
  for(i=0; i<DMACA_AES_EVAL_BUF_SIZE; i+=DMACA_AES_EVAL_REFBUF_SIZE)
  {
    memcpy(pSrcData_HsbSram+i, RefInputData, DMACA_AES_EVAL_REFBUF_SIZE*sizeof(unsigned int));
  }

  test_ram_aes_ram(256, pSrcData_HsbSram, (unsigned int *)pDstData_HsbSram);
  gpio_clr_gpio_pin(DMACA_AES_EVAL_LED3);
  print(DMACA_AES_EVAL_USART, "\r\nDone!");

  // End of tests: go to sleep.
  SLEEP(AVR32_PM_SMODE_STATIC);
  while (true);
}
Пример #27
0
/*
 * This starts a minimal TLS server that only does a
 * handshake and then closes the connection.  This is
 * strictly used to test TLS session negotiation
 * behavior with EST.
 */
static void us1060c_start_tls_server (char *cipherstring)
{
    BIO *conn;
    BIO *listener;
    BIO *berr;
    char h_p[25];
    SSL *ssl;
    SSL_CTX *ssl_ctx = NULL;
    int nid, rv;
    EC_KEY *ecdh = NULL;

    berr = BIO_new_fp(stderr, BIO_NOCLOSE);

    ssl_ctx = SSL_CTX_new(SSLv23_server_method());
    if (!ssl_ctx) {
	printf("Failed to create SSL context\n");
	ERR_print_errors(berr);
	return;
    }

    SSL_CTX_set_mode(ssl_ctx, SSL_MODE_AUTO_RETRY);

    if (SSL_CTX_use_certificate_chain_file(ssl_ctx, US1060C_RSA_CERT) != 1) {
	printf("Failed to load server certificate\n");
	ERR_print_errors(berr);
	return;
    }
    if (SSL_CTX_use_PrivateKey_file(ssl_ctx, US1060C_RSA_KEY, SSL_FILETYPE_PEM) != 1) {
	printf("Failed to load server private key\n");
	ERR_print_errors(berr);
	return;
    }

    SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_SSLv2 |
	                         SSL_OP_NO_SSLv3 |
				 SSL_OP_NO_TLSv1 |
                                 SSL_OP_SINGLE_ECDH_USE | 
				 SSL_OP_SINGLE_DH_USE |
			         SSL_OP_NO_TICKET);

    nid = OBJ_sn2nid("prime256v1");
    ecdh = EC_KEY_new_by_curve_name(nid);
    if (ecdh == NULL) {
	printf("Failed to retreive ECDH curve\n");
	ERR_print_errors(berr);
	return;
    }
    SSL_CTX_set_tmp_ecdh(ssl_ctx, ecdh);
    EC_KEY_free(ecdh);

    if (SSL_CTX_set_cipher_list(ssl_ctx, cipherstring) != 1) {
	printf("Failed to set server cipher list\n");
	ERR_print_errors(berr);
	return;
    }
    SSL_CTX_set_srp_username_callback(ssl_ctx, us1060_srp_cb);

    sprintf(h_p, "%s:%d", US1060C_SERVER_IP, US1060C_TLS_PORT);
    listener = BIO_new_accept(h_p);
    if (listener == NULL) {
	printf("IP connection failed\n");
	return;
    }
    BIO_set_bind_mode(listener, BIO_BIND_REUSEADDR);

    /*
     * The first call to do_accept binds the socket
     */
    if (BIO_do_accept(listener) <= 0) {
	printf("TCP bind failed\n");
	BIO_free_all(listener);
	return;
    }

    /*
     * The second call to do_accept waits for a new
     * connection request on the listener.
     * Note that we are in blocking mode for this socket
     */
    if (BIO_do_accept(listener) <= 0) {
	printf("TCP accept failed\n");
	BIO_free_all(listener);
	return;
    }
    conn = BIO_pop(listener);

    ssl = SSL_new(ssl_ctx);
    SSL_set_bio(ssl, conn, conn);
    /*
     * Now that we have everything ready, let's start waiting for
     * a client to contact us.  Normally we might using a pthread
     * or some other construct to avoid blocking on the main 
     * thread while waiting for an incoming connection.  This
     * code is simply a contrived example, we will wait on the
     * main thread for an incoming connection.
     */
    rv = SSL_accept(ssl);
    if (rv <= 0) {
	printf("\nFailed to complete TLS handshake %d\n", rv);
	ERR_print_errors(berr);
    }
#ifdef WIN32
    SLEEP(2);
#endif 
    SSL_shutdown(ssl);
    SSL_free(ssl);
    SSL_CTX_free(ssl_ctx);
    BIO_free(berr);
    (void)BIO_reset(listener);
    BIO_free_all(listener);
#ifndef WIN32
    pthread_exit(0);
#else
    ExitThread(0); 
#endif
}
Пример #28
0
void PIC::decodeCmd(int pc)
{
//    {

        qDebug() << "CMDLIST" <<m_CmdList[pc];
        //qDebug() << pc << "PC";
        k_long=m_CmdList[pc] & 0x7FF;
        //qDebug() << k_long << "klong";
        k=m_CmdList[pc] & 0xFF;
        qDebug() << k << "k";
        f=m_CmdList[pc] & 0x7F;
        //qDebug() << f <<"f";
        d=m_CmdList[pc] & 0x80;
        d=(d>>7); //Test
        l=d;
        b=m_CmdList[pc] & 0x380;
        b = b / 128;
        //qDebug() << b << "b";
        qDebug() << PreScalerWert << "PreScalerWert";

        PIC::getPreScaler();
        PIC::SetBank();
        PIC::ChkIndirect();



        CheckIndirect();

     int ByteCmd=m_CmdList[pc] & 0x3F00;
     //qDebug() << ByteCmd << "byteCMD";
     int BitCmd=m_CmdList[pc] & 0x3C00;
     //qDebug() << BitCmd << "BitCMD";
     int ShrtCmd=m_CmdList[pc] & 0x3800;
     //qDebug() << ShrtCmd << "ShrtCMD";


     if(ByteCmd == 0x0700 )
        ADDWF();
     else if(ByteCmd == 0x0500)
        ANDWF();
     else if((m_CmdList[pc] & 0x03F80)  == 0x0180)
        CLRF();
     else if(ByteCmd == 0x0100)
        CLRW();
     else if(ByteCmd == 0x0900)
        COMF();
     else if(ByteCmd == 0x0300)
        DECF();
     else if(ByteCmd == 0x0B00)
        DECFSZ();
     else if(ByteCmd == 0x0A00)
        INCF();
     else if(ByteCmd == 0x0F00)
        INCFSZ();
     else if(ByteCmd == 0x0400)
        IORWF();
     else if(ByteCmd == 0x0800)
        MOVF();
     else if((m_CmdList[pc] & 0x3F80) == 0x0080)
        MOVWF();
     else if((m_CmdList[pc] & 0x3F9F) == 0x0000)
        NOP();
     else if(ByteCmd == 0x0D00)
        RLF();
     else if(ByteCmd == 0x0C00)
        RRF();
     else if(ByteCmd == 0x0200)
        SUBWF();
     else if(ByteCmd == 0x0E00)
        SWAPF();
     else if(ByteCmd == 0x0600)
        XORWF();
     else if(BitCmd == 0x1000)
        BCF();
     else if(BitCmd == 0x1400)
        BSF();
     else if(BitCmd == 0x1800)
        BTFSC();
     else if(BitCmd == 0x1C00)
        BTFSS();
     //ADDLW kann durch don't care Bit 3E bzw. 3F sein
     else if((m_CmdList[pc] & 0x3E00 ) == 0x3E00)
        ADDLW();
     else if((m_CmdList[pc] & 0x3F00 ) == 0x3F00)
        ADDLW();
     else if(ByteCmd == 0x3900)
        ANDLW();
     else if(ShrtCmd == 0x2000)
        CALL();
     else if((m_CmdList[pc]& 0XFFFF) == 0x0064)
        CLRWDT();
     else if(ShrtCmd == 0x2800)
        GOTO();
     else if((ByteCmd) == 0x3A00)
        XORLW();
     else if((m_CmdList[pc] & 0x3E00 ) == 0x3C00)
        SUBLW();
     else if((m_CmdList[pc] & 0xFFFF ) == 0x0063)
        SLEEP();
    else if((m_CmdList[pc] & 0xFFFF ) == 0x0008)
        RETURN();
    else if((BitCmd) == 0x3400)
        RETURNLW();
    else if((m_CmdList[pc] & 0xFFFF ) == 0x0009)
        RETURNFIE();
    else if((ByteCmd) == 0x3000)
        MOVLW();
    else if((ByteCmd) == 0x3100)
        MOVLW();
    else if((ByteCmd) == 0x3200)
        MOVLW();
    else if((ByteCmd) == 0x3300)
        MOVLW();
    else if((ShrtCmd) == 0x3800)
        IORLW();

    //zählt nach jeder Befehlsabarbeitung einen Programmzyklus hoch, bizyklische Befehle zählen zusätzlich während des Befehls rauf
     PIC::ExtClock();
     PIC::IncrementCycles();
     PIC::setTmr0();
     PIC::LaufZeit();
     //PreScalerCounter++;
     PIC::SyncSpecialReg();
     PIC::RBPeakAnalyzer();
     PIC::InterruptAnalyzer();


     //Diagnoseausgaben
     qDebug() << "---------------------------------";
     //qDebug() << regModel->reg[bank][PORTB] << "PortB";
     qDebug() << regModel->reg[bank][INDIRECT] << "INDIRECT";
     qDebug() << regModel->reg[bank][FSR] << "FSR";
     //qDebug() << regModel->reg[bank][0x15] << "15h";
     qDebug() << cycles << "Programmzyklen";
     qDebug() << "---------------------------------";

}
Пример #29
0
/*
 * Test2 - exercise the response  variations triggered
 *         by est_client_get_csrattrs()
 */
static void us896_test2(void) {
    EST_CTX *ctx;
    unsigned char *pkey = NULL;
    unsigned char *cacerts = NULL;
    int cacerts_len = 0;
    EST_ERROR rc = EST_ERR_NONE;
    unsigned char *retrieved_cacerts = NULL;
    int retrieved_cacerts_len = 0;
    EVP_PKEY *priv_key;

    SLEEP(1);

    LOG_FUNC_NM
    ;

    /*
     * Read in the CA certificates
     */
    cacerts_len = read_binary_file(CLIENT_UT_CACERT, &cacerts);
    CU_ASSERT(cacerts_len > 0);

    /*
     * Read in the private key file
     */
    priv_key = read_private_key(CLIENT_UT_PUBKEY);
    if (priv_key == NULL) {
        printf("\nError while reading private key file %s\n", CLIENT_UT_PUBKEY);
        return;
    }

    ctx = est_client_init(cacerts, cacerts_len, EST_CERT_FORMAT_PEM,
            client_manual_cert_verify);
    CU_ASSERT(ctx != NULL);

    rc = est_client_set_auth(ctx, "", "", NULL, priv_key);
    CU_ASSERT(rc == EST_ERR_NONE);

    est_client_set_server(ctx, US896_SERVER_IP, US896_SERVER_PORT, NULL);

    /*
     * issue the get ca certs request
     */
    rc = est_client_get_cacerts(ctx, &retrieved_cacerts_len);
    /*
     * should be successful, and should have obtained a valid buffer
     * containing the CA certs
     */
    CU_ASSERT(rc == EST_ERR_NONE);
    CU_ASSERT(retrieved_cacerts_len > 0);

    retrieved_cacerts = malloc(retrieved_cacerts_len);

    rc = est_client_copy_cacerts(ctx, retrieved_cacerts);

    /*
     * output the retrieved ca certs and compare to what they should be
     */
    if (retrieved_cacerts) {

        printf("\nRetrieved CA Certs buffer:\n %s\n", retrieved_cacerts);
        printf("Retrieved CA certs buffer length: %d\n", retrieved_cacerts_len);
    }
    free(retrieved_cacerts);

    /* 
     * All of these are negative tests and require that code in the
     * EST server is modified such that it will allow bad/corrupted
     * attributes to be initialized so they can be sent to the client.
     */
#ifdef NEGATIVE_UNIT_TEST
    unsigned char *csr_data;
    int csr_len;

    /* clear callback */
    if (est_set_csr_cb(ectx, NULL)) {
        printf("\nUnable to set EST CSR Attributes callback.  Aborting!!!\n");
        exit(1);
    }

    rc = est_server_init_csrattrs(ectx, TEST_CORRUPT_ATTR1, strlen(TEST_CORRUPT_ATTR1));
    CU_ASSERT(rc == EST_ERR_NONE);

    rc = est_client_get_csrattrs(ctx, &csr_data, &csr_len);
    CU_ASSERT(rc != EST_ERR_NONE);
    CU_ASSERT(csr_len == 0);
    CU_ASSERT(csr_data == NULL);

    rc = est_server_init_csrattrs(ectx, TEST_CORRUPT_ATTR2, strlen(TEST_CORRUPT_ATTR2));
    CU_ASSERT(rc == EST_ERR_NONE);

    rc = est_client_get_csrattrs(ctx, &csr_data, &csr_len);
    CU_ASSERT(rc != EST_ERR_NONE);
    CU_ASSERT(csr_len == 0);
    CU_ASSERT(csr_data == NULL);

    rc = est_server_init_csrattrs(ectx, TEST_SHORT_ATTR, strlen(TEST_SHORT_ATTR));
    CU_ASSERT(rc == EST_ERR_NONE);

    rc = est_client_get_csrattrs(ctx, &csr_data, &csr_len);
    CU_ASSERT(rc != EST_ERR_NONE);
    CU_ASSERT(csr_len == 0);
    CU_ASSERT(csr_data == NULL);

    rc = est_server_init_csrattrs(ectx, TEST_LONG_ATTR, strlen(TEST_LONG_ATTR));
    CU_ASSERT(rc == EST_ERR_NONE);

    rc = est_client_get_csrattrs(ctx, &csr_data, &csr_len);
    CU_ASSERT(rc != EST_ERR_NONE);
    CU_ASSERT(csr_len == 0);
    CU_ASSERT(csr_data == NULL);

#endif

    if (ctx) {
        est_destroy(ctx);
    }
    if (cacerts) {
        free(cacerts);
    }
    if (pkey) {
        free(pkey);
    }
}
UINT __stdcall IOToElevator1(void *args)			
{
	CDataPool	dp1("Ele1", sizeof(struct myDpData)) ;
	struct		myDpData *Ele1DP = (struct myDpData *)(dp1.LinkDataPool());

	while(flag) {	
		if (ps1.Read()>0) {
			ps1.Wait();
			m1->Wait();

			Ele1Status = *Ele1DP;
			
			m1->Signal();
			cs1.Signal();
		}

		//FLOOR 9
		m1->Wait();
		MOVE_CURSOR(0,1);
		printf("          |");
		if (Ele1Status.floor == 9) 
			printf("._.");
		else
			printf("   ");
		printf("|   ");
		MOVE_CURSOR(0,2);
		printf("Floor 9   |");
		if (Ele1Status.floor == 9) {
			printf("|");
			if (Ele1Status.door == OPEN) 
				printf("O");
			else
				printf("-");
			printf("|");
		}
		else
			printf("   ");
		printf("|   ");
		MOVE_CURSOR(0,3);
		printf("          |");
		if (Ele1Status.floor == 9) 
			printf("^-^");
		else
			printf("   ");
		printf("|   ");

		//FLOOR 8
		MOVE_CURSOR(0,5);
		printf("          |");
		if (Ele1Status.floor == 8) 
			printf("._.");
		else
			printf("   ");
		printf("|   ");
		MOVE_CURSOR(0,6);
		printf("Floor 8   |");
		if (Ele1Status.floor == 8) {
			printf("|");
			if (Ele1Status.door == OPEN) 
				printf("O");
			else
				printf("-");
			printf("|");
		}
		else
			printf("   ");
		printf("|   ");
		MOVE_CURSOR(0,7);
		printf("          |");
		if (Ele1Status.floor == 8) 
			printf("^-^");
		else
			printf("   ");
		printf("|   ");

		//FLOOR 7
		MOVE_CURSOR(0,9);
		printf("          |");
		if (Ele1Status.floor == 7) 
			printf("._.");
		else
			printf("   ");
		printf("|   ");
		MOVE_CURSOR(0,10);
		printf("Floor 7   |");
		if (Ele1Status.floor == 7) {
			printf("|");
			if (Ele1Status.door == OPEN) 
				printf("O");
			else
				printf("-");
			printf("|");
		}
		else
			printf("   ");
		printf("|   ");
		MOVE_CURSOR(0,11);
		printf("          |");
		if (Ele1Status.floor == 7) 
			printf("^-^");
		else
			printf("   ");
		printf("|   ");

		//FLOOR 6
		MOVE_CURSOR(0,13);
		printf("          |");
		if (Ele1Status.floor == 6) 
			printf("._.");
		else
			printf("   ");
		printf("|   ");
		MOVE_CURSOR(0,14);
		printf("Floor 6   |");
		if (Ele1Status.floor == 6) {
			printf("|");
			if (Ele1Status.door == OPEN) 
				printf("O");
			else
				printf("-");
			printf("|");
		}
		else
			printf("   ");
		printf("|   ");
		MOVE_CURSOR(0,15);
		printf("          |");
		if (Ele1Status.floor == 6) 
			printf("^-^");
		else
			printf("   ");
		printf("|   ");

		//FLOOR 5
		MOVE_CURSOR(0,17);
		printf("          |");
		if (Ele1Status.floor == 5) 
			printf("._.");
		else
			printf("   ");
		printf("|   ");
		MOVE_CURSOR(0,18);
		printf("Floor 5   |");
		if (Ele1Status.floor == 5) {
			printf("|");
			if (Ele1Status.door == OPEN) 
				printf("O");
			else
				printf("-");
			printf("|");
		}
		else
			printf("   ");
		printf("|   ");
		MOVE_CURSOR(0,19);
		printf("          |");
		if (Ele1Status.floor == 5) 
			printf("^-^");
		else
			printf("   ");
		printf("|   ");

		//FLOOR 4
		MOVE_CURSOR(0,21);
		printf("          |");
		if (Ele1Status.floor == 4) 
			printf("._.");
		else
			printf("   ");
		printf("|   ");
		MOVE_CURSOR(0,22);
		printf("Floor 4   |");
		if (Ele1Status.floor == 4) {
			printf("|");
			if (Ele1Status.door == OPEN) 
				printf("O");
			else
				printf("-");
			printf("|");
		}
		else
			printf("   ");
		printf("|   ");
		MOVE_CURSOR(0,23);
		printf("          |");
		if (Ele1Status.floor == 4) 
			printf("^-^");
		else
			printf("   ");
		printf("|   ");

		//FLOOR 3
		MOVE_CURSOR(0,25);
		printf("          |");
		if (Ele1Status.floor == 3) 
			printf("._.");
		else
			printf("   ");
		printf("|   ");
		MOVE_CURSOR(0,26);
		printf("Floor 3   |");
		if (Ele1Status.floor == 3) {
			printf("|");
			if (Ele1Status.door == OPEN) 
				printf("O");
			else
				printf("-");
			printf("|");
		}
		else
			printf("   ");
		printf("|   ");
		MOVE_CURSOR(0,27);
		printf("          |");
		if (Ele1Status.floor == 3) 
			printf("^-^");
		else
			printf("   ");
		printf("|   ");

		//FLOOR 2
		MOVE_CURSOR(0,29);
		printf("          |");
		if (Ele1Status.floor == 2) 
			printf("._.");
		else
			printf("   ");
		printf("|   ");
		MOVE_CURSOR(0,30);
		printf("Floor 2   |");
		if (Ele1Status.floor == 2) {
			printf("|");
			if (Ele1Status.door == OPEN) 
				printf("O");
			else
				printf("-");
			printf("|");
		}
		else
			printf("   ");
		printf("|   ");
		MOVE_CURSOR(0,31);
		printf("          |");
		if (Ele1Status.floor == 2) 
			printf("^-^");
		else
			printf("   ");
		printf("|   ");

		//FLOOR 1
		MOVE_CURSOR(0,33);
		printf("          |");
		if (Ele1Status.floor == 1) 
			printf("._.");
		else
			printf("   ");
		printf("|   ");

		MOVE_CURSOR(0,34);
		printf("Floor 1   |");
		if (Ele1Status.floor == 1) {
			printf("|");
			if (Ele1Status.door == OPEN) 
				printf("O");
			else
				printf("-");
			printf("|");
		}
		else
			printf("   ");
		printf("|   ");

		MOVE_CURSOR(0,35);
		printf("          |");
		if (Ele1Status.floor == 1) 
			printf("^-^");
		else
			printf("   ");
		printf("|   ");

		//FLOOR 0
		MOVE_CURSOR(0,37);
		printf("          |");
		if (Ele1Status.floor == 0) 
			printf("._.");
		else
			printf("   ");
		printf("|   ");
		MOVE_CURSOR(0,38);
		printf("Floor 0   |");
		if (Ele1Status.floor == 0) {
			printf("|");
			if (Ele1Status.door == OPEN) 
				printf("O");
			else
				printf("-");
			printf("|");
		}
		else
			printf("   ");
		printf("|   ");
		MOVE_CURSOR(0,39);
		printf("          |");
		if (Ele1Status.floor == 0) 
			printf("^-^");
		else
			printf("   ");
		printf("|   ");


		MOVE_CURSOR(0,41);
		printf("Buttons in Ele1");
		MOVE_CURSOR(7,42);
		for (int i = 7; i < 10; i++) {
			if (Ele1Status.lights[i] == 1) {
				TEXT_COLOUR(14);
			}
			printf("[%d] ", i);
			TEXT_COLOUR(7);
		}
		MOVE_CURSOR(7,43);
		for (int i = 4; i < 7; i++) {
			if (Ele1Status.lights[i] == 1) {
				TEXT_COLOUR(14);
			}
			printf("[%d] ", i);
			TEXT_COLOUR(7);
		}
		MOVE_CURSOR(7,44);
		for (int i = 1; i < 4; i++) {
			if (Ele1Status.lights[i] == 1) {
				TEXT_COLOUR(14);
			}
			printf("[%d] ", i);
			TEXT_COLOUR(7);
		}
		MOVE_CURSOR(11,45);
		if (Ele1Status.lights[0] == 1) {
			TEXT_COLOUR(14);
		}
		printf("[0]");
		TEXT_COLOUR(7);
		//printf("Ele1 Read value for Floor = %d                                \n", Ele1Status.floor) ;
		//printf("Ele1 Read value for Usage = %d                                \n", Ele1Status.usage);
		//printf("Ele1 Read value for Door = %d                                 \n", Ele1Status.direction) ; 
		//printf("Ele1 Read value for Direction = %d                            \n", Ele1Status.direction) ; 
		//printf("Ele1 Read values for floor array = ") ;
		//for(int i=0; i < 10; i ++) {
		//	printf("%d ", Ele1Status.floors[i]) ;
		//}
		fflush(stdout);
		MOVE_CURSOR(0,50);
		fflush(stdout);
		m1->Signal();

		SLEEP(10);
	}
	return 0 ;									
}