code
stringlengths 67
466k
| docstring
stringlengths 1
13.2k
|
---|---|
public static BufferedImage resizeToHeight(BufferedImage originalImage, int heightOut) {
int width = originalImage.getWidth();
int height = originalImage.getHeight();
int heightPercent = (heightOut * 100) / height;
int newWidth = (width * heightPercent) / 100;
BufferedImage resizedImage =
new BufferedImage(newWidth, heightOut, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, newWidth, heightOut, null);
g.dispose();
return resizedImage;
} | Resizes an image to the specified height, changing width in the same proportion
@param originalImage Image in memory
@param heightOut The height to resize
@return New Image in memory |
public static BufferedImage resizeToWidth(BufferedImage originalImage, int widthOut) {
int width = originalImage.getWidth();
int height = originalImage.getHeight();
int widthPercent = (widthOut * 100) / width;
int newHeight = (height * widthPercent) / 100;
BufferedImage resizedImage =
new BufferedImage(widthOut, newHeight, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, widthOut, newHeight, null);
g.dispose();
return resizedImage;
} | Resizes an image to the specified width, changing width in the same proportion
@param originalImage Image in memory
@param widthOut The width to resize
@return New Image in memory |
public static BufferedImage joinImages(List<BufferedImage> images, int lines, int height, int minHeight, boolean scale) {
// Array of input images.
List<BufferedImage> input = new ArrayList<BufferedImage>();
int actualHeight = height;
// if not scale, start from 1, so will use the max height of images, not more than that.
if (!scale) {
actualHeight = 1;
}
for (BufferedImage imageToJoin : images) {
try {
BufferedImage img = MyImageUtils.trim(imageToJoin);
if (scale) {
actualHeight = Integer.min(actualHeight, img.getHeight());
} else {
actualHeight = Integer.max(actualHeight, img.getHeight());
}
input.add(img);
} catch (Exception x) {
x.printStackTrace();
}
}
// minimum height for the posts is 480
if (scale && actualHeight < minHeight
&& input.size() > 0) {
actualHeight = minHeight;
}
int totalWidth = 0;
List<BufferedImage> fixedInput = new ArrayList<BufferedImage>();
for (BufferedImage img : input) {
BufferedImage newImg = img;
if (scale && img.getHeight() > actualHeight) {
newImg = MyImageUtils.resizeToHeight(img, actualHeight);
}
fixedInput.add(newImg);
totalWidth += newImg.getWidth();
}
// Create the output image and fill with white.
BufferedImage output = getWhiteImage(actualHeight * lines, totalWidth / lines);
drawImages(lines, scale, input, actualHeight, output.getGraphics());
return output;
} | Join images
@param images Images to join
@param lines Total of lines
@param height Image height to scale
@param minHeight Minimum height of image.
@param scale If should scale images to fit
@return Joined image |
public byte[] getData(byte[] dst, int offset)
{
final int end = Math.min(data.length, dst.length - offset) & ~0x01;
for (int i = 0; i < end; ++i)
dst[offset + i] = (byte) data[i];
return dst;
}
/**
* Sets the first translation item value from input of unit millisecond.
* <p>
* The method is for DPTs dealing with periods of time, in particular
* {@link #DPT_TIMEPERIOD}, {@link #DPT_TIMEPERIOD_10}, {@link #DPT_TIMEPERIOD_100}
* {@link #DPT_TIMEPERIOD_SEC}, {@link #DPT_TIMEPERIOD_MIN} and
* {@link #DPT_TIMEPERIOD_HOURS}. The milliseconds are converted to the unit of the
* set DPT, with the result rounded to the nearest representable value (with 0.5
* rounded up).<br>
* On any other DPT, the input is treated equal to {@link #setValue(int)}.
*
* @param milliseconds the value in milliseconds, 0 <= <code>milliseconds</code>
* @throws KNXFormatException on milliseconds out of range for DPT
*/
public final void setTimePeriod(long milliseconds) throws KNXFormatException
{
data = toDPT(milliseconds);
}
/* (non-Javadoc)
* @see tuwien.auto.calimero.dptxlator.DPTXlator#getSubTypes()
*/
public final Map getSubTypes()
{
return types;
}
/**
* @return the subtypes of the 2-byte unsigned translator type
* @see DPTXlator#getSubTypesStatic()
*/
protected static Map getSubTypesStatic()
{
return types;
}
private int fromDPT(int index)
{
final int v = (data[2 * index] << 8) | data[2 * index + 1];
if (dpt.equals(DPT_TIMEPERIOD_10))
return v * 10;
else if (dpt.equals(DPT_TIMEPERIOD_100))
return v * 100;
return v;
}
private String makeString(int index)
{
return appendUnit(String.valueOf(fromDPT(index)));
}
protected void toDPT(String value, short[] dst, int index) throws KNXFormatException
{
try {
toDPT(Integer.decode(removeUnit(value)).intValue(), dst, index);
}
catch (final NumberFormatException e) {
throw logThrow(LogLevel.WARN, "wrong value format " + value, null, value);
}
}
private short[] toDPT(long ms) throws KNXFormatException
{
// prevent round up to 0 from negative milliseconds
if (ms < 0)
throw logThrow(LogLevel.WARN, "negative input value " + Long.toString(ms),
null, Long.toString(ms));
long v = ms;
if (dpt.equals(DPT_TIMEPERIOD_SEC))
v = Math.round(ms / 1000.0);
else if (dpt.equals(DPT_TIMEPERIOD_MIN))
v = Math.round(ms / 1000.0 / 60.0);
else if (dpt.equals(DPT_TIMEPERIOD_HOURS))
v = Math.round(ms / 1000.0 / 60.0 / 60.0);
final short[] buf = new short[2];
toDPT((int) v, buf, 0);
return buf;
} | /* (non-Javadoc)
@see tuwien.auto.calimero.dptxlator.DPTXlator#getData(byte[], int) |
public static String getLine(String content, int line) {
if (content == null) {
return null;
}
String[] contentSplit = content.replace("\r\n", "\n").split("\n");
if (contentSplit.length < line) {
return null;
}
return contentSplit[line - 1];
} | Gets a specific line of a text (String)
@param content text
@param line line to get
@return the specified line |
public static String regexFindFirst(String pattern, String str) {
return regexFindFirst(Pattern.compile(pattern), str, 1);
} | Gets the first group of a regex
@param pattern Pattern
@param str String to find
@return the matching group |
public static List<String> asListLines(String content) {
List<String> retorno = new ArrayList<String>();
content = content.replace(CARRIAGE_RETURN, RETURN);
content = content.replace(RETURN, CARRIAGE_RETURN);
for (String str : content.split(CARRIAGE_RETURN)) {
retorno.add(str);
}
return retorno;
} | Split string content into list
@param content String content
@return list |
public static List<String> asListLinesIgnore(String content, Pattern ignorePattern) {
List<String> retorno = new ArrayList<String>();
content = content.replace(CARRIAGE_RETURN, RETURN);
content = content.replace(RETURN, CARRIAGE_RETURN);
for (String str : content.split(CARRIAGE_RETURN)) {
if (!ignorePattern.matcher(str).matches()) {
retorno.add(str);
}
}
return retorno;
} | Split string content into list, ignoring matches of the pattern
@param content String content
@param ignorePattern Pattern to ignore
@return list |
public static Map<String, String> getContentMap(File file, String separator) throws IOException {
List<String> content = getContentLines(file);
Map<String, String> map = new LinkedHashMap<String, String>();
for (String line : content) {
String[] spl = line.split(separator);
if (line.trim().length() > 0) {
map.put(spl[0], (spl.length > 1 ? spl[1] : ""));
}
}
return map;
} | Get content of a file as a Map<String, String>, using separator to split values
@param file File to get content
@param separator The separator
@return The map with the values
@throws IOException I/O Error |
public static void saveContentMap(Map<String, String> map, File file) throws IOException {
FileWriter out = new FileWriter(file);
for (String key : map.keySet()) {
if (map.get(key) != null) {
out.write(key.replace(":", "#escapedtwodots#") + ":"
+ map.get(key).replace(":", "#escapedtwodots#") + "\r\n");
}
}
out.close();
} | Save map to file
@param map Map to save
@param file File to save
@throws IOException I/O error |
public static String getContent(String stringUrl) {
if (stringUrl.equalsIgnoreCase("clipboard")) {
try {
return getFromClipboard();
} catch (Exception e) {
//it's ok.
}
}
return getContent(stringUrl, null);
} | Returns content for the given URL
@param stringUrl URL
@return Response content |
public static String getContent(String stringUrl, Map<String, String> requestProperties) {
try {
URL url = new URL(stringUrl);
URLConnection conn = url.openConnection();
if (requestProperties != null) {
for (Entry<String, String> entry : requestProperties.entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
}
InputStream is = conn.getInputStream();
if ("gzip".equals(conn.getContentEncoding())) {
is = new GZIPInputStream(is);
}
return MyStreamUtils.readContent(is);
} catch (Exception e) {
e.printStackTrace();
}
return null;
} | Returns content for the given URL
@param stringUrl URL
@param requestProperties Properties
@return Response content |
public static String trimClean(String text) {
while (text.contains(CARRIAGE_RETURN)) {
text = text.replace(CARRIAGE_RETURN, " ");
}
while (text.contains(CARRIAGE)) {
text = text.replace(CARRIAGE, " ");
}
while (text.contains(RETURN)) {
text = text.replace(RETURN, " ");
}
while (text.contains("\b")) {
text = text.replace("\b", " ");
}
text = text.replaceAll("\\s+", " ");
return text.trim();
} | /*
Removed - use https://github.com/rrice/java-string-similarity public static double
similarScore(String str1, String str2) { SimilarityStrategy strategy = new
JaroWinklerStrategy(); StringSimilarityService service = new StringSimilarityServiceImpl(
strategy);
return service.score(str1, str2); } public static String[] fileSimilar(File dir, String name) {
return fileSimilar(dir, name, 50); }
public static String[] fileSimilar(File dir, String name, int adherence) { File mostSimilar =
null; double similarity = 0;
for (File arq : dir.listFiles()) { if (arq.isDirectory()) { continue; }
double score = similarScore(arq.getName(), name);
if (score >= (adherence / 100.0) && score > similarity) { mostSimilar = arq; similarity =
score; } }
if (mostSimilar == null) { return new String[] { null, "0" }; } return new String[] {
mostSimilar.getName(), String.valueOf(similarity) }; } |
public static String getTabularData(String[] labels, String[][] data, int padding) {
int[] size = new int[labels.length];
for (int i = 0; i < labels.length; i++) {
size[i] = labels[i].length() + padding;
}
for (String[] row : data) {
for (int i = 0; i < labels.length; i++) {
if (row[i].length() >= size[i]) {
size[i] = row[i].length() + padding;
}
}
}
StringBuffer tabularData = new StringBuffer();
for (int i = 0; i < labels.length; i++) {
tabularData.append(labels[i]);
tabularData.append(fill(' ', size[i] - labels[i].length()));
}
tabularData.append("\n");
for (int i = 0; i < labels.length; i++) {
tabularData.append(fill('=', size[i] - 1)).append(" ");
}
tabularData.append("\n");
for (String[] row : data) {
for (int i = 0; i < labels.length; i++) {
tabularData.append(row[i]);
tabularData.append(fill(' ', size[i] - row[i].length()));
}
tabularData.append("\n");
}
return tabularData.toString();
} | Return tabular data
@param labels Labels array
@param data Data bidimensional array
@param padding Total space between fields
@return String |
public static String replaceHtmlEntities(String content, Map<String, Character> map) {
for (Entry<String, Character> entry : escapeStrings.entrySet()) {
if (content.indexOf(entry.getKey()) != -1) {
content = content.replace(entry.getKey(), String.valueOf(entry.getValue()));
}
}
return content;
} | Replace HTML entities
@param content Content
@param map Map
@return Replaced content |
public void add(ServiceReference<S> declarationBinderRef) throws InvalidFilterException {
BinderDescriptor binderDescriptor = new BinderDescriptor(declarationBinderRef);
declarationBinders.put(declarationBinderRef, binderDescriptor);
} | Add the declarationBinderRef to the ImportersManager, create the corresponding.
BinderDescriptor.
@param declarationBinderRef the ServiceReference<DeclarationBinder> of the DeclarationBinder
@throws InvalidFilterException |
public void modified(ServiceReference<S> declarationBinderRef) throws InvalidFilterException {
declarationBinders.get(declarationBinderRef).update(declarationBinderRef);
} | Update the BinderDescriptor of the declarationBinderRef.
@param declarationBinderRef the ServiceReference<DeclarationBinder> of the DeclarationBinder |
public void createLinks(ServiceReference<S> declarationBinderRef) {
for (D declaration : linkerManagement.getMatchedDeclaration()) {
if (linkerManagement.canBeLinked(declaration, declarationBinderRef)) {
linkerManagement.link(declaration, declarationBinderRef);
}
}
} | Create all the links possible between the DeclarationBinder and all the ImportDeclaration matching the.
ImportDeclarationFilter of the Linker.
@param declarationBinderRef the ServiceReference<DeclarationBinder> of the DeclarationBinder |
public void updateLinks(ServiceReference<S> serviceReference) {
for (D declaration : linkerManagement.getMatchedDeclaration()) {
boolean isAlreadyLinked = declaration.getStatus().getServiceReferencesBounded().contains(serviceReference);
boolean canBeLinked = linkerManagement.canBeLinked(declaration, serviceReference);
if (isAlreadyLinked && !canBeLinked) {
linkerManagement.unlink(declaration, serviceReference);
} else if (!isAlreadyLinked && canBeLinked) {
linkerManagement.link(declaration, serviceReference);
}
}
} | Update all the links of the DeclarationBinder.
@param declarationBinderRef the ServiceReference<DeclarationBinder> of the DeclarationBinder |
public void removeLinks(ServiceReference<S> declarationBinderRef) {
for (D declaration : linkerManagement.getMatchedDeclaration()) {
if (declaration.getStatus().getServiceReferencesBounded().contains(declarationBinderRef)) {
linkerManagement.unlink(declaration, declarationBinderRef);
}
}
} | Remove all the existing links of the DeclarationBinder.
@param declarationBinderRef the ServiceReference<DeclarationBinder> of the DeclarationBinder |
public Set<S> getMatchedDeclarationBinder() {
Set<S> bindedSet = new HashSet<S>();
for (Map.Entry<ServiceReference<S>, BinderDescriptor> e : declarationBinders.entrySet()) {
if (e.getValue().match) {
bindedSet.add(getDeclarationBinder(e.getKey()));
}
}
return bindedSet;
} | Return a set of all DeclarationBinder matching the DeclarationBinderFilter of the Linker.
@return a Set of all DeclarationBinder matching the DeclarationBinderFilter of the Linker. |
public void applyFilterChanges(Filter binderServiceFilter) {
this.binderServiceFilter = binderServiceFilter;
Set<ServiceReference<S>> added = new HashSet<ServiceReference<S>>();
Set<ServiceReference<S>> removed = new HashSet<ServiceReference<S>>();
for (Map.Entry<ServiceReference<S>, BinderDescriptor> e : declarationBinders.entrySet()) {
boolean matchFilter = this.binderServiceFilter.matches(e.getValue().properties);
if (matchFilter != e.getValue().match && matchFilter) {
added.add(e.getKey());
} else if (matchFilter != e.getValue().match && !matchFilter) {
removed.add(e.getKey());
}
e.getValue().match = matchFilter;
}
for (ServiceReference<S> binderReference : removed) {
removeLinks(binderReference);
}
for (ServiceReference<S> binderReference : added) {
createLinks(binderReference);
}
} | Compute and apply all the modifications bring by the modification of the DeclarationBinderFilter.
<p/>
Find all the DeclarationBinder that are now matching the filter and all that are no more matching the filter.
<ul>
<li>Remove all the links of the ones which are no more matching the DeclarationBinderFilter.</li>
<li>Create the links of the ones which are now matching the DeclarationBinderFilter.</li>
</ul>
@param binderServiceFilter |
@Override
public void handleApplicationCommandRequest(SerialMessage serialMessage,
int offset, int endpoint) {
logger.trace("Handle Message Sensor Binary Request");
logger.debug(String.format("Received Sensor Binary Request for Node ID = %d", this.getNode().getNodeId()));
int command = serialMessage.getMessagePayloadByte(offset);
switch (command) {
case SENSOR_BINARY_GET:
logger.warn(String.format("Command 0x%02X not implemented.", command));
return;
case SENSOR_BINARY_REPORT:
logger.trace("Process Sensor Binary Report");
int value = serialMessage.getMessagePayloadByte(offset + 1);
logger.debug(String.format("Sensor Binary report from nodeId = %d, value = 0x%02X", this.getNode().getNodeId(), value));
Object eventValue;
if (value == 0) {
eventValue = "CLOSED";
} else {
eventValue = "OPEN";
}
ZWaveEvent zEvent = new ZWaveEvent(ZWaveEvent.ZWaveEventType.SENSOR_EVENT, this.getNode().getNodeId(), endpoint, eventValue);
this.getController().notifyEventListeners(zEvent);
break;
default:
logger.warn(String.format("Unsupported Command 0x%02X for command class %s (0x%02X).",
command,
this.getCommandClass().getLabel(),
this.getCommandClass().getKey()));
}
} | {@inheritDoc} |
public static List<File> extract(File zipFile, File outputFolder) throws IOException {
List<File> extracted = new ArrayList<File>();
byte[] buffer = new byte[2048];
if (!outputFolder.exists()) {
outputFolder.mkdir();
}
ZipInputStream zipInput = new ZipInputStream(new FileInputStream(zipFile));
ZipEntry zipEntry = zipInput.getNextEntry();
while (zipEntry != null) {
String neFileNameName = zipEntry.getName();
File newFile = new File(outputFolder + File.separator + neFileNameName);
newFile.getParentFile().mkdirs();
if (!zipEntry.isDirectory()) {
FileOutputStream fos = new FileOutputStream(newFile);
int size;
while ((size = zipInput.read(buffer)) > 0) {
fos.write(buffer, 0, size);
}
fos.close();
extracted.add(newFile);
}
zipEntry = zipInput.getNextEntry();
}
zipInput.closeEntry();
zipInput.close();
return extracted;
} | Extracts the zip file to the output folder
@param zipFile ZIP File to extract
@param outputFolder Output Folder
@return A Collection with the extracted files
@throws IOException I/O Error |
public static void validateZip(File file) throws IOException {
ZipInputStream zipInput = new ZipInputStream(new FileInputStream(file));
ZipEntry zipEntry = zipInput.getNextEntry();
while (zipEntry != null) {
zipEntry = zipInput.getNextEntry();
}
try {
if (zipInput != null) {
zipInput.close();
}
} catch (IOException e) {
}
} | Checks if a Zip is valid navigating through the entries
@param file File to validate
@throws IOException I/O Error |
public static void compress(File dir, File zipFile) throws IOException {
FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
recursiveAddZip(dir, zos, dir);
zos.finish();
zos.close();
} | Compress a directory into a zip file
@param dir Directory
@param zipFile ZIP file to create
@throws IOException I/O Error |
public static void recursiveAddZip(File parent, ZipOutputStream zout, File fileSource)
throws IOException {
File[] files = fileSource.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
recursiveAddZip(parent, zout, files[i]);
continue;
}
byte[] buffer = new byte[1024];
FileInputStream fin = new FileInputStream(files[i]);
ZipEntry zipEntry =
new ZipEntry(files[i].getAbsolutePath()
.replace(parent.getAbsolutePath(), "").substring(1)); //$NON-NLS-1$
zout.putNextEntry(zipEntry);
int length;
while ((length = fin.read(buffer)) > 0) {
zout.write(buffer, 0, length);
}
zout.closeEntry();
fin.close();
}
} | Recursively add files to a ZipOutputStream
@param parent Parent file
@param zout ZipOutputStream to append
@param fileSource The file source
@throws IOException I/O Error |
public UPnPStateVariable getStateVariable(String name) {
if (name.equals("Time"))
return time;
else if (name.equals("Result"))
return result;
else return null;
} | /* (non-Javadoc)
@see org.osgi.service.upnp.UPnPService#getStateVariable(java.lang.String) |
public BindingInfo createBindingInfo(Service service, String namespace,
Object obj) {
ServiceInfo si = new ServiceInfo();
si.setTargetNamespace(ProtobufBindingFactory.PROTOBUF_BINDING_ID);
BindingInfo info = new BindingInfo(si,
ProtobufBindingFactory.PROTOBUF_BINDING_ID);
return info;
} | /*
The concept of BindingInfo can not be applied to protocol buffers. Here
we create BindingInfo merely to make this compatible with CXF framework. |
public static ReplyDetailWarpper getDummyTextReplyDetailWarpper() {
ReplyDetail replyDetail = new ReplyDetail();
replyDetail.setDescription("欢迎订阅javatech,这是微信公众平台开发模式的一个尝试,更多详情请见 https://github.com/usc/wechat-mp-sdk \n" +
"Welcome subscribe javatech, this is an attempt to development model of wechat management platform, please via https://github.com/usc/wechat-mp-sdk to see more details");
return new ReplyDetailWarpper("text", Arrays.asList(replyDetail));
} | dummy reply. please according to your own situation to build ReplyDetailWarpper, and remove those code in production. |
public static ReplyDetailWarpper getDummyNewsReplyDetailWarpper() {
ReplyDetail replyDetail1 = new ReplyDetail();
replyDetail1.setTitle("fork me");
replyDetail1.setMediaUrl("http://c.hiphotos.baidu.com/baike/c%3DbaikeA4%2C10%2C95/sign=c1767bbf4b36acaf4de0c1ad15b2e851/29381f30e924b899a39841be6e061d950b7b02087af4d6b3.jpg");
replyDetail1.setUrl("https://github.com/usc/wechat-mp-sdk");
replyDetail1.setDescription("hello world, wechat mp sdk is coming");
ReplyDetail replyDetail2 = new ReplyDetail();
replyDetail2.setTitle("star me");
replyDetail2.setMediaUrl("http://e.hiphotos.baidu.com/baike/pic/item/96dda144ad345982665e49810df431adcaef84c9.jpg");
replyDetail2.setUrl("https://github.com/usc/wechat-mp-web");
replyDetail2.setDescription("wechat mp web demo");
return new ReplyDetailWarpper("news", Arrays.asList(replyDetail1, replyDetail2));
} | dummy reply. please according to your own situation to build ReplyDetailWarpper, and remove those code in production. |
public static RawFrame create(int mediumType, byte[] data, int offset)
throws KNXFormatException
{
switch (mediumType) {
case KNXMediumSettings.MEDIUM_TP0:
throw new KNXFormatException("TP0 raw frame not supported yet");
case KNXMediumSettings.MEDIUM_TP1:
return createTP1(data, offset);
case KNXMediumSettings.MEDIUM_PL110:
return createPL110(data, offset);
case KNXMediumSettings.MEDIUM_PL132:
return createPL132(data, offset);
case KNXMediumSettings.MEDIUM_RF:
throw new KNXFormatException("RF raw frame not supported yet");
default:
throw new KNXFormatException("unknown KNX medium for raw frame", mediumType);
}
} | Creates a raw frame out of a byte array for the specified communication medium.
<p>
This method just invokes one of the other medium type specific creation methods
according the given medium type.
@param mediumType KNX communication medium, one of the media types declared in
{@link KNXMediumSettings}
@param data byte array containing the raw frame structure
@param offset start offset of frame structure in <code>data</code>, 0 <=
offset < <code>data.length</code>
@return the created raw frame for the specified medium
@throws KNXFormatException on unknown/not supported KNX medium or no valid frame
structure |
public static RawFrame createPL110(byte[] data, int offset) throws KNXFormatException
{
if ((data[0] & 0x10) == 0x10)
return new PL110LData(data, offset);
return new PL110Ack(data, offset);
} | Creates a raw frame out of a byte array for the PL110 communication medium.
<p>
@param data byte array containing the PL110 raw frame structure
@param offset start offset of frame structure in <code>data</code>, 0 <=
offset < <code>data.length</code>
@return the created PL110 raw frame
@throws KNXFormatException on no valid frame structure |
public static RawFrame createPL132(byte[] data, int offset) throws KNXFormatException
{
if (data.length - offset == 2)
return new PL132Ack(data, offset);
return new PL132LData(data, offset);
} | Creates a raw frame out of a byte array for the PL132 communication medium.
<p>
@param data byte array containing the PL132 raw frame structure
@param offset start offset of frame structure in <code>data</code>, 0 <=
offset < <code>data.length</code>
@return the created PL132 raw frame
@throws KNXFormatException on no valid frame structure |
public static Datapoint create(XMLReader r) throws KNXMLException
{
if (r.getPosition() != XMLReader.START_TAG)
r.read();
if (r.getPosition() == XMLReader.START_TAG) {
if (readDPType(r))
return new StateDP(r);
return new CommandDP(r);
}
throw new KNXMLException("no KNX datapoint", null, r.getLineNumber());
} | Creates a new datapoint from XML input.
<p>
If the current XML element position is no start tag, the next element tag is read.
The datapoint element is then expected to be the current element in the reader.
@param r a XML reader
@return the created datapoint, either of type {@link StateDP} or {@link CommandDP}
@throws KNXMLException if the XML element is no datapoint or could not be read
correctly |
public void save(XMLWriter w) throws KNXMLException
{
/* XML layout:
<datapoint stateBased=[true|false] name=string mainNumber=int dptID=string
priority=string>
knxAddress
...
</datapoint>
*/
final List att = new ArrayList();
att.add(new Attribute(ATTR_STATEBASED, Boolean.toString(stateBased)));
att.add(new Attribute(ATTR_NAME, name));
att.add(new Attribute(ATTR_MAINNUMBER, Integer.toString(mainNo)));
att.add(new Attribute(ATTR_DPTID, dptID == null ? "" : dptID));
att.add(new Attribute(ATTR_PRIORITY, priority.toString()));
w.writeElement(TAG_DATAPOINT, att, null);
main.save(w);
doSave(w);
w.endElement();
} | Saves this datapoint in XML format to the supplied XML writer.
<p>
@param w a XML writer
@throws KNXMLException on error saving this datapoint |
private static boolean readDPType(XMLReader r) throws KNXMLException
{
final String a = r.getCurrent().getAttribute(ATTR_STATEBASED);
if ("false".equalsIgnoreCase(a))
return false;
if ("true".equalsIgnoreCase(a))
return true;
throw new KNXMLException("malformed attribute " + ATTR_STATEBASED, a, r
.getLineNumber());
} | /* returns true for state based DP, false for command based DP |
public static String readContent(InputStream is) {
String ret = "";
try {
String line;
BufferedReader in = new BufferedReader(new InputStreamReader(is));
StringBuffer out = new StringBuffer();
while ((line = in.readLine()) != null) {
out.append(line).append(CARRIAGE_RETURN);
}
ret = out.toString();
} catch (Exception e) {
e.printStackTrace();
}
return ret;
} | Gets string content from InputStream
@param is InputStream to read
@return InputStream content |
public static boolean streamHasText(InputStream in, String text) {
final byte[] readBuffer = new byte[8192];
StringBuffer sb = new StringBuffer();
try {
if (in.available() > 0) {
int bytesRead = 0;
while ((bytesRead = in.read(readBuffer)) != -1) {
sb.append(new String(readBuffer, 0, bytesRead));
if (sb.toString().contains(text)) {
sb = null;
return true;
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
} | Checks if the InputStream have the text
@param in InputStream to read
@param text Text to check
@return whether the inputstream has the text |
public byte[] getData(byte[] dst, int offset)
{
final int end = Math.min(data.length, dst.length - offset) & ~0x01;
for (int i = 0; i < end; ++i)
dst[offset + i] = (byte) data[i];
return dst;
}
/* (non-Javadoc)
* @see tuwien.auto.calimero.dptxlator.DPTXlator#getSubTypes()
*/
public Map getSubTypes()
{
return types;
}
/**
* @return the subtypes of the 2-byte float translator type
* @see DPTXlator#getSubTypesStatic()
*/
protected static Map getSubTypesStatic()
{
return types;
}
private String makeString(int index)
{
return appendUnit(String.valueOf(fromDPT(index)));
}
private float fromDPT(int index)
{
final int i = 2 * index;
// DPT bits high byte: MEEEEMMM, low byte: MMMMMMMM
// left align all mantissa bits
int v = ((data[i] & 0x80) << 24) | ((data[i] & 0x7) << 28) | (data[i + 1] << 20);
// normalize
v >>= 20;
final int exp = (data[i] & 0x78) >> 3;
return (float) ((1 << exp) * v * 0.01);
}
private void toDPT(float value, short[] dst, int index) throws KNXFormatException
{
if (value < min || value > max)
throw logThrow(LogLevel.WARN, "translation error for " + value,
"value out of range [" + dpt.getLowerValue() + ".." + dpt.getUpperValue()
+ "]", Float.toString(value));
// encoding: value = (0.01*M)*2^E
float v = value * 100.0f;
int e = 0;
for (; v < -2048.0f; v /= 2)
e++;
for (; v > 2047.0f; v /= 2)
e++;
final int m = Math.round(v) & 0x7FF;
short msb = (short) (e << 3 | m >> 8);
if (value < 0.0f)
msb |= 0x80;
dst[2 * index] = msb;
dst[2 * index + 1] = ubyte(m);
}
protected void toDPT(String value, short[] dst, int index) throws KNXFormatException
{
try {
toDPT(Float.parseFloat(removeUnit(value)), dst, index);
}
catch (final NumberFormatException e) {
throw logThrow(LogLevel.WARN, "wrong value format " + value, null, value);
}
}
private float getLimit(String limit) throws KNXFormatException
{
try {
final float f = Float.parseFloat(limit);
if (f >= -671088.64f && f <= 670760.96f)
return f;
}
catch (final NumberFormatException e) {}
throw logThrow(LogLevel.ERROR, "limit " + limit, "invalid DPT range", limit);
}
} | /* (non-Javadoc)
@see tuwien.auto.calimero.dptxlator.DPTXlator#getData(byte[], int) |
private static void tryWritePreferenceOnDisk(Preferences preference) throws BackingStoreException {
final String DUMMY_PROP="dummywrite";
instance.put(DUMMY_PROP,"test");
instance.flush();
instance.remove(DUMMY_PROP);
instance.flush();
} | This ensures that we are able to use the default preference from JSDK, to check basically if we are in Android or Not
@param preference
@throws BackingStoreException |
public void sendRequest(KNXAddress dst, Priority p, byte[] nsdu)
throws KNXTimeoutException, KNXLinkClosedException
{
doSend(createEMI(CEMILData.MC_LDATA_REQ, dst, p, nsdu), false, dst);
} | /* (non-Javadoc)
@see tuwien.auto.calimero.link.KNXNetworkLink#sendRequest
(tuwien.auto.calimero.KNXAddress, tuwien.auto.calimero.Priority, byte[]) |
public void sendRequestWait(KNXAddress dst, Priority p, byte[] nsdu)
throws KNXTimeoutException, KNXLinkClosedException
{
doSend(createEMI(CEMILData.MC_LDATA_REQ, dst, p, nsdu), true, dst);
} | /* (non-Javadoc)
@see tuwien.auto.calimero.link.KNXNetworkLink#sendRequestWait
(tuwien.auto.calimero.KNXAddress, tuwien.auto.calimero.Priority, byte[]) |
public void send(CEMILData msg, boolean waitForCon) throws KNXTimeoutException,
KNXLinkClosedException
{
doSend(createEMI(msg), waitForCon, msg.getDestination());
} | /* (non-Javadoc)
@see tuwien.auto.calimero.link.KNXNetworkLink#send
(tuwien.auto.calimero.cemi.CEMILData, boolean) |
public void close()
{
synchronized (this) {
if (closed)
return;
closed = true;
}
try {
normalMode();
}
catch (final KNXException e) {
logger.error("could not switch BCU back to normal mode", e);
}
conn.close();
notifier.quit();
} | /* (non-Javadoc)
@see tuwien.auto.calimero.link.KNXNetworkLink#close() |
private void doSend(byte[] msg, boolean wait, KNXAddress dst)
throws KNXAckTimeoutException, KNXLinkClosedException
{
if (closed)
throw new KNXLinkClosedException("link closed");
try {
logger.info("send message to " + dst + (wait ? ", wait for ack" : ""));
logger.trace("EMI " + DataUnitBuilder.toHex(msg, " "));
conn.send(msg, wait);
logger.trace("send to " + dst + " succeeded");
}
catch (final KNXPortClosedException e) {
logger.error("send error, closing link", e);
close();
throw new KNXLinkClosedException("link closed, " + e.getMessage());
}
} | dst is just for log information |
static public String bb2hex(byte[] bb) {
String result = "";
for (int i=0; i<bb.length; i++) {
result = result + String.format("%02X ", bb[i]);
}
return result;
} | Converts a byte array to a hexadecimal string representation
@param bb the byte array to convert
@return string the string representation |
private static byte calculateChecksum(byte[] buffer) {
byte checkSum = (byte)0xFF;
for (int i=1; i<buffer.length-1; i++) {
checkSum = (byte) (checkSum ^ buffer[i]);
}
logger.trace(String.format("Calculated checksum = 0x%02X", checkSum));
return checkSum;
} | Calculates a checksum for the specified buffer.
@param buffer the buffer to calculate.
@return the checksum value. |
public byte[] getMessageBuffer() {
ByteArrayOutputStream resultByteBuffer = new ByteArrayOutputStream();
byte[] result;
resultByteBuffer.write((byte)0x01);
int messageLength = messagePayload.length +
(this.messageClass == SerialMessageClass.SendData &&
this.messageType == SerialMessageType.Request ? 5 : 3); // calculate and set length
resultByteBuffer.write((byte) messageLength);
resultByteBuffer.write((byte) messageType.ordinal());
resultByteBuffer.write((byte) messageClass.getKey());
try {
resultByteBuffer.write(messagePayload);
} catch (IOException e) {
}
// callback ID and transmit options for a Send Data message.
if (this.messageClass == SerialMessageClass.SendData && this.messageType == SerialMessageType.Request) {
resultByteBuffer.write(transmitOptions);
resultByteBuffer.write(callbackId);
}
resultByteBuffer.write((byte) 0x00);
result = resultByteBuffer.toByteArray();
result[result.length - 1] = 0x01;
result[result.length - 1] = calculateChecksum(result);
logger.debug("Assembled message buffer = " + SerialMessage.bb2hex(result));
return result;
} | Gets the SerialMessage as a byte array.
@return the message |
public static String getLibraryHeader(boolean verbose)
{
if (!verbose)
return calimero + " version " + version;
final StringBuffer buf = new StringBuffer();
buf.append(calimero).append(sep);
buf.append("version ").append(version).append(sep);
buf.append(tuwien).append(sep);
buf.append(group).append(sep);
buf.append(copyright);
return buf.toString();
} | Returns a default library header representation with general/usage information.
<p>
It includes stuff like the library name, library version, name and institute of the
'Vienna University of Technology' where the library was developed, and copyright.
The returned information parts are divided using the newline ('\n') character.
@param verbose <code>true</code> to return all header information just mentioned,
<code>false</code> to only return library name and version comprised of
one line (no line separators)
@return header as string |
public static String getBundleListing()
{
final StringBuffer buf = new StringBuffer();
buf.append(getBundle("log service", "tuwien.auto.calimero.log.LogService", 1)
+ sep);
buf.append(getBundle("cEMI", "tuwien.auto.calimero.cemi.CEMI", 1)).append(sep);
buf.append(getBundle("KNXnet/IP",
"tuwien.auto.calimero.knxnetip.KNXnetIPConnection", 1)).append(sep);
buf.append(getBundle("serial", "tuwien.auto.calimero.serial.FT12Connection", 1))
.append(sep);
buf.append(getBundle("KNX network link",
"tuwien.auto.calimero.link.KNXNetworkLink", 1)).append(sep);
buf.append(getBundle("DPT translator",
"tuwien.auto.calimero.dptxlator.DPTXlator", 1)).append(sep);
buf.append(getBundle("data points", "tuwien.auto.calimero.datapoint.Datapoint",
1)).append(sep);
buf.append(getBundle("network buffer",
"tuwien.auto.calimero.buffer.NetworkBuffer", 1)).append(sep);
buf.append(getBundle("process", "tuwien.auto.calimero.process."
+ "ProcessCommunicator", 1) + sep);
buf.append(getBundle("management", "tuwien.auto.calimero.mgmt.ManagementClient",
1)).append(sep);
buf.append(getBundle("XML", "tuwien.auto.calimero.xml.def.DefaultXMLReader", 2));
return buf.toString();
} | Returns a listing containing all library bundles stating the bundle's presence for
use.
<p>
For loading a bundle, the default system class loader is used. A bundle is present
if it can be loaded using the class loader, otherwise it is considered not
available for use.<br>
An available bundle entry starts with a '+' and consists of a short bundle name and
the base package identifier string, a bundle not present starts with '-' and
consists of a short name and is marked with the suffix "- not available".<br>
The bundle entries in the returned string are separated using the newline ('\n')
character.
@return the bundle listing as string |
public static void main(String[] args)
{
if (args.length > 0 && (args[0].equals("--version") || args[0].equals("-v")))
out(getLibraryHeader(false));
else {
out(getLibraryHeader(true));
out("available bundles:");
out(getBundleListing());
}
} | This entry routine of the library prints information to the standard
output stream (System.out), mainly for user information.
<p>
Recognized options for output:
<ul>
<li>no options: default library header information and bundle listing</li>
<li>-v, --version: prints library name and version</li>
</ul>
@param args argument list with options controlling output information |
private static String getBundle(String friendlyName, String className, int truncate)
{
try {
cl.loadClass(className);
int start = className.length();
for (int i = 0; i < truncate; ++i)
start = className.lastIndexOf('.', start - 1);
final String bundle = className.substring(0, start);
return "+ " + friendlyName + align(friendlyName) + "- " + bundle;
}
catch (final ClassNotFoundException e) {}
catch (final NoClassDefFoundError e) {}
return "- " + friendlyName + align(friendlyName) + "- not available";
} | to check availability, then class name is truncated to bundle id |
public void send(CEMI frame, BlockingMode mode) throws KNXConnectionClosedException
{
try {
super.send(frame, NONBLOCKING);
// we always succeed...
setState(OK);
}
catch (final KNXTimeoutException e) {}
} | Sends a cEMI frame to the joined multicast group.
<p>
@param frame cEMI message to send
@param mode arbitrary value, does not influence behavior, since routing is always a
unconfirmed, nonblocking service |
public final void setHopCount(int hopCount)
{
if (hopCount < 0 || hopCount > 255)
throw new KNXIllegalArgumentException("hop count out of range");
try {
((MulticastSocket) socket).setTimeToLive(hopCount);
}
catch (final IOException e) {
logger.error("failed to set hop count", e);
}
} | Sets the default hop count (TTL) used in the IP header of encapsulated cEMI
messages.
<p>
This value is used to limit the multicast geographically, although this is just a
rough estimation. The hop count value is forwarded to the underlying multicast
socket used for communication.
@param hopCount hop count value, 0 <= value <= 255 |
void handleService(KNXnetIPHeader h, byte[] data, int offset)
throws KNXFormatException
{
final int svc = h.getServiceType();
if (h.getVersion() != KNXNETIP_VERSION_10)
close(ConnectionCloseEvent.INTERNAL, "protocol version changed",
LogLevel.ERROR, null);
else if (svc == KNXnetIPHeader.ROUTING_IND) {
final RoutingIndication ind = new RoutingIndication(data, offset,
h.getTotalLength() - h.getStructLength());
fireFrameReceived(ind.getCEMI());
}
else if (svc == KNXnetIPHeader.ROUTING_LOST_MSG) {
final RoutingLostMessage lost = new RoutingLostMessage(data, offset);
fireLostMessage(lost);
}
else
logger.warn("received unknown frame (service type 0x"
+ Integer.toHexString(svc) + ") - ignored");
} | /* (non-Javadoc)
@see tuwien.auto.calimero.knxnetip.ConnectionImpl#handleService
(tuwien.auto.calimero.knxnetip.servicetype.KNXnetIPHeader, byte[], int) |
public PolynomialSplineFunction calculateSpline(){
/*
* 1.Calculate the minimum bounding rectangle
*/
ArrayList<Point2D.Double> points = new ArrayList<Point2D.Double>();
for(int i = 0; i < t.size(); i++){
Point2D.Double p = new Point2D.Double();
p.setLocation(t.get(i).x, t.get(i).y);
points.add(p);
}
Point2D.Double[] rect = null;
try{
rect = RotatingCalipers.getMinimumBoundingRectangle(points);
}
catch(IllegalArgumentException e)
{
}
catch(EmptyStackException e){
}
/*
* 1.1 Rotate that the major axis is parallel with the xaxis
*/
Point2D.Double majorDirection = null;
Point2D.Double p1 = rect[2]; //top left
Point2D.Double p2 = p1.distance(rect[1]) > p1.distance(rect[3]) ? rect[1] : rect[3]; //Point to long side
Point2D.Double p3 = p1.distance(rect[1]) > p1.distance(rect[3]) ? rect[3] : rect[1]; //Point to short side
majorDirection = new Point2D.Double(p2.x-p1.x, p2.y-p1.y);
double width = p1.distance(p2);
double inRad = -1*Math.atan2(majorDirection.y, majorDirection.x);
boolean doTransform = (Math.abs(Math.abs(inRad)-Math.PI)>0.001);
if(doTransform)
{
angleRotated = inRad;
for(int i = 0; i < t.size(); i++){
double x = t.get(i).x;
double y = t.get(i).y;
double newX = x*Math.cos(inRad)-y*Math.sin(inRad);
double newY = x*Math.sin(inRad)+y*Math.cos(inRad);
rotatedTrajectory.add(newX, newY, 0);
points.get(i).setLocation(newX, newY);
}
for(int i = 0; i < rect.length; i++){
rect[i].setLocation(rect[i].x*Math.cos(inRad)-rect[i].y*Math.sin(inRad), rect[i].x*Math.sin(inRad)+rect[i].y*Math.cos(inRad));
}
p1 = rect[2]; //top left
p2 = p1.distance(rect[1]) > p1.distance(rect[3]) ? rect[1] : rect[3]; //Point to long side
p3 = p1.distance(rect[1]) > p1.distance(rect[3]) ? rect[3] : rect[1]; //Point to short side
}
else{
angleRotated = 0;
rotatedTrajectory = t;
}
/*
* 2. Divide the rectangle in n equal segments
* 2.1 Calculate line in main direction
* 2.2 Project the points in onto this line
* 2.3 Calculate the distance between the start of the line and the projected point
* 2.4 Assign point to segment according to distance of (2.3)
*/
List<List<Point2D.Double>> pointsInSegments =null;
boolean allSegmentsContainingAtLeastTwoPoints = true;
do{
allSegmentsContainingAtLeastTwoPoints = true;
double segmentWidth = p1.distance(p2)/nSegments;
pointsInSegments = new ArrayList<List<Point2D.Double>>(nSegments);
for(int i = 0; i < nSegments; i++){
pointsInSegments.add(new ArrayList<Point2D.Double>());
}
for(int i = 0; i < points.size(); i++){
Point2D.Double projPoint = projectPointToLine(p1, p2, points.get(i));
int index = (int)(p1.distance(projPoint)/segmentWidth);
if(index>(nSegments-1)){
index = (nSegments-1);
}
pointsInSegments.get(index).add(points.get(i));
}
for(int i = 0; i < pointsInSegments.size(); i++){
if(pointsInSegments.get(i).size()<2){
if(nSegments>2){
nSegments--;
i = pointsInSegments.size();
allSegmentsContainingAtLeastTwoPoints = false;
}
}
}
}while(allSegmentsContainingAtLeastTwoPoints==false);
/*
* 3. Calculate the mean standard deviation over each segment: <s>
*/
Point2D.Double eMajorP1 = new Point2D.Double(p1.x - (p3.x-p1.x)/2.0,p1.y - (p3.y-p1.y)/2.0);
Point2D.Double eMajorP2 = new Point2D.Double(p2.x - (p3.x-p1.x)/2.0,p2.y - (p3.y-p1.y)/2.0);
double sumMean=0;
int Nsum = 0;
for(int i = 0; i < nSegments; i++){
StandardDeviation sd = new StandardDeviation();
double[] distances = new double[pointsInSegments.get(i).size()];
for(int j = 0; j < pointsInSegments.get(i).size(); j++){
int factor = 1;
if(isLeft(eMajorP1, eMajorP2, pointsInSegments.get(i).get(j))){
factor = -1;
}
distances[j] = factor*distancePointLine(eMajorP1, eMajorP2, pointsInSegments.get(i).get(j));
}
if(distances.length >0){
sd.setData(distances);
sumMean += sd.evaluate();
Nsum++;
}
}
double s = sumMean/Nsum;
if(s<0.000000000001){
s = width/nSegments;
}
/*
* 4. Build a kd-tree
*/
KDTree<Point2D.Double> kdtree = new KDTree<Point2D.Double>(2);
for(int i = 0; i< points.size(); i++){
try {
//To ensure that all points have a different key, add small random number
kdtree.insert(new double[]{points.get(i).x,points.get(i).y}, points.get(i));
} catch (KeySizeException e) {
e.printStackTrace();
} catch (KeyDuplicateException e) {
//Do nothing! It is not important
}
}
/*
* 5. Using the first point f in trajectory and calculate the center of mass
* of all points around f (radius: 3*<s>))
*/
List<Point2D.Double> near = null;
Point2D.Double first = minDistancePointToLine(p1, p3, points);
double r1 = 3*s;
try {
near = kdtree.nearestEuclidean(new double[]{first.x ,first.y}, r1);
} catch (KeySizeException e) {
e.printStackTrace();
}
double cx = 0;
double cy = 0;
for(int i = 0; i < near.size(); i++){
cx += near.get(i).x;
cy += near.get(i).y;
}
cx /= near.size();
cy /= near.size();
splineSupportPoints = new ArrayList<Point2D.Double>();
splineSupportPoints.add(new Point2D.Double(cx, cy));
/*
* 6. The second point is determined by finding the center-of-mass of particles in the p/2 radian
* section of an annulus, r1 < r < 2r1, that is directed toward the angle with the highest number
* of particles within p/2 radians.
* 7. This second point is then used as the center of the annulus for choosing the third point, and the process is repeated (6. & 7.).
*/
/*
* 6.1 Find all points in the annolous
*/
/*
* 6.2 Write each point in a coordinate system centered at the center of the sphere, calculate direction and
* check if it in the allowed bounds
*/
int nCircleSegments = 100;
double deltaRad = 2*Math.PI/nCircleSegments;
boolean stop = false;
int minN = 7;
double tempr1 = r1;
double allowedDeltaDirection = 0.5*Math.PI;
while(stop==false){
List<Point2D.Double> nearestr1 = null;
List<Point2D.Double> nearest2xr1 = null;
try {
nearestr1 = kdtree.nearestEuclidean(new double[]{splineSupportPoints.get(splineSupportPoints.size()-1).x, splineSupportPoints.get(splineSupportPoints.size()-1).y},tempr1);
nearest2xr1 = kdtree.nearestEuclidean(new double[]{splineSupportPoints.get(splineSupportPoints.size()-1).x, splineSupportPoints.get(splineSupportPoints.size()-1).y},2*tempr1);
} catch (KeySizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
nearest2xr1.removeAll(nearestr1);
double lThreshRad = 0;
double hThreshRad = Math.PI/2;
double stopThresh = 2*Math.PI;
if(splineSupportPoints.size()>1){
double directionInRad = Math.atan2(splineSupportPoints.get(splineSupportPoints.size()-1).y-splineSupportPoints.get(splineSupportPoints.size()-2).y,
splineSupportPoints.get(splineSupportPoints.size()-1).x-splineSupportPoints.get(splineSupportPoints.size()-2).x)+Math.PI;
lThreshRad = directionInRad - allowedDeltaDirection/2 - Math.PI/4;
if(lThreshRad<0){
lThreshRad = 2*Math.PI+lThreshRad;
}
if(lThreshRad>2*Math.PI){
lThreshRad = lThreshRad - 2*Math.PI;
}
hThreshRad = directionInRad + allowedDeltaDirection/2 + Math.PI/4;
if(hThreshRad<0){
hThreshRad = 2*Math.PI+hThreshRad;
}
if(hThreshRad>2*Math.PI){
hThreshRad = hThreshRad - 2*Math.PI;
}
stopThresh = directionInRad + allowedDeltaDirection/2 - Math.PI/4;
if(stopThresh>2*Math.PI){
stopThresh = stopThresh - 2*Math.PI;
}
}
double newCx=0;
double newCy=0;
int newCN = 0;
int candN = 0;
//Find center with highest density of points
double lastDist = 0;
double newDist = 0;
do{
lastDist=Math.min(Math.abs(lThreshRad-stopThresh), 2*Math.PI-Math.abs(lThreshRad-stopThresh));
candN=0;
double candCx =0;
double candCy =0;
for(int i = 0; i < nearest2xr1.size(); i++){
Point2D.Double centerOfCircle = splineSupportPoints.get(splineSupportPoints.size()-1);
Vector2d relativeToCircle = new Vector2d(nearest2xr1.get(i).x-centerOfCircle.x,nearest2xr1.get(i).y-centerOfCircle.y);
relativeToCircle.normalize();
double angleInRadians = Math.atan2(relativeToCircle.y, relativeToCircle.x)+Math.PI;
if(lThreshRad<hThreshRad){
if(angleInRadians>lThreshRad && angleInRadians < hThreshRad){
candCx+=nearest2xr1.get(i).x;
candCy+=nearest2xr1.get(i).y;
candN++;
}
}
else{
if(angleInRadians>lThreshRad || angleInRadians < hThreshRad){
candCx+=nearest2xr1.get(i).x;
candCy+=nearest2xr1.get(i).y;
candN++;
}
}
}
if(candN>0 && candN > newCN ){
candCx /= candN;
candCy /= candN;
newCx = candCx;
newCy = candCy;
newCN = candN;
}
lThreshRad += deltaRad;
hThreshRad += deltaRad;
if(lThreshRad>2*Math.PI){
lThreshRad = lThreshRad - 2*Math.PI;
}
if(hThreshRad>2*Math.PI){
hThreshRad = hThreshRad - 2*Math.PI;
}
newDist=Math.min(Math.abs(lThreshRad-stopThresh), 2*Math.PI-Math.abs(lThreshRad-stopThresh));
}while((newDist-lastDist)>0);
//Check if the new center is valid
if(splineSupportPoints.size()>1){
double currentDirectionInRad = Math.atan2(splineSupportPoints.get(splineSupportPoints.size()-1).y-splineSupportPoints.get(splineSupportPoints.size()-2).y,
splineSupportPoints.get(splineSupportPoints.size()-1).x-splineSupportPoints.get(splineSupportPoints.size()-2).x)+Math.PI;
double candDirectionInRad = Math.atan2(newCy-splineSupportPoints.get(splineSupportPoints.size()-1).y,
newCx-splineSupportPoints.get(splineSupportPoints.size()-1).x)+Math.PI;
double dDir = Math.max(currentDirectionInRad, candDirectionInRad)-Math.min(currentDirectionInRad, candDirectionInRad);
if(dDir>2*Math.PI){
dDir = 2*Math.PI-dDir;
}
if(dDir>allowedDeltaDirection){
stop = true;
}
}
boolean enoughPoints = (newCN<minN);
boolean isNormalRadius = Math.abs(tempr1-r1)<Math.pow(10, -18);
boolean isExtendedRadius = Math.abs(tempr1-3*r1)<Math.pow(10, -18);
if(enoughPoints&& isNormalRadius){
//Not enough points, extend search radius
tempr1 = 3*r1;
}
else if(enoughPoints && isExtendedRadius){
//Despite radius extension: Not enough points!
stop = true;
}
else if(stop==false){
splineSupportPoints.add(new Point2D.Double(newCx,newCy));
tempr1 = r1;
}
}
//Sort
Collections.sort(splineSupportPoints, new Comparator<Point2D.Double>() {
public int compare(Point2D.Double o1, Point2D.Double o2) {
if(o1.x<o2.x){
return -1;
}
if(o1.x>o2.x){
return 1;
}
return 0;
}
});
//Add endpoints
if(splineSupportPoints.size()>1){
Vector2d start = new Vector2d(splineSupportPoints.get(0).x-splineSupportPoints.get(1).x, splineSupportPoints.get(0).y-splineSupportPoints.get(1).y);
start.normalize();
start.scale(r1*8);
splineSupportPoints.add(0, new Point2D.Double(splineSupportPoints.get(0).x+start.x, splineSupportPoints.get(0).y+start.y));
Vector2d end = new Vector2d(splineSupportPoints.get(splineSupportPoints.size()-1).x-splineSupportPoints.get(splineSupportPoints.size()-2).x,
splineSupportPoints.get(splineSupportPoints.size()-1).y-splineSupportPoints.get(splineSupportPoints.size()-2).y);
end.normalize();
end.scale(r1*6);
splineSupportPoints.add(new Point2D.Double(splineSupportPoints.get(splineSupportPoints.size()-1).x+end.x, splineSupportPoints.get(splineSupportPoints.size()-1).y+end.y));
}
else{
Vector2d majordir = new Vector2d(-1, 0);
majordir.normalize();
majordir.scale(r1*8);
splineSupportPoints.add(0, new Point2D.Double(splineSupportPoints.get(0).x+majordir.x, splineSupportPoints.get(0).y+majordir.y));
majordir.scale(-1);
splineSupportPoints.add(new Point2D.Double(splineSupportPoints.get(splineSupportPoints.size()-1).x+majordir.x, splineSupportPoints.get(splineSupportPoints.size()-1).y+majordir.y));
}
//Interpolate spline
double[] supX = new double[splineSupportPoints.size()];
double[] supY = new double[splineSupportPoints.size()];
for(int i = 0; i < splineSupportPoints.size(); i++){
supX[i] = splineSupportPoints.get(i).x;
supY[i] = splineSupportPoints.get(i).y;
}
SplineInterpolator sIinter = new SplineInterpolator();
spline = sIinter.interpolate(supX, supY);
return spline;
} | Calculates a spline to a trajectory. Attention: The spline is fitted through a rotated version of the trajectory.
To fit the spline the trajectory is rotated into its main direction. You can access this rotated trajectory by
{@link #getRotatedTrajectory() getRotatedTrajectory}.
@return The fitted spline |
@Override
protected void useImportDeclaration(ImportDeclaration importDeclaration) throws BinderException {
LOG.debug("Create proxy" + importDeclaration.getMetadata());
JAXWSImportDeclarationWrapper pojo = JAXWSImportDeclarationWrapper.create(importDeclaration);
//Try to load the class
final Class<?> klass;
try {
klass = loadClass(context, pojo.getClazz());
} catch (ClassNotFoundException e) {
LOG.error("Failed to load class", e);
return;
}
final ClassLoader origin = Thread.currentThread().getContextClassLoader();
try {
ClientProxyFactoryBean factory;
Object objectProxy;
Thread.currentThread().setContextClassLoader(this.getClass().getClassLoader());
LOG.debug(String.valueOf(klass));
//use annotations if present
if (klass.isAnnotationPresent(WebService.class)) {
factory = new JaxWsProxyFactoryBean();
} else {
factory = new ClientProxyFactoryBean();
}
factory.getInInterceptors().add(new LoggingInInterceptor());
factory.getOutInterceptors().add(new LoggingOutInterceptor());
//set the class XXX only one class is supported
factory.setServiceClass(klass);
factory.setAddress(pojo.getEndpoint());
LOG.debug(String.valueOf(factory.getAddress()));
LOG.debug(String.valueOf(factory.getServiceFactory()));
//create the proxy
objectProxy = factory.create();
// set the importDeclaration has handled
handleImportDeclaration(importDeclaration);
//Publish object
map.put(importDeclaration, registerProxy(objectProxy, klass));
} finally {
Thread.currentThread().setContextClassLoader(origin);
}
} | /*--------------------------*
ImporterService methods *
-------------------------- |
protected ServiceRegistration registerProxy(Object objectProxy, Class clazz) {
Dictionary<String, Object> props = new Hashtable<String, Object>();
ServiceRegistration registration;
registration = context.registerService(clazz, objectProxy, props);
return registration;
} | Utility method to register a proxy has a Service in OSGi. |
@Override
protected void denyImportDeclaration(ImportDeclaration importDeclaration) {
LOG.debug("CXFImporter destroy a proxy for " + importDeclaration);
ServiceRegistration serviceRegistration = map.get(importDeclaration);
serviceRegistration.unregister();
// set the importDeclaration has unhandled
super.unhandleImportDeclaration(importDeclaration);
map.remove(importDeclaration);
} | Destroy the proxy & update the map containing the registration ref.
@param importDeclaration |
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
Signature signature = new Signature();
boolean hasRights = checkSignature(signature, request);
if (hasRights) {
log.info("signature-success:{}", signature);
WebUtil.outputString(response, signature.getEchostr());
} else {
log.info("signature-not-match:{}", signature);
}
} catch (Exception e) {
log.error("signature-error", e);
}
} | TODO please custom it. |
public final String getAttribute(String name)
{
synchronized (attributes) {
for (final Iterator i = attributes.iterator(); i.hasNext();) {
final Attribute a = (Attribute) i.next();
if (a.getName().equals(name))
return a.getValue();
}
}
return null;
} | /* (non-Javadoc)
@see tuwien.auto.calimero.xml.Element#getAttribute(java.lang.String) |
public static JsonRtn updateGroup(License license, Group group) {
if (group == null) {
return JsonRtnUtil.buildFailureJsonRtn(JsonRtn.class, "missing group");
}
return HttpUtil.postBodyRequest(WechatRequest.UPDATE_GROUP, license, new GroupWarpper(group), GroupJsonRtn.class);
} | TODO-Shunli: now update group always failed, tip system error, check later |
public void write(String logService, LogLevel level, String msg)
{
doFileWrite(logService, level, msg, null);
} | /* (non-Javadoc)
@see tuwien.auto.calimero.log.LogStreamWriter#write
(java.lang.String, tuwien.auto.calimero.log.LogLevel, java.lang.String) |
public static Result generate(@Nonnull final String code, @Nonnull final ImmutableSettings settings) {
Check.notNull(code, "code");
final ImmutableSettings.Builder settingsBuilder = new ImmutableSettings.Builder(Check.notNull(settings, "settings"));
final InterfaceAnalysis analysis = InterfaceAnalyzer.analyze(code);
final Clazz clazz = scaffoldClazz(analysis, settings);
// immutable settings
settingsBuilder.fields(clazz.getFields());
settingsBuilder.immutableName(clazz.getName());
settingsBuilder.imports(clazz.getImports());
final Interface definition = new Interface(new Type(clazz.getPackage(), analysis.getInterfaceName(), GenericDeclaration.UNDEFINED));
settingsBuilder.mainInterface(definition);
settingsBuilder.interfaces(clazz.getInterfaces());
settingsBuilder.packageDeclaration(clazz.getPackage());
final String implementationCode = SourceCodeFormatter.format(ImmutableObjectRenderer.toString(clazz, settingsBuilder.build()));
final String testCode = SourceCodeFormatter.format(ImmutableObjectTestRenderer.toString(clazz, settingsBuilder.build()));
return new Result(implementationCode, testCode);
} | The specified interface must not contain methods, that changes the state of this object itself.
@param code
source code of an interface which describes how to generate the <i>immutable</i>
@param settings
settings to generate code
@return generated source code as string in a result wrapper |
public static void addJarToClasspath(ClassLoader loader, URL url) throws IOException,
IllegalAccessException, IllegalArgumentException, InvocationTargetException,
NoSuchMethodException, SecurityException {
URLClassLoader sysloader = (URLClassLoader) loader;
Class<?> sysclass = URLClassLoader.class;
Method method =
sysclass.getDeclaredMethod(MyClasspathUtils.ADD_URL_METHOD, new Class[] {URL.class});
method.setAccessible(true);
method.invoke(sysloader, new Object[] {url});
} | Add an URL to the given classloader
@param loader ClassLoader
@param url URL to add
@throws IOException I/O Error
@throws InvocationTargetException Invocation Error
@throws IllegalArgumentException Illegal Argument
@throws IllegalAccessException Illegal Access
@throws SecurityException Security Constraint
@throws NoSuchMethodException Method not found |
public static void delete(File file) throws IOException {
if (file.isDirectory()) {
// directory is empty, then delete it
if (file.list().length == 0) {
file.delete();
} else {
// list all the directory contents
String files[] = file.list();
for (String temp : files) {
// construct the file structure
File fileDelete = new File(file, temp);
// recursive delete
delete(fileDelete);
}
// check the directory again, if empty then delete it
if (file.list().length == 0) {
file.delete();
}
}
} else {
// if file, then delete it
file.delete();
}
} | http://www.mkyong.com/java/how-to-delete-directory-in-java/ |
public static int getAPDUService(byte[] apdu)
{
// high 4 bits of APCI
final int apci4 = (apdu[0] & 0x03) << 2 | (apdu[1] & 0xC0) >> 6;
// lowest 6 bits of APCI
final int apci6 = apdu[1] & 0x3f;
// group value codes
if (apci4 == 0) {
if (apci6 == 0)
return 0;
}
else if (apci4 == 1)
return 0x40;
else if (apci4 == 2)
return 0x80;
// individual address codes
else if (apci4 == 3 || apci4 == 4 || apci4 == 5) {
if (apci6 == 0)
return apci4 << 6;
}
// ADC codes
else if (apci4 == 6 || apci4 == 7)
return apci4 << 6;
// memory codes
else if (apci4 == 8 || apci4 == 9 || apci4 == 10) {
if ((apci6 & 0x30) == 0)
return apci4 << 6;
}
// the rest
else
return apci4 << 6 | apci6;
// unknown codes
final int code = apci4 << 6 | apci6;
logger.warn("unknown APCI service code 0x" + Integer.toHexString(code));
return code;
} | Returns the application layer service of a given protocol data unit.
<p>
@param apdu application layer protocol data unit
@return APDU service code |
public static byte[] createAPDU(int service, byte[] asdu)
{
if (asdu.length > 254)
throw new KNXIllegalArgumentException(
"ASDU length exceeds maximum of 254 bytes");
final byte[] apdu = new byte[2 + asdu.length];
apdu[0] = (byte) ((service >> 8) & 0x03);
apdu[1] |= (byte) service;
for (int i = 0; i < asdu.length; ++i)
apdu[i + 2] = asdu[i];
return apdu;
} | Creates an application layer protocol data unit out of a service code and a service
data unit.
<p>
The transport layer bits in the first byte (TL / AL control field) are set 0. For
creating a compact APDU, refer to {@link #createCompactAPDU(int, byte[])}.
@param service application layer service code
@param asdu application layer service data unit, <code>asdu.length</code> <
255
@return APDU as byte array |
public static byte[] createCompactAPDU(int service, byte[] asdu)
{
final byte[] apdu =
new byte[(asdu != null && asdu.length > 0) ? 1 + asdu.length : 2];
if (apdu.length > 255)
throw new KNXIllegalArgumentException(
"APDU length exceeds maximum of 255 bytes");
apdu[0] = (byte) ((service >> 8) & 0x03);
apdu[1] = (byte) service;
if (asdu != null && asdu.length > 0) {
// maximum of 6 bits in asdu[0] are valid
apdu[1] |= asdu[0] & 0x3F;
for (int i = 1; i < asdu.length; ++i)
apdu[i + 1] = asdu[i];
}
return apdu;
} | Creates a compact application layer protocol data unit out of a service code and a
service data unit.
<p>
The transport layer bits in the first byte (TL / AL control field) are set 0. If
the compact APDU shall not contain any ASDU information, <code>asdu</code> can be
left <code>null</code>.
@param service application layer service code
@param asdu application layer service data unit, <code>asdu.length</code> <
255; or <code>null</code> for no ASDU
@return APDU as byte array |
public static byte[] extractASDU(byte[] apdu)
{
final int svc = getAPDUService(apdu);
int offset = 2;
int mask = 0xff;
// 0x40 A_GroupValue_Response-PDU
// 0x80 A_GroupValue_Write-PDU
if (svc == 0x40 || svc == 0x80) {
// only adjust for optimized read.res and write
if (apdu.length <= 2) {
offset = 1;
mask = 0x3f;
}
}
// 0x0180 A_ADC_Read-PDU
// 0x01C0 A_ADC_Response-PDU
else if (svc == 0x0180 || svc == 0x01C0) {
offset = 1;
mask = 0x3f;
}
// 0x0200 A_Memory_Read-PDU
// 0x0240 A_Memory_Response-PDU
// 0x0280 A_Memory_Write-PDU
else if (svc == 0x0200 || svc == 0x0240 || svc == 0x0280) {
offset = 1;
mask = 0x0f;
}
final byte[] asdu = new byte[apdu.length - offset];
for (int i = 0; i < asdu.length; ++i)
asdu[i] = apdu[offset + i];
asdu[0] &= mask;
return asdu;
} | Returns a copy of the ASDU contained in the supplied APDU.
<p>
The application layer service data unit (ASDU) is the APDU with the application
layer service code removed.
@param apdu application layer protocol data unit for which to get the ASDU
@return the ASDU as byte array |
public static String decode(byte[] tpdu, KNXAddress dst)
{
if (tpdu.length < 1)
throw new KNXIllegalArgumentException("TPDU length too short");
final String s = decodeTPCI(tpdu[0] & 0xff, dst);
if (tpdu.length > 1)
return s + ", " + decodeAPCI(getAPDUService(tpdu));
return s;
} | Decodes a protocol data unit into a textual representation.
<p>
Currently, the transport layer protocol control information (TPCI) and the
application layer protocol control information (APCI) is decoded. Decoding might be
extended in the future.<br>
The optional KNX destination address helps to determine the exact transport layer
service.
@param tpdu transport layer protocol data unit to decode
@param dst KNX destination address belonging to the TPDU, might be
<code>null</code>
@return textual representation of control information in the TPDU |
public static String decodeTPCI(int tpci, KNXAddress dst)
{
final int ctrl = tpci & 0xff;
if ((ctrl & 0xFC) == 0) {
if (dst == null)
return "T-broadcast/group/ind";
if (dst.getRawAddress() == 0)
return "T-broadcast";
if (dst instanceof GroupAddress)
return "T-group";
return "T-individual";
}
if ((ctrl & 0xC0) == 0x40)
return "T-connected seq " + (ctrl >> 2 & 0xF);
if (ctrl == T_CONNECT)
return "T-connect";
if (ctrl == T_DISCONNECT)
return "T-disconnect";
if ((ctrl & 0xC3) == T_ACK)
return "T-ack seq " + (ctrl >> 2 & 0xF);
if ((ctrl & 0xC3) == T_NAK)
return "T-nak seq " + (ctrl >> 2 & 0xF);
return "unknown TPCI";
} | Decodes a transport layer protocol control information into a textual
representation.
<p>
@param tpci transport layer protocol control information
@param dst KNX destination address belonging to the tpci, might be
<code>null</code>
@return textual representation of TPCI |
public byte[] toByteArray()
{
final byte[] buf = super.toByteArray();
int i = 2;
buf[i++] = (byte) knxmedium;
buf[i++] = (byte) devicestatus;
final byte[] addr = address.toByteArray();
buf[i++] = addr[0];
buf[i++] = addr[1];
buf[i++] = (byte) (projectInstallID >> 8);
buf[i++] = (byte) projectInstallID;
for (int k = 0; k < 6; ++k)
buf[i++] = serial[k];
for (int k = 0; k < 4; ++k)
buf[i++] = mcaddress[k];
for (int k = 0; k < 6; ++k)
buf[i++] = mac[k];
for (int k = 0; k < name.length(); ++k)
buf[i++] = (byte) name.charAt(k);
return buf;
} | /* (non-Javadoc)
@see tuwien.auto.calimero.knxnetip.util.DIB#toByteArray() |
public void destroyDestination(Destination d)
{
// method invocation is idempotent
synchronized (proxies) {
final AggregatorProxy p = (AggregatorProxy) proxies.get(d.getAddress());
if (p == null)
return;
if (p.getDestination() == d) {
proxies.remove(d.getAddress());
d.destroy();
}
else
logger.warn("not owner of " + d.getAddress());
}
} | /* (non-Javadoc)
@see tuwien.auto.calimero.mgmt.TransportLayer#destroyDestination
(tuwien.auto.calimero.mgmt.Destination) |
public void connect(Destination d) throws KNXTimeoutException, KNXLinkClosedException
{
final AggregatorProxy p = getProxy(d);
if (!d.isConnectionOriented()) {
logger.error("destination not connection oriented: " + d.getAddress());
return;
}
if (d.getState() != Destination.DISCONNECTED)
return;
p.setState(Destination.CONNECTING);
final byte[] tpdu = new byte[] { (byte) CONNECT };
lnk.sendRequestWait(d.getAddress(), Priority.SYSTEM, tpdu);
p.setState(Destination.OPEN_IDLE);
logger.trace("connected with " + d.getAddress());
} | /* (non-Javadoc)
@see tuwien.auto.calimero.mgmt.TransportLayer#connect
(tuwien.auto.calimero.mgmt.Destination) |
public void disconnect(Destination d) throws KNXLinkClosedException
{
if (detached)
throw new KNXIllegalStateException("TL detached");
if (d.getState() != Destination.DESTROYED
&& d.getState() != Destination.DISCONNECTED)
disconnectIndicate(getProxy(d), true);
} | /* (non-Javadoc)
@see tuwien.auto.calimero.mgmt.TransportLayer#disconnect
(tuwien.auto.calimero.mgmt.Destination) |
public void sendData(KNXAddress addr, Priority p, byte[] tsdu)
throws KNXTimeoutException, KNXLinkClosedException
{
if (detached)
throw new KNXIllegalStateException("TL detached");
tsdu[0] &= 0x03;
lnk.sendRequestWait(addr, p, tsdu);
} | /* (non-Javadoc)
@see tuwien.auto.calimero.mgmt.TransportLayer#sendData
(tuwien.auto.calimero.KNXAddress, tuwien.auto.calimero.Priority, byte[]) |
private void fireFrameType(CEMI frame, int type)
{
final FrameEvent e = new FrameEvent(this, frame);
for (final Iterator i = listeners.iterator(); i.hasNext();) {
final TransportListener l = (TransportListener) i.next();
try {
if (type == 0)
l.broadcast(e);
else if (type == 1)
l.group(e);
else if (type == 2)
l.dataIndividual(e);
else if (type == 3)
l.dataConnected(e);
}
catch (final RuntimeException rte) {
removeTransportListener(l);
logger.error("removed event listener", rte);
}
}
} | type 0 = broadcast, 1 = group, 2 = individual, 3 = connected |
public void registerDeclaration(T declaration) {
synchronized (declarationsRegistered) {
if (declarationsRegistered.containsKey(declaration)) {
throw new IllegalStateException("The given Declaration has already been registered.");
}
Dictionary<String, Object> props = new Hashtable<String, Object>();
if(declaration.getMetadata().get("id") != null){
props.put("importer.id",declaration.getMetadata().get("id").toString());
}
String[] clazzes = new String[]{klass.getName()};
ServiceRegistration registration;
registration = bundleContext.registerService(clazzes, declaration, props);
declarationsRegistered.put(declaration, registration);
}
} | Utility method to register an Declaration has a Service in OSGi.
If you use it make sure to use unregisterDeclaration(...) to unregister the Declaration
@param declaration the Declaration to register |
public void unregisterDeclaration(T declaration) {
ServiceRegistration registration;
synchronized (declarationsRegistered) {
registration = declarationsRegistered.remove(declaration);
if (registration == null) {
throw new IllegalStateException("The given Declaration has never been registered"
+ "or have already been unregistered.");
}
}
registration.unregister();
} | Utility method to unregister an Declaration of OSGi.
Use it only if you have used registerDeclaration(...) to register the Declaration
@param declaration the Declaration to unregister |
public void resetResendCount() {
this.resendCount = 0;
if (this.initializationComplete)
this.nodeStage = NodeStage.NODEBUILDINFO_DONE;
this.lastUpdated = Calendar.getInstance().getTime();
} | Resets the resend counter and possibly resets the
node stage to DONE when previous initialization was
complete. |
public void addCommandClass(ZWaveCommandClass commandClass)
{
ZWaveCommandClass.CommandClass key = commandClass.getCommandClass();
if (!supportedCommandClasses.containsKey(key)) {
supportedCommandClasses.put(key, commandClass);
if (commandClass instanceof ZWaveEventListener)
this.controller.addEventListener((ZWaveEventListener)commandClass);
this.lastUpdated = Calendar.getInstance().getTime();
}
} | Adds a command class to the list of supported command classes by this node.
Does nothing if command class is already added.
@param commandClass the command class instance to add. |
public ZWaveCommandClass resolveCommandClass(ZWaveCommandClass.CommandClass commandClass, int endpointId)
{
if (commandClass == null)
return null;
ZWaveMultiInstanceCommandClass multiInstanceCommandClass = (ZWaveMultiInstanceCommandClass)supportedCommandClasses.get(ZWaveCommandClass.CommandClass.MULTI_INSTANCE);
if (multiInstanceCommandClass != null && multiInstanceCommandClass.getVersion() == 2) {
ZWaveEndpoint endpoint = multiInstanceCommandClass.getEndpoint(endpointId);
if (endpoint != null) {
ZWaveCommandClass result = endpoint.getCommandClass(commandClass);
if (result != null)
return result;
}
}
ZWaveCommandClass result = getCommandClass(commandClass);
if (result == null)
return result;
if (multiInstanceCommandClass != null && multiInstanceCommandClass.getVersion() == 1 &&
result.getInstances() >= endpointId)
return result;
return endpointId == 1 ? result : null;
} | Resolves a command class for this node. First endpoint is checked.
If endpoint == 1 or (endpoint != 1 and version of the multi instance
command == 1) then return a supported command class on the node itself.
If endpoint != 1 and version of the multi instance command == 2 then
first try command classes of endpoints. If not found the return a
supported command class on the node itself.
Returns null if a command class is not found.
@param commandClass The command class to resolve.
@param endpointId the endpoint / instance to resolve this command class for.
@return the command class. |
public void advanceNodeStage() {
this.setQueryStageTimeStamp(Calendar.getInstance().getTime());
switch (this.nodeStage) {
case NODEBUILDINFO_EMPTYNODE:
try {
this.setNodeStage(ZWaveNode.NodeStage.NODEBUILDINFO_PROTOINFO);
this.controller.identifyNode(this.nodeId);
} catch (SerialInterfaceException e) {
logger.error("Got error: {}, while identifying node {}", e.getLocalizedMessage(), this.nodeId);
}
break;
case NODEBUILDINFO_PROTOINFO:
if (nodeId != this.controller.getOwnNodeId())
{
ZWaveNoOperationCommandClass zwaveCommandClass = (ZWaveNoOperationCommandClass)supportedCommandClasses.get(ZWaveCommandClass.CommandClass.NO_OPERATION);
if (zwaveCommandClass == null)
break;
this.setNodeStage(ZWaveNode.NodeStage.NODEBUILDINFO_PING);
this.controller.sendData(zwaveCommandClass.getNoOperationMessage());
} else
{
this.setNodeStage(ZWaveNode.NodeStage.NODEBUILDINFO_DONE); // nothing more to do for this node.
}
break;
case NODEBUILDINFO_PING:
case NODEBUILDINFO_WAKEUP:
this.setNodeStage(ZWaveNode.NodeStage.NODEBUILDINFO_DETAILS);
this.controller.requestNodeInfo(nodeId);
break;
case NODEBUILDINFO_DETAILS:
// try and get the manufacturerSpecific command class.
ZWaveManufacturerSpecificCommandClass manufacturerSpecific = (ZWaveManufacturerSpecificCommandClass)this.getCommandClass(ZWaveCommandClass.CommandClass.MANUFACTURER_SPECIFIC);
if (manufacturerSpecific != null) {
// if this node implements the Manufacturer Specific command class, we use it to get manufacturer info.
this.setNodeStage(ZWaveNode.NodeStage.NODEBUILDINFO_MANSPEC01);
this.controller.sendData(manufacturerSpecific.getManufacturerSpecificMessage());
break;
}
logger.warn("Node {} does not support MANUFACTURER_SPECIFIC, proceeding to version node stage.", this.getNodeId());
case NODEBUILDINFO_MANSPEC01:
this.setNodeStage(ZWaveNode.NodeStage.NODEBUILDINFO_VERSION); // nothing more to do for this node.
// try and get the version command class.
ZWaveVersionCommandClass version = (ZWaveVersionCommandClass)this.getCommandClass(ZWaveCommandClass.CommandClass.VERSION);
boolean checkVersionCalled = false;
for (ZWaveCommandClass zwaveCommandClass : this.getCommandClasses()) {
if (version != null && zwaveCommandClass.getMaxVersion() > 1) {
version.checkVersion(zwaveCommandClass); // check version for this command class.
checkVersionCalled = true;
} else
zwaveCommandClass.setVersion(1);
}
if (checkVersionCalled) // wait for another call of advanceNodeStage before continuing.
break;
case NODEBUILDINFO_VERSION:
this.setNodeStage(ZWaveNode.NodeStage.NODEBUILDINFO_INSTANCES); // nothing more to do for this node.
// try and get the multi instance / channel command class.
ZWaveMultiInstanceCommandClass multiInstance = (ZWaveMultiInstanceCommandClass)this.getCommandClass(ZWaveCommandClass.CommandClass.MULTI_INSTANCE);
if (multiInstance != null) {
multiInstance.initEndpoints();
break;
}
logger.trace("Node {} does not support MULTI_INSTANCE, proceeding to static node stage.", this.getNodeId());
case NODEBUILDINFO_INSTANCES:
this.setNodeStage(ZWaveNode.NodeStage.NODEBUILDINFO_STATIC);
if (queriesPending == -1) {
queriesPending = 0;
for (ZWaveCommandClass zwaveCommandClass : this.getCommandClasses()) {
logger.trace("Inspecting command class {}", zwaveCommandClass.getCommandClass().getLabel());
if (zwaveCommandClass instanceof ZWaveCommandClassInitialization) {
logger.debug("Found initializable command class {}", zwaveCommandClass.getCommandClass().getLabel());
ZWaveCommandClassInitialization zcci = (ZWaveCommandClassInitialization)zwaveCommandClass;
int instances = zwaveCommandClass.getInstances();
if (instances == 0)
{
Collection<SerialMessage> initqueries = zcci.initialize();
for (SerialMessage serialMessage : initqueries) {
this.controller.sendData(serialMessage);
queriesPending++;
}
} else {
for (int i = 1; i <= instances; i++) {
Collection<SerialMessage> initqueries = zcci.initialize();
for (SerialMessage serialMessage : initqueries) {
this.controller.sendData(this.encapsulate(serialMessage, zwaveCommandClass, i));
queriesPending++;
}
}
}
} else if (zwaveCommandClass instanceof ZWaveMultiInstanceCommandClass) {
ZWaveMultiInstanceCommandClass multiInstanceCommandClass = (ZWaveMultiInstanceCommandClass)zwaveCommandClass;
for (ZWaveEndpoint endpoint : multiInstanceCommandClass.getEndpoints()) {
for (ZWaveCommandClass endpointCommandClass : endpoint.getCommandClasses()) {
logger.trace("Inspecting command class {} for endpoint {}", endpointCommandClass.getCommandClass().getLabel(), endpoint.getEndpointId());
if (endpointCommandClass instanceof ZWaveCommandClassInitialization) {
logger.debug("Found initializable command class {}", endpointCommandClass.getCommandClass().getLabel());
ZWaveCommandClassInitialization zcci2 = (ZWaveCommandClassInitialization)endpointCommandClass;
Collection<SerialMessage> initqueries = zcci2.initialize();
for (SerialMessage serialMessage : initqueries) {
this.controller.sendData(this.encapsulate(serialMessage, endpointCommandClass, endpoint.getEndpointId()));
queriesPending++;
}
}
}
}
}
}
}
if (queriesPending-- > 0) // there is still something to be initialized.
break;
logger.trace("Done getting static values, proceeding to done node stage.", this.getNodeId());
case NODEBUILDINFO_STATIC:
this.setNodeStage(ZWaveNode.NodeStage.NODEBUILDINFO_DONE); // nothing more to do for this node.
initializationComplete = true;
if (this.isListening())
return;
ZWaveWakeUpCommandClass wakeup = (ZWaveWakeUpCommandClass)this.getCommandClass(ZWaveCommandClass.CommandClass.WAKE_UP);
if (wakeup == null)
return;
logger.debug("Node {} is a battery operated device. Tell it to go to sleep.", this.getNodeId());
this.controller.sendData(wakeup.getNoMoreInformationMessage());
break;
case NODEBUILDINFO_DONE:
case NODEBUILDINFO_DEAD:
break;
default:
logger.error("Unknown node state {} encountered on Node {}", this.nodeStage.getLabel(), this.getNodeId());
}
} | Advances the initialization stage for this node.
Every node follows a certain path through it's
initialization phase. These stages are visited one by
one to finally end up with a completely built node structure
through querying the controller / node.
TODO: Handle the rest of the node stages |
public SerialMessage encapsulate(SerialMessage serialMessage,
ZWaveCommandClass commandClass, int endpointId) {
ZWaveMultiInstanceCommandClass multiInstanceCommandClass;
if (serialMessage == null)
return null;
// no encapsulation necessary.
if (endpointId == 1 && commandClass.getInstances() == 1 && commandClass.getEndpoint() == null)
return serialMessage;
multiInstanceCommandClass = (ZWaveMultiInstanceCommandClass)this.getCommandClass(ZWaveCommandClass.CommandClass.MULTI_INSTANCE);
if (multiInstanceCommandClass != null) {
logger.debug("Encapsulating message for node {}, instance / endpoint {}", this.getNodeId(), endpointId);
switch (multiInstanceCommandClass.getVersion()) {
case 2:
if (commandClass.getEndpoint() != null) {
serialMessage = multiInstanceCommandClass.getMultiChannelEncapMessage(serialMessage, commandClass.getEndpoint());
return serialMessage;
}
break;
case 1:
default:
if (commandClass.getInstances() >= endpointId) {
serialMessage = multiInstanceCommandClass.getMultiInstanceEncapMessage(serialMessage, endpointId);
return serialMessage;
}
break;
}
}
if (endpointId != 1) {
logger.warn("Encapsulating message for node {}, instance / endpoint {} failed, will discard message.", this.getNodeId(), endpointId);
return null;
}
return serialMessage;
} | Encapsulates a serial message for sending to a
multi-instance instance/ multi-channel endpoint on
a node.
@param serialMessage the serial message to encapsulate
@param commandClass the command class used to generate the message.
@param endpointId the instance / endpoint to encapsulate the message for
@param node the destination node.
@return SerialMessage on success, null on failure. |
public static String getPostString(InputStream is, String encoding) {
try {
StringWriter sw = new StringWriter();
IOUtils.copy(is, sw, encoding);
return sw.toString();
} catch (IOException e) {
// no op
return null;
} finally {
IOUtils.closeQuietly(is);
}
} | get string from post stream
@param is
@param encoding
@return |
public static void outputString(final HttpServletResponse response, final Object obj) {
try {
response.setContentType("text/javascript");
response.setCharacterEncoding("utf-8");
disableCache(response);
response.getWriter().write(obj.toString());
response.getWriter().flush();
response.getWriter().close();
} catch (IOException e) {
}
} | response simple String
@param response
@param obj |
public byte[] getData(byte[] dst, int offset)
{
final int items = Math.min(data.length, dst.length - offset) / stringLength;
final int end = items * stringLength;
if (end == 0)
logger.error("destination range has to be multiple of 14 bytes "
+ "for KNX strings");
for (int i = 0; i < end; ++i)
dst[offset + i] = (byte) data[i];
return dst;
}
/* (non-Javadoc)
* @see tuwien.auto.calimero.dptxlator.DPTXlator#getSubTypes()
*/
public final Map getSubTypes()
{
return types;
}
/**
* @return the subtypes of the string translator type
* @see DPTXlator#getSubTypesStatic()
*/
protected static Map getSubTypesStatic()
{
return types;
}
private String fromDPT(int index)
{
final int offset = index * stringLength;
final char[] output = new char[stringLength];
int strlen = 0;
for (int i = offset; i < (offset + stringLength) && data[i] != 0; ++i) {
output[strlen] = (char) data[i];
++strlen;
}
return new String(output, 0, strlen);
}
private void toDPT(byte[] buf, int offset)
{
// check character set, default to ASCII 7 bit encoding
int rangeMax = 0x7f;
if (dpt.equals(DPT_STRING_8859_1))
rangeMax = 0xff;
final int items = (buf.length - offset) / stringLength;
if (items == 0) {
logger.error("source range has to be multiple of 14 bytes for KNX strings");
return;
}
data = new short[items * stringLength];
// 7 bit encoded characters of ISO-8859-1 are equal to ASCII
// the lower 256 characters of UCS correspond to ISO-8859-1
for (int i = 0; i < data.length; ++i) {
final short c = ubyte(buf[offset + i]);
data[i] = c <= rangeMax ? c : replacement;
}
} | /* (non-Javadoc)
@see tuwien.auto.calimero.dptxlator.DPTXlator#getData(byte[], int) |
@Override
public void handleApplicationCommandRequest(SerialMessage serialMessage,
int offset, int endpoint) {
logger.trace("Handle Message Switch Binary Request");
logger.debug(String.format("Received Switch Binary Request for Node ID = %d", this.getNode().getNodeId()));
int command = serialMessage.getMessagePayloadByte(offset);
switch (command) {
case SWITCH_BINARY_SET:
case SWITCH_BINARY_GET:
logger.warn(String.format("Command 0x%02X not implemented.", command));
return;
case SWITCH_BINARY_REPORT:
logger.trace("Process Switch Binary Report");
int value = serialMessage.getMessagePayloadByte(offset + 1);
logger.debug(String.format("Switch Binary report from nodeId = %d, value = 0x%02X", this.getNode().getNodeId(), value));
Object eventValue;
if (value == 0) {
eventValue = "OFF";
} else {
eventValue = "ON";
}
ZWaveEvent zEvent = new ZWaveEvent(ZWaveEventType.SWITCH_EVENT, this.getNode().getNodeId(), endpoint, eventValue);
this.getController().notifyEventListeners(zEvent);
break;
default:
logger.warn(String.format("Unsupported Command 0x%02X for command class %s (0x%02X).",
command,
this.getCommandClass().getLabel(),
this.getCommandClass().getKey()));
}
} | {@inheritDoc} |
public final synchronized void setDomainAddress(final byte[] domain)
{
if (domain == null)
doa = broadcastDomain;
else if (domain.length != 6)
throw new KNXIllegalArgumentException("invalid length of domain address");
else
doa = (byte[]) domain.clone();
} | Sets a new domain address.
<p>
@param domain byte array containing the domain address to use in KNX messages,
address is given in network byte order, <code>domain.length</code> = 6,
supplying <code>null</code> defaults to the broadcast domain |
public static Array2DRowRealMatrix getRadiusOfGyrationTensor(Trajectory t){
double meanx =0;
double meany =0;
for(int i = 0; i < t.size(); i++){
meanx+= t.get(i).x;
meany+= t.get(i).y;
}
meanx = meanx/t.size();
meany = meany/t.size();
double e11 = 0;
double e12 = 0;
double e21 = 0;
double e22 = 0;
for(int i = 0; i < t.size(); i++){
e11 += Math.pow(t.get(i).x-meanx,2);
e12 += (t.get(i).x-meanx)*(t.get(i).y-meany);
e22 += Math.pow(t.get(i).y-meany,2);
}
e11 = e11 / t.size();
e12 = e12 / t.size();
e21 = e12;
e22 = e22 / t.size();
int rows = 2;
int columns = 2;
Array2DRowRealMatrix gyr = new Array2DRowRealMatrix(rows, columns);
gyr.addToEntry(0, 0, e11);
gyr.addToEntry(0, 1, e12);
gyr.addToEntry(1, 0, e21);
gyr.addToEntry(1, 1, e22);
return gyr;
} | Calculates the radius of gyration tensor according to formula (6.3) in
ELEMENTS OF THE RANDOM WALK by Rudnick and Gaspari
@return Radius of gyration tensor |
public final void setDate(int year, int month, int day)
{
set(data, 0, YEAR, year);
set(data, 0, MONTH, month);
set(data, 0, DAY, day);
} | Sets year, month and day of month information of the first date/time item.
<p>
This method does not reset other item data or discard other translation items.
@param year year value, 1900 <= year <= 2155
@param month month value, 1 <= month <= 12
@param day day value, 1 <= day <= 31 |
public final void setValue(long milliseconds)
{
initCalendar();
synchronized (c) {
c.clear();
c.setTimeInMillis(milliseconds);
data = new short[8];
set(data, 0, YEAR, c.get(Calendar.YEAR));
set(data, 0, MONTH, c.get(Calendar.MONTH) + 1);
set(data, 0, DAY, c.get(Calendar.DAY_OF_MONTH));
set(data, 0, HOUR, c.get(Calendar.HOUR_OF_DAY));
set(data, 0, MINUTE, c.get(Calendar.MINUTE));
set(data, 0, SECOND, c.get(Calendar.SECOND));
final int dow = c.get(Calendar.DAY_OF_WEEK);
set(data, 0, DOW, dow == Calendar.SUNDAY ? 7 : dow - 1);
setBit(0, DST, c.get(Calendar.DST_OFFSET) != 0);
data[6] &= ~(NO_YEAR | NO_DATE | NO_TIME | NO_DOW);
}
} | Sets the date/time for the first date/time item using UTC millisecond information.
<p>
Following fields are set: year, month, day, day of week, hour, minute, second,
daylight time. All according fields are set to used state.<br>
The <code>value</code> is interpreted by a calendar obtained by
{@link Calendar#getInstance()}.<br>
The new value item replaces any other items contained in this translator.
@param milliseconds time value in milliseconds, as used by {@link Calendar} |
public final void setDateTimeFlag(int field, boolean value)
{
if (field == CLOCK_SYNC) {
setBitEx(0, QUALITY, value);
return;
}
final int f = field - WORKDAY;
if (f < 0 || f >= FLAG_MASKS.length)
throw new KNXIllegalArgumentException("illegal field");
setBit(0, FLAG_MASKS[f], value);
} | Sets date/time information for the given field of the first date/time item.
<p>
Allowed fields are {@link #CLOCK_FAULT}, {@link #CLOCK_SYNC}, {@link #WORKDAY}
and {@link #DAYLIGHT}.<br>
This method does not reset other item data or discard other translation items.
@param field field number
@param value <code>true</code> to set the information flag, <code>false</code>
to clear |
public final boolean isValidField(int field)
{
if (field < 0 || field >= FIELD_MASKS.length)
throw new KNXIllegalArgumentException("illegal field");
return !getBit(0, FIELD_MASKS[field]);
} | Returns whether a field is valid, i.e. supported and used for date/time
information.
<p>
Only data of valid fields are required to be set or examined. A field set to not
valid shall be ignored, it is not supported and contains no valid data.<br>
Possible fields allowed to be set valid or not valid are {@link #YEAR},
{@link #DATE}, {@link #TIME}, {@link #DAY_OF_WEEK} and {@link #WORKDAY}.
@param field field number
@return <code>true</code> if field is supported and in use, <code>false</code>
otherwise |
public byte[] getData(byte[] dst, int offset)
{
final int end = Math.min(data.length, dst.length - offset) & ~7;
for (int i = 0; i < end; ++i)
dst[offset + i] = (byte) data[i];
return dst;
}
/**
* Specifies the formatting to use for date/time string representations returned by
* the translator.
* <p>
* A string in extended format contains all valid information of the date/time type.
* In extended format, additionally the day of week, daylight time, work-day and clock
* synchronization signal information is considered in the output format. Otherwise
* this fields are always ignored, i.e only clock fault, year, month, day, hour,
* minute and second will get used, if valid.
* <p>
* The used format is extended by default.
*
* @param extended string format to use, <code>true</code> for extended format
*/
public final void useValueFormat(boolean extended)
{
extFormat = extended;
}
/* (non-Javadoc)
* @see tuwien.auto.calimero.dptxlator.DPTXlator#getSubTypes()
*/
public Map getSubTypes()
{
return types;
}
/**
* @return the subtypes of the date with time translator type
* @see DPTXlator#getSubTypesStatic()
*/
protected static Map getSubTypesStatic()
{
return types;
}
private void checkRange(int field, int v)
{
if (v < MIN_VALUES[field] || v > MAX_VALUES[field])
throw new KNXIllegalArgumentException(FIELDS[field] + " out of range: " + v);
}
// check on hour = 24, minutes and seconds have to be 0
private boolean check24Hours(int hr, int min, int sec)
{
if (hr != 24 || min == 0 && sec == 0)
return true;
return false;
}
private String fromDPT(int index)
{
if (getBit(index, FAULT))
return "corrupted date/time";
final StringBuffer sb = new StringBuffer(20);
final int i = index * 8;
// year
if (!getBit(index, NO_YEAR))
sb.append(data[i] + MIN_YEAR);
if (!getBit(index, NO_DATE)) {
// month
sb.append('/').append(data[i + 1]);
// day
sb.append('/').append(data[i + 2]);
}
if (extFormat) {
if (!getBit(index, NO_DOW))
sb.append(", ").append(DAYS[data[i + 3] >> 5]);
if (!getBit(index, NO_WD))
sb.append(getBit(index, WD) ? " (" : " (no ").append(WORKDAY_SIGN)
.append(')');
}
if (!getBit(index, NO_TIME)) {
// hr:min:sec
sb.append(' ').append(data[i + 3] & 0x1F);
sb.append(':').append(data[i + 4]).append(':').append(data[i + 5]);
// daylight saving time
if (extFormat && getBit(index, DST))
sb.append(' ').append(DAYLIGHT_SIGN);
}
if (extFormat)
sb.append(getBitEx(index, QUALITY) ? ", in " : ", no ").append(SYNC_SIGN);
return sb.toString();
}
private long fromDPTMilliseconds(int index) throws KNXFormatException
{
if (getBit(index, FAULT) || !isValidField(index, YEAR)
|| !isValidField(index, DATE))
throw new KNXFormatException("insufficient information for calendar");
initCalendar();
final int i = index * 8;
synchronized (c) {
c.clear();
c.set(data[i] + MIN_YEAR, data[i + 1] - 1, data[i + 2]);
if (isValidField(index, TIME)) {
// we use 23:59:59.999 in calendar for 24:00:00
final boolean cheat = (data[i + 3] & 0x1F) == 24;
c.set(Calendar.HOUR_OF_DAY, cheat ? 23 : data[i + 3] & 0x1F);
c.set(Calendar.MINUTE, cheat ? 59 : data[i + 4]);
c.set(Calendar.SECOND, cheat ? 59 : data[i + 5]);
if (cheat)
c.set(Calendar.MILLISECOND, 999);
}
try {
final long ms = c.getTimeInMillis();
if (isValidField(index, DAY_OF_WEEK)) {
int day = c.get(Calendar.DAY_OF_WEEK);
day = day == Calendar.SUNDAY ? 7 : day - 1;
if ((data[i + 3] >> 5) != day)
throw new KNXFormatException("differing day of week");
}
if (getDateTimeFlag(index, DAYLIGHT) != (c.get(Calendar.DST_OFFSET) != 0))
throw new KNXFormatException("differing daylight saving time");
return ms;
}
catch (final IllegalArgumentException e) {
throw new KNXFormatException("invalid calendar value " + e.getMessage());
}
}
}
private boolean getDateTimeFlag(int index, int field)
{
if (field == CLOCK_SYNC)
return getBitEx(index, QUALITY);
final int f = field - WORKDAY;
if (f < 0 || f >= FLAG_MASKS.length)
throw new KNXIllegalArgumentException("illegal field");
return getBit(index, FLAG_MASKS[f]);
}
private boolean isValidField(int index, int field)
{
return !getBit(index, FIELD_MASKS[field]);
}
private boolean getBit(int index, int mask)
{
return (data[8 * index + 6] & mask) != 0;
}
private boolean getBitEx(int index, int mask)
{
return (data[8 * index + 7] & mask) != 0;
}
private void set(short[] dst, int index, int field, int v)
{
checkRange(field, v);
final int i = 8 * index + field;
if (field == YEAR)
dst[i] = (short) (v - MIN_YEAR);
else if (field == DOW)
// NOTE: DoW id is not field index
dst[i - 3] = (short) (v << 5 | (dst[i - 3] & 0x1F));
else if (field == HOUR)
dst[i] = (short) (v | (dst[i] & 0xE0));
else
dst[i] = (short) v;
}
private void setBit(int index, int mask, boolean bit)
{
setBit(data, index, mask, bit);
}
private void setBit(short[] dst, int index, int mask, boolean bit)
{
if (bit)
dst[8 * index + 6] |= mask;
else
dst[8 * index + 6] &= ~mask;
}
private void setBitEx(int index, int mask, boolean bit)
{
setBitEx(data, index, mask, bit);
}
private void setBitEx(short[] v, int index, int mask, boolean bit)
{
if (bit)
v[8 * index + 7] |= mask;
else
v[8 * index + 7] &= ~mask;
}
// dst is assumed to be cleared
protected void toDPT(String value, short[] dst, int index) throws KNXFormatException
{
final StringTokenizer t = new StringTokenizer(value, ":-/ (,.)");
final int k = 8 * index;
// dpt fields: yr mth day [doW hr] min sec [dst wd] sync
// mark all fields not used
dst[k + 6] = NO_WD | NO_YEAR | NO_DATE | NO_DOW | NO_TIME;
int sync = 0;
int day = 0;
final int maxTokens = 10;
final short[] numbers = new short[maxTokens];
int count = 0;
// parse whole string, only handle word and year tokens, store numbers
for (int i = 0; i < maxTokens && t.hasMoreTokens(); ++i) {
final String s = t.nextToken();
try {
final short no = Short.parseShort(s);
if (no < 0)
throw logThrow(LogLevel.WARN, "negative date/time " + s, null, s);
if (no >= MIN_YEAR && no <= MAX_YEAR) {
set(dst, index, YEAR, no);
setBit(dst, index, NO_YEAR, false);
}
else
numbers[count++] = no;
}
catch (final NumberFormatException e) {
// parse number failed, check for word token
if (s.equalsIgnoreCase(DAYLIGHT_SIGN))
setBit(dst, index, DST, true);
else if (s.equalsIgnoreCase(WORKDAY_SIGN)) {
setBit(dst, index, NO_WD, false);
setBit(dst, index, WD, true);
}
else if (s.equalsIgnoreCase("no") || s.equalsIgnoreCase("in")) {
if (++sync > 1 || !t.hasMoreTokens()
|| !t.nextToken().equalsIgnoreCase(SYNC_SIGN))
throw logThrow(LogLevel.WARN, s + ": '" + SYNC_SIGN
+ "' expected", null, s);
// check sync'd or not sync'd
if (s.charAt(0) == 'i' || s.charAt(0) == 'I')
setBitEx(dst, index, QUALITY, true);
}
else if (s.length() == 3 && ++day == 1) {
final String prefix = s.toLowerCase();
int dow = DAYS.length - 1;
while (dow >= 0 && !DAYS[dow].toLowerCase().startsWith(prefix))
--dow;
final boolean anyday = dow == 0 && t.hasMoreTokens()
&& t.nextToken().equalsIgnoreCase("day");
if (dow <= 0 && !anyday)
throw logThrow(LogLevel.WARN, s + ": wrong weekday", null, s);
set(dst, index, DOW, dow);
setBit(dst, index, NO_DOW, false);
}
else
throw logThrow(LogLevel.WARN, "wrong date/time " + s, null, s);
}
}
// find out date/time combination, and store numbers into fields
if (count == 0)
return;
if (count == 1 || count == 4)
throw logThrow(LogLevel.WARN, "ambiguous date/time " + value, null, value);
int field = count == 3 ? HOUR : MONTH;
if (field == HOUR || count == 5)
setBit(dst, index, NO_TIME, false);
if (field == MONTH)
setBit(dst, index, NO_DATE, false);
for (int i = 0; i < count; ++i, ++field)
set(dst, index, field, numbers[i]);
// check time field, if set
if (field == SECOND + 1
&& !check24Hours(numbers[count - 3], numbers[count - 2], numbers[count - 1]))
throw logThrow(LogLevel.WARN, "incorrect time " + value, null, value);
}
private static synchronized void initCalendar()
{
if (c == null) {
c = Calendar.getInstance();
c.setLenient(false);
}
}
} | /* (non-Javadoc)
@see tuwien.auto.calimero.dptxlator.DPTXlator#getData(byte[], int) |
public double convert(double value, double temperatur, double viscosity){
return temperatur*kB / (Math.PI*viscosity*value);
} | Converters the diffusion coefficient to hydrodynamic diameter and vice versa
@param value Diffusion coefficient in [m^2 s^-1] or hydrodynamic diameter in [m]
@param temperatur Temperatur in [Kelvin]
@param viscosity Viscosity in [kg m^-1 s^-1]
@return Hydrodynmaic diameter [m] / diffusion coefficient [m^2 s^-1] |
public static double ViscosityByAndradeEquation(double temperatur, SOLVENT s){
double res = 0;
double a;
double b;
switch (s) {
case WATER:
if(temperatur<274 || temperatur>373){
throw new IllegalArgumentException("The andrade equation can not be applied for this solvent/temperatur combination.");
}
a = -6.944;
b = 2036.8;
res = Math.exp(a+b/temperatur)*Math.pow(10, -3);
break;
case BENZENE:
if(temperatur<273 || temperatur>483){
throw new IllegalArgumentException("The andrade equation can not be applied for this solvent/temperatur combination.");
}
a = -4.825;
b = 1289.2;
res = Math.exp(a+b/temperatur)*Math.pow(10, -3);
break;
case ACETONE:
if(temperatur<183 || temperatur>329){
throw new IllegalArgumentException("The andrade equation can not be applied for this solvent/temperatur combination.");
}
a = -4.003;
b = 842.5;
res = Math.exp(a+b/temperatur)*Math.pow(10, -3);
break;
case ETHANOL:
if(temperatur<163 || temperatur>516){
throw new IllegalArgumentException("The andrade equation can not be applied for this solvent/temperatur combination.");
}
a = -5.878;
b = 1755.8;
res = Math.exp(a+b/temperatur)*Math.pow(10, -3);
break;
default:
break;
}
return res;
} | Calculates the viscosity for different solvent in dependence from the temperatur [k]. Please see
https://de.wikipedia.org/wiki/Andrade-Gleichung
@param temperatur Temperatur in Kelvin [K]
@return Viscosity in [kg m^-1 s^-1] |
short getStructLength()
{
int len = device.getStructLength() + suppfam.getStructLength();
if (mfr != null)
len += mfr.getStructLength();
return (short) len;
} | /* (non-Javadoc)
@see tuwien.auto.calimero.knxnetip.servicetype.ServiceType#getStructLength() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.