Search in sources :

Example 1 with PlcDINT

use of org.apache.plc4x.java.spi.values.PlcDINT in project plc4x by apache.

the class FirmataProtocolLogic method publishAnalogEvents.

protected void publishAnalogEvents(int pin, int value) {
    // Try sending the subscription event to all listeners.
    for (Map.Entry<DefaultPlcConsumerRegistration, Consumer<PlcSubscriptionEvent>> entry : consumers.entrySet()) {
        final DefaultPlcConsumerRegistration registration = entry.getKey();
        final Consumer<PlcSubscriptionEvent> consumer = entry.getValue();
        // Only if the current data point matches the subscription, publish the event to it.
        for (PlcSubscriptionHandle handle : registration.getSubscriptionHandles()) {
            if (handle instanceof FirmataSubscriptionHandle) {
                FirmataSubscriptionHandle subscriptionHandle = (FirmataSubscriptionHandle) handle;
                // (The bit subscribed to in this field actually changed).
                if (subscriptionHandle.getField() instanceof FirmataFieldAnalog) {
                    FirmataFieldAnalog analogField = (FirmataFieldAnalog) subscriptionHandle.getField();
                    // Check if this field would include the current pin.
                    if ((analogField.getAddress() <= pin) && (analogField.getAddress() + analogField.getNumberOfElements() >= pin)) {
                        // Build an update event containing the current values for all subscribed fields.
                        List<PlcValue> values = new ArrayList<>(analogField.getNumberOfElements());
                        for (int i = analogField.getAddress(); i < analogField.getAddress() + analogField.getNumberOfElements(); i++) {
                            if (analogValues.containsKey(i)) {
                                values.add(new PlcDINT(analogValues.get(i).intValue()));
                            } else // This could be the case if only some of the requested array values are available
                            {
                                values.add(new PlcDINT(-1));
                            }
                        }
                        sendUpdateEvents(consumer, subscriptionHandle.getName(), values);
                    }
                }
            }
        }
    }
}
Also used : DefaultPlcConsumerRegistration(org.apache.plc4x.java.spi.model.DefaultPlcConsumerRegistration) PlcDINT(org.apache.plc4x.java.spi.values.PlcDINT) PlcSubscriptionHandle(org.apache.plc4x.java.api.model.PlcSubscriptionHandle) FirmataSubscriptionHandle(org.apache.plc4x.java.firmata.readwrite.model.FirmataSubscriptionHandle) Consumer(java.util.function.Consumer) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) FirmataFieldAnalog(org.apache.plc4x.java.firmata.readwrite.field.FirmataFieldAnalog)

Example 2 with PlcDINT

use of org.apache.plc4x.java.spi.values.PlcDINT in project plc4x by apache.

the class ScraperTest method scraper_schedulesJob.

@Test
void scraper_schedulesJob() throws InterruptedException, PlcConnectionException {
    PlcDriverManager driverManager = new PlcDriverManager();
    MockConnection connection = (MockConnection) driverManager.getConnection("mock:m1");
    connection.setDevice(mockDevice);
    when(mockDevice.read(any())).thenReturn(new ResponseItem<>(PlcResponseCode.OK, new PlcDINT(1)));
    ScraperImpl scraper = new ScraperImpl((j, a, m) -> {
    }, driverManager, Collections.singletonList(new ScrapeJobImpl("job1", 10, Collections.singletonMap("m1", "mock:m1"), Collections.singletonMap("field1", "qry1"))));
    scraper.start();
    Thread.sleep(1_000);
    // Assert that tasks got done.
    assertThat(scraper.getScheduler()).isInstanceOf(ScheduledThreadPoolExecutor.class);
    assertThat(scraper.getNumberOfActiveTasks()).isEqualTo(1);
    assertThat(((ScheduledThreadPoolExecutor) scraper.getScheduler()).getCompletedTaskCount()).isGreaterThan(10);
}
Also used : PlcDINT(org.apache.plc4x.java.spi.values.PlcDINT) ScheduledThreadPoolExecutor(java.util.concurrent.ScheduledThreadPoolExecutor) PlcDriverManager(org.apache.plc4x.java.PlcDriverManager) PooledPlcDriverManager(org.apache.plc4x.java.utils.connectionpool.PooledPlcDriverManager) MockConnection(org.apache.plc4x.java.mock.connection.MockConnection) Test(org.junit.jupiter.api.Test)

Example 3 with PlcDINT

use of org.apache.plc4x.java.spi.values.PlcDINT in project plc4x by apache.

the class Plc4XDf1Protocol method decode.

@Override
protected void decode(ChannelHandlerContext ctx, DF1Symbol msg, List<Object> out) throws Exception {
    logger.debug("Received DF1 Command incoming {}", msg);
    if (msg instanceof DF1SymbolMessageFrameNAK) {
        logger.warn("Received a response NAK, notify all requests");
        for (Map.Entry<Integer, PlcRequestContainer> entry : requests.entrySet()) {
            entry.getValue().getResponseFuture().complete(new DefaultPlcReadResponse((PlcReadRequest) entry.getValue().getRequest(), Collections.singletonMap("erster", new ResponseItem<>(PlcResponseCode.INTERNAL_ERROR, new PlcDINT(-1)))));
        }
        return;
    } else if (msg instanceof DF1SymbolMessageFrameACK) {
        logger.warn("Received a response ACK :D");
        return;
    }
    assert msg instanceof DF1SymbolMessageFrame;
    DF1Command command = ((DF1SymbolMessageFrame) msg).getCommand();
    int transactionId = command.getTransactionCounter();
    if (!requests.containsKey(transactionId)) {
        logger.warn("Received a response to unknown transaction id {}", transactionId);
        ctx.fireExceptionCaught(new RuntimeException("Received a response to unknown transaction id"));
        ctx.close();
        return;
    }
    // As every response has a matching request, get this request based on the tpdu.
    PlcRequestContainer requestContainer = requests.remove(transactionId);
    PlcRequest request = requestContainer.getRequest();
    // Handle the response.
    PlcResponse response = null;
    if (request instanceof PlcReadRequest) {
        /*
            Things to do
            - check response code (if there is something like that?
            - cast the bytes to right datatype
            - create Response
             */
        // We can do this as we have only one fieldName in DF1
        final String fieldName = ((PlcReadRequest) request).getFieldNames().iterator().next();
        // TODO can there be another code than ok?
        final PlcResponseCode responseCode = PlcResponseCode.OK;
        // TODO maybe check for different status bytes
        final Df1Field field = (Df1Field) ((PlcReadRequest) request).getField(fieldName);
        // Cast byte and create response item
        PlcValue responseItem = null;
        byte[] data = ((DF1UnprotectedReadResponse) command).getData();
        switch(field.getDataType()) {
            case BIT:
                break;
            case INTEGER:
                // TODO: type conversion is untested
                responseItem = new PlcDINT((int) data[0] + ((int) data[1] << 8));
                break;
            case FLOAT:
                break;
            case BIT_STRING:
                break;
            case ARRAY:
                break;
            // TODO add all other cases here...
            default:
                throw new NotImplementedException("The DataType " + field.getDataType() + " is currently not implemented!");
        }
        response = new DefaultPlcReadResponse(((PlcReadRequest) request), Collections.singletonMap(fieldName, new ResponseItem<>(responseCode, responseItem)));
    } else if (request instanceof PlcWriteRequest) {
        logger.warn("Writing is currently not implemented but received a write response?!");
        ctx.close();
        throw new NotImplementedException("This is currently not implemented!");
    }
    // Confirm the response being handled.
    if (response != null) {
        requestContainer.getResponseFuture().complete(response);
    }
}
Also used : PlcRequestContainer(org.apache.plc4x.java.spi.messages.PlcRequestContainer) PlcDINT(org.apache.plc4x.java.spi.values.PlcDINT) PlcRequest(org.apache.plc4x.java.api.messages.PlcRequest) NotImplementedException(org.apache.commons.lang3.NotImplementedException) PlcResponseCode(org.apache.plc4x.java.api.types.PlcResponseCode) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) PlcValue(org.apache.plc4x.java.api.value.PlcValue) PlcResponse(org.apache.plc4x.java.api.messages.PlcResponse) PlcWriteRequest(org.apache.plc4x.java.api.messages.PlcWriteRequest) DefaultPlcReadResponse(org.apache.plc4x.java.spi.messages.DefaultPlcReadResponse) PlcReadRequest(org.apache.plc4x.java.api.messages.PlcReadRequest) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Map(java.util.Map) Df1Field(org.apache.plc4x.java.df1.field.Df1Field)

Example 4 with PlcDINT

use of org.apache.plc4x.java.spi.values.PlcDINT in project plc4x by apache.

the class PlcEntityManagerComplexTest method read.

@Test
public void read() throws OPMException, PlcConnectionException {
    Map<String, PlcValue> results = new HashMap<>();
    String prefix = MyEntity.class.getName() + ".";
    results.put(prefix + "counter", new PlcDINT(1));
    results.put(prefix + "counter2", new PlcLINT(1L));
    PlcEntityManager manager = getPlcEntityManager(results);
    MyEntity myEntity = manager.read(MyEntity.class, "s7://localhost:5555/0/0");
    assertEquals(1, (long) myEntity.getCounter());
    assertEquals(1, myEntity.getCounter2());
}
Also used : PlcDINT(org.apache.plc4x.java.spi.values.PlcDINT) HashMap(java.util.HashMap) PlcLINT(org.apache.plc4x.java.spi.values.PlcLINT) Test(org.junit.jupiter.api.Test)

Example 5 with PlcDINT

use of org.apache.plc4x.java.spi.values.PlcDINT in project plc4x by apache.

the class ScraperTest method restart_works.

@Test
void restart_works() throws PlcConnectionException {
    PlcDriverManager driverManager = new PlcDriverManager();
    MockConnection connection = (MockConnection) driverManager.getConnection("mock:m1");
    connection.setDevice(mockDevice);
    when(mockDevice.read(any())).thenReturn(new ResponseItem<>(PlcResponseCode.OK, new PlcDINT(1)));
    Scraper scraper = new ScraperImpl((j, a, m) -> {
    }, driverManager, Collections.singletonList(new ScrapeJobImpl("job1", 1, Collections.singletonMap("m1", "mock:m1"), Collections.singletonMap("field1", "qry1"))));
    scraper.start();
    assertThat(scraper.getNumberOfActiveTasks()).isEqualTo(1);
    scraper.stop();
    assertThat(scraper.getNumberOfActiveTasks()).isZero();
    scraper.start();
    assertThat(scraper.getNumberOfActiveTasks()).isEqualTo(1);
}
Also used : PlcDINT(org.apache.plc4x.java.spi.values.PlcDINT) PlcDriverManager(org.apache.plc4x.java.PlcDriverManager) PooledPlcDriverManager(org.apache.plc4x.java.utils.connectionpool.PooledPlcDriverManager) MockConnection(org.apache.plc4x.java.mock.connection.MockConnection) Test(org.junit.jupiter.api.Test)

Aggregations

PlcDINT (org.apache.plc4x.java.spi.values.PlcDINT)5 Test (org.junit.jupiter.api.Test)3 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 PlcDriverManager (org.apache.plc4x.java.PlcDriverManager)2 MockConnection (org.apache.plc4x.java.mock.connection.MockConnection)2 PooledPlcDriverManager (org.apache.plc4x.java.utils.connectionpool.PooledPlcDriverManager)2 HashMap (java.util.HashMap)1 Map (java.util.Map)1 ScheduledThreadPoolExecutor (java.util.concurrent.ScheduledThreadPoolExecutor)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1 Consumer (java.util.function.Consumer)1 NotImplementedException (org.apache.commons.lang3.NotImplementedException)1 PlcReadRequest (org.apache.plc4x.java.api.messages.PlcReadRequest)1 PlcRequest (org.apache.plc4x.java.api.messages.PlcRequest)1 PlcResponse (org.apache.plc4x.java.api.messages.PlcResponse)1 PlcWriteRequest (org.apache.plc4x.java.api.messages.PlcWriteRequest)1 PlcSubscriptionHandle (org.apache.plc4x.java.api.model.PlcSubscriptionHandle)1 PlcResponseCode (org.apache.plc4x.java.api.types.PlcResponseCode)1 PlcValue (org.apache.plc4x.java.api.value.PlcValue)1 Df1Field (org.apache.plc4x.java.df1.field.Df1Field)1