Advertisement
Guest User

Theia USB Service

a guest
Dec 30th, 2020
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // browser/fusb-service-contribution.ts
  2.  
  3. import { interfaces } from "inversify";
  4. import { UsbService, workspacePath } from "../../common/usb-service-protocol";
  5. import { WebSocketConnectionProvider } from "@theia/core/lib/browser";
  6.  
  7. export function bindUsbService(bind: interfaces.Bind): void {
  8.     bind(UsbService).toDynamicValue(ctx => {
  9.         const provider = ctx.container.get(WebSocketConnectionProvider);
  10.         return provider.createProxy<UsbService>(workspacePath);
  11.     }).inSingletonScope();
  12. };
  13.  
  14.  
  15. // common/usb-service-protocol.ts
  16.  
  17. import { Event } from "@theia/core";
  18. import { Device } from "usb";
  19. export const workspacePath = '/services/ves/usb';
  20.  
  21. export const UsbService = Symbol('UsbService');
  22. export interface UsbService {
  23.     onDeviceConnected: Event<Device>;
  24. }
  25.  
  26.  
  27. // node/usb-service-module.ts
  28.  
  29. import { ContainerModule } from 'inversify';
  30. import { ConnectionHandler, JsonRpcConnectionHandler } from '@theia/core';
  31. import { DefaultUsbService } from './default-usb-service';
  32. import { UsbService, workspacePath } from '../common/usb-service-protocol';
  33.  
  34. export default new ContainerModule(bind => {
  35.     bind(DefaultUsbService).toSelf().inSingletonScope();
  36.     bind(UsbService).toService(DefaultUsbService);
  37.  
  38.     bind(ConnectionHandler).toDynamicValue(ctx =>
  39.         new JsonRpcConnectionHandler(workspacePath, () => {
  40.             return ctx.container.get(UsbService);
  41.         })
  42.     ).inSingletonScope()
  43. });
  44.  
  45.  
  46. // node/default-usb-service.ts
  47.  
  48. import { injectable, postConstruct } from "inversify";
  49. import { UsbService } from "../common/usb-service-protocol";
  50. import { Device, on } from "usb";
  51. import { Emitter } from "@theia/core";
  52.  
  53. @injectable()
  54. export class DefaultUsbService implements UsbService {
  55.     protected readonly onDeviceConnectedEmitter = new Emitter<Device>();
  56.     readonly onDeviceConnected = this.onDeviceConnectedEmitter.event;
  57.  
  58.     @postConstruct()
  59.     protected init(): void {
  60.         const self = this;
  61.         on('attach', async function (device) {
  62.             console.log('attach');
  63.             self.onDeviceConnectedEmitter.fire(device);
  64.         });
  65.     }
  66. }
  67.  
  68.  
  69. // somewhere in frontend
  70.  
  71. this.usbService.onDeviceConnected(() => console.log("connected!"));
  72.  
  73.  
  74. // error
  75.  
  76. root INFO attach
  77. root ERROR TypeError: Cannot read property 'apply' of undefined
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement