Home Forums TrueRNG Hardware random number generator TrueRNG 3 and WebUSB?

This topic contains 3 replies, has 2 voices, and was last updated by  SarahC 1 year, 11 months ago.

Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #2646

    paramarkaz
    Member

    Hello. Has anyone been able to read TrueRNG 3 data into Chrome using WebUSB? If so, any sample code, tutorials, or suggestions would be appreciated. Thanks in advance.

    #2664

    SarahC
    Member

    It’s still a very rough and new API – I’m trying to find if there’s an ability to read in serial bytes, no luck yet.

    This simple demo just shows the available TrueRNG V2′s in the popup.

    For the V3, you’ll need to go to device manager, and find the vendor and product ID’s and swap them in the code:

    <!DOCTYPE html>
    <html lang="en" class=" zznfdvyc idc0_340"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <title>CodePen - WebUSB API Connection Interaction</title>
    </head>
    <body translate="no">
    
    	<div>
    	<h1>WebUSB API Connect Demo</h1>
    	<p>This demo uses the WebUSB API, an experimental API with very limited support. You'll have to run this demo locally.</p>
    	<p>In supported environments, the browser needs to request permission to interact with a device the first time:
    	<button id="permission">Request Device Permission</button></p>
    	</div>
    
    	<div id="status">Not Connected</div>
    
    <script>
    	  
    let requestBtn = document.getElementById("permission");
    let usbText = document.querySelector("status");
    
    let device;
    
    console.clear();
    
    // TrueRNG Version 2 ID
    const deviceProps = {
      vendorId: 0x04D8,
      productId: 0xF5FE 
    };
    
    if (navigator.usb) {
    requestBtn.addEventListener("click", () => {
      navigator.usb.
      requestDevice({
    	filters: [deviceProps] }).
    
      then(d => {
    	device = d;
    	device.open().then(e => {
    	  console.log("opened: ", device);
    	  console.log("vendorId: " + device.vendorId);
    	  console.log("productId: " + device.productId);
    	  console.log("serialNumber: " + device.serialNumber);
    	});
      }).
      catch(error => {
    	console.log(error);
      });
    });
    
    navigator.usb.addEventListener("connect", function (e) {
      console.log("connect");
      usbConnected();
    });
    
    navigator.usb.addEventListener("disconnect", function (e) {
      console.log("disconnect");
      usbDisconnected();
    });
    }
    
    function usbConnected() {
    	usbText.innerHTML = "Connected";
    }
    
    function usbDisconnected() {
        usbText.innerHTML = "Not Connected";
    }
    
    </script>
     
    </body>
    </html>
    • This reply was modified 1 year, 11 months ago by  SarahC.
    #2666

    SarahC
    Member

    It’s got a lot better:

    https://web.dev/serial/

    #2667

    SarahC
    Member

    Here’s a USB Serial reader for all the TrueRNG devices:

    <!DOCTYPE html>
    <html lang="en">
    <head>
    	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>WebUSB serial read</title>
    	
    </head>
    <body>
    <button id="connect">Connect to device</button>
    <p>Open the browser console to see received messages from the MCU!</p>
    </body>
    <script>
    var serial = {};
    
    (function() {
      'use strict';
    
      serial.getPorts = function() {
        return navigator.usb.getDevices().then(devices => {
          return devices.map(device => new serial.Port(device));
        });
      };
    
      serial.requestPort = function() {
        const filters = [
          { 'vendorId': 0x04D8}
        ];
        return navigator.usb.requestDevice({ 'filters': filters }).then(
          device => new serial.Port(device)
        );
      }
    
      serial.Port = function(device) {
        this.device_ = device;
        this.interfaceNumber_ = 2;  // original interface number of WebUSB Arduino demo
        this.endpointIn_ = 5;       // original in endpoint ID of WebUSB Arduino demo
        this.endpointOut_ = 4;      // original out endpoint ID of WebUSB Arduino demo
      };
    
      serial.Port.prototype.connect = function() {
        let readLoop = () => {
          this.device_.transferIn(this.endpointIn_, 64).then(result => {
            this.onReceive(result.data);
            readLoop();
          }, error => {
            this.onReceiveError(error);
          });
        };
    
        return this.device_.open()
            .then(() => {
              if (this.device_.configuration === null) {
                return this.device_.selectConfiguration(1);
              }
            })
            .then(() => {
              var configurationInterfaces = this.device_.configuration.interfaces;
              configurationInterfaces.forEach(element => {
                element.alternates.forEach(elementalt => {
                  if (elementalt.interfaceClass==0xff) {
                    this.interfaceNumber_ = element.interfaceNumber;
                    elementalt.endpoints.forEach(elementendpoint => {
                      if (elementendpoint.direction == "out") {
                        this.endpointOut_ = elementendpoint.endpointNumber;
                      }
                      if (elementendpoint.direction=="in") {
                        this.endpointIn_ =elementendpoint.endpointNumber;
                      }
                    })
                  }
                })
              })
            })
            .then(() => this.device_.claimInterface(this.interfaceNumber_))
            .then(() => this.device_.selectAlternateInterface(this.interfaceNumber_, 0))
            .then(() => this.device_.controlTransferOut({
                'requestType': 'class',
                'recipient': 'interface',
                'request': 0x22,
                'value': 0x01,
                'index': this.interfaceNumber_}))
            .then(() => {
              readLoop();
            });
      };
    
      serial.Port.prototype.disconnect = function() {
        return this.device_.controlTransferOut({
                'requestType': 'class',
                'recipient': 'interface',
                'request': 0x22,
                'value': 0x00,
                'index': this.interfaceNumber_})
            .then(() => this.device_.close());
      };
    
      serial.Port.prototype.send = function(data) {
        return this.device_.transferOut(this.endpointOut_, data);
      };
    })();
    
    serial.requestPort = function() {
      const filters = [
        { 'vendorId': 0x04D8 }
      ];
      return navigator.usb.requestDevice({ 'filters': filters }).then(
        device => new serial.Port(device)
      );
    }
    
    var port
    let connectButton = document.querySelector('#connect')
    let textDecoder = new TextDecoder()
    
    connectButton.addEventListener('click', function() {
      if (port) { // If port is already connected, disconnect it
        connectButton.textContent = 'Connect'
        port.disconnect()
        port = null
        console.log('Device is disconnected.')
      } else { // If there is no port, then connect to a new port
        serial.requestPort().then(selectedPort => {
          port = selectedPort
          port.connect().then(() => {
            console.log('Device is connected to Product ID: ' + port.device_.productId.toString(16) + ' and Vendor ID: ' + port.device_.vendorId.toString(16))
    
            connectButton.textContent = 'Disconnect'
            port.onReceive = data => { console.log(textDecoder.decode(data))}
            port.onReceiveError = error => { console.log('Receive error: ' + error)}
          }, error => { console.log('Connection error: ' + error) })
        }).catch(error => { console.log('Connection error: ' + error) })
      }
    })
    </script>
     
    </body>
    </html>
Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic.