Java Code Examples for org.pmw.tinylog.Logger#error()

The following examples show how to use org.pmw.tinylog.Logger#error() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GpioReadPerfTest.java    From diozero with MIT License 6 votes vote down vote up
public static void test(int pin, int iterations) {
	try (DigitalInputDevice gpio = new DigitalInputDevice(pin)) {
		for (int j = 0; j < 5; j++) {
			long start_nano = System.nanoTime();
			for (int i = 0; i < iterations; i++) {
				gpio.getValue();
			}
			long duration_ns = System.nanoTime() - start_nano;

			Logger.info("Duration for {} iterations: {}s", Integer.valueOf(iterations),
					String.format("%.4f", Float.valueOf(((float) duration_ns) / 1000 / 1000 / 1000)));
		}
	} catch (RuntimeIOException e) {
		Logger.error(e, "Error: {}", e);
	}
}
 
Example 2
Source File: HCSR04UsingWait.java    From diozero with MIT License 6 votes vote down vote up
public static void main(String[] args) {
	if (args.length != 2) {
		Logger.error("Usage: {} <trigger GPIO> <echo GPIO>", HCSR04UsingWait.class.getName());
		System.exit(1);
	}
	int trigger_pin = Integer.parseInt(args[0]);
	int echo_pin = Integer.parseInt(args[1]);
	
	try (HCSR04UsingWait device = new HCSR04UsingWait(trigger_pin, echo_pin)) {
		while (true) {
			Logger.info("Distance = {} cm", String.format("%.3f", Double.valueOf(device.getDistanceCm())));
			SleepUtil.sleepMillis(1000);
		}
	} catch (RuntimeIOException ex) {
		Logger.error(ex, "I/O error with HC-SR04 device: {}", ex.getMessage());
	}
}
 
Example 3
Source File: GsonAnimationTest.java    From diozero with MIT License 6 votes vote down vote up
public static void main(String[] args) {
	Collection<OutputDeviceInterface> one_target = Arrays.asList(value -> System.out.println(value));
	Collection<OutputDeviceInterface> two_targets = Arrays.asList(
			value -> System.out.println("1: " + value), value -> System.out.println("2: " + value));

	try {
		animate(one_target, 10, Elastic::easeOut, 1, "/animation1.json", "/animation3.json");
		animate(one_target, 10, Elastic::easeOut, 1, "/animation3.json");
		animate(two_targets, 100, Cubic::easeIn, 1, "/animation2.json");
	} catch (IOException e) {
		Logger.error(e, "Error: {}", e);
	} finally {
		// Required if there are non-daemon threads that will prevent the
		// built-in clean-up routines from running
		DeviceFactoryHelper.getNativeDeviceFactory().close();
	}
}
 
Example 4
Source File: McpEeprom.java    From diozero with MIT License 6 votes vote down vote up
public void writeBytes(int address, byte[] data) {
	if ((address + data.length) > type.getMemorySizeBytes()) {
		Logger.error("Attempt to write beyond memory size - no data written");
		return;
	}
	
	int page = address / type.getPageSizeBytes();
	int bytes_remaining = data.length;
	do {
		int remaining_page_size = type.getPageSizeBytes() - (address % type.getPageSizeBytes());
		int bytes_to_write = remaining_page_size < bytes_remaining ? remaining_page_size : bytes_remaining;
		
		byte[] addr_bytes = getAddressByteArray(address);
		byte[] buffer = new byte[addr_bytes.length+bytes_to_write];
		System.arraycopy(addr_bytes, 0, buffer, 0, addr_bytes.length);
		System.arraycopy(data, data.length - bytes_remaining, buffer, addr_bytes.length, bytes_to_write);
		device.write(buffer);
		
		bytes_remaining -= bytes_to_write;
		page++;
		address = page * type.getPageSizeBytes();
		
		SleepUtil.sleepMillis(type.getWriteCycleTimeMillis());
	} while (bytes_remaining > 0);
}
 
Example 5
Source File: MFRC522Test.java    From diozero with MIT License 5 votes vote down vote up
public static void main(String[] args) {
	if (args.length < 3) {
		Logger.error("Usage: {} <spi-controller> <chip-select> <rst-gpio>", MFRC522Test.class.getName());
		System.exit(1);
	}
	int index = 0;
	int controller = Integer.parseInt(args[index++]);
	int chip_select = Integer.parseInt(args[index++]);
	int reset_pin = Integer.parseInt(args[index++]);
	
	waitForCard(controller, chip_select, reset_pin);
}
 
Example 6
Source File: DiozeroProtosConverter.java    From diozero with MIT License 5 votes vote down vote up
public static GpioEventTrigger convert(DiozeroProtos.Gpio.Trigger trigger) {
	switch (trigger) {
	case TRIGGER_NONE:
		return GpioEventTrigger.NONE;
	case TRIGGER_RISING:
		return GpioEventTrigger.RISING;
	case TRIGGER_FALLING:
		return GpioEventTrigger.FALLING;
	case TRIGGER_BOTH:
		return GpioEventTrigger.BOTH;
	default:
		Logger.error("Invalid Gpio.Trigger value: {}", trigger);
		return GpioEventTrigger.BOTH;
	}
}
 
Example 7
Source File: LEDTest.java    From diozero with MIT License 5 votes vote down vote up
public static void main(String[] args) {
	if (args.length < 1) {
		Logger.error("Usage: {} <gpio>", LEDTest.class.getName());
		System.exit(1);
	}
	test(Integer.parseInt(args[0]));
}
 
Example 8
Source File: DiozeroProtosConverter.java    From diozero with MIT License 5 votes vote down vote up
public static DiozeroProtos.Gpio.Trigger convert(GpioEventTrigger trigger) {
	switch (trigger) {
	case NONE:
		return DiozeroProtos.Gpio.Trigger.TRIGGER_NONE;
	case RISING:
		return DiozeroProtos.Gpio.Trigger.TRIGGER_RISING;
	case FALLING:
		return DiozeroProtos.Gpio.Trigger.TRIGGER_FALLING;
	case BOTH:
		return DiozeroProtos.Gpio.Trigger.TRIGGER_BOTH;
	default:
		Logger.error("Invalid GpioEventTrigger value: {}", trigger);
		return DiozeroProtos.Gpio.Trigger.TRIGGER_BOTH;
	}
}
 
Example 9
Source File: MCP23017Test.java    From diozero with MIT License 5 votes vote down vote up
public static void test(int intAPin, int intBPin, int inputPin, int outputPin) {
	try (MCP23017 mcp23017 = new MCP23017(intAPin, intBPin);
			Button button = new Button(mcp23017, inputPin, GpioPullUpDown.PULL_UP);
			LED led = new LED(mcp23017, outputPin)) {
		Logger.debug("On");
		led.on();
		SleepUtil.sleepSeconds(1);

		Logger.debug("Off");
		led.off();
		SleepUtil.sleepSeconds(1);

		Logger.debug("Blink");
		led.blink(0.5f, 0.5f, 10, false);

		button.whenPressed(led::on);
		button.whenReleased(led::off);

		Logger.debug("Waiting for 10s - *** Press the button connected to MCP23017 pin {} ***",
				Integer.valueOf(inputPin));
		SleepUtil.sleepSeconds(10);
		button.whenPressed(null);
		button.whenReleased(null);
	} catch (RuntimeIOException e) {
		Logger.error(e, "Error: {}", e);
	}

	Logger.debug("Done");
}
 
Example 10
Source File: LDRListenerTestMcpAdc.java    From diozero with MIT License 5 votes vote down vote up
public static void test(McpAdc.Type type, int chipSelect, int pin, float vRef, int r1) {
	try (McpAdc adc = new McpAdc(type, chipSelect, vRef); LDR ldr = new LDR(adc, pin, r1)) {
		ldr.addListener((event) -> Logger.info("valueChanged({})", event));
		SleepUtil.sleepSeconds(10);
	} catch (RuntimeIOException e) {
		Logger.error(e, "Error: {}", e);
	}
}
 
Example 11
Source File: DataStaxSessionFactory.java    From cassandra-jdbc-driver with Apache License 2.0 5 votes vote down vote up
static DataStaxSessionWrapper getSession(final CassandraConfiguration config, final String keyspace) {
    final String targetKeyspace = Strings.isNullOrEmpty(keyspace)
            || config.getKeyspace().equals(keyspace) ? config.getKeyspace() : keyspace;
    DataStaxSessionWrapper session = null;

    try {
        session = _sessionCache.get(config.getConnectionUrl(), new Callable<DataStaxSessionWrapper>() {
            public DataStaxSessionWrapper call() throws Exception {
                return newSession(config, targetKeyspace);
            }
        });

        if (session.isClosed() || !session.getLoggedKeyspace().equals(targetKeyspace)) {
            // FIXME this will cause connection issues in other threads
            _sessionCache.invalidate(config.getConnectionUrl());
            session = getSession(config, targetKeyspace);
        }

        // active the session and increase the reference counter
        session.open();
    } catch (Exception e) {
        Logger.error(e, "Failed to obtain session object");
        throw new RuntimeException(e);
    }

    return session;
}
 
Example 12
Source File: ButtonControlledLed.java    From diozero with MIT License 5 votes vote down vote up
public static void main(String[] args) {
	if (args.length < 2) {
		Logger.error("Usage: {} <button-pin> <led-pin>", ButtonControlledLed.class.getName());
		System.exit(1);
	}
	test(Integer.parseInt(args[0]), Integer.parseInt(args[1]));
}
 
Example 13
Source File: AdcListenerTest.java    From diozero with MIT License 5 votes vote down vote up
public static void test(int adcNumber, float vRef) {
	try (AnalogInputDevice adc = new AnalogInputDevice(adcNumber, vRef)) {
		//adc.addListener((event) -> Logger.info("valueChanged({})", event));
		for (int i = 0; i < 10; i++) {
			Logger.info("Scaled: {}, Unscaled: {}", Float.valueOf(adc.getScaledValue()),
					Float.valueOf(adc.getUnscaledValue()));
			SleepUtil.sleepSeconds(1);
		}
	} catch (RuntimeIOException e) {
		Logger.error(e, "Error: {}", e);
	}
}
 
Example 14
Source File: DiozeroProtosConverter.java    From diozero with MIT License 5 votes vote down vote up
public static DiozeroProtos.Gpio.PullUpDown convert(GpioPullUpDown pud) {
	switch (pud) {
	case NONE:
		return DiozeroProtos.Gpio.PullUpDown.PUD_NONE;
	case PULL_DOWN:
		return DiozeroProtos.Gpio.PullUpDown.PUD_PULL_DOWN;
	case PULL_UP:
		return DiozeroProtos.Gpio.PullUpDown.PUD_PULL_UP;
	default:
		Logger.error("Invalid GpioPullUpDown value: {}", pud);
		return DiozeroProtos.Gpio.PullUpDown.PUD_NONE;
	}
}
 
Example 15
Source File: CLIMain.java    From dragonite-java with Apache License 2.0 5 votes vote down vote up
private static ProxyClientConfig clientConfigFromConfigParser(final ProxyJSONConfigParser configParser) {
    try {
        return configParser.getClientConfig();
    } catch (final JSONConfigException e) {
        Logger.error(e, "Failed to parse config");
        return null;
    }
}
 
Example 16
Source File: InputWaitTest.java    From diozero with MIT License 5 votes vote down vote up
public static void main(String[] args) {
	if (args.length < 1) {
		Logger.error("Usage: {} <input-pin>", InputWaitTest.class.getName());
		System.exit(1);
	}
	test(Integer.parseInt(args[0]));
}
 
Example 17
Source File: MCP23xxx.java    From diozero with MIT License 4 votes vote down vote up
@Override
@SuppressWarnings("resource")
public void valueChanged(DigitalInputEvent event) {
	Logger.debug("valueChanged({})", event);
	
	if (! event.getValue()) {
		Logger.info("valueChanged(): value was false - ignoring");
		return;
	}
	
	// Check the event is for one of the interrupt gpios
	boolean process_event = false;
	for (DigitalInputDevice interrupt_gpio : interruptGpios) {
		if (interrupt_gpio != null && event.getGpio() == interrupt_gpio.getGpio()) {
			process_event = true;
			break;
		}
	}
	if (! process_event) {
		Logger.error("Unexpected interrupt event on gpio {}", Integer.valueOf(event.getGpio()));
		return;
	}
	
	synchronized (this) {
		try {
			byte[] intf = new byte[2];
			byte[] intcap = new byte[2];
			if (interruptMode == InterruptMode.MIRRORED) {
				intf[0] = readByte(getIntFReg(0));
				intcap[0] = readByte(getIntCapReg(0));
				intf[1] = readByte(getIntFReg(1));
				intcap[1] = readByte(getIntCapReg(1));
			} else if (interruptMode != InterruptMode.DISABLED) {
				if (interruptGpios[0] != null && event.getGpio() == interruptGpios[0].getGpio()) {
					intf[0] = readByte(getIntFReg(0));
					intcap[0] = readByte(getIntCapReg(0));
				} else {
					intf[1] = readByte(getIntFReg(1));
					intcap[1] = readByte(getIntCapReg(1));
				}
			}
			for (int port=0; port<numPorts; port++) {
				for (byte bit=0; bit<8; bit++) {
					if (BitManipulation.isBitSet(intf[port], bit)) {
						int gpio = bit + port*8;
						boolean value = BitManipulation.isBitSet(intcap[port], bit);
						DigitalInputEvent e = new DigitalInputEvent(gpio, event.getEpochTime(), event.getNanoTime(), value);
						// Notify the appropriate input device
						MCP23xxxDigitalInputDevice in_device = getInputDevice((byte) gpio);
						if (in_device != null) {
							in_device.valueChanged(e);
						}
					}
				}
			}
		} catch (Throwable t) {
			// Log and ignore
			Logger.error(t, "IO error handling interrupts: {}", t);
		}
	}
}
 
Example 18
Source File: ReadBlock.java    From diozero with MIT License 4 votes vote down vote up
public static void main(String[] args) {
	if (args.length < 5) {
		Logger.error("Usage: {} <spi-controller> <chip-select> <rst-gpio> <auth-key-hex> <sector> [use-key-a=true]", ReadBlock.class.getName());
		System.exit(1);
	}
	int index = 0;
	int controller = Integer.parseInt(args[index++]);
	int chip_select = Integer.parseInt(args[index++]);
	int reset_pin = Integer.parseInt(args[index++]);
	byte[] auth_key = Hex.decodeHex(args[index++]);
	byte sector = Byte.parseByte(args[index++]);
	boolean use_key_a = true;
	if (args.length > 5) {
		use_key_a = Boolean.parseBoolean(args[index++]);
	}
	
	int blocks_per_sector = 4;
	byte block_start_addr = (byte) (sector * blocks_per_sector);
	byte block_end_addr = (byte) (block_start_addr + blocks_per_sector - 1);
	
	try (MFRC522 rfid = new MFRC522(controller, chip_select, reset_pin)) {
		while (true) {
			Logger.info("Scanning for RFID tags...");
			MFRC522.UID uid = null;
			while (uid == null) {
				SleepUtil.sleepSeconds(1);
				if (rfid.isNewCardPresent()) {
					uid = rfid.readCardSerial();
				}
			}
			Logger.info("Found card with UID 0x{}, type: {}", Hex.encodeHexString(uid.getUidBytes()), uid.getType());
			
			// Authenticate using key A or B
			Logger.info("Authenticating using key {}...", use_key_a ? "A" : "B");
			StatusCode status = rfid.authenticate(use_key_a, block_end_addr, auth_key, uid);
			Logger.info("Authentication status: {}", status);
			if (status == StatusCode.OK) {
				/*
				 * MIFARE Classic 1K (MF1S503x):
					 * 	Has 16 sectors * 4 blocks/sector * 16 bytes/block = 1024 bytes.
					 * 	The blocks are numbered 0-63.
					 * 	Block 3 in each sector is the Sector Trailer. See http://www.mouser.com/ds/2/302/MF1S503x-89574.pdf sections 8.6 and 8.7:
					 * 		Bytes 0-5:   Key A
					 * 		Bytes 6-8:   Access Bits
					 * 		Bytes 9:     User data
					 * 		Bytes 10-15: Key B (or user data)
					 * 	Block 0 is read-only manufacturer data.
					 * 	To access a block, an authentication using a key from the block's sector must be performed first.
					 * 	Example: To read from block 10, first authenticate using a key from sector 3 (blocks 8-11).
				 */
				byte[] data = rfid.mifareRead(block_start_addr);
				if (data == null) {
					Logger.info("Unable to read data on block 0x{}", Integer.toHexString(block_start_addr));
				} else {
					Logger.info("Data on block 0x{}: 0x{}", Integer.toHexString(block_start_addr), Hex.encodeHexString(data));
				}
				rfid.dumpMifareClassicSectorToConsole(uid, auth_key, sector);
			}
			
			// Halt PICC
			rfid.haltA();
			
			// Stop encryption on PCD
			rfid.stopCrypto1();
		}
	}
}
 
Example 19
Source File: ProxyClient.java    From dragonite-java with Apache License 2.0 4 votes vote down vote up
private void prepareUnderlyingConnection(final DragoniteSocketParameters dragoniteSocketParameters) throws IOException, InterruptedException, DragoniteException, ServerRejectedException, IncorrectHeaderException {
    dragoniteClientSocket = new DragoniteClientSocket(remoteAddress, UnitConverter.mbpsToSpeed(upMbps), dragoniteSocketParameters);
    dragoniteClientSocket.setDescription("Proxy");

    try {
        //Send info header
        final byte[] infoHeaderBytes = new ClientInfoHeader(downMbps, upMbps, SystemInfo.getUsername(), ProxyGlobalConstants.APP_VERSION, SystemInfo.getOS()).toBytes();
        dragoniteClientSocket.send(infoHeaderBytes);

        //Receive response
        final byte[] response = dragoniteClientSocket.read();
        final ServerResponseHeader responseHeader = new ServerResponseHeader(response);

        //Check response
        if (responseHeader.getStatus() != 0) {
            Logger.error("The server has rejected this connection (Error code {}): {}", responseHeader.getStatus(), responseHeader.getMsg());
            throw new ServerRejectedException(responseHeader.getMsg());
        } else if (responseHeader.getMsg().length() > 0) {
            Logger.info("Server welcome message: {}", responseHeader.getMsg());
        }

    } catch (final InterruptedException | IOException | DragoniteException | IncorrectHeaderException | ServerRejectedException e) {
        Logger.error(e, "Unable to connect to remote server");
        try {
            dragoniteClientSocket.closeGracefully();
        } catch (InterruptedException | SenderClosedException | IOException ignored) {
        }
        throw e;
    }

    multiplexer = new Multiplexer(bytes -> {
        try {
            dragoniteClientSocket.send(bytes);
        } catch (InterruptedException | IncorrectSizeException | IOException | SenderClosedException e) {
            Logger.error(e, "Multiplexer is unable to send data");
        }
    }, ProxyGlobalConstants.MAX_FRAME_SIZE);

    if (muxReceiveThread != null) muxReceiveThread.interrupt();

    muxReceiveThread = new Thread(() -> {
        byte[] buf;
        try {
            while ((buf = dragoniteClientSocket.read()) != null) {
                multiplexer.onReceiveBytes(buf);
            }
        } catch (InterruptedException | ConnectionNotAliveException e) {
            Logger.error(e, "Cannot receive data from underlying socket");
        } finally {
            synchronized (connectLock) {
                try {
                    dragoniteClientSocket.closeGracefully();
                } catch (final Exception ignored) {
                }
                multiplexer.close();
            }
        }
    }, "PC-MuxReceive");
    muxReceiveThread.start();

    Logger.info("Connection established with {}", remoteAddress.toString());
}
 
Example 20
Source File: ProtobufMqttProtocolHandler.java    From diozero with MIT License 4 votes vote down vote up
@Override
public void messageArrived(String topic, MqttMessage message) {
	Logger.debug("topic: {}", topic);

	try {
		switch (topic) {
		case MqttProviderConstants.RESPONSE_TOPIC:
			DiozeroProtos.Response response = DiozeroProtos.Response.parseFrom(message.getPayload());
			processResponse(DiozeroProtosConverter.convert(response));
			break;
		case MqttProviderConstants.GPIO_DIGITAL_READ_RESPONSE_TOPIC:
			DiozeroProtos.Gpio.DigitalReadResponse digital_read_response = DiozeroProtos.Gpio.DigitalReadResponse
					.parseFrom(message.getPayload());
			processResponse(DiozeroProtosConverter.convert(digital_read_response));
			break;
		case MqttProviderConstants.GPIO_PWM_READ_RESPONSE_TOPIC:
			DiozeroProtos.Gpio.PwmReadResponse pwm_read_response = DiozeroProtos.Gpio.PwmReadResponse
					.parseFrom(message.getPayload());
			processResponse(DiozeroProtosConverter.convert(pwm_read_response));
			break;
		case MqttProviderConstants.GPIO_ANALOG_READ_RESPONSE_TOPIC:
			DiozeroProtos.Gpio.AnalogReadResponse analog_read_response = DiozeroProtos.Gpio.AnalogReadResponse
					.parseFrom(message.getPayload());
			processResponse(DiozeroProtosConverter.convert(analog_read_response));
			break;
		case MqttProviderConstants.GPIO_NOTIFICATION_TOPIC:
			processEvent(DiozeroProtosConverter
					.convert(DiozeroProtos.Gpio.Notification.parseFrom(message.getPayload())));
			break;
		case MqttProviderConstants.I2C_READ_BYTE_RESPONSE_TOPIC:
			DiozeroProtos.I2C.ReadByteResponse i2c_read_byte_response = DiozeroProtos.I2C.ReadByteResponse
					.parseFrom(message.getPayload());
			processResponse(DiozeroProtosConverter.convert(i2c_read_byte_response));
			break;
		case MqttProviderConstants.I2C_READ_RESPONSE_TOPIC:
			DiozeroProtos.I2C.ReadResponse i2c_read_response = DiozeroProtos.I2C.ReadResponse
					.parseFrom(message.getPayload());
			processResponse(DiozeroProtosConverter.convert(i2c_read_response));
			break;
		case MqttProviderConstants.SPI_RXDATA_RESPONSE_TOPIC:
			DiozeroProtos.Spi.SpiResponse spi_response = DiozeroProtos.Spi.SpiResponse
					.parseFrom(message.getPayload());
			processResponse(DiozeroProtosConverter.convert(spi_response));
			break;
		default:
			Logger.warn("Unrecognised topic {}", topic);
		}
	} catch (InvalidProtocolBufferException e) {
		Logger.error(e, "Error: {}", e);
	}
}