Skip to content

Mock device communications

For testing purposes, you can mock response sent by the device. You can use MockProtocol (it implements the ComProtocol).

Configure your tap device instance to use this protocol

1) Using a mock protocol

Using a Mock protocol produces something similar to what you have with an IoTize device.

Using a pre-implemented mock protocol

import { MockProtocol } from "@iotize/device-com-mock.js"
import { Response, ApiRequest } from "@iotize/device-client.js/client/impl";
import { FormatHelper } from "@iotize/device-client.js/core";
import { Tap } from "@iotize/device-client.js/device";

// Create a MockProtocol instance
let mockProtocol = new MockProtocol()

// Configure responses you want to mock
mockProtocol
    .mapResponse(
        // the request to match
        ApiRequest.GET("/1024//9"), // Application name (see http://developer.iotize.com/content/tap-device/service/InterfaceService/#getappname)
        // The mock response to return
        Response.SUCCESS(FormatHelper.hexStringToBuffer("MyMockSerialNumber"))
    )

// Create your tap instance from this protocol
let tap = Tap.fromProtocol(mockProtocol)

// Do not forget to connect first
await tap.connect()

// Get application name
let applicationName = (await tap.service.interface.getAppName()).body()
// applicationName = "MyMockSerialNumber"

MockProtocol moclProtocol = new MockProtocol();
// Map a specific response to a command
mockProtocol.mapResponse(Command.GET("/1/2/3"), Response.SUCCESS("Hello World".getBytes()));
// Command GET /1/2/3 will now always return a successful response with "Hello World" payload

// Map a dynamic response to a command: 
mockProtocol.mapResponse(Command.GET("/1/2/3"), new ResponseAdapter<byte[]>() {
            @Override
            public Response<byte[]> adapt(Command request) {
                Response<byte[]> response = // your custom response here...
                return response;
            }
        });


// Map a response with a custom filter
mockProtocol.mapResponse(new Filter<Command>() {
             @Override
             public boolean isFiltered(Command command) {
                 boolean isFiltered = // return false if you want to apply the ResponseAdapter to this command
                 return isFiltered;
             }
         }
         , new ResponseAdapter<byte[]>() {
            @Override
            public Response<byte[]> adapt(Command request) {
                Response<byte[]> response = // your custom response here...
                return response;
            }
        });
let mockProtocol = MockProtocol()