Beispiel #1
0
void board_get_uuid(uuid_byte_t uuid_bytes)
{
	uint32_t *chip_uuid = (uint32_t *) KINETIS_SIM_UIDH;
	uint32_t *uuid_words = (uint32_t *) uuid_bytes;

	for (unsigned int i = 0; i < PX4_CPU_UUID_WORD32_LENGTH; i++) {
		uint32_t current_uuid_bytes = SWAP_UINT32(chip_uuid[i]);
		memcpy(uuid_words, &current_uuid_bytes, sizeof(uint32_t));
		++uuid_words;
	}
}
Beispiel #2
0
/**
 * Adds size to the beginning of a packet and a crc32 at the end. Then send the packet.
 */
void tunerStudioWriteCrcPacket(const uint8_t command, const void *buf, const uint16_t size) {
	// todo: max size validation
	*(uint16_t *) crcIoBuffer = SWAP_UINT16(size + 1);   // packet size including command
	*(uint8_t *) (crcIoBuffer + 2) = command;
	if (size != 0)
		memcpy(crcIoBuffer + 3, buf, size);
	// CRC on whole packet
	uint32_t crc = crc32((void *) (crcIoBuffer + 2), (uint32_t) (size + 1));
	*(uint32_t *) (crcIoBuffer + 2 + 1 + size) = SWAP_UINT32(crc);

//	scheduleMsg(&logger, "TunerStudio: CRC command %x size %d", command, size);

	tunerStudioWriteData(crcIoBuffer, size + 2 + 1 + 4);      // with size, command and CRC
}
Beispiel #3
0
static uint32_t readEgtPacket(int egtChannel) {
	uint32_t egtPacket;
	if (driver == NULL) {
		return 0xFFFFFFFF;
	}

	spiStart(driver, &spiConfig[egtChannel]);
	spiSelect(driver);

	spiReceive(driver, sizeof(egtPacket), &egtPacket);

	spiUnselect(driver);
	spiStop(driver);
	egtPacket = SWAP_UINT32(egtPacket);
	return egtPacket;
}
Beispiel #4
0
void handleCrc32Check(ts_channel_s *tsChannel, ts_response_format_e mode, uint16_t pageId, uint16_t offset,
		uint16_t count) {
	tsState.crc32CheckCommandCounter++;

	count = SWAP_UINT16(count);

	count = getTunerStudioPageSize(pageId);

	scheduleMsg(&tsLogger, "CRC32 request: pageId %d offset %d size %d", pageId, offset, count);

	uint32_t crc = SWAP_UINT32(crc32((void * ) getWorkingPageAddr(0), count));

	scheduleMsg(&tsLogger, "CRC32 response: %x", crc);

	tsSendResponse(tsChannel, mode, (const uint8_t *) &crc, 4);
}
Beispiel #5
0
/**
 * Adds size to the beginning of a packet and a crc32 at the end. Then send the packet.
 */
void tunerStudioWriteCrcPacket(ts_channel_s *tsChannel, const uint8_t responseCode, const void *buf, const uint16_t size) {
	uint8_t *writeBuffer = tsChannel->writeBuffer;

	*(uint16_t *) writeBuffer = SWAP_UINT16(size + 1);   // packet size including command
	*(uint8_t *) (writeBuffer + 2) = responseCode;
	tunerStudioWriteData(tsChannel, writeBuffer, 3);      // header

	// CRC on whole packet
	uint32_t crc = crc32((void *) (writeBuffer + 2), 1); // command part of CRC
	crc = crc32inc((void *) buf, crc, (uint32_t) (size)); // combined with packet CRC
	*(uint32_t *) (writeBuffer) = SWAP_UINT32(crc);

	if (size > 0) {
		tunerStudioWriteData(tsChannel, (const uint8_t*)buf, size);      // body
	}

	tunerStudioWriteData(tsChannel, writeBuffer, 4);      // CRC footer
}
Beispiel #6
0
int main() {
    cfguInit();
    CFGU_GetSystemModel(&MODEL_3DS);
	FILE * file;
	shouldRenderDebug = true;
	if ((file = fopen("settings.bin", "r"))) {
        fread(&shouldRenderDebug,sizeof(bool),1,file);
        fread(&shouldSpeedup,sizeof(bool),1,file);
        osSetSpeedupEnable(shouldSpeedup);
		fclose(file);
	}
    
	sf2d_init();
	csndInit();
	noItem = newItem(ITEM_NULL, 0);
	
	currentMenu = MENU_TITLE;
	currentSelection = 0;
	quitGame = false;

	icons = sfil_load_PNG_buffer(icons2_png, SF2D_PLACE_RAM);
	font = sfil_load_PNG_buffer(Font_png, SF2D_PLACE_RAM);
	bottombg = sfil_load_PNG_buffer(bottombg_png, SF2D_PLACE_RAM);
	
	dirtColor[0] = SWAP_UINT32(sf2d_get_pixel(icons, 16, 0)); 
	dirtColor[1] = SWAP_UINT32(sf2d_get_pixel(icons, 16, 1)); 
	dirtColor[2] = SWAP_UINT32(sf2d_get_pixel(icons, 16, 2)); 
	dirtColor[3] = SWAP_UINT32(sf2d_get_pixel(icons, 16, 3)); 
	dirtColor[4] = SWAP_UINT32(sf2d_get_pixel(icons, 16, 4)); 

	loadSound(&snd_playerHurt, "resources/playerhurt.raw");
	loadSound(&snd_playerDeath, "resources/playerdeath.raw");
	loadSound(&snd_monsterHurt, "resources/monsterhurt.raw");
	loadSound(&snd_test, "resources/test.raw");
	loadSound(&snd_pickup, "resources/pickup.raw");
	loadSound(&snd_bossdeath, "resources/bossdeath.raw");
	loadSound(&snd_craft, "resources/craft.raw");
	
	bakeLights();
	
	int i;
	for (i = 0; i < 5; ++i) {
		minimap[i] = sf2d_create_texture(128, 128, TEXFMT_RGBA8,
				SF2D_PLACE_RAM);
		sf2d_texture_tile32(minimap[i]);
	}
	
	sf2d_set_vblank_wait(true);

	sf2d_set_clear_color(0xFF000000);

	k_up.input = KEY_DUP | KEY_CPAD_UP | KEY_CSTICK_UP;
	k_down.input = KEY_DDOWN | KEY_CPAD_DOWN | KEY_CSTICK_DOWN;
	k_left.input = KEY_DLEFT | KEY_CPAD_LEFT | KEY_CSTICK_LEFT;
	k_right.input = KEY_DRIGHT | KEY_CPAD_RIGHT | KEY_CSTICK_RIGHT;
	k_attack.input = KEY_A | KEY_B | KEY_L | KEY_ZR;
	k_menu.input = KEY_X | KEY_Y | KEY_R | KEY_ZL;
	k_pause.input = KEY_START;
	k_accept.input = KEY_A;
	k_decline.input = KEY_B;
	k_delete.input = KEY_X;
	k_menuNext.input = KEY_R;
	k_menuPrev.input = KEY_L;

	if ((file = fopen("btnSave.bin", "rb"))) {
		fread(&k_up.input, sizeof(int), 1, file);
		fread(&k_down.input, sizeof(int), 1, file);
		fread(&k_left.input, sizeof(int), 1, file);
		fread(&k_right.input, sizeof(int), 1, file);
		fread(&k_attack.input, sizeof(int), 1, file);
		fread(&k_menu.input, sizeof(int), 1, file);
		fread(&k_pause.input, sizeof(int), 1, file);
		fread(&k_accept.input, sizeof(int), 1, file);
		fread(&k_decline.input, sizeof(int), 1, file);
		fread(&k_delete.input, sizeof(int), 1, file);
		fread(&k_menuNext.input, sizeof(int), 1, file);
		fread(&k_menuPrev.input, sizeof(int), 1, file);
		fclose(file);
	}
	
	if ((file = fopen("lastTP.bin", "r"))) {
		char fnbuf[256];
		fgets(fnbuf, 256, file); // get directory to texturepack
		loadTexturePack(fnbuf);   
		fclose(file);
	}

	tickCount = 0;
	initRecipes();
	defineTables();
	while (aptMainLoop()) {
		++tickCount;
		hidScanInput();
		tickKeys(hidKeysHeld(), hidKeysDown());

		if (quitGame) break;

		if (initGame > 0) setupGame(initGame == 1 ? true : false);

		if (currentMenu == 0) {
			tick();
			sf2d_start_frame(GFX_TOP, GFX_LEFT);

			offsetX = xscr;
			offsetY = yscr;
			sf2d_draw_rectangle(0, 0, 400, 240, 0xFF0C0C0C); //RGBA8(12, 12, 12, 255)); //You might think "real" black would be better, but it actually looks better that way
			renderLightsToStencil();

			renderBackground(xscr, yscr);
			renderEntities(player.x, player.y, &eManager);
			renderPlayer();
			
			resetStencilStuff();
			offsetX = 0;
			offsetY = 0;
			
			if(shouldRenderDebug){
			    sprintf(fpsstr, " FPS: %.0f, X:%d, Y:%d, E:%d", sf2d_get_fps(), player.x, player.y, eManager.lastSlot[currentLevel]);
			    drawText(fpsstr, 2, 225);
            }
			
			sf2d_end_frame();

            sf2d_start_frame(GFX_BOTTOM, GFX_LEFT);
                if(!shouldRenderMap){
                    sf2d_draw_texture(bottombg, 0, 0);
                    renderGui();
                } else {
                    renderZoomedMap();
                }
            sf2d_end_frame();
		} else {
			tickMenu(currentMenu);
			renderMenu(currentMenu, xscr, yscr);
		}

		sf2d_swapbuffers();
	}

	freeRecipes();

	freeLightBakes();
	sf2d_free_texture(icons);
	sf2d_free_texture(minimap[0]);
	sf2d_free_texture(minimap[1]);
	sf2d_free_texture(minimap[2]);
	sf2d_free_texture(minimap[3]);
	sf2d_free_texture(minimap[4]);
	freeSounds();
	csndExit();
    cfguExit();
	sf2d_fini();
	return 0;
}
Beispiel #7
0
void adminCmdSetSP(Worker *self, Session *session, char *args, zmsg_t *replyMsg) {
    if (strlen (args) == 0) {
        info("Set SP needs a argument!");
    }
    else {
        char **arg;
        int argc;

        info("Set SP with argument: %s", args);
        arg = strSplit(args, ' ');
        argc = 0;
        while (arg[++argc] != NULL);
        if (argc != 1) {
            info("Wrong number of arguments, must be 1.");
        }
        else {
            Sp_t sp = atoi(arg[0]);
            info("Setting SP to %d.", sp);
            session->game.commanderSession.currentCommander->currentSP = sp;
            zoneBuilderUpdateSP(session->game.commanderSession.currentCommander->pcId, sp, replyMsg);


            /// TESTING PURPOSES , to test HEAL SKILL
            ActorId_t actorId = SWAP_UINT32(0x21680100);
            SkillId_t skillId = 40001;
            PositionXZ pos;
            pos.x = 0;
            pos.z = 0;

            int AmountHealed = 10;
            session->game.commanderSession.currentCommander->currentHP += AmountHealed;

            // Heal info
            zoneBuilderHealInfo(session->game.commanderSession.currentCommander->pcId,
                                AmountHealed,
                                session->game.commanderSession.currentCommander->maxHP, replyMsg);
            // Update stats
            zoneBuilderUpdateAllStatus(
                session->game.commanderSession.currentCommander->pcId,
                session->game.commanderSession.currentCommander->currentHP,
                session->game.commanderSession.currentCommander->maxHP,
                session->game.commanderSession.currentCommander->currentSP,
                session->game.commanderSession.currentCommander->maxSP,
                replyMsg);
            // Effect in skill
            zoneBuilderNormalUnk12_60(actorId, replyMsg);
            // Effect in Commander
            zoneBuilderBuffAdd(session->game.commanderSession.currentCommander->pcId, session->game.commanderSession.currentCommander, replyMsg);
            // Disable skill
            zoneBuilderNormalUnk10_56(
                session->game.commanderSession.currentCommander->pcId,
                skillId,
                &session->game.commanderSession.currentCommander->pos,
                &pos,
                false,
                replyMsg
            );
            /// END TEST
        }
        free(arg);
    }
}
Beispiel #8
0
/// called every 10ms from clock.c - check all temp sensors that are ready for checking
void temp_sensor_tick() {
	temp_sensor_t i = 0;
	for (; i < NUM_TEMP_SENSORS; i++) {
		if (temp_sensors_runtime[i].next_read_time) {
			temp_sensors_runtime[i].next_read_time--;
		}
		else {
			uint16_t	temp = 0;
			#ifdef	TEMP_MAX31855
			uint32_t value = 0;
			struct max31855_plat_data *max31855;
			#endif
			//time to deal with this temp sensor
			switch(temp_sensors[i].temp_type) {
				#ifdef	TEMP_MAX31855
				case TT_MAX31855:
				#ifdef __arm__
				        max31855 = (struct max31855_plat_data*)temp_sensors[i].plat_data;
					spiAcquireBus(max31855->bus);
					spiStart(max31855->bus, max31855->config);
					spiSelect(max31855->bus);
					spiReceive(max31855->bus, 4, &value);
					spiUnselect(max31855->bus);
					spiReleaseBus(max31855->bus);

					value = SWAP_UINT32(value);

					temp_sensors_runtime[i].temp_flags = 0;
					if (value & (1 << 16)) {
                                        #ifdef HALT_ON_TERMOCOUPLE_FAILURE
						emergency_stop();
                                        #endif
					}
					else {
						temp = value >> 18;
						if (temp & (1 << 13))
							temp = 0;
					}
				#else
					temp = 0;
				#endif

					break;
				#endif
				#ifdef	TEMP_MAX6675
				case TT_MAX6675:
					#ifdef	PRR
						PRR &= ~MASK(PRSPI);
					#elif defined PRR0
						PRR0 &= ~MASK(PRSPI);
					#endif

					SPCR = MASK(MSTR) | MASK(SPE) | MASK(SPR0);

					// enable TT_MAX6675
					WRITE(SS, 0);

					// No delay required, see
					// https://github.com/triffid/Teacup_Firmware/issues/22

					// read MSB
					SPDR = 0;
					for (;(SPSR & MASK(SPIF)) == 0;);
					temp = SPDR;
					temp <<= 8;

					// read LSB
					SPDR = 0;
					for (;(SPSR & MASK(SPIF)) == 0;);
					temp |= SPDR;

					// disable TT_MAX6675
					WRITE(SS, 1);

					temp_sensors_runtime[i].temp_flags = 0;
					if ((temp & 0x8002) == 0) {
						// got "device id"
						temp_sensors_runtime[i].temp_flags |= PRESENT;
						if (temp & 4) {
							// thermocouple open
							temp_sensors_runtime[i].temp_flags |= TCOPEN;
						}
						else {
							temp = temp >> 3;
						}
					}

					// this number depends on how frequently temp_sensor_tick is called. the MAX6675 can give a reading every 0.22s, so set this to about 250ms
					temp_sensors_runtime[i].next_read_time = 25;

					break;
				#endif	/* TEMP_MAX6675	*/

				#ifdef	TEMP_THERMISTOR
				case TT_THERMISTOR:
					do {
						uint8_t j, table_num;
						//Read current temperature
						temp = analog_read(i);
						// for thermistors the thermistor table number is in the additional field
						table_num = temp_sensors[i].additional;

						//Calculate real temperature based on lookup table
						for (j = 1; j < NUMTEMPS; j++) {
							if (pgm_read_word(&(temptable[table_num][j][0])) > temp) {
								// Thermistor table is already in 14.2 fixed point
								#ifndef	EXTRUDER
								if (DEBUG_PID && (debug_flags & DEBUG_PID))
									sersendf_P(PSTR("pin:%d Raw ADC:%d table entry: %d"),temp_sensors[i].temp_pin,temp,j);
								#endif
								// Linear interpolating temperature value
								// y = ((x - x₀)y₁ + (x₁-x)y₀ ) / (x₁ - x₀)
								// y = temp
								// x = ADC reading
								// x₀= temptable[j-1][0]
								// x₁= temptable[j][0]
								// y₀= temptable[j-1][1]
								// y₁= temptable[j][1]
								// y =
								// Wikipedia's example linear interpolation formula.
								temp = (
								//     ((x - x₀)y₁
									((uint32_t)temp - pgm_read_word(&(temptable[table_num][j-1][0]))) * pgm_read_word(&(temptable[table_num][j][1]))
								//                 +
									+
								//                   (x₁-x)
									(pgm_read_word(&(temptable[table_num][j][0])) - (uint32_t)temp)
								//                         y₀ )
									* pgm_read_word(&(temptable[table_num][j-1][1])))
								//                              /
									/
								//                                (x₁ - x₀)
									(pgm_read_word(&(temptable[table_num][j][0])) - pgm_read_word(&(temptable[table_num][j-1][0])));
								#ifndef	EXTRUDER
								if (DEBUG_PID && (debug_flags & DEBUG_PID))
									sersendf_P(PSTR(" temp:%d.%d"),temp/4,(temp%4)*25);
								#endif
								break;
							}
						}
						#ifndef	EXTRUDER
						if (DEBUG_PID && (debug_flags & DEBUG_PID))
							sersendf_P(PSTR(" Sensor:%d\n"),i);
						#endif


						//Clamp for overflows
						if (j == NUMTEMPS)
							temp = temptable[table_num][NUMTEMPS-1][1];

						temp_sensors_runtime[i].next_read_time = 0;
					} while (0);
					break;
				#endif	/* TEMP_THERMISTOR */

				#ifdef	TEMP_AD595
				case TT_AD595:
					temp = analog_read(i);

					// convert
					// >>8 instead of >>10 because internal temp is stored as 14.2 fixed point
					temp = (temp * 500L) >> 8;

					temp_sensors_runtime[i].next_read_time = 0;

					break;
				#endif	/* TEMP_AD595 */

				#ifdef	TEMP_PT100
				case TT_PT100:
					#warning TODO: PT100 code
					break
				#endif	/* TEMP_PT100 */

				#ifdef	TEMP_INTERCOM
				case TT_INTERCOM:
					temp = read_temperature(temp_sensors[i].temp_pin);

					temp_sensors_runtime[i].next_read_time = 25;

					break;
				#endif	/* TEMP_INTERCOM */

				#ifdef	TEMP_DUMMY
				case TT_DUMMY:
					temp = temp_sensors_runtime[i].last_read_temp;

					if (temp_sensors_runtime[i].target_temp > temp)
						temp++;
					else if (temp_sensors_runtime[i].target_temp < temp)
						temp--;

					temp_sensors_runtime[i].next_read_time = 0;

					break;
				#endif	/* TEMP_DUMMY */

				default: /* prevent compiler warning */
					break;
			}
			/* Exponentially Weighted Moving Average alpha constant for smoothing
			   noisy sensors. Instrument Engineer's Handbook, 4th ed, Vol 2 p126
			   says values of 0.05 to 0.1 for TEMP_EWMA are typical. */
			#ifndef TEMP_EWMA
				#define TEMP_EWMA 1.0
			#endif
			#define EWMA_SCALE  1024L
			#define EWMA_ALPHA  ((long) (TEMP_EWMA * EWMA_SCALE))
			temp_sensors_runtime[i].last_read_temp = (uint16_t) ((EWMA_ALPHA * temp +
			  (EWMA_SCALE-EWMA_ALPHA) * temp_sensors_runtime[i].last_read_temp
			                                         ) / EWMA_SCALE);
		}
		if (labs((int16_t)(temp_sensors_runtime[i].last_read_temp - temp_sensors_runtime[i].target_temp)) < (TEMP_HYSTERESIS*4)) {
			if (temp_sensors_runtime[i].temp_residency < (TEMP_RESIDENCY_TIME*120))
				temp_sensors_runtime[i].temp_residency++;
		}
		else {
			// Deal with flakey sensors which occasionally report a wrong value
			// by setting residency back, but not entirely to zero.
			if (temp_sensors_runtime[i].temp_residency > 10)
				temp_sensors_runtime[i].temp_residency -= 10;
			else
				temp_sensors_runtime[i].temp_residency = 0;
		}

		if (temp_sensors[i].heater < NUM_HEATERS) {
			heater_tick(temp_sensors[i].heater, temp_sensors[i].temp_type, temp_sensors_runtime[i].last_read_temp, temp_sensors_runtime[i].target_temp);
		}

    if (DEBUG_PID && (debug_flags & DEBUG_PID))
      sersendf_P(PSTR("DU temp: {%d %d %d.%d}"), i,
                 temp_sensors_runtime[i].last_read_temp,
                 temp_sensors_runtime[i].last_read_temp / 4,
                 (temp_sensors_runtime[i].last_read_temp & 0x03) * 25);
	}
Beispiel #9
0
void runBinaryProtocolLoop(ts_channel_s *tsChannel, bool_t isConsoleRedirect) {
	int wasReady = false;
	while (true) {
		int isReady = ts_serial_ready(isConsoleRedirect);
		if (!isReady) {
			chThdSleepMilliseconds(10);
			wasReady = false;
			continue;
		}

		if (!wasReady) {
			wasReady = true;
//			scheduleSimpleMsg(&logger, "ts channel is now ready ", hTimeNow());
		}

		tsState.tsCounter++;

		int recieved = chnReadTimeout(tsChannel->channel, &firstByte, 1, TS_READ_TIMEOUT);
		if (recieved != 1) {
//			tunerStudioError("ERROR: no command");
			continue;
		}
//		scheduleMsg(logger, "Got first=%x=[%c]", firstByte, firstByte);
		if (handlePlainCommand(tsChannel, firstByte))
			continue;

		recieved = chnReadTimeout(tsChannel->channel, &secondByte, 1, TS_READ_TIMEOUT);
		if (recieved != 1) {
			tunerStudioError("ERROR: no second");
			continue;
		}
//		scheduleMsg(logger, "Got secondByte=%x=[%c]", secondByte, secondByte);

		uint32_t incomingPacketSize = firstByte * 256 + secondByte;

		if (incomingPacketSize == BINARY_SWITCH_TAG) {
			// we are here if we get a binary switch request while already in binary mode. We will just ignore it.
			tunerStudioWriteData(tsChannel, (const uint8_t *) &BINARY_RESPONSE, 2);
			continue;
		}

		if (incomingPacketSize == 0 || incomingPacketSize > (sizeof(tsChannel->crcReadBuffer) - CRC_WRAPPING_SIZE)) {
			scheduleMsg(&tsLogger, "TunerStudio: invalid size: %d", incomingPacketSize);
			tunerStudioError("ERROR: CRC header size");
			sendErrorCode(tsChannel);
			continue;
		}

		recieved = chnReadTimeout(tsChannel->channel, (uint8_t* )tsChannel->crcReadBuffer, 1, TS_READ_TIMEOUT);
		if (recieved != 1) {
			tunerStudioError("ERROR: did not receive command");
			continue;
		}

		char command = tsChannel->crcReadBuffer[0];
		if (!isKnownCommand(command)) {
			scheduleMsg(&tsLogger, "unexpected command %x", command);
			sendErrorCode(tsChannel);
			continue;
		}

//		scheduleMsg(logger, "TunerStudio: reading %d+4 bytes(s)", incomingPacketSize);

		recieved = chnReadTimeout(tsChannel->channel, (uint8_t * ) (tsChannel->crcReadBuffer + 1),
				incomingPacketSize + CRC_VALUE_SIZE - 1, TS_READ_TIMEOUT);
		int expectedSize = incomingPacketSize + CRC_VALUE_SIZE - 1;
		if (recieved != expectedSize) {
			scheduleMsg(&tsLogger, "got ONLY %d for packet size %d/%d for command %c", recieved, incomingPacketSize,
					expectedSize, command);
			tunerStudioError("ERROR: not enough");
			continue;
		}

		uint32_t expectedCrc = *(uint32_t*) (tsChannel->crcReadBuffer + incomingPacketSize);

		expectedCrc = SWAP_UINT32(expectedCrc);

		uint32_t actualCrc = crc32(tsChannel->crcReadBuffer, incomingPacketSize);
		if (actualCrc != expectedCrc) {
			scheduleMsg(&tsLogger, "TunerStudio: CRC %x %x %x %x", tsChannel->crcReadBuffer[incomingPacketSize + 0],
					tsChannel->crcReadBuffer[incomingPacketSize + 1], tsChannel->crcReadBuffer[incomingPacketSize + 2],
					tsChannel->crcReadBuffer[incomingPacketSize + 3]);

			scheduleMsg(&tsLogger, "TunerStudio: command %c actual CRC %x/expected %x", tsChannel->crcReadBuffer[0],
					actualCrc, expectedCrc);
			tunerStudioError("ERROR: CRC issue");
			continue;
		}

//		scheduleMsg(logger, "TunerStudio: P00-07 %x %x %x %x %x %x %x %x", crcIoBuffer[0], crcIoBuffer[1],
//				crcIoBuffer[2], crcIoBuffer[3], crcIoBuffer[4], crcIoBuffer[5], crcIoBuffer[6], crcIoBuffer[7]);

		int success = tunerStudioHandleCrcCommand(tsChannel, tsChannel->crcReadBuffer, incomingPacketSize);
		if (!success)
			print("got unexpected TunerStudio command %x:%c\r\n", command, command);

	}
}
Beispiel #10
0
/*!
    \brief This function displays the filter options and read parameters to 
            create the filter.

    \param[in]   none

    \return      0 for success, -ve otherwise

    \note

    \warning
*/
static _i32 FiltersMenu()
{
    _i32  selection = -1;
    _i8   equalYesNo = -1;
    _i8   dropYesNo = -1;
    _u32  frameTypeLength = 0;
    _i32  fatherId = 0;
    _u32  macAddress[MAC_ADDR_LENGTH] = {'\0'};
    _u32  ipAddress[IP_ADDR_LENGTH] = {'\0'};
    _u8   filterData[MAC_ADDR_LENGTH] = {'\0'};
    _i32  retVal = -1;
    _i32  idx = 0;

    printf("\nPlease select a filter parameter:\n");
    printf("\n1. Source MAC address\n");
    printf("2. Destination MAC address\n");
    printf("3. BSSID\n");
    printf("4. Frame type\n");
    printf("5. Frame subtype\n");
    printf("6. Source IP address\n");
    printf("7. Destination IP address\n");
    printf("8. Packet length\n");
    printf("9. Remove filter and exit menu\n");
    printf("10. Enable filter and exit menu\n");
    printf("Selection: \n");
    while(1)
    {
        fflush(stdin);
        scanf_s("%d",&selection, sizeof(selection));

        switch(selection)
        {
            case 1:
            case 2:
            case 3:
                PrintFilterType(selection);
                printf("\nEnter the MAC address (xx:xx:xx:xx:xx:xx): \n");
                fflush(stdin);
                scanf("%2x:%2x:%2x:%2x:%2x:%2x", &macAddress[0],
                                                 &macAddress[1],
                                                 &macAddress[2],
                                                 &macAddress[3],
                                                 &macAddress[4],
                                                 &macAddress[5]);
                for(idx = 0 ; idx < MAC_ADDR_LENGTH ; idx++ )
                {
                    filterData[idx] = (_u8)macAddress[idx];
                }
                break;

            case 4:
                PrintFilterType(selection);
                printf("Enter the frame type byte: \n");
                fflush(stdin);
                scanf_s("%2x",&frameTypeLength, sizeof(frameTypeLength));
                filterData[0] = (_u8)frameTypeLength;
                break;

            case 5:
                PrintFilterType(selection);

                printf("\nCreating a frame subtype filter requires a parent frame type filter\r\n");

                printf("Enter the frame type byte: \n");
                fflush(stdin);
                scanf_s("%2x",&frameTypeLength, sizeof(frameTypeLength));
                filterData[0] = (_u8)frameTypeLength;
                break;

            case 6:
            case 7:
                PrintFilterType(selection);
                printf("Enter the IP address: \n");
                fflush(stdin);
                scanf("%u.%u.%u.%u",&ipAddress[0],&ipAddress[1],&ipAddress[2],
                                                                 &ipAddress[3]);
                for(idx = 0 ; idx < IP_ADDR_LENGTH ; idx++ )
                {
                    filterData[idx] = (_u8)ipAddress[idx];
                }
                break;

            case 8:
                PrintFilterType(selection);
                printf("Enter desired length in Bytes (Maximum = 1472): \n");
                fflush(stdin);
                scanf_s("%u",&frameTypeLength, sizeof(frameTypeLength));
                *(_u32 *)filterData = SWAP_UINT32(frameTypeLength);
                printf("Target what lengths? (h - Higher than %u | l - Lower than %u): \n",
                                                  frameTypeLength,frameTypeLength);
                fflush(stdin);
                scanf_s("%c",&equalYesNo, sizeof(equalYesNo));
                printf("Drop packets or not? (y/n): \n");
                fflush(stdin);
                scanf_s("%c",&dropYesNo, sizeof(dropYesNo));
                printf("Enter filter ID of parent. Otherwise 0: \n");
                fflush(stdin);
                scanf_s("%u", &fatherId, sizeof(fatherId));
                retVal= RxFiltersExample('1',selection,filterData,equalYesNo,dropYesNo,
                                                                   (_i8)fatherId);
                ASSERT_ON_ERROR(retVal);

                printf("\nPlease select a filter parameter:\n");
                printf("\n1. Source MAC address\n");
                printf("2. Destination MAC address\n");
                printf("3. BSSID\n");
                printf("4. Frame type\n");
                printf("5. Frame subtype\n");
                printf("6. Source IP address\n");
                printf("7. Destination IP address\n");
                printf("8. Packet length\n");
                printf("9. Remove filter and exit menu\n");
                printf("10. Enable filter and exit menu\n");
                printf("\nSelection: \n");
                continue;
                break;

            case 9:
                retVal = RxFiltersExample('2',0,NULL,0,0,0);
                ASSERT_ON_ERROR(retVal);

                return SUCCESS;
                break;

            case 10:
                retVal = RxFiltersExample('3',0,NULL,0,0,0);
                ASSERT_ON_ERROR(retVal);

                return SUCCESS;
                break;

            default:
                continue;
        }

        printf("Equal or not equal? (y/n): \n");
        fflush(stdin);
        scanf_s("%c",&equalYesNo, sizeof(equalYesNo));

        printf("Drop the packet? (y/n): \n");
        fflush(stdin);
        scanf_s("%c",&dropYesNo, sizeof(dropYesNo));

        printf("Enter filter ID of parent. Otherwise 0:: \n");
        fflush(stdin);
        scanf_s("%u", &fatherId, sizeof(fatherId));

        retVal = RxFiltersExample('1', selection, filterData,
                         equalYesNo, dropYesNo, (_i8)fatherId);
        if((retVal < 0) && (retVal != INVALID_PARENT_FILTER_ID))
        {
            return retVal;
        }

        printf("\nPlease select a filter parameter:\n");
        printf("\n1. Source MAC address\n");
        printf("2. Destination MAC address\n");
        printf("3. BSSID\n");
        printf("4. Frame type\n");
        printf("5. Frame subtype\n");
        printf("6. Source IP address\n");
        printf("7. Destination IP address\n");
        printf("8. Packet length\n");
        printf("9. Remove and exit\n");
        printf("10. Enable and exit\n");
        printf("Selection:\n");
    }

    return SUCCESS;
}
Beispiel #11
0
static msg_t tsThreadEntryPoint(void *arg) {
	(void) arg;
	chRegSetThreadName("tunerstudio thread");

	int wasReady = false;
	while (true) {
		int isReady = ts_serail_ready();
		if (!isReady) {
			chThdSleepMilliseconds(10);
			wasReady = false;
			continue;
		}

		if (!wasReady) {
			wasReady = TRUE;
//			scheduleSimpleMsg(&logger, "ts channel is now ready ", hTimeNow());
		}

		tsCounter++;

		int recieved = chSequentialStreamRead(getTsSerialDevice(), &firstByte, 1);
		if (recieved != 1) {
			tunerStudioError("ERROR: no command");
			continue;
		}
//		scheduleMsg(&logger, "Got first=%x=[%c]", firstByte, firstByte);
		if (handlePlainCommand(firstByte))
			continue;

		recieved = chSequentialStreamRead(getTsSerialDevice(), &secondByte, 1);
		if (recieved != 1) {
			tunerStudioError("ERROR: no second");
			continue;
		}
//		scheduleMsg(&logger, "Got secondByte=%x=[%c]", secondByte, secondByte);

		uint32_t incomingPacketSize = firstByte * 256 + secondByte;

		if (incomingPacketSize == 0 || incomingPacketSize > (sizeof(crcIoBuffer) - CRC_WRAPPING_SIZE)) {
			scheduleMsg(&logger, "TunerStudio: invalid size: %d", incomingPacketSize);
			tunerStudioError("ERROR: size");
			sendErrorCode();
			continue;
		}

		recieved = chnReadTimeout(getTsSerialDevice(), crcIoBuffer, 1, MS2ST(TS_READ_TIMEOUT));
		if (recieved != 1) {
			tunerStudioError("ERROR: did not receive command");
			continue;
		}

		char command = crcIoBuffer[0];
		if (!isKnownCommand(command)) {
			scheduleMsg(&logger, "unexpected command %x", command);
			sendErrorCode();
			continue;
		}

//		scheduleMsg(&logger, "TunerStudio: reading %d+4 bytes(s)", incomingPacketSize);

		recieved = chnReadTimeout(getTsSerialDevice(), (uint8_t * ) (crcIoBuffer + 1), incomingPacketSize + CRC_VALUE_SIZE - 1,
				MS2ST(TS_READ_TIMEOUT));
		int expectedSize = incomingPacketSize + CRC_VALUE_SIZE - 1;
		if (recieved != expectedSize) {
			scheduleMsg(&logger, "got ONLY %d for packet size %d/%d for command %c", recieved, incomingPacketSize,
					expectedSize, command);
			tunerStudioError("ERROR: not enough");
			continue;
		}

		uint32_t expectedCrc = *(uint32_t*) (crcIoBuffer + incomingPacketSize);

		expectedCrc = SWAP_UINT32(expectedCrc);

		uint32_t actualCrc = crc32(crcIoBuffer, incomingPacketSize);
		if (actualCrc != expectedCrc) {
			scheduleMsg(&logger, "TunerStudio: CRC %x %x %x %x", crcIoBuffer[incomingPacketSize + 0],
					crcIoBuffer[incomingPacketSize + 1], crcIoBuffer[incomingPacketSize + 2],
					crcIoBuffer[incomingPacketSize + 3]);

			scheduleMsg(&logger, "TunerStudio: command %c actual CRC %x/expected %x", crcIoBuffer[0], actualCrc,
					expectedCrc);
			tunerStudioError("ERROR: CRC issue");
			continue;
		}

//		scheduleMsg(&logger, "TunerStudio: P00-07 %x %x %x %x %x %x %x %x", crcIoBuffer[0], crcIoBuffer[1],
//				crcIoBuffer[2], crcIoBuffer[3], crcIoBuffer[4], crcIoBuffer[5], crcIoBuffer[6], crcIoBuffer[7]);

		int success = tunerStudioHandleCrcCommand(crcIoBuffer, incomingPacketSize);
		if (!success)
			print("got unexpected TunerStudio command %x:%c\r\n", command, command);

	}
#if defined __GNUC__
	return 0;
#endif
}