getSubImage outside Raster - exception

I have an image that has a width of 512px. This piece of code will throw
RasterFormatException (x+width) is outside Raster
I dont understand what im doing wrong, when i check the raster size it says its 512
private void automaticStaticSpriteLoader(String loadedName, String imgLoc, BufferedImage[] biArray, int numberOfSpritesToLoad, int numberOfSpritesInImage, int percentComplete){
try {
temporaryBigImg = ImageIO.read(getClass().getResource(imgLoc + ".png"));
} catch (IOException e) {
System.out.println(classNumber + " Error Loading Sprite Images. Shutting Down.");
e.printStackTrace();
}
for(int i = 0; i<numberOfSpritesToLoad;i++){
biArray[i] = temporaryBigImg.getSubimage(counterX, counterY, 32, 32);
System.out.println("CounterX = " + counterX + " CounterY = " + counterY + " Current Index = " + i);
if(counterX == 512){
counterY += 32;
counterX = -32;
}
counterX+=32;
}
}

You are updating counterXand counterY too late.
You have to check if counterX >= 512 and eventually increment counterY and reset counterX before you call getSubImage.
The code, as in your post will first call getSubImage(512, 0, 32, 32), then test if counterX == 512 (but the test is never reached). Try printing the actual values you pass in, and you will see what is wrong.

Related

Autokey Encryption

I am working on a project to write to and read from a TP Link / Kaza power strip or smart plug.
The data that is sent is encrypted json that has been "autokey encrypted".
So far I have been able to convert a typescript encrypt function and it works well. I get the expected result. However, I need to add a "header" to my encrypted data. That data is 3 null bytes followed by a byte that is a measure of the length of the encrypted bytes.
The typescript example has this bit of code to "encrypt with headers", however, I've hit a bit of a wall trying to convert it to something usable. Can someone nudge me along the path ?
First are the two typescript functions: (borrowed from https://github.com/plasticrake/tplink-smarthome-crypto/blob/master/src/index.ts)
/**
* Encrypts input where each byte is XOR'd with the previous encrypted byte.
*
* #param input - Data to encrypt
* #param firstKey - Value to XOR first byte of input
* #returns encrypted buffer
*/
export function encrypt(input: Buffer | string, firstKey = 0xab): Buffer {
const buf = Buffer.from(input);
let key = firstKey;
for (let i = 0; i < buf.length; i += 1) {
// eslint-disable-next-line no-bitwise
buf[i] ^= key;
key = buf[i];
}
return buf;
}
/**
* Encrypts input that has a 4 byte big-endian length header;
* each byte is XOR'd with the previous encrypted byte.
*
* #param input - Data to encrypt
* #param firstKey - Value to XOR first byte of input
* #returns encrypted buffer with header
*/
export function encryptWithHeader(
input: Buffer | string,
firstKey = 0xab
): Buffer {
const msgBuf = encrypt(input, firstKey);
const outBuf = Buffer.alloc(msgBuf.length + 4);
outBuf.writeUInt32BE(msgBuf.length, 0);
msgBuf.copy(outBuf, 4);
return outBuf;
}
Second is what I have so far.
// This part works well and produces the expected results
String encrypt(String input)
{
int16_t firstKey = 0xab;
String buf;
int key;
int i;
buf = input;
key = firstKey;
i = 0;
for (;i < buf.length();(i = i + 1))
{
buf[i] ^= key;
key = buf[i];
}
return buf;
}
// This does not function yet, as I'm pretty lost..
// This was orginally converted from typescript with https://andrei-markeev.github.io/ts2c/
// I started work on converting this, but ran into errors I don't know how to solve.
String encryptWithHeader(String input){
String msgBuf;
String outBuf;
int16_t firstKey = 0xab;
char * null = NULL;
msgBuf = encrypt(input);
outBuf = msgBuf.length() +1;
//this is where I got lost...
assert(null != NULL);
null[0] = '\0';
strncat(null, outBuf, msgBuf.length());
str_int16_t_cat(null, 4);
outBuf = msgBuf + 4
return outBuf;
}
Finally, the data:
//this is the unencrypted json
String offMsg = "{\"system\":{\"set_relay_state\":{\"state\":0}}}";
//current encrypt function produces:
d0f281f88bff9af7d5ef94b6c5a0d48bf99cf091e8b7c4b0d1a5c0e2d8a381f286e793f6d4eedea3dea3
//the working "withheaders" should produce:
00002ad0f281f88bff9af7d5ef94b6c5a0d48bf99cf091e8b7c4b0d1a5c0e2d8a381f286e793f6d4eedea3dea3
Admittedly my C/C++ ability is very limited and I can spell typescript, that's about all. I have a very extensive history with PHP. As useful as that is. So, I understand the basics of data structures and whatnot, but I'm venturing off into areas I've never been in. Any help would be greatly appreciated.
It looks like the encryption is fairly simple: write the current character XORed with the key to the buffer and make that newly written character the new key. It also looks like the "withHeaders" version adds the length of the encrypted string as a 4 byte integer to the start of the buffer. I think it might be easier to allocate a character array and pass that array to a function that writes the result to that buffer. For example:
void encryptWithHeader(byte buffer[], int bufferLength, byte key, String message) {
int i;
uint32_t messageLength = message.length();
Serial.println(message);
Serial.println(message.length());
// check that we won't overrun the buffer
if ( messageLength + 5 < bufferLength) {
buffer[0] = messageLength >> 24 & 0xFF;
buffer[1] = messageLength >> 16 & 0xFF;
buffer[2] = messageLength >> 8 & 0xFF;
buffer[3] = messageLength & 0xFF;
for (i = 0; i < messageLength; i++) {
buffer[i + 4] = message[i] ^ key;
key = buffer[i + 4];
}
}
else { // we would have overrun the buffer
Serial.println("not enough room in buffer for message");
}
}
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
byte theBuffer[64];
int i;
String offMsg = "{\"system\":{\"set_relay_state\":{\"state\":0}}}";
encryptWithHeader(theBuffer, 64, 0xab, offMsg);
// now print it out to check
for (i = 0; i < offMsg.length() + 4; i++) {
if (theBuffer[i] < 0x10) // adds an extra zero if a byte prints as on1y 1 char
Serial.print("0");
Serial.print(theBuffer[i], HEX);
}
while (true)
;
}
If you want to send the character buffer to a remote device you can send it out one byte at a time:
for (i = 0; i < offMsg.length() + 4; i++)
Serial.write(theBuffer[i]);

Can I send tone() function wirelessly?

I have a simple RPM Simulator (opensource) that generates values through the tone() function.
I need to send the RPM wirelessly through an nrf24l01 to a second Arduino that uses the RPM as a shiftlight, both come from chippernut.
The tone() function only sends to the pin, trying to read the values did not work.
How can i get the value of x (RPM) after it leaves the tone function?
I have tried reading it through analogRead, digitalRead, BitRead, tried printing the value of x which stays constant, to no avail, and it updates very slowly if it reads the output pin.
This is the code:
float RPM_MIN = 2500;
float RPM_MAX = 8000;
int Accel_Rate = 20;
float pulses_per_rev = 2.0; // make sure to keep the decimal
boolean accel = false;
float x;
long previousMillis = 0;
unsigned long currentMillis=0;
//float RPM_PRINT; //my addition to get a value to print
void setup() {
Serial.begin(57600);
pinMode(5, OUTPUT);
RPM_MIN = (RPM_MIN / 60);
RPM_MAX = (RPM_MAX / 60);
x = RPM_MIN;
}
void loop() {
while (accel==false){
currentMillis = millis();
if(currentMillis - previousMillis > Accel_Rate) {
previousMillis = currentMillis;
x++;
tone(5,x*pulses_per_rev);
if (x>RPM_MAX){accel=true;}
}
}
while (accel==true){
currentMillis = millis();
if(currentMillis - previousMillis > Accel_Rate) {
previousMillis = currentMillis;
x--;
tone(5,x*pulses_per_rev);
if (x<RPM_MIN){accel=false;}
}
}
//RPM_PRINT = x*pulses_per_rev;
//RPM_PRINT = digitalRead(5);
//RPM_PRINT = analogRead(5);
//Serial.println(RPM_PRINT);
}
Expected Result is a Value between 2000-8000 that is constantly changing
actual result is 1/0 or 81,33 or 4,1 or 900-980 updating once every few seconds.
How can I solve?

Reading JSON from Serial port missing part of the starting data

When reading a JSON string from the serial port on an ESP8266 it cuts off the beginning of the data.
I have tried reading data from the Serial port and printing each character, however it is cutting off part of the begging of the data.
void setup() {
Serial.begin(115200);
while (!Serial) {
;
}
}
void loop() {
int curSize = 30;
char* buffer = new char[curSize];
std::fill_n(buffer, curSize, 0);
int pos = 0;
Serial.print("Sending: ");
while(Serial.available() == false) delay(500);
while (Serial.available()) {
char c = Serial.read();
Serial.print(c);
if(pos == curSize-1){
char* newBuffer = increaseBuffer(buffer, curSize, curSize + 30);
curSize += 30;
delete[] buffer;
buffer = newBuffer;
}
if(c == '\n'){
buffer[pos] = 0;
pos = 0;
break;
}
buffer[pos++] = c;
}
if(buffer[0] != 0) {
sendBuffer(buffer);
}
delete[] buffer;
}
char* increaseBuffer(char* orig, int oldSize, int newSize){
char* data = new char[newSize];
std::fill_n(data, newSize, 0);
for(int i = 0; i < newSize; i++){
if(i < oldSize) data[i] = orig[i];
else data[i] = '\0';
}
return data;
}
JSON data used (and expected output)
{"type":0,"ver":"0.0.1","T":[28,29,29,29,29,29,29,29,29,29],"H":[59.1608,59.1608,60,59.1608,60,60,60,59.1608,59.1608,59.1608],"DP":[20.36254,20.36254,20.59363,20.36254,20.59363,20.59363,20.59363,20.36254,20.36254],"HI":[30.90588,30.90588,31.0335,30.90588,31.0335,31.0335,31.0335,30.90588,30.90588]}
examples of what is actually output
Example 1: 9,29,29,29,29,29,29,29,29],"H":[59.1608,59.1608,60,59.1608,60,60,60,59.1608,59.1608,59.1608],"DP":[20.36254,20.36254,20.59363,20.36254,20.59363,20.59363,20.59363,20.36254,20.36254],"HI":[30.90588,30.90588,31.0335,30.90588,31.0335,31.0335,31.0335,30.90588,30.90588]}
Example 2: 29,29,29,29,29,29,29,29,29],"H":[59.1608,59.1608,60,59.1608,60,60,60,59.1608,59.1608,59.1608],"DP":[20.36254,20.36254,20.59363,20.36254,20.59363,20.59363,20.59363,20.36254,20.36254],"HI":[30.90588,30.90588,31.0335,30.90588,31.0335,31.0335,31.0335,30.90588,30.90588]}
Try making the delay 1 instead of 500 in the blocking loop that's waiting for data to start coming in. I'm going to guess what happens is that on one iteration of that loop Serial.available() is false and during the delay you start to get data coming in that ends up getting written over by the time your delay ends to check again.
What I'm picturing is the following. If you were to expand out that delay(500) to be delay(1) called 500 times.
while(Serial.available() == false){
delay(1);
delay(1);
// ...
delay(1); // first character comes in
delay(1);
delay(1); // second character comes in
// ...
delay(1); // n character comes in
}
Then after the delay is over you start actually collecting the characters that are coming in.

Misunderstanding of the OOP in a chess game design in java

I've a problem with code that I'm writing to practice my java skills.
I'm trying to write a chess game. Anyway, in my project I have a class called ChessGUI which contains the GUI and the methods I need to play (multiplayer). I'm willing to change the code later to a MVC pattern so it can be easier to read/edit/understand.
I've an abstract class called Figure and i extended it in 12 classes (6 figures per color):
However in my ChessGui class I have a method called CheckAvailableSquares() which I call whenever a piece on the board has been selected (by a mouse click) to show me on the board the available squares which I can move my selected piece to.
private void CheckAvailableSquares(Figure figure){
for (int row = 0; row < 8; row++){
for (int col = 0; col < 8; col++){
if (row == figure.getRowPos() && col == figure.getColPos()) //bypass the actual square where my piece stands
continue;
if (figure.isValidMove(board,figure.getRowPos(), figure.getColPos(),row,col)){
board[row][col].setBackground(Color.GREEN);
}
}
}
}
In every figure sub-class there is a method called isValidMove() which becomes the current position of the piece and the wanted position and return a boolean value if the move is valid.
As you know the pawn can move 2 squares per time on it's first move, that's why I added a boolean attribute to the classes WhitePawn&BlackPawn called firstMovePlayed. It has the false value and whenever the isMoveValid() method is called and the wanted move is valid it should be changed to true. like that:
public class WhitePawn extends Figure {
private boolean firstMovePlayed = false;
public WhitePawn(){
super.setColor(Color.WHITE);
}
#Override
public boolean isValidMove(Square[][] board, int currentRow, int currentCol, int wantedRow, int wantedCol){
int rowDelta = currentRow - wantedRow; //no Math.abs because a pawn can't move backwards.
int colDelta = Math.abs(wantedCol - currentCol);
//if we have an own piece on the wanted square
if (!board[wantedRow][wantedCol].isEmpty() && board[wantedRow][wantedCol].getFigure().getColor().equals(Color.WHITE)) {
return false;
}
//on the first move a pawn can move 2 square at a time, and when moving 2 square he can't capture. A pawn can't move two square if there is another piece in the way. TODO: en passant ??????
if (rowDelta == 2 && colDelta == 0 && board[wantedRow][wantedCol].isEmpty() && board[wantedRow + 1][wantedCol].isEmpty() && !firstMovePlayed) {
firstMovePlayed = true;
return true;
}
else if (rowDelta == 1 && colDelta == 1 && !board[wantedRow][wantedCol].isEmpty()) { //capture
if (board[wantedRow][wantedCol].getFigure().getColor() != board[currentRow][currentCol].getFigure().getColor())
firstMovePlayed = true;
return true;
}
else if (rowDelta == 1 && colDelta == 0 && board[wantedRow][wantedCol].isEmpty()) { //moving one square forward without a capture
firstMovePlayed = true;
return true;
}
//those were the only possibilities to move a pawn
return false;
}}
The problem is:
whenever I call the method CheckAvailableSquares() to check the availability of the squares the firstMovePlayed boolean will be set to true!!
I'm really sorry for taking too long of your time but I really can't figure it out :/
here is the rest of the relevant code from ChessGui class:
public void actionPerformed(ActionEvent e) {
//looking for the square which fired the ActionListener:
for (int i = 0; i < 8; i++){
for (int j = 0; j < 8; j++){
if(board[i][j] == e.getSource()){
processClick(i, j);
}
}
}
}
private void processClick(int i, int j){
if(bufRow == 99 && bufCol == 99){ //select a figure to move and wait for the next click
if (board[i][j].isEmpty()) { //if there is no figure on the square that has benn clicked
System.out.println("no Figures on this square");
return;
}
else {//save the chosen square (button) in buffers so that we can move it later.
//decide who's turn it is:
if (board[i][j].getFigure().getColor().equals(Color.WHITE) && !whiteToPlay)
System.out.println("It's black's turn to play!");
else if (board[i][j].getFigure().getColor().equals(Color.BLACK) && !blackToPlay)
System.out.println("It's white's turn to play!");
if ((board[i][j].getFigure().getColor().equals(Color.WHITE) && whiteToPlay) || board[i][j].getFigure().getColor().equals(Color.BLACK) && blackToPlay) {
board[i][j].setHighleightedIcon(board[i][j].getFigure().getHilightedIcon()); //change the icon of the chosen square
bufRow = i; //save the chosen figure to move it later
bufCol = j;
System.out.println("Selectd figure on Raw: " + bufRow + " Column: " + bufCol);
switchTurns();
CheckAvailableSquares(board[bufRow][bufCol].getFigure());
}
}
}
else
moveFigure(i, j);
}
private void moveFigure(int wantedRow, int wantedCol) {
if (board[bufRow][bufCol].getFigure().isValidMove(board, bufRow, bufCol, wantedRow, wantedCol)) { // check if the move is valid for the figure
// if (board[wantedRow][wantedCol].isEmpty()) { //if the wanted square is empty (not a capture)
//move the figure to the wanted square after deleting it from the old square
board[wantedRow][wantedCol].setFigure(board[bufRow][bufCol].getFigure());
board[wantedRow][wantedCol].setSquareIcon(board[bufRow][bufCol].getFigure().getIcon());
board[bufRow][bufCol].emptySquare();
//update the location of the piece
board[wantedRow][wantedCol].getFigure().setNewPos(wantedRow,wantedCol);
System.out.println("Moved [" + bufRow + ", " + bufCol + "] To: [" + wantedRow + ", " + wantedCol + "].");
//reset the buffers
bufRow = 99;
bufCol = 99;
resetSquaresColors();
/*}
else if (!board[wantedRow][wantedCol].isEmpty()){ //if it's a capture
if(board[wantedRow][wantedCol].getFigure().getColor() != board[bufRow][bufCol].getFigure().getColor()) { //can't capture own pieces!
board[wantedRow][wantedCol].setFigure(board[bufRow][bufCol].getFigure());
board[wantedRow][wantedCol].setSquareIcon(board[wantedRow][wantedCol].getFigure().getIcon());
board[bufRow][bufCol].emptySquare();
//update the location of the piece
board[wantedRow][wantedCol].getFigure().setRowPos(wantedRow);
board[wantedRow][wantedCol].getFigure().setColPos(wantedCol);
System.out.println("Moved [" + bufRow + ", " + bufCol + "] To: [" + wantedRow + ", " + wantedCol + "].");
//reset the buffers
bufRow = 99;
bufCol = 99;
}
}*/
} else { //if it's not a valid move
board[bufRow][bufCol].setIcon(board[bufRow][bufCol].getFigure().getIcon());
//reset the buffers
bufRow = 99;
bufCol = 99;
resetSquaresColors();
System.out.println("Not a valid move");
switchTurns();
}
}
private void CheckAvailableSquares(Figure figure){
for (int row = 0; row < 8; row++){
for (int col = 0; col < 8; col++){
if (row == figure.getRowPos() && col == figure.getColPos()) //bypass the actual square where my piece stands
continue;
if (figure.isValidMove(board,figure.getRowPos(), figure.getColPos(),row,col)){
Square sqr = board[row][col];
if (sqr.isEmpty()) //if the square is empty
sqr.setAvailableIcon(new ImageIcon("Icons/available_square.png"));
else //if there is a piece on the square
sqr.setAvailableIcon(sqr.getFigure().getAvailableIcon());
}
}
}
}
Thanks alot & forgive any mistakes in my poor English!

how to Get Average %User Time in Perfmon

I also understand I can also use this programatically by creating a performance counter by using System.Diagnostics.PerformanceCounter, and get the counter value using NextValue() method.
Process p = Process.GetProcessById(10204);
PerformanceCounter ramCounter = new PerformanceCounter("Process", "Working Set - Private", p.ProcessName);
PerformanceCounter cpuCounter = new PerformanceCounter("Process", "% User Time", p.ProcessName);
while (true)
{
Thread.Sleep(1000);
double ram = ramCounter.NextValue();
double cpu = cpuCounter.NextValue();
Console.WriteLine("RAM: " + (ram / 1024 / 1024) + "MB");
Console.WriteLine("CPU: " + (cpu) + " %");
}
I found this code online and In Here I am more insterested in Calculating Average CPU and Average RAM at the end of this test and store it in a Var to compare it against another variable. any nice ideas
thanks
using System;
using System.Diagnostics;
using System.Threading;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
double totalRam = 0.0d;
double cpu = 0.0d;
Process p = Process.GetProcessById(1188);
var ramCounter = new PerformanceCounter("Process", "Working Set - Private", p.ProcessName);
var cpuCounter = new PerformanceCounter("Process", "% User Time", p.ProcessName);
int n = 0;
while (n < 20)
{
Thread.Sleep(1000);
double ram = ramCounter.NextValue();
cpu += cpuCounter.NextValue();
totalRam += (ram / 1024 / 1024);
n++;
}
double avgRam = totalRam/n;
double avgCpu = cpu/n;
Console.WriteLine("Average Ram is {0} ", avgRam);
Console.WriteLine("Average Cpu is {0} ", avgCpu);
Console.ReadLine();
}
}
}