List of usage examples for java.nio ByteBuffer putShort
public abstract ByteBuffer putShort(short value);
From source file:nodomain.freeyourgadget.gadgetbridge.service.devices.pebble.PebbleProtocol.java
@Override public byte[] encodeAppStart(UUID uuid, boolean start) { if (mFwMajor >= 3) { final short LENGTH_APPRUNSTATE = 17; ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + LENGTH_APPRUNSTATE); buf.order(ByteOrder.BIG_ENDIAN); buf.putShort(LENGTH_APPRUNSTATE); buf.putShort(ENDPOINT_APPRUNSTATE); buf.put(start ? APPRUNSTATE_START : APPRUNSTATE_STOP); buf.putLong(uuid.getMostSignificantBits()); buf.putLong(uuid.getLeastSignificantBits()); return buf.array(); } else {//from www. ja va 2s. c om ArrayList<Pair<Integer, Object>> pairs = new ArrayList<>(); int param = start ? 1 : 0; pairs.add(new Pair<>(1, (Object) param)); return encodeApplicationMessagePush(ENDPOINT_LAUNCHER, uuid, pairs); } }
From source file:nodomain.freeyourgadget.gadgetbridge.service.devices.pebble.PebbleProtocol.java
@Override public byte[] encodeSetMusicInfo(String artist, String album, String track, int duration, int trackCount, int trackNr) { String[] parts = { artist, album, track }; if (duration == 0 || mFwMajor < 3) { return encodeMessage(ENDPOINT_MUSICCONTROL, MUSICCONTROL_SETMUSICINFO, 0, parts); } else {/*from w w w . j av a 2 s . com*/ // Calculate length first int length = LENGTH_PREFIX + 9; if (parts != null) { for (String s : parts) { if (s == null || s.equals("")) { length++; // encode null or empty strings as 0x00 later continue; } length += (1 + s.getBytes().length); } } // Encode Prefix ByteBuffer buf = ByteBuffer.allocate(length); buf.order(ByteOrder.BIG_ENDIAN); buf.putShort((short) (length - LENGTH_PREFIX)); buf.putShort(ENDPOINT_MUSICCONTROL); buf.put(MUSICCONTROL_SETMUSICINFO); // Encode Pascal-Style Strings for (String s : parts) { if (s == null || s.equals("")) { buf.put((byte) 0x00); continue; } int partlength = s.getBytes().length; if (partlength > 255) partlength = 255; buf.put((byte) partlength); buf.put(s.getBytes(), 0, partlength); } buf.order(ByteOrder.LITTLE_ENDIAN); buf.putInt(duration * 1000); buf.putShort((short) (trackCount & 0xffff)); buf.putShort((short) (trackNr & 0xffff)); return buf.array(); } }
From source file:nodomain.freeyourgadget.gadgetbridge.service.devices.pebble.PebbleProtocol.java
@Override public byte[] encodeAppDelete(UUID uuid) { if (mFwMajor >= 3) { if (UUID_PEBBLE_HEALTH.equals(uuid)) { return encodeActivateHealth(false); }/*from ww w.j a v a 2 s. co m*/ if (UUID_WORKOUT.equals(uuid)) { return encodeActivateHRM(false); } if (UUID_WEATHER.equals(uuid)) { //TODO: probably it wasn't present in firmware 3 return encodeActivateWeather(false); } return encodeBlobdb(uuid, BLOBDB_DELETE, BLOBDB_APP, null); } else { final short LENGTH_REMOVEAPP_2X = 17; ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + LENGTH_REMOVEAPP_2X); buf.order(ByteOrder.BIG_ENDIAN); buf.putShort(LENGTH_REMOVEAPP_2X); buf.putShort(ENDPOINT_APPMANAGER); buf.put(APPMANAGER_REMOVEAPP); buf.putLong(uuid.getMostSignificantBits()); buf.putLong(uuid.getLeastSignificantBits()); return buf.array(); } }
From source file:com.healthmarketscience.jackcess.impl.TableImpl.java
/** * Serialize a row of Objects into a byte buffer. * /* w w w. j a v a 2 s.c om*/ * @param rowArray row data, expected to be correct length for this table * @param buffer buffer to which to write the row data * @param minRowSize min size for result row * @param rawVarValues optional, pre-written values for var length columns * (enables re-use of previously written values). * @return the given buffer, filled with the row data */ private ByteBuffer createRow(Object[] rowArray, ByteBuffer buffer, int minRowSize, Map<ColumnImpl, byte[]> rawVarValues) throws IOException { buffer.putShort(_maxColumnCount); NullMask nullMask = new NullMask(_maxColumnCount); //Fixed length column data comes first int fixedDataStart = buffer.position(); int fixedDataEnd = fixedDataStart; for (ColumnImpl col : _columns) { if (col.isVariableLength()) { continue; } Object rowValue = col.getRowValue(rowArray); if (col.storeInNullMask()) { if (col.writeToNullMask(rowValue)) { nullMask.markNotNull(col); } rowValue = null; } if (rowValue != null) { // we have a value to write nullMask.markNotNull(col); // remainingRowLength is ignored when writing fixed length data buffer.position(fixedDataStart + col.getFixedDataOffset()); buffer.put(col.write(rowValue, 0)); } // always insert space for the entire fixed data column length // (including null values), access expects the row to always be at least // big enough to hold all fixed values buffer.position(fixedDataStart + col.getFixedDataOffset() + col.getLength()); // keep track of the end of fixed data if (buffer.position() > fixedDataEnd) { fixedDataEnd = buffer.position(); } } // reposition at end of fixed data buffer.position(fixedDataEnd); // only need this info if this table contains any var length data if (_maxVarColumnCount > 0) { int maxRowSize = getFormat().MAX_ROW_SIZE; // figure out how much space remains for var length data. first, // account for already written space maxRowSize -= buffer.position(); // now, account for trailer space int trailerSize = (nullMask.byteSize() + 4 + (_maxVarColumnCount * 2)); maxRowSize -= trailerSize; // for each non-null long value column we need to reserve a small // amount of space so that we don't end up running out of row space // later by being too greedy for (ColumnImpl varCol : _varColumns) { if ((varCol.getType().isLongValue()) && (varCol.getRowValue(rowArray) != null)) { maxRowSize -= getFormat().SIZE_LONG_VALUE_DEF; } } //Now write out variable length column data short[] varColumnOffsets = new short[_maxVarColumnCount]; int varColumnOffsetsIndex = 0; for (ColumnImpl varCol : _varColumns) { short offset = (short) buffer.position(); Object rowValue = varCol.getRowValue(rowArray); if (rowValue != null) { // we have a value nullMask.markNotNull(varCol); byte[] rawValue = null; ByteBuffer varDataBuf = null; if (((rawValue = rawVarValues.get(varCol)) != null) && (rawValue.length <= maxRowSize)) { // save time and potentially db space, re-use raw value varDataBuf = ByteBuffer.wrap(rawValue); } else { // write column value varDataBuf = varCol.write(rowValue, maxRowSize); } maxRowSize -= varDataBuf.remaining(); if (varCol.getType().isLongValue()) { // we already accounted for some amount of the long value data // above. add that space back so we don't double count maxRowSize += getFormat().SIZE_LONG_VALUE_DEF; } buffer.put(varDataBuf); } // we do a loop here so that we fill in offsets for deleted columns while (varColumnOffsetsIndex <= varCol.getVarLenTableIndex()) { varColumnOffsets[varColumnOffsetsIndex++] = offset; } } // fill in offsets for any remaining deleted columns while (varColumnOffsetsIndex < varColumnOffsets.length) { varColumnOffsets[varColumnOffsetsIndex++] = (short) buffer.position(); } // record where we stopped writing int eod = buffer.position(); // insert padding if necessary padRowBuffer(buffer, minRowSize, trailerSize); buffer.putShort((short) eod); //EOD marker //Now write out variable length offsets //Offsets are stored in reverse order for (int i = _maxVarColumnCount - 1; i >= 0; i--) { buffer.putShort(varColumnOffsets[i]); } buffer.putShort(_maxVarColumnCount); //Number of var length columns } else { // insert padding for row w/ no var cols padRowBuffer(buffer, minRowSize, nullMask.byteSize()); } nullMask.write(buffer); //Null mask buffer.flip(); return buffer; }
From source file:nodomain.freeyourgadget.gadgetbridge.service.devices.pebble.PebbleProtocol.java
private byte[] encodeBlobdb(Object key, byte command, byte db, byte[] blob) { int length = 5; int key_length; if (key instanceof UUID) { key_length = LENGTH_UUID; } else if (key instanceof String) { key_length = ((String) key).getBytes().length; } else {/*www . j a v a 2s . c o m*/ LOG.warn("unknown key type"); return null; } if (key_length > 255) { LOG.warn("key is too long"); return null; } length += key_length; if (blob != null) { length += blob.length + 2; } ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + length); buf.order(ByteOrder.BIG_ENDIAN); buf.putShort((short) length); buf.putShort(ENDPOINT_BLOBDB); buf.order(ByteOrder.LITTLE_ENDIAN); buf.put(command); buf.putShort((short) mRandom.nextInt()); // token buf.put(db); buf.put((byte) key_length); if (key instanceof UUID) { UUID uuid = (UUID) key; buf.order(ByteOrder.BIG_ENDIAN); buf.putLong(uuid.getMostSignificantBits()); buf.putLong(uuid.getLeastSignificantBits()); buf.order(ByteOrder.LITTLE_ENDIAN); } else { buf.put(((String) key).getBytes()); } if (blob != null) { buf.putShort((short) blob.length); buf.put(blob); } return buf.array(); }
From source file:nodomain.freeyourgadget.gadgetbridge.service.devices.pebble.PebbleProtocol.java
byte[] encodeApplicationMessagePush(short endpoint, UUID uuid, ArrayList<Pair<Integer, Object>> pairs) { int length = LENGTH_UUID + 3; // UUID + (PUSH + id + length of dict) for (Pair<Integer, Object> pair : pairs) { if (pair.first == null || pair.second == null) continue; length += 7; // key + type + length if (pair.second instanceof Integer) { length += 4;// ww w .j a v a 2 s. c o m } else if (pair.second instanceof Short) { length += 2; } else if (pair.second instanceof Byte) { length += 1; } else if (pair.second instanceof String) { length += ((String) pair.second).getBytes().length + 1; } else if (pair.second instanceof byte[]) { length += ((byte[]) pair.second).length; } else { LOG.warn("unknown type: " + pair.second.getClass().toString()); } } ByteBuffer buf = ByteBuffer.allocate(LENGTH_PREFIX + length); buf.order(ByteOrder.BIG_ENDIAN); buf.putShort((short) length); buf.putShort(endpoint); // 48 or 49 buf.put(APPLICATIONMESSAGE_PUSH); buf.put(++last_id); buf.putLong(uuid.getMostSignificantBits()); buf.putLong(uuid.getLeastSignificantBits()); buf.put((byte) pairs.size()); buf.order(ByteOrder.LITTLE_ENDIAN); for (Pair<Integer, Object> pair : pairs) { if (pair.first == null || pair.second == null) continue; buf.putInt(pair.first); if (pair.second instanceof Integer) { buf.put(TYPE_INT); buf.putShort((short) 4); // length buf.putInt((int) pair.second); } else if (pair.second instanceof Short) { buf.put(TYPE_INT); buf.putShort((short) 2); // length buf.putShort((short) pair.second); } else if (pair.second instanceof Byte) { buf.put(TYPE_INT); buf.putShort((short) 1); // length buf.put((byte) pair.second); } else if (pair.second instanceof String) { String str = (String) pair.second; buf.put(TYPE_CSTRING); buf.putShort((short) (str.getBytes().length + 1)); buf.put(str.getBytes()); buf.put((byte) 0); } else if (pair.second instanceof byte[]) { byte[] bytes = (byte[]) pair.second; buf.put(TYPE_BYTEARRAY); buf.putShort((short) bytes.length); buf.put(bytes); } } return buf.array(); }
From source file:nodomain.freeyourgadget.gadgetbridge.service.devices.pebble.PebbleProtocol.java
private byte[] encodeWeatherForecast(WeatherSpec weatherSpec) { final short WEATHER_FORECAST_LENGTH = 20; String[] parts = { weatherSpec.location, weatherSpec.currentCondition }; // Calculate length first short attributes_length = 0; if (parts != null) { for (String s : parts) { if (s == null || s.equals("")) { continue; }/* w w w . jav a 2s . c om*/ attributes_length += (2 + s.getBytes().length); } } short pin_length = (short) (WEATHER_FORECAST_LENGTH + attributes_length); ByteBuffer buf = ByteBuffer.allocate(pin_length); buf.order(ByteOrder.LITTLE_ENDIAN); buf.put((byte) 3); // unknown, always 3? buf.putShort((short) (weatherSpec.currentTemp - 273)); buf.put(Weather.mapToPebbleCondition(weatherSpec.currentConditionCode)); buf.putShort((short) (weatherSpec.todayMaxTemp - 273)); buf.putShort((short) (weatherSpec.todayMinTemp - 273)); buf.put(Weather.mapToPebbleCondition(weatherSpec.tomorrowConditionCode)); buf.putShort((short) (weatherSpec.tomorrowMaxTemp - 273)); buf.putShort((short) (weatherSpec.tomorrowMinTemp - 273)); buf.putInt(weatherSpec.timestamp); buf.put((byte) 0); // automatic location 0=manual 1=auto buf.putShort(attributes_length); // Encode Pascal-Style Strings if (parts != null) { for (String s : parts) { if (s == null || s.equals("")) { continue; } int partlength = s.getBytes().length; if (partlength > 512) partlength = 512; buf.putShort((short) partlength); buf.put(s.getBytes(), 0, partlength); } } return encodeBlobdb(UUID_LOCATION, BLOBDB_INSERT, BLOBDB_WEATHER, buf.array()); }
From source file:nodomain.freeyourgadget.gadgetbridge.service.devices.pebble.PebbleProtocol.java
private byte[] encodeExtensibleNotification(int id, int timestamp, String title, String subtitle, String body, String sourceName, boolean hasHandle, String[] cannedReplies) { final short ACTION_LENGTH_MIN = 10; String[] parts = { title, subtitle, body }; // Calculate length first byte actions_count; short actions_length; String dismiss_string;//from w w w . j a va2 s. co m String open_string = "Open on phone"; String mute_string = "Mute"; String reply_string = "Reply"; if (sourceName != null) { mute_string += " " + sourceName; } byte dismiss_action_id; if (hasHandle && !"ALARMCLOCKRECEIVER".equals(sourceName)) { actions_count = 3; dismiss_string = "Dismiss"; dismiss_action_id = 0x02; actions_length = (short) (ACTION_LENGTH_MIN * actions_count + dismiss_string.getBytes().length + open_string.getBytes().length + mute_string.getBytes().length); } else { actions_count = 1; dismiss_string = "Dismiss all"; dismiss_action_id = 0x03; actions_length = (short) (ACTION_LENGTH_MIN * actions_count + dismiss_string.getBytes().length); } int replies_length = -1; if (cannedReplies != null && cannedReplies.length > 0) { actions_count++; for (String reply : cannedReplies) { replies_length += reply.getBytes().length + 1; } actions_length += ACTION_LENGTH_MIN + reply_string.getBytes().length + replies_length + 3; // 3 = attribute id (byte) + length(short) } byte attributes_count = 0; int length = 21 + 10 + actions_length; if (parts != null) { for (String s : parts) { if (s == null || s.equals("")) { continue; } attributes_count++; length += (3 + s.getBytes().length); } } // Encode Prefix ByteBuffer buf = ByteBuffer.allocate(length + LENGTH_PREFIX); buf.order(ByteOrder.BIG_ENDIAN); buf.putShort((short) (length)); buf.putShort(ENDPOINT_EXTENSIBLENOTIFS); buf.order(ByteOrder.LITTLE_ENDIAN); // ! buf.put((byte) 0x00); // ? buf.put((byte) 0x01); // add notifications buf.putInt(0x00000000); // flags - ? buf.putInt(id); buf.putInt(0x00000000); // ANCS id buf.putInt(timestamp); buf.put((byte) 0x01); // layout - ? buf.put(attributes_count); buf.put(actions_count); byte attribute_id = 0; // Encode Pascal-Style Strings if (parts != null) { for (String s : parts) { attribute_id++; if (s == null || s.equals("")) { continue; } int partlength = s.getBytes().length; if (partlength > 255) partlength = 255; buf.put(attribute_id); buf.putShort((short) partlength); buf.put(s.getBytes(), 0, partlength); } } // dismiss action buf.put(dismiss_action_id); buf.put((byte) 0x04); // dismiss buf.put((byte) 0x01); // number attributes buf.put((byte) 0x01); // attribute id (title) buf.putShort((short) dismiss_string.getBytes().length); buf.put(dismiss_string.getBytes()); // open and mute actions if (hasHandle && !"ALARMCLOCKRECEIVER".equals(sourceName)) { buf.put((byte) 0x01); buf.put((byte) 0x02); // generic buf.put((byte) 0x01); // number attributes buf.put((byte) 0x01); // attribute id (title) buf.putShort((short) open_string.getBytes().length); buf.put(open_string.getBytes()); buf.put((byte) 0x04); buf.put((byte) 0x02); // generic buf.put((byte) 0x01); // number attributes buf.put((byte) 0x01); // attribute id (title) buf.putShort((short) mute_string.getBytes().length); buf.put(mute_string.getBytes()); } if (cannedReplies != null && replies_length > 0) { buf.put((byte) 0x05); buf.put((byte) 0x03); // reply action buf.put((byte) 0x02); // number attributes buf.put((byte) 0x01); // title buf.putShort((short) reply_string.getBytes().length); buf.put(reply_string.getBytes()); buf.put((byte) 0x08); // canned replies buf.putShort((short) replies_length); for (int i = 0; i < cannedReplies.length - 1; i++) { buf.put(cannedReplies[i].getBytes()); buf.put((byte) 0x00); } // last one must not be zero terminated, else we get an additional emply reply buf.put(cannedReplies[cannedReplies.length - 1].getBytes()); } return buf.array(); }
From source file:nodomain.freeyourgadget.gadgetbridge.service.devices.pebble.PebbleProtocol.java
byte[] encodeActivateHealth(boolean activate) { byte[] blob;/* w w w .j a v a 2 s .c om*/ if (activate) { ByteBuffer buf = ByteBuffer.allocate(9); buf.order(ByteOrder.LITTLE_ENDIAN); ActivityUser activityUser = new ActivityUser(); Integer heightMm = activityUser.getHeightCm() * 10; buf.putShort(heightMm.shortValue()); Integer weigthDag = activityUser.getWeightKg() * 100; buf.putShort(weigthDag.shortValue()); buf.put((byte) 0x01); //activate tracking buf.put((byte) 0x00); //activity Insights buf.put((byte) 0x00); //sleep Insights buf.put((byte) activityUser.getAge()); buf.put((byte) activityUser.getGender()); blob = buf.array(); } else { blob = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; } return encodeBlobdb("activityPreferences", BLOBDB_INSERT, BLOBDB_PREFERENCES, blob); }
From source file:com.healthmarketscience.jackcess.impl.IndexData.java
/** * Writes the index definitions into a table definition buffer. * @param buffer Buffer to write to//from ww w.j a va2 s . co m * @param indexes List of IndexBuilders to write definitions for */ protected static void writeDefinitions(TableCreator creator, ByteBuffer buffer) throws IOException { ByteBuffer rootPageBuffer = creator.getPageChannel().createPageBuffer(); writeDataPage(rootPageBuffer, NEW_ROOT_DATA_PAGE, creator.getTdefPageNumber(), creator.getFormat()); for (IndexBuilder idx : creator.getIndexes()) { buffer.putInt(MAGIC_INDEX_NUMBER); // seemingly constant magic value // write column information (always MAX_COLUMNS entries) List<IndexBuilder.Column> idxColumns = idx.getColumns(); for (int i = 0; i < MAX_COLUMNS; ++i) { short columnNumber = COLUMN_UNUSED; byte flags = 0; if (i < idxColumns.size()) { // determine column info IndexBuilder.Column idxCol = idxColumns.get(i); flags = idxCol.getFlags(); // find actual table column number for (ColumnBuilder col : creator.getColumns()) { if (col.getName().equalsIgnoreCase(idxCol.getName())) { columnNumber = col.getColumnNumber(); break; } } if (columnNumber == COLUMN_UNUSED) { // should never happen as this is validated before throw new IllegalArgumentException("Column with name " + idxCol.getName() + " not found"); } } buffer.putShort(columnNumber); // table column number buffer.put(flags); // column flags (e.g. ordering) } TableCreator.IndexState idxState = creator.getIndexState(idx); buffer.put(idxState.getUmapRowNumber()); // umap row ByteUtil.put3ByteInt(buffer, creator.getUmapPageNumber()); // umap page // write empty root index page creator.getPageChannel().writePage(rootPageBuffer, idxState.getRootPageNumber()); buffer.putInt(idxState.getRootPageNumber()); buffer.putInt(0); // unknown buffer.put(idx.getFlags()); // index flags (unique, etc.) ByteUtil.forward(buffer, 5); // unknown } }