idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
38,100 | @ SuppressWarnings ( "unchecked" ) public void setJsonToken ( HashMap < String , Object > jRTObject , Story storyContext ) throws Exception { threads . clear ( ) ; List < Object > jThreads = ( List < Object > ) jRTObject . get ( "threads" ) ; for ( Object jThreadTok : jThreads ) { HashMap < String , Object > jThreadObj = ( HashMap < String , Object > ) jThreadTok ; Thread thread = new Thread ( jThreadObj , storyContext ) ; threads . add ( thread ) ; } threadCounter = ( int ) jRTObject . get ( "threadCounter" ) ; } | look up RTObjects from paths for currentContainer within elements . |
38,101 | public Iterable < Entry < String , ProfileNode > > getDescendingOrderedNodes ( ) { if ( nodes == null ) return null ; List < Entry < String , ProfileNode > > averageStepTimes = new LinkedList < Entry < String , ProfileNode > > ( nodes . entrySet ( ) ) ; Collections . sort ( averageStepTimes , new Comparator < Entry < String , ProfileNode > > ( ) { public int compare ( Entry < String , ProfileNode > o1 , Entry < String , ProfileNode > o2 ) { return ( int ) ( o1 . getValue ( ) . totalMillisecs - o2 . getValue ( ) . totalMillisecs ) ; } } ) ; return averageStepTimes ; } | Returns a sorted enumerable of the nodes in descending order of how long they took to run . |
38,102 | VariablePointerValue resolveVariablePointer ( VariablePointerValue varPointer ) throws Exception { int contextIndex = varPointer . getContextIndex ( ) ; if ( contextIndex == - 1 ) contextIndex = getContextIndexOfVariableNamed ( varPointer . getVariableName ( ) ) ; RTObject valueOfVariablePointedTo = getRawVariableWithName ( varPointer . getVariableName ( ) , contextIndex ) ; VariablePointerValue doubleRedirectionPointer = valueOfVariablePointedTo instanceof VariablePointerValue ? ( VariablePointerValue ) valueOfVariablePointedTo : ( VariablePointerValue ) null ; if ( doubleRedirectionPointer != null ) { return doubleRedirectionPointer ; } else { return new VariablePointerValue ( varPointer . getVariableName ( ) , contextIndex ) ; } } | or the exact position of a temporary on the callstack . |
38,103 | StoryState copy ( ) { StoryState copy = new StoryState ( story ) ; copy . getOutputStream ( ) . addAll ( outputStream ) ; outputStreamDirty ( ) ; copy . currentChoices . addAll ( currentChoices ) ; if ( hasError ( ) ) { copy . currentErrors = new ArrayList < String > ( ) ; copy . currentErrors . addAll ( currentErrors ) ; } if ( hasWarning ( ) ) { copy . currentWarnings = new ArrayList < String > ( ) ; copy . currentWarnings . addAll ( currentWarnings ) ; } copy . callStack = new CallStack ( callStack ) ; copy . variablesState = new VariablesState ( copy . callStack , story . getListDefinitions ( ) ) ; copy . variablesState . copyFrom ( variablesState ) ; copy . evaluationStack . addAll ( evaluationStack ) ; if ( ! divertedPointer . isNull ( ) ) copy . divertedPointer . assign ( divertedPointer ) ; copy . setPreviousPointer ( getPreviousPointer ( ) ) ; copy . visitCounts = new HashMap < String , Integer > ( visitCounts ) ; copy . turnIndices = new HashMap < String , Integer > ( turnIndices ) ; copy . currentTurnIndex = currentTurnIndex ; copy . storySeed = storySeed ; copy . previousRandom = previousRandom ; copy . setDidSafeExit ( didSafeExit ) ; return copy ; } | I wonder if there s a sensible way to enforce that .. ?? |
38,104 | void trimWhitespaceFromFunctionEnd ( ) { assert ( callStack . getCurrentElement ( ) . type == PushPopType . Function ) ; int functionStartPoint = callStack . getCurrentElement ( ) . functionStartInOuputStream ; if ( functionStartPoint == - 1 ) { functionStartPoint = 0 ; } for ( int i = outputStream . size ( ) - 1 ; i >= functionStartPoint ; i -- ) { RTObject obj = outputStream . get ( i ) ; if ( ! ( obj instanceof StringValue ) ) continue ; StringValue txt = ( StringValue ) obj ; if ( obj instanceof ControlCommand ) break ; if ( txt . isNewline ( ) || txt . isInlineWhitespace ( ) ) { outputStream . remove ( i ) ; outputStreamDirty ( ) ; } else { break ; } } } | whitespace is trimmed in one go here when we pop the function . |
38,105 | public HashMap < String , Object > getJsonToken ( ) throws Exception { HashMap < String , Object > obj = new HashMap < String , Object > ( ) ; HashMap < String , Object > choiceThreads = null ; for ( Choice c : currentChoices ) { c . originalThreadIndex = c . getThreadAtGeneration ( ) . threadIndex ; if ( callStack . getThreadWithIndex ( c . originalThreadIndex ) == null ) { if ( choiceThreads == null ) choiceThreads = new HashMap < String , Object > ( ) ; choiceThreads . put ( Integer . toString ( c . originalThreadIndex ) , c . getThreadAtGeneration ( ) . jsonToken ( ) ) ; } } if ( choiceThreads != null ) obj . put ( "choiceThreads" , choiceThreads ) ; obj . put ( "callstackThreads" , callStack . getJsonToken ( ) ) ; obj . put ( "variablesState" , variablesState . getjsonToken ( ) ) ; obj . put ( "evalStack" , Json . listToJArray ( evaluationStack ) ) ; obj . put ( "outputStream" , Json . listToJArray ( outputStream ) ) ; obj . put ( "currentChoices" , Json . listToJArray ( currentChoices ) ) ; if ( ! divertedPointer . isNull ( ) ) obj . put ( "currentDivertTarget" , getDivertedPointer ( ) . getPath ( ) . getComponentsString ( ) ) ; obj . put ( "visitCounts" , Json . intHashMapToJObject ( visitCounts ) ) ; obj . put ( "turnIndices" , Json . intHashMapToJObject ( turnIndices ) ) ; obj . put ( "turnIdx" , currentTurnIndex ) ; obj . put ( "storySeed" , storySeed ) ; obj . put ( "previousRandom" , previousRandom ) ; obj . put ( "inkSaveVersion" , kInkSaveStateVersion ) ; obj . put ( "inkFormatVersion" , Story . inkVersionCurrent ) ; return obj ; } | Object representation of full JSON state . Usually you should use LoadJson and ToJson since they serialise directly to String for you . But it may be useful to get the object representation so that you can integrate it into your own serialisation system . |
38,106 | void pushToOutputStream ( RTObject obj ) { StringValue text = obj instanceof StringValue ? ( StringValue ) obj : null ; if ( text != null ) { List < StringValue > listText = trySplittingHeadTailWhitespace ( text ) ; if ( listText != null ) { for ( StringValue textObj : listText ) { pushToOutputStreamIndividual ( textObj ) ; } outputStreamDirty ( ) ; return ; } } pushToOutputStreamIndividual ( obj ) ; } | in dealing with them later . |
38,107 | void removeExistingGlue ( ) { for ( int i = outputStream . size ( ) - 1 ; i >= 0 ; i -- ) { RTObject c = outputStream . get ( i ) ; if ( c instanceof Glue ) { outputStream . remove ( i ) ; } else if ( c instanceof ControlCommand ) { break ; } } outputStreamDirty ( ) ; } | Only called when non - whitespace is appended |
38,108 | List < StringValue > trySplittingHeadTailWhitespace ( StringValue single ) { String str = single . value ; int headFirstNewlineIdx = - 1 ; int headLastNewlineIdx = - 1 ; for ( int i = 0 ; i < str . length ( ) ; ++ i ) { char c = str . charAt ( i ) ; if ( c == '\n' ) { if ( headFirstNewlineIdx == - 1 ) headFirstNewlineIdx = i ; headLastNewlineIdx = i ; } else if ( c == ' ' || c == '\t' ) continue ; else break ; } int tailLastNewlineIdx = - 1 ; int tailFirstNewlineIdx = - 1 ; for ( int i = 0 ; i < str . length ( ) ; ++ i ) { char c = str . charAt ( i ) ; if ( c == '\n' ) { if ( tailLastNewlineIdx == - 1 ) tailLastNewlineIdx = i ; tailFirstNewlineIdx = i ; } else if ( c == ' ' || c == '\t' ) continue ; else break ; } if ( headFirstNewlineIdx == - 1 && tailLastNewlineIdx == - 1 ) return null ; List < StringValue > listTexts = new ArrayList < StringValue > ( ) ; int innerStrStart = 0 ; int innerStrEnd = str . length ( ) ; if ( headFirstNewlineIdx != - 1 ) { if ( headFirstNewlineIdx > 0 ) { StringValue leadingSpaces = new StringValue ( str . substring ( 0 , headFirstNewlineIdx ) ) ; listTexts . add ( leadingSpaces ) ; } listTexts . add ( new StringValue ( "\n" ) ) ; innerStrStart = headLastNewlineIdx + 1 ; } if ( tailLastNewlineIdx != - 1 ) { innerStrEnd = tailFirstNewlineIdx ; } if ( innerStrEnd > innerStrStart ) { String innerStrText = str . substring ( innerStrStart , innerStrEnd ) ; listTexts . add ( new StringValue ( innerStrText ) ) ; } if ( tailLastNewlineIdx != - 1 && tailFirstNewlineIdx > headLastNewlineIdx ) { listTexts . add ( new StringValue ( "\n" ) ) ; if ( tailLastNewlineIdx < str . length ( ) - 1 ) { int numSpaces = ( str . length ( ) - tailLastNewlineIdx ) - 1 ; StringValue trailingSpaces = new StringValue ( str . substring ( tailLastNewlineIdx + 1 , numSpaces + tailLastNewlineIdx + 1 ) ) ; listTexts . add ( trailingSpaces ) ; } } return listTexts ; } | - A newline on its own is returned in an list for consistency . |
38,109 | public String report ( ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( String . format ( "%d CONTINUES / LINES:\n" , numContinues ) ) ; sb . append ( String . format ( "TOTAL TIME: %s\n" , formatMillisecs ( continueTotal ) ) ) ; sb . append ( String . format ( "SNAPSHOTTING: %s\n" , formatMillisecs ( snapTotal ) ) ) ; sb . append ( String . format ( "OTHER: %s\n" , formatMillisecs ( continueTotal - ( stepTotal + snapTotal ) ) ) ) ; sb . append ( rootNode . toString ( ) ) ; return sb . toString ( ) ; } | Generate a printable report based on the data recording during profiling . |
38,110 | public String megalog ( ) { StringBuilder sb = new StringBuilder ( ) ; sb . append ( "Step type\tDescription\tPath\tTime\n" ) ; for ( StepDetails step : stepDetails ) { sb . append ( step . type ) ; sb . append ( "\t" ) ; sb . append ( step . obj . toString ( ) ) ; sb . append ( "\t" ) ; sb . append ( step . obj . getPath ( ) ) ; sb . append ( "\t" ) ; sb . append ( Double . toString ( step . time ) ) ; sb . append ( '\n' ) ; } return sb . toString ( ) ; } | Create a large log of all the internal instructions that were evaluated while profiling was active . Log is in a tab - separated format for easy loading into a spreadsheet application . |
38,111 | public void awaitNanos ( final long timeout ) throws InterruptedException { long remaining = timeout ; queueLock . lock ( ) ; try { while ( test ( ) && remaining > 0 ) { remaining = condition . awaitNanos ( remaining ) ; } } finally { queueLock . unlock ( ) ; } } | wake me when the condition is satisfied or timeout |
38,112 | public void await ( ) throws InterruptedException { queueLock . lock ( ) ; try { while ( test ( ) ) { condition . await ( ) ; } } finally { queueLock . unlock ( ) ; } } | wake if signal is called or wait indefinitely |
38,113 | public boolean push ( final N n ) { if ( stackTop < size ) { stack [ ( stackTop ++ ) & mask ] = n ; return true ; } return false ; } | add an element to the stack |
38,114 | public void clear ( ) { for ( int i = 1 ; i <= 2 * m + 3 ; i ++ ) { n [ i ] = i + 1 ; } f [ 1 ] = 0F ; f [ 2 * m + 3 ] = 1F ; for ( int i = 1 ; i <= m ; i ++ ) { f [ 2 * i + 1 ] = quantiles [ i - 1 ] ; } for ( int i = 1 ; i <= m + 1 ; i ++ ) { f [ 2 * i ] = ( f [ 2 * i - 1 ] + f [ 2 * i + 1 ] ) / 2F ; } for ( int i = 1 ; i <= 2 * m + 3 ; i ++ ) { d [ i ] = 1F + 2 * ( m + 1 ) * f [ i ] ; } isInitializing = true ; ni = 1 ; } | clear existing samples |
38,115 | public void add ( final float x ) { if ( isInitializing ) { q [ ni ++ ] = x ; if ( ni == 2 * m + 3 + 1 ) { Arrays . sort ( q ) ; isInitializing = false ; } } else { addMeasurement ( x ) ; } } | Add a measurement to estimate |
38,116 | public float [ ] getEstimates ( ) throws InsufficientSamplesException { if ( ! isInitializing ) { for ( int i = 1 ; i <= m ; i ++ ) { e [ i - 1 ] = q [ 2 * i + 1 ] ; } return e ; } else { throw new InsufficientSamplesException ( ) ; } } | get the estimates based on the last sample |
38,117 | public static void print ( final PrintStream out , final String name , final Percentile p ) { if ( p . isReady ( ) ) { try { final StringBuilder sb = new StringBuilder ( 512 ) ; final float [ ] q = p . getQuantiles ( ) ; final float [ ] e = p . getEstimates ( ) ; final int SCREENWIDTH = 80 ; sb . append ( name ) ; sb . append ( ", min(" ) ; sb . append ( p . getMin ( ) ) ; sb . append ( "), max(" ) ; sb . append ( p . getMax ( ) ) ; sb . append ( ')' ) ; sb . append ( "\n" ) ; final float max = e [ e . length - 1 ] ; for ( int i = 0 ; i < q . length ; i ++ ) { sb . append ( String . format ( "%4.3f" , q [ i ] ) ) ; sb . append ( ": " ) ; final int len = ( int ) ( e [ i ] / max * SCREENWIDTH ) ; for ( int j = 0 ; j < len ; j ++ ) { sb . append ( '#' ) ; } sb . append ( " " ) ; sb . append ( String . format ( "%4.3f\n" , e [ i ] ) ) ; } out . println ( sb . toString ( ) ) ; } catch ( InsufficientSamplesException e ) { } } } | print a nice histogram of percentiles |
38,118 | public final boolean push ( final N n ) { int spin = 0 ; for ( ; ; ) { final long writeLock = seqLock . tryWriteLock ( ) ; if ( writeLock > 0L ) { try { final int stackTop = this . stackTop . get ( ) ; if ( size > stackTop ) { try { stack . set ( stackTop , n ) ; stackNotEmptyCondition . signal ( ) ; return true ; } finally { this . stackTop . set ( stackTop + 1 ) ; } } else { return false ; } } finally { seqLock . unlock ( writeLock ) ; } } spin = Condition . progressiveYield ( spin ) ; } } | add an element to the stack failing if the stack is unable to grow |
38,119 | public final N peek ( ) { int spin = 0 ; for ( ; ; ) { final long readLock = seqLock . readLock ( ) ; final int stackTop = this . stackTop . get ( ) ; if ( stackTop > 0 ) { final N n = stack . get ( stackTop - 1 ) ; if ( seqLock . readLockHeld ( readLock ) ) { return n ; } } else { return null ; } spin = Condition . progressiveYield ( spin ) ; } } | peek at the top of the stack |
38,120 | public final void clear ( ) { int spin = 0 ; for ( ; ; ) { final long writeLock = seqLock . tryWriteLock ( ) ; if ( writeLock > 0L ) { final int stackTop = this . stackTop . get ( ) ; if ( stackTop > 0 ) { try { for ( int i = 0 ; i < stackTop ; i ++ ) { stack . set ( i , null ) ; } stackNotFullCondition . signal ( ) ; return ; } finally { this . stackTop . set ( 0 ) ; } } else { return ; } } spin = Condition . progressiveYield ( spin ) ; } } | clear the stack - does not null old references |
38,121 | public static int getCapacity ( int capacity ) { int c = 1 ; if ( capacity >= MAX_POWER2 ) { c = MAX_POWER2 ; } else { while ( c < capacity ) c <<= 1 ; } if ( isPowerOf2 ( c ) ) { return c ; } else { throw new RuntimeException ( "Capacity is not a power of 2." ) ; } } | return the next power of two after |
38,122 | public static Class < ? > getPrimitiveType ( Class < ? > wrapperType ) { if ( Boolean . class . equals ( wrapperType ) ) { return Boolean . TYPE ; } else if ( Byte . class . equals ( wrapperType ) ) { return Byte . TYPE ; } else if ( Character . class . equals ( wrapperType ) ) { return Character . TYPE ; } else if ( Short . class . equals ( wrapperType ) ) { return Short . TYPE ; } else if ( Integer . class . equals ( wrapperType ) ) { return Integer . TYPE ; } else if ( Long . class . equals ( wrapperType ) ) { return Long . TYPE ; } else if ( Float . class . equals ( wrapperType ) ) { return Float . TYPE ; } else if ( Double . class . equals ( wrapperType ) ) { return Double . TYPE ; } else { return null ; } } | Returns the corresponding primitive type for the given primitive wrapper or null if the type is not a primitive wrapper . |
38,123 | private static String getEncodingName ( final InputStream is , final byte [ ] start , final int count ) { final int b0 = start [ 0 ] & 0xFF ; final int b1 = start [ 1 ] & 0xFF ; final int b2 = start [ 2 ] & 0xFF ; if ( count > 1 ) { if ( b0 == 0xFE && b1 == 0xFF ) return "UTF-16BE" ; if ( b0 == 0xFF && b1 == 0xFE ) return "UTF-16LE" ; } if ( count >= 3 ) if ( b0 == 0xEF && b1 == 0xBB && b2 == 0xBF ) { try { is . skip ( 3 ) ; } catch ( final IOException ignore ) { } return "UTF-8" ; } if ( count == 4 ) { final byte [ ] [ ] arrays = { { ( byte ) 0x00 , ( byte ) 0x00 , ( byte ) 0x00 , ( byte ) 0x3C } , { ( byte ) 0x3C , ( byte ) 0x00 , ( byte ) 0x00 , ( byte ) 0x00 } , { ( byte ) 0x00 , ( byte ) 0x3C , ( byte ) 0x00 , ( byte ) 0x3F } , { ( byte ) 0x3C , ( byte ) 0x00 , ( byte ) 0x3F , ( byte ) 0x00 } , { ( byte ) 0x4C , ( byte ) 0x6F , ( byte ) 0xA7 , ( byte ) 0x94 } } ; final String [ ] encodings = { "ISO-10646-UCS-4" , "ISO-10646-UCS-4" , "UTF-16BE" , "UTF-16LE" , "CP037" } ; for ( int i = 0 ; i < encodings . length ; ++ i ) if ( Arrays . equals ( arrays [ i ] , start ) ) return encodings [ i ] ; } return "UTF-8" ; } | the detection is done equally to the one in xerces parser |
38,124 | private int restart ( final boolean basic , final Destination dst , final int eraseCode , final int channel ) throws KNXTimeoutException , KNXRemoteException , KNXLinkClosedException , KNXDisconnectException , InterruptedException { int time = 0 ; if ( basic ) { send ( dst , priority , DataUnitBuilder . createLengthOptimizedAPDU ( RESTART , null ) , 0 ) ; } else { final byte [ ] sdu = new byte [ ] { 0x01 , ( byte ) eraseCode , ( byte ) channel , } ; final byte [ ] send = DataUnitBuilder . createLengthOptimizedAPDU ( RESTART , sdu ) ; final byte [ ] apdu = sendWait2 ( dst , priority , send , RESTART , 3 , 3 ) ; if ( ( apdu [ 1 ] & 0x32 ) == 0 ) throw new KNXInvalidResponseException ( "restart response bit not set" ) ; final String [ ] codes = new String [ ] { "Success" , "Access Denied" , "Unsupported Erase Code" , "Invalid Channel Number" , "Unknown Error" } ; final int error = Math . min ( apdu [ 2 ] & 0xff , 4 ) ; if ( error > 0 ) throw new KNXRemoteException ( "master reset: " + codes [ error ] ) ; time = ( ( apdu [ 3 ] & 0xff ) << 8 ) | ( apdu [ 4 ] & 0xff ) ; } if ( dst . isConnectionOriented ( ) ) { final Object lock = new Object ( ) ; final TransportListener l = new TLListener ( ) { public void disconnected ( final Destination d ) { if ( d . equals ( dst ) ) synchronized ( lock ) { lock . notify ( ) ; } } ; } ; tl . addTransportListener ( l ) ; try { synchronized ( lock ) { while ( dst . getState ( ) != Destination . State . Disconnected ) lock . wait ( ) ; } } finally { tl . removeTransportListener ( l ) ; } tl . disconnect ( dst ) ; } return time ; } | for erase codes 1 3 4 the channel should be 0 |
38,125 | List < byte [ ] > readProperty2 ( final Destination dst , final int objIndex , final int propertyId , final int start , final int elements ) throws KNXTimeoutException , KNXRemoteException , KNXDisconnectException , KNXLinkClosedException , InterruptedException { return readProperty ( dst , objIndex , propertyId , start , elements , false ) ; } | as readProperty but collects all responses until response timeout is reached |
38,126 | private void send ( final Destination d , final Priority p , final byte [ ] apdu , final int response ) throws KNXTimeoutException , KNXDisconnectException , KNXLinkClosedException { svcResponse = response ; if ( d . isConnectionOriented ( ) ) { tl . connect ( d ) ; tl . sendData ( d , p , apdu ) ; } else tl . sendData ( d . getAddress ( ) , p , apdu ) ; } | helper which sets the expected svc response and sends in CO or CL mode |
38,127 | private static byte [ ] extractPropertyElements ( final byte [ ] apdu , final int objIndex , final int propertyId , final int elements ) throws KNXRemoteException { final int oi = apdu [ 2 ] & 0xff ; final int pid = apdu [ 3 ] & 0xff ; if ( oi != objIndex || pid != propertyId ) throw new KNXInvalidResponseException ( String . format ( "property response mismatch, expected OI %d PID %d (received %d|%d)" , objIndex , propertyId , oi , pid ) ) ; final int number = ( apdu [ 4 ] & 0xFF ) >>> 4 ; if ( number == 0 ) throw new KNXRemoteException ( "property access OI " + oi + " PID " + pid + " failed/forbidden" ) ; if ( number != elements ) throw new KNXInvalidResponseException ( String . format ( "property access OI %d PID %d expected %d elements (received %d)" , oi , pid , elements , number ) ) ; final byte [ ] prop = new byte [ apdu . length - 6 ] ; for ( int i = 0 ; i < prop . length ; ++ i ) prop [ i ] = apdu [ i + 6 ] ; return prop ; } | returns property read . res element values |
38,128 | private static Collection < ? extends KNXAddress > ensureDeviceAck ( final KNXMediumSettings settings , final Collection < ? extends KNXAddress > acknowledge ) { if ( settings . getMedium ( ) != KNXMediumSettings . MEDIUM_TP1 ) throw new KNXIllegalArgumentException ( "TP-UART link supports only TP1 medium" ) ; final IndividualAddress device = settings . getDeviceAddress ( ) ; if ( device . getDevice ( ) == 0 || device . getDevice ( ) == 0xff ) return acknowledge ; final ArrayList < KNXAddress > l = new ArrayList < > ( acknowledge ) ; l . add ( device ) ; return l ; } | if possible add this link to the list of addresses to acknowledge |
38,129 | public void setProperty ( final int objectType , final int objectInstance , final int propertyId , final int start , final int elements , final byte ... data ) throws KNXTimeoutException , KNXRemoteException , KNXPortClosedException , InterruptedException { final CEMIDevMgmt req = new CEMIDevMgmt ( CEMIDevMgmt . MC_PROPWRITE_REQ , objectType , objectInstance , propertyId , start , elements , data ) ; send ( req , null ) ; findFrame ( CEMIDevMgmt . MC_PROPWRITE_CON , req ) ; } | Sets property value elements of an interface object property . |
38,130 | public byte [ ] getProperty ( final int objectType , final int objectInstance , final int propertyId , final int start , final int elements ) throws KNXTimeoutException , KNXRemoteException , KNXPortClosedException , InterruptedException { final CEMIDevMgmt req = new CEMIDevMgmt ( CEMIDevMgmt . MC_PROPREAD_REQ , objectType , objectInstance , propertyId , start , elements ) ; send ( req , null ) ; return findFrame ( CEMIDevMgmt . MC_PROPREAD_CON , req ) ; } | Gets property value elements of an interface object property . |
38,131 | private Optional < InetAddress > onSameSubnet ( final InetAddress remote ) { try { return Collections . list ( NetworkInterface . getNetworkInterfaces ( ) ) . stream ( ) . flatMap ( ni -> ni . getInterfaceAddresses ( ) . stream ( ) ) . filter ( ia -> ia . getAddress ( ) instanceof Inet4Address ) . peek ( ia -> logger . trace ( "match local address {}/{} to {}" , ia . getAddress ( ) , ia . getNetworkPrefixLength ( ) , remote ) ) . filter ( ia -> matchesPrefix ( ia . getAddress ( ) , ia . getNetworkPrefixLength ( ) , remote ) ) . map ( ia -> ia . getAddress ( ) ) . findFirst ( ) ; } catch ( final SocketException ignore ) { } return Optional . empty ( ) ; } | finds a local IPv4 address with its network prefix matching the remote address |
38,132 | private Destination getOrCreateDestination ( final IndividualAddress device , final boolean keepAlive , final boolean verifyByServer ) { final Destination d = ( ( TransportLayerImpl ) tl ) . getDestination ( device ) ; return d != null ? d : tl . createDestination ( device , true , keepAlive , verifyByServer ) ; } | work around for implementation in TL which unconditionally throws if dst exists |
38,133 | public void activateBusmonitor ( ) throws IOException { logger . debug ( "activate TP-UART busmonitor" ) ; os . write ( ActivateBusmon ) ; busmonSequence = 0 ; busmon = true ; } | Activate busmonitor mode the TP - UART controller is set completely passive . |
38,134 | private static byte [ ] cEmiToTP1 ( final byte [ ] frame ) { final int stdMaxApdu = 15 ; final int cEmiPrefix = 10 ; final boolean std = frame . length <= cEmiPrefix + stdMaxApdu ; final byte [ ] tp1 ; if ( std ) { tp1 = new byte [ frame . length - 2 ] ; int i = 0 ; tp1 [ i ++ ] = ( byte ) ( ( frame [ 2 ] & 0xfc ) | StdFrameFormat | RepeatFlag ) ; tp1 [ i ++ ] = frame [ 4 ] ; tp1 [ i ++ ] = frame [ 5 ] ; tp1 [ i ++ ] = frame [ 6 ] ; tp1 [ i ++ ] = frame [ 7 ] ; final int len = frame [ 8 ] ; tp1 [ i ++ ] = ( byte ) ( ( frame [ 3 ] & 0xf0 ) | len ) ; tp1 [ i ++ ] = frame [ 9 ] ; for ( int k = 0 ; k < len ; k ++ ) tp1 [ i ++ ] = frame [ 10 + k ] ; } else { tp1 = new byte [ frame . length ] ; for ( int i = 1 ; i < frame . length ; i ++ ) tp1 [ i - 1 ] = frame [ i ] ; tp1 [ 0 ] |= ( byte ) ( frame [ 0 ] | ExtFrameFormat | RepeatFlag ) ; } tp1 [ tp1 . length - 1 ] = ( byte ) checksum ( tp1 ) ; return tp1 ; } | returns a TP1 std or ext frame |
38,135 | public static HidReport createFeatureService ( final BusAccessServerService service , final BusAccessServerFeature feature , final byte [ ] frame ) { return new HidReport ( service , feature , frame ) ; } | Creates a new report for use with the Bus Access Server feature service . |
38,136 | public static List < HidReport > create ( final KnxTunnelEmi emi , final byte [ ] frame ) { final List < HidReport > l = new ArrayList < > ( ) ; final EnumSet < PacketType > packetType = EnumSet . of ( PacketType . Start ) ; int maxData = maxDataStartPacket ; if ( frame . length > maxData ) packetType . add ( PacketType . Partial ) ; int offset = 0 ; for ( int i = 1 ; i < 6 ; i ++ ) { final int to = Math . min ( frame . length , offset + maxData ) ; final byte [ ] range = Arrays . copyOfRange ( frame , offset , to ) ; offset = to ; if ( offset >= frame . length ) packetType . add ( PacketType . End ) ; l . add ( new HidReport ( i , packetType . clone ( ) , Protocol . KnxTunnel , emi , noEmiMsgCode , range ) ) ; if ( offset >= frame . length ) break ; packetType . remove ( PacketType . Start ) ; maxData = maxDataPartialPacket ; } return l ; } | Creates a new report containing an EMI frame . |
38,137 | private byte [ ] unifyLData ( final CEMI ldata , final boolean emptySrc , final List < Integer > types ) { final byte [ ] data ; if ( ldata instanceof CEMILDataEx ) { final CEMILDataEx ext = ( ( CEMILDataEx ) ldata ) ; final List < AddInfo > additionalInfo = ext . additionalInfo ( ) ; synchronized ( additionalInfo ) { for ( final Iterator < AddInfo > i = additionalInfo . iterator ( ) ; i . hasNext ( ) ; ) { final AddInfo info = i . next ( ) ; if ( ! types . contains ( info . getType ( ) ) ) { logger . warn ( "remove L-Data additional info {}" , info ) ; i . remove ( ) ; } } } } data = ldata . toByteArray ( ) ; data [ 0 ] = 0 ; data [ 1 + data [ 1 ] + 1 ] = 0 ; if ( emptySrc ) { data [ 1 + data [ 1 ] + 3 ] = 0 ; data [ 1 + data [ 1 ] + 4 ] = 0 ; } return data ; } | additional info . types provides the list of add . info types we want to keep everything else is removed |
38,138 | public static LibraryAdapter open ( final Logger logger , final String portId , final int baudrate , final int idleTimeout ) throws KNXException { Throwable t = null ; if ( CommConnectionAdapter . isAvailable ( ) ) { logger . debug ( "open Java ME serial port connection (CommConnection) for {}" , portId ) ; try { return new CommConnectionAdapter ( logger , portId , baudrate ) ; } catch ( final KNXException e ) { t = e ; } } if ( SerialComAdapter . isAvailable ( ) ) { logger . debug ( "open Calimero native serial port connection (serialcom) for {}" , portId ) ; SerialComAdapter conn = null ; try { conn = new SerialComAdapter ( logger , portId ) ; conn . setBaudRate ( baudrate ) ; conn . setTimeouts ( new SerialComAdapter . Timeouts ( idleTimeout , 0 , 250 , 0 , 0 ) ) ; conn . setParity ( SerialComAdapter . PARITY_EVEN ) ; conn . setControl ( SerialComAdapter . STOPBITS , SerialComAdapter . ONE_STOPBIT ) ; conn . setControl ( SerialComAdapter . DATABITS , 8 ) ; conn . setControl ( SerialComAdapter . FLOWCTRL , SerialComAdapter . FLOWCTRL_NONE ) ; logger . debug ( "setup serial port: baudrate " + conn . getBaudRate ( ) + ", even parity, " + conn . getControl ( SerialComAdapter . DATABITS ) + " databits, " + conn . getControl ( SerialComAdapter . STOPBITS ) + " stopbits, timeouts: " + conn . getTimeouts ( ) ) ; return conn ; } catch ( final IOException e ) { if ( conn != null ) conn . close ( ) ; t = e ; } } try { final Class < ? > c = Class . forName ( "tuwien.auto.calimero.serial.RxtxAdapter" ) ; logger . debug ( "using rxtx library for serial port access" ) ; final Class < ? extends LibraryAdapter > adapter = LibraryAdapter . class ; return adapter . cast ( c . getConstructors ( ) [ 0 ] . newInstance ( new Object [ ] { logger , portId , Integer . valueOf ( baudrate ) } ) ) ; } catch ( final ClassNotFoundException e ) { logger . warn ( "no rxtx library adapter found" ) ; } catch ( final Exception | NoClassDefFoundError e ) { t = e instanceof InvocationTargetException ? e . getCause ( ) : e ; } if ( t instanceof KNXException ) throw ( KNXException ) t ; if ( t != null ) throw new KNXException ( "failed to open serial port " + portId , t ) ; throw new KNXException ( "no serial adapter available to open " + portId ) ; } | Factory method to open a serial connection using one of the available library adapters . |
38,139 | private void setRepeat ( final boolean repeat ) { final boolean flag = mc == MC_LDATA_IND ? ! repeat : repeat ; if ( flag ) ctrl1 |= 0x20 ; else ctrl1 &= 0xDF ; } | Sets the repeat flag in control field using the message code type for decision . |
38,140 | public static boolean hasTranslator ( final int mainNumber , final String dptId ) { try { final MainType t = getMainType ( getMainNumber ( mainNumber , dptId ) ) ; if ( t != null ) return t . getSubTypes ( ) . get ( dptId ) != null ; } catch ( final NumberFormatException e ) { } catch ( final KNXException e ) { } return false ; } | Does a lookup if the specified DPT is supported by a DPT translator . |
38,141 | public static DPTXlator createTranslator ( final String dptId , final byte ... data ) throws KNXException , KNXIllegalArgumentException { final DPTXlator t = createTranslator ( 0 , dptId ) ; if ( data . length > 0 ) t . setData ( data ) ; return t ; } | Creates a DPT translator for the given datapoint type ID . |
38,142 | public static KNXNetworkLinkIP newSecureRoutingLink ( final NetworkInterface netif , final InetAddress mcGroup , final byte [ ] groupKey , final Duration latencyTolerance , final KNXMediumSettings settings ) throws KNXException { return new KNXNetworkLinkIP ( ROUTING , SecureConnection . newRouting ( netif , mcGroup , groupKey , latencyTolerance ) , settings ) ; } | Creates a new secure network link using the KNX IP Secure Routing protocol . |
38,143 | public static KNXMediumSettings create ( final int medium , final IndividualAddress device ) { switch ( medium ) { case MEDIUM_TP1 : return new TPSettings ( device ) ; case MEDIUM_PL110 : return new PLSettings ( device , null ) ; case MEDIUM_RF : return new RFSettings ( device ) ; case MEDIUM_KNXIP : return new KnxIPSettings ( device ) ; default : throw new KNXIllegalArgumentException ( "unknown medium type " + medium ) ; } } | Creates the medium settings for the specified KNX medium . |
38,144 | public static RawFrame create ( final int mediumType , final byte [ ] data , final int offset , final boolean extBusmon ) throws KNXFormatException { switch ( mediumType ) { case KNXMediumSettings . MEDIUM_TP1 : return createTP1 ( data , offset ) ; case KNXMediumSettings . MEDIUM_PL110 : return createPL110 ( data , offset , extBusmon ) ; case KNXMediumSettings . MEDIUM_RF : return new RFLData ( data , offset ) ; 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 . This method just invokes one of the other medium type specific creation methods according the given medium type . |
38,145 | public static RawFrame createTP1 ( final byte [ ] data , final int offset ) throws KNXFormatException { final int ctrl = data [ offset ] & 0xff ; if ( ( ctrl & 0x10 ) == 0x10 ) { if ( ( ctrl & 0x40 ) == 0x00 ) return new TP1LData ( data , offset ) ; else if ( ctrl == 0xF0 ) return new TP1LPollData ( data , offset ) ; throw new KNXFormatException ( "invalid raw frame control field" , ctrl ) ; } return new TP1Ack ( data , offset ) ; } | Creates a raw frame out of a byte array for the TP1 communication medium . |
38,146 | private boolean skipComment ( final String s ) throws KNXMLException { if ( s . startsWith ( "!--" ) ) { String comment = s ; while ( canRead ( ) && ! comment . endsWith ( "--" ) ) comment = read ( '>' ) ; return true ; } return false ; } | checks if < marks begin of a comment and if so skips over it |
38,147 | public String getProperty ( final int objIndex , final int pid ) throws KNXException , InterruptedException { return getPropertyTranslated ( objIndex , pid , 1 , 1 ) . getValue ( ) ; } | Gets the first property element using the associated property data type of the requested property . |
38,148 | public Description getDescriptionByIndex ( final int objIndex , final int propIndex ) throws KNXException , InterruptedException { return createDesc ( objIndex , pa . getDescription ( objIndex , 0 , propIndex ) ) ; } | Gets the property description based on the property index . |
38,149 | public void scanProperties ( final boolean allProperties , final Consumer < Description > consumer ) throws KNXException , InterruptedException { for ( int index = 0 ; scan ( index , allProperties , consumer ) > 0 ; ++ index ) ; } | Does a property description scan of the properties in all interface objects . |
38,150 | public void scanProperties ( final int objIndex , final boolean allProperties , final Consumer < Description > consumer ) throws KNXException , InterruptedException { scan ( objIndex , allProperties , consumer ) ; } | Does a property description scan of the properties of one interface object . |
38,151 | public static SearchResponse from ( final KNXnetIPHeader h , final byte [ ] data , final int offset ) throws KNXFormatException { final int svcType = h . getServiceType ( ) ; if ( svcType != KNXnetIPHeader . SEARCH_RES && svcType != KNXnetIPHeader . SearchResponse ) throw new KNXIllegalArgumentException ( "not a search response" ) ; return new SearchResponse ( svcType , data , offset , h . getTotalLength ( ) - h . getStructLength ( ) ) ; } | Creates a new search response from a byte array . |
38,152 | public static TunnelingFeature newGet ( final int channelId , final int seq , final InterfaceFeature featureId ) { return new TunnelingFeature ( KNXnetIPHeader . TunnelingFeatureGet , channelId , seq , featureId , Success ) ; } | Creates a new tunneling feature - get service . |
38,153 | public static TunnelingFeature newResponse ( final int channelId , final int seq , final InterfaceFeature featureId , final ReturnCode result , final byte ... featureValue ) { return new TunnelingFeature ( KNXnetIPHeader . TunnelingFeatureResponse , channelId , seq , featureId , result , featureValue ) ; } | Creates a new tunneling feature - response service . |
38,154 | public static TunnelingFeature newSet ( final int channelId , final int seq , final InterfaceFeature featureId , final byte ... featureValue ) { return new TunnelingFeature ( KNXnetIPHeader . TunnelingFeatureSet , channelId , seq , featureId , Success , featureValue ) ; } | Creates a new tunneling feature - set service . |
38,155 | public static TunnelingFeature newInfo ( final int channelId , final int seq , final InterfaceFeature featureId , final byte ... featureValue ) { return new TunnelingFeature ( KNXnetIPHeader . TunnelingFeatureInfo , channelId , seq , featureId , Success , featureValue ) ; } | Creates a new tunneling feature - info service . |
38,156 | public static KNXAddress create ( final XmlReader r ) throws KNXMLException { if ( r . getEventType ( ) != XmlReader . START_ELEMENT ) r . nextTag ( ) ; if ( r . getEventType ( ) == XmlReader . START_ELEMENT ) { final String type = r . getAttributeValue ( null , ATTR_TYPE ) ; if ( GroupAddress . ATTR_GROUP . equals ( type ) ) return new GroupAddress ( r ) ; else if ( IndividualAddress . ATTR_IND . equals ( type ) ) return new IndividualAddress ( r ) ; } throw new KNXMLException ( "not a KNX address" , r ) ; } | Creates a KNX address from xml input the KNX address element is expected to be the current or next element from the parser . |
38,157 | public void save ( final XmlWriter w ) throws KNXMLException { w . writeStartElement ( TAG_ADDRESS ) ; w . writeAttribute ( ATTR_TYPE , getType ( ) ) ; w . writeCharacters ( toString ( ) ) ; w . writeEndElement ( ) ; } | Writes the KNX address in XML format to the supplied writer . |
38,158 | public static SearchRequest from ( final KNXnetIPHeader h , final byte [ ] data , final int offset ) throws KNXFormatException { final int svcType = h . getServiceType ( ) ; if ( svcType != KNXnetIPHeader . SEARCH_REQ && svcType != KNXnetIPHeader . SearchRequest ) throw new KNXIllegalArgumentException ( "not a search request" ) ; return new SearchRequest ( svcType , data , offset , h . getTotalLength ( ) - h . getStructLength ( ) ) ; } | Creates a new search request from a byte array . |
38,159 | public void loop ( ) throws IOException { final long start = System . currentTimeMillis ( ) ; final byte [ ] buf = new byte [ maxRcvBuf ] ; try { if ( timeout > 0 ) s . setSoTimeout ( timeout ) ; while ( ! quit ) { if ( total > 0 ) { final long now = System . currentTimeMillis ( ) ; int to = ( int ) ( start + total - now ) ; if ( to <= 0 ) break ; final int sto = s . getSoTimeout ( ) ; if ( sto > 0 ) to = Math . min ( to , sto ) ; s . setSoTimeout ( to ) ; } try { final DatagramPacket p = new DatagramPacket ( buf , buf . length ) ; s . receive ( p ) ; final byte [ ] data = p . getData ( ) ; onReceive ( ( InetSocketAddress ) p . getSocketAddress ( ) , data , p . getOffset ( ) , p . getLength ( ) ) ; } catch ( final SocketTimeoutException e ) { if ( total == 0 || start + total > System . currentTimeMillis ( ) ) onTimeout ( ) ; } catch ( final IOException e ) { if ( ! reboundSocket ) throw e ; reboundSocket = false ; } } } catch ( final InterruptedIOException e ) { Thread . currentThread ( ) . interrupt ( ) ; } catch ( final IOException e ) { if ( ! quit ) throw e ; } finally { quit ( ) ; } } | Runs the looper . |
38,160 | public Destination getDestination ( final IndividualAddress remote ) { final AggregatorProxy proxy = proxies . get ( remote ) ; return proxy != null ? proxy . getDestination ( ) : null ; } | Returns the destination object for the remote individual address if such exists . |
38,161 | static RFLData newForTransmitOnlyDevice ( final boolean batteryOk , final int frameType , final int frameNumber , final byte [ ] serial , final GroupAddress dst , final byte [ ] tpdu ) { return new RFLData ( batteryOk , true , frameType , frameNumber , serial , new IndividualAddress ( 0x05ff ) , dst , tpdu ) ; } | - datapoints shall be numbered as DP1 = GroupAddr 0x0001 DP2 = 0x0002 ... |
38,162 | static String replace ( final String text , final boolean toReference ) { return toReference ? replaceWithRef ( text ) : replaceFromRef ( text ) ; } | wrapper for reference replacement |
38,163 | private int coding ( final String unit ) throws KNXFormatException { expUnitAdjustment = 0 ; switch ( unit ) { case "Wh" : return 0b00000000 ; case "MWh" : expUnitAdjustment = 6 ; return 0b10000000 ; case "kJ" : expUnitAdjustment = 3 ; return 0b00001000 ; case "GJ" : expUnitAdjustment = 9 ; return 0b10001000 ; case "l" : expUnitAdjustment = - 3 ; return 0b00010000 ; case "kg" : return 0b00011000 ; case "W" : return 0b00101000 ; case "MW" : expUnitAdjustment = 6 ; return 0b10101000 ; case "kJ/h" : expUnitAdjustment = 3 ; return 0b00110000 ; case "GJ/h" : expUnitAdjustment = 9 ; return 0b10110000 ; case "l/h" : expUnitAdjustment = - 3 ; return 0b00111000 ; case "l/min" : expUnitAdjustment = - 3 ; return 0b01000000 ; case "ml/s" : expUnitAdjustment = - 6 ; return 0b01001000 ; case "kg/h" : return 0b01010000 ; case "" : return dimensionlessCounter ; default : throw newException ( "unsupported unit" , unit ) ; } } | try to find the coding based on unit |
38,164 | final int setParity ( final int parity ) { try { return setControl ( PARITY , parity ) ; } catch ( final IOException e ) { logger . error ( "set parity failed" , e ) ; } return 0 ; } | return previous parity mode |
38,165 | public void save ( final XmlWriter w ) throws KNXMLException { w . writeStartElement ( TAG_DATAPOINT ) ; w . writeAttribute ( ATTR_STATEBASED , Boolean . toString ( stateBased ) ) ; w . writeAttribute ( ATTR_NAME , name ) ; w . writeAttribute ( ATTR_MAINNUMBER , Integer . toString ( mainNo ) ) ; w . writeAttribute ( ATTR_DPTID , dptId == null ? "" : dptId ) ; w . writeAttribute ( ATTR_PRIORITY , priority . toString ( ) ) ; main . save ( w ) ; doSave ( w ) ; w . writeEndElement ( ) ; } | Saves this datapoint in XML format to the supplied XML writer . |
38,166 | @ SuppressWarnings ( "unused" ) protected boolean handleServiceType ( final KNXnetIPHeader h , final byte [ ] data , final int offset , final InetAddress src , final int port ) throws KNXFormatException , IOException { return false ; } | This stub always returns false . |
38,167 | protected final void setState ( final int newState ) { if ( closing < 2 ) { if ( internalState == OK && newState == ClientConnection . CEMI_CON_PENDING ) return ; internalState = newState ; if ( updateState ) state = newState ; } else state = internalState = CLOSED ; } | Request to set this connection into a new connection state . |
38,168 | protected boolean checkChannelId ( final int id , final String svcType ) { if ( id == channelId ) return true ; logger . warn ( "received service " + svcType + " with wrong channel ID " + id + ", expected " + channelId + " - ignored" ) ; return false ; } | Validates channel id received in a packet against the one assigned to this connection . |
38,169 | protected ServiceRequest getServiceRequest ( final KNXnetIPHeader h , final byte [ ] data , final int offset ) throws KNXFormatException { try { return PacketHelper . getServiceRequest ( h , data , offset ) ; } catch ( final KNXFormatException e ) { final ServiceRequest req = PacketHelper . getEmptyServiceRequest ( h , data , offset ) ; logger . warn ( "received request with unknown cEMI data " + DataUnitBuilder . toHex ( Arrays . copyOfRange ( data , offset + 4 , offset + h . getTotalLength ( ) - h . getStructLength ( ) ) , " " ) , e ) ; return req ; } } | Extracts the service request out of the supplied packet data . |
38,170 | public static CEMI fromEmi ( final byte [ ] frame ) throws KNXFormatException { if ( frame . length < 4 ) throw new KNXFormatException ( "EMI frame too short" ) ; int mc = frame [ 0 ] & 0xff ; boolean domainBcast = true ; if ( mc == Emi1_LSysBcast_req || mc == Emi1_LSysBcast_con || mc == Emi1_LSysBcast_ind ) domainBcast = false ; if ( mc == Emi1_LData_ind ) mc = CEMILData . MC_LDATA_IND ; if ( mc == Emi1_LData_con ) mc = CEMILData . MC_LDATA_CON ; if ( mc == Emi1_LSysBcast_req ) mc = CEMILData . MC_LDATA_REQ ; if ( mc == Emi1_LSysBcast_con ) mc = CEMILData . MC_LDATA_CON ; if ( mc == Emi1_LSysBcast_ind ) mc = CEMILData . MC_LDATA_IND ; if ( mc == CEMIBusMon . MC_BUSMON_IND ) { return CEMIBusMon . newWithStatus ( frame [ 1 ] & 0xff , ( frame [ 2 ] & 0xff ) << 8 | ( frame [ 3 ] & 0xff ) , false , Arrays . copyOfRange ( frame , 4 , frame . length ) ) ; } final Priority p = Priority . get ( frame [ 1 ] >> 2 & 0x3 ) ; final boolean ack = ( frame [ 1 ] & 0x02 ) != 0 ; final boolean c = ( frame [ 1 ] & 0x01 ) != 0 ; final int dst = ( frame [ 4 ] & 0xff ) << 8 | ( frame [ 5 ] & 0xff ) ; final KNXAddress a = ( frame [ 6 ] & 0x80 ) != 0 ? ( KNXAddress ) new GroupAddress ( dst ) : new IndividualAddress ( dst ) ; final int hops = frame [ 6 ] >> 4 & 0x07 ; final int len = ( frame [ 6 ] & 0x0f ) + 1 ; final byte [ ] tpdu = Arrays . copyOfRange ( frame , 7 , len + 7 ) ; final int src = ( ( frame [ 2 ] & 0xff ) << 8 ) | ( frame [ 3 ] & 0xff ) ; if ( c ) return new CEMILData ( mc , new IndividualAddress ( src ) , a , tpdu , p , c ) ; final boolean repeat = mc == CEMILData . MC_LDATA_IND ? false : true ; return new CEMILData ( mc , new IndividualAddress ( src ) , a , tpdu , p , repeat , domainBcast , ack , hops ) ; } | Creates a new cEMI message out of the supplied EMI frame . |
38,171 | int init ( final ByteArrayInputStream is , final boolean parseDoA ) throws KNXFormatException { final int ctrl = is . read ( ) ; if ( ( ctrl & 0x53 ) != 0x10 ) throw new KNXFormatException ( "invalid control field" , ctrl ) ; type = LDATA_FRAME ; ext = ( ctrl & 0x80 ) == 0 ; repetition = ( ctrl & 0x20 ) == 0 ; p = Priority . get ( ( ctrl >> 2 ) & 0x3 ) ; final int ctrle = ext ? readCtrlEx ( is ) : 0 ; if ( parseDoA ) { doa = new byte [ 2 ] ; is . read ( doa , 0 , 2 ) ; } src = new IndividualAddress ( ( is . read ( ) << 8 ) | is . read ( ) ) ; final int addr = ( is . read ( ) << 8 ) | is . read ( ) ; final int npci = is . read ( ) ; final int len ; if ( ext ) { hopcount = ( ctrle & 0x70 ) >> 4 ; setDestination ( addr , ( ctrle & 0x80 ) != 0 ) ; len = npci ; } else { hopcount = ( npci & 0x70 ) >> 4 ; setDestination ( addr , ( npci & 0x80 ) != 0 ) ; len = npci & 0x0f ; } return len ; } | Inits the basic fields for TP1 and PL110 L - Data format reading the input stream . |
38,172 | public static void updateDeviceList ( ) throws SecurityException , UsbException { ( ( org . usb4java . javax . Services ) UsbHostManager . getUsbServices ( ) ) . scan ( ) ; } | Scans for USB device connection changes so subsequent traversals provide an updated view of attached USB interfaces . |
38,173 | public static List < UsbDevice > getKnxDevices ( ) { final List < UsbDevice > knx = new ArrayList < > ( ) ; for ( final UsbDevice d : getDevices ( ) ) { final int vendor = d . getUsbDeviceDescriptor ( ) . idVendor ( ) & 0xffff ; for ( final int v : vendorIds ) if ( v == vendor ) knx . add ( d ) ; } return knx ; } | Returns the list of KNX devices currently attached to the host based on known KNX vendor IDs . |
38,174 | public static List < UsbDevice > getVirtualSerialKnxDevices ( ) throws SecurityException { final List < UsbDevice > knx = new ArrayList < > ( ) ; for ( final UsbDevice d : getDevices ( ) ) { final int vendor = d . getUsbDeviceDescriptor ( ) . idVendor ( ) & 0xffff ; final int product = d . getUsbDeviceDescriptor ( ) . idProduct ( ) & 0xffff ; for ( int i = 0 ; i < virtualSerialVendorIds . length ; i ++ ) { final int v = virtualSerialVendorIds [ i ] ; if ( v == vendor && virtualSerialProductIds [ i ] == product ) knx . add ( d ) ; } } return knx ; } | internal use only |
38,175 | public final DD0 deviceDescriptor ( ) throws KNXPortClosedException , KNXTimeoutException , InterruptedException { return DD0 . from ( ( int ) toUnsigned ( getFeature ( BusAccessServerFeature . DeviceDescriptorType0 ) ) ) ; } | Returns the KNX device descriptor type 0 of the USB interface . |
38,176 | private void removeClaimedInterfaceNumberOnWindows ( ) { try { final Class < ? extends UsbDevice > c = dev . getClass ( ) ; final Class < ? > abstractDevice = c . getSuperclass ( ) ; final Field field = abstractDevice . getDeclaredField ( "claimedInterfaceNumbers" ) ; field . setAccessible ( true ) ; final Object set = field . get ( dev ) ; if ( set instanceof Set < ? > ) { @ SuppressWarnings ( "unchecked" ) final Set < Byte > numbers = ( Set < Byte > ) set ; numbers . remove ( knxUsbIf . getUsbInterfaceDescriptor ( ) . bInterfaceNumber ( ) ) ; } } catch ( final Exception e ) { logger . error ( "on removing claimed interface number, subsequent claims might fail!" , e ) ; } } | Subsequent claims of that interface then always fail . |
38,177 | private static String trimAtNull ( final String s ) { final int end = s . indexOf ( ( char ) 0 ) ; return end > - 1 ? s . substring ( 0 , end ) : s ; } | sometimes the usb4java high - level API returns strings which exceed past the null terminator |
38,178 | private static UsbDevice findDeviceByNameLowLevel ( final String name ) throws KNXException { final List < String > list = getDeviceDescriptionsLowLevel ( ) ; if ( name . isEmpty ( ) ) list . removeIf ( i -> ! isKnxInterfaceId ( i . substring ( i . indexOf ( "ID" ) + 3 , i . indexOf ( "\n" ) ) ) ) ; else list . removeIf ( i -> i . toLowerCase ( ) . indexOf ( name . toLowerCase ( ) ) == - 1 ) ; if ( list . isEmpty ( ) ) throw new KNXException ( "no USB device found with name matching '" + name + "'" ) ; final String desc = list . get ( 0 ) ; final String id = desc . substring ( desc . indexOf ( "ID" ) + 3 , desc . indexOf ( "\n" ) ) ; return findDevice ( id ) ; } | string . Pass that ID to findDevice . which will do the lookup by ID . |
38,179 | private static List < String > getDeviceDescriptionsLowLevel ( ) { final Context ctx = new Context ( ) ; final int err = LibUsb . init ( ctx ) ; if ( err != 0 ) { slogger . error ( "LibUsb initialization error {}: {}" , - err , LibUsb . strError ( err ) ) ; return Collections . emptyList ( ) ; } try { final DeviceList list = new DeviceList ( ) ; final int res = LibUsb . getDeviceList ( ctx , list ) ; if ( res < 0 ) { slogger . error ( "LibUsb device list error {}: {}" , - res , LibUsb . strError ( res ) ) ; return Collections . emptyList ( ) ; } try { return StreamSupport . stream ( list . spliterator ( ) , false ) . map ( UsbConnection :: printInfo ) . collect ( Collectors . toList ( ) ) ; } finally { LibUsb . freeDeviceList ( list , true ) ; } } finally { LibUsb . exit ( ctx ) ; } } | This method avoids any further issues down the road by using the ASCII descriptors . |
38,180 | public static int getAPDUService ( final byte [ ] apdu ) { if ( apdu . length < 2 ) throw new KNXIllegalArgumentException ( "getting APDU service from [0x" + toHex ( apdu , "" ) + "], APCI length < 2" ) ; final int apci4 = ( apdu [ 0 ] & 0x03 ) << 2 | ( apdu [ 1 ] & 0xC0 ) >> 6 ; final int apci6 = apdu [ 1 ] & 0x3f ; if ( apci4 == 0 ) { if ( apci6 == 0 ) return 0 ; } else if ( apci4 == 1 ) return 0x40 ; else if ( apci4 == 2 ) return 0x80 ; else if ( apci4 == 3 || apci4 == 4 || apci4 == 5 ) { if ( apci6 == 0 ) return apci4 << 6 ; } else if ( apci4 == 6 ) return apci4 << 6 ; else if ( apci4 == 7 ) { if ( apdu . length > 5 || apci6 > 0x30 ) return apci4 << 6 | apci6 ; return apci4 << 6 ; } else if ( apci4 == 8 || apci4 == 9 || apci4 == 10 ) return apci4 << 6 ; else return apci4 << 6 | apci6 ; 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 . |
38,181 | public static int getTPDUService ( final byte [ ] tpdu ) { final int ctrl = tpdu [ 0 ] & 0xff ; if ( ( ctrl & 0xFC ) == 0 ) return 0 ; if ( ( ctrl & 0xFC ) == 0x04 ) return 0x04 ; if ( ( ctrl & 0xC0 ) == 0x40 ) return T_DATA_CONNECTED ; if ( ctrl == T_CONNECT ) return T_CONNECT ; if ( ctrl == T_DISCONNECT ) return T_DISCONNECT ; if ( ( ctrl & 0xC3 ) == T_ACK ) return T_ACK ; if ( ( ctrl & 0xC3 ) == T_NAK ) return T_NAK ; logger . warn ( "unknown TPCI service code 0x" + Integer . toHexString ( ctrl ) ) ; return ctrl ; } | Returns the transport layer service of a given protocol data unit . |
38,182 | public static JettyServerContract launchServerContract ( int port , HttpObject ... objects ) { JettyServerContract server = new JettyServerDelegate ( new Server ( port ) ) ; server . setHandler ( new HttpObjectsJettyHandler ( Collections . singletonList ( new GenericHeaderField ( "Cache-Control" , "no-cache" ) ) , objects ) ) ; server . start ( ) ; return server ; } | Replaced checked exceptions with unchecked exceptions . |
38,183 | private void setC4Document ( C4Document c4doc ) { synchronized ( lock ) { replaceC4Document ( c4doc ) ; data = null ; if ( c4doc != null && ! c4doc . deleted ( ) ) { data = c4doc . getSelectedBody2 ( ) ; } updateDictionary ( ) ; } } | Sets c4doc and updates my root dictionary |
38,184 | public ReplicatorConfiguration setHeaders ( Map < String , String > headers ) { if ( readonly ) { throw new IllegalStateException ( "ReplicatorConfiguration is readonly mode." ) ; } this . headers = new HashMap < > ( headers ) ; return getReplicatorConfiguration ( ) ; } | Sets the extra HTTP headers to send in all requests to the remote target . |
38,185 | public ReplicatorConfiguration setPullFilter ( ReplicationFilter pullFilter ) { if ( readonly ) { throw new IllegalStateException ( "ReplicatorConfiguration is readonly mode." ) ; } this . pullFilter = pullFilter ; return getReplicatorConfiguration ( ) ; } | Sets a filter object for validating whether the documents can be pulled from the remote endpoint . Only documents for which the object returns true are replicated . |
38,186 | public ReplicatorConfiguration setPushFilter ( ReplicationFilter pushFilter ) { if ( readonly ) { throw new IllegalStateException ( "ReplicatorConfiguration is readonly mode." ) ; } this . pushFilter = pushFilter ; return getReplicatorConfiguration ( ) ; } | Sets a filter object for validating whether the documents can be pushed to the remote endpoint . |
38,187 | public MutableArray setData ( List < Object > data ) { synchronized ( lock ) { internalArray . clear ( ) ; for ( Object obj : data ) { internalArray . append ( Fleece . toCBLObject ( obj ) ) ; } return this ; } } | Set an array as a content . Allowed value types are List Date Map Number null String Array Blob and Dictionary . The List and Map must contain only the above types . Setting the new array content will replcace the current data including the existing Array and Dictionary objects . |
38,188 | public MutableArray setValue ( int index , Object value ) { synchronized ( lock ) { if ( Fleece . valueWouldChange ( value , internalArray . get ( index ) , internalArray ) && ( ! internalArray . set ( index , Fleece . toCBLObject ( value ) ) ) ) { throwRangeException ( index ) ; } return this ; } } | Set an object at the given index . |
38,189 | public MutableArray setString ( int index , String value ) { return setValue ( index , value ) ; } | Sets an String object at the given index . |
38,190 | public MutableArray setNumber ( int index , Number value ) { return setValue ( index , value ) ; } | Sets an NSNumber object at the given index . |
38,191 | public MutableArray setBlob ( int index , Blob value ) { return setValue ( index , value ) ; } | Sets a Blob object at the given index . |
38,192 | public MutableArray setDate ( int index , Date value ) { return setValue ( index , value ) ; } | Sets a Date object at the given index . |
38,193 | public MutableArray setArray ( int index , Array value ) { return setValue ( index , value ) ; } | Sets a Array object at the given index . |
38,194 | public MutableArray setDictionary ( int index , Dictionary value ) { return setValue ( index , value ) ; } | Sets a Dictionary object at the given index . |
38,195 | public MutableArray addValue ( Object value ) { synchronized ( lock ) { internalArray . append ( Fleece . toCBLObject ( value ) ) ; return this ; } } | Adds an object to the end of the array . |
38,196 | public MutableArray insertValue ( int index , Object value ) { synchronized ( lock ) { if ( ! internalArray . insert ( index , Fleece . toCBLObject ( value ) ) ) { throwRangeException ( index ) ; } return this ; } } | Inserts an object at the given index . |
38,197 | public MutableArray insertString ( int index , String value ) { return insertValue ( index , value ) ; } | Inserts a String object at the given index . |
38,198 | public MutableArray insertNumber ( int index , Number value ) { return insertValue ( index , value ) ; } | Inserts a Number object at the given index . |
38,199 | public MutableArray insertBlob ( int index , Blob value ) { return insertValue ( index , value ) ; } | Inserts a Blob object at the given index . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.