Browse Source

新配置与接入rpc

gemercheung 3 years ago
parent
commit
6ba669c52b

+ 0 - 7
.env

@@ -1,7 +0,0 @@
-PORT=6688
-PRIVATE_IP=172.18.197.114
-PUBLIC_IP=120.24.252.95
-ALL_IPS=['192.168.0']
-STUNS_SEVER="stun:172.18.156.41:3478,stun:120.24.252.95:3478"
-GRPC_URL="192.168.0.152:3000"
-REDIS_URL="redis://:192.168.0.47:6379/9"

+ 18 - 0
config.yaml

@@ -0,0 +1,18 @@
+http:
+  host: '0.0.0.0'
+  port: 6688
+
+grpc:
+  url: '192.168.0.200:3000'
+
+redis:
+  port: 6379
+  host: '192.168.0.47' #远程调试需要设置bindip 为0.0.0.0 并且设置密码
+  password: '' # 非远程不需要密码
+  decode_responses: true
+  db: 9
+# PRIVATE_IP=172.18.197.114
+# PUBLIC_IP=120.24.252.95
+# STUNS_SEVER="stun:172.18.156.41:3478,stun:120.24.252.95:3478"
+# GRPC_URL="192.168.0.48:3000"
+# REDIS_URL="redis://:192.168.0.47:6379/9"

+ 2 - 0
package.json

@@ -32,6 +32,7 @@
     "@nestjs/platform-ws": "^8.4.4",
     "@nestjs/websockets": "^8.4.4",
     "buffer": "^6.0.3",
+    "js-yaml": "^4.1.0",
     "multistream": "^4.1.0",
     "nestjs-redis": "^1.3.3",
     "node-datachannel": "^0.3.2",
@@ -47,6 +48,7 @@
     "@nestjs/testing": "^8.0.0",
     "@types/express": "^4.17.13",
     "@types/jest": "27.4.1",
+    "@types/js-yaml": "^4.0.5",
     "@types/node": "^16.0.0",
     "@types/supertest": "^2.0.11",
     "@typescript-eslint/eslint-plugin": "^5.0.0",

+ 4 - 11
src/app.controller.ts

@@ -22,9 +22,9 @@ export class AppController implements OnModuleInit {
 
   onModuleInit() {
     // console.log('this.client', this.client);
-    this.sceneGrpcService =
-      this.client.getService<SceneGrpcService>('SceneGrpcService');
-    console.log('this.sceneGrpcService', this.sceneGrpcService);
+    // this.sceneGrpcService =
+    //   this.client.getService<SceneGrpcService>('SceneGrpcService');
+    // console.log('this.sceneGrpcService', this.sceneGrpcService);
   }
   @Get()
   getHello(): string {
@@ -81,14 +81,7 @@ export class AppController implements OnModuleInit {
       //   trace_id: '2b6e3444-63eb-40a7-8049-1d6616f16664',
       //   user_id: '31a6322c-78f1-4744-99df-bc042f50bebc',
       // };
-      // const initReply = this.sceneGrpcService.test({
-      //   name: 'lala',
-      // });
-      // initReply.subscribe((val) => {
-      //   console.log('val', val);
-      // });
-      // console.log('initReply')
-      this.sceneService.pushTheFirstFrame();
+      // console.log('initReply');
     } catch (error) {
       console.log('test', error);
     }

+ 6 - 1
src/app.module.ts

@@ -6,9 +6,14 @@ import { MetaGateway } from './meta.gateway';
 import { RoomModule } from './room/room.module';
 import { SceneModule } from './scene/scene.module';
 // import { RedisModule } from './redis/redis.module';
+import configuration from './config/configuration';
 
 @Module({
-  imports: [ConfigModule.forRoot(), RoomModule, SceneModule],
+  imports: [
+    ConfigModule.forRoot({ isGlobal: true, load: [configuration] }),
+    RoomModule,
+    SceneModule,
+  ],
   controllers: [AppController],
   providers: [AppService, MetaGateway],
 })

+ 11 - 0
src/config/configuration.ts

@@ -0,0 +1,11 @@
+import { readFileSync } from 'fs';
+import * as yaml from 'js-yaml';
+import { join } from 'path';
+
+const YAML_CONFIG_FILENAME = '../config.yaml';
+
+export default () => {
+  return yaml.load(
+    readFileSync(join(__dirname, YAML_CONFIG_FILENAME), 'utf8'),
+  ) as Record<string, any>;
+};

+ 6 - 3
src/main.ts

@@ -3,16 +3,19 @@ import { AppModule } from './app.module';
 // import { WsAdapter } from '@nestjs/platform-ws';
 import { WsAdapter } from './ws-adapter';
 import { Logger } from '@nestjs/common';
+import { ConfigService } from '@nestjs/config';
 
-const port = process.env.PORT || 3100;
 async function bootstrap() {
   const app = await NestFactory.create(AppModule);
   app.enableCors();
   app.useWebSocketAdapter(new WsAdapter(app));
+  const configService = app.get(ConfigService);
 
-  await app.listen(port, '0.0.0.0', function () {
+  const http = configService.get('http');
+
+  await app.listen(http.port, http.host, function () {
     const logger = new Logger('bootstrap');
-    logger.log(`listening on port ${port}`);
+    logger.log(`listening on port ${http.port}`);
   });
 }
 bootstrap();

+ 0 - 1
src/meta.gateway.ts

@@ -219,7 +219,6 @@ export class MetaGateway
       cleanup();
     });
     this.gameChanel.onMessage((event) => {
-      console.log('gameChanel onMessage', event);
       this.sceneService.handleMessage(event);
     });
     this.gameChanel.onError(() => {

+ 10 - 8
src/redis/redis.module.ts

@@ -2,16 +2,18 @@ import { Module } from '@nestjs/common';
 // import { ClientsModule, Transport } from '@nestjs/microservices';
 import { RedisService } from './redis.service';
 import { RedisModule as CacheModule } from 'nestjs-redis';
+import configuration from 'src/config/configuration';
 
-const options = {
-  port: 6379,
-  host: '192.168.0.47', // 远程调试需要设置bindip 为0.0.0.0 并且设置密码
-  password: '', // 非远程不需要密码
-  decode_responses: true,
-  db: 9,
-};
+// const options = {
+//   port: 6379,
+//   host: '192.168.0.47', // 远程调试需要设置bindip 为0.0.0.0 并且设置密码
+//   password: '', // 非远程不需要密码
+//   decode_responses: true,
+//   db: 9,
+// };
+console.log('redis-config', configuration().redis);
 @Module({
-  imports: [CacheModule.register(options)],
+  imports: [CacheModule.register(configuration().redis)],
   providers: [RedisService],
   exports: [RedisService],
 })

+ 5 - 0
src/scene/actionType.ts

@@ -0,0 +1,5 @@
+export enum ActionType {
+  rotate = 1014,
+  userStatus = 1024,
+  status = 1009,
+}

+ 5 - 4
src/scene/grpc-scene.options.ts

@@ -1,14 +1,15 @@
 import { Transport, ClientOptions } from '@nestjs/microservices';
 import { join } from 'path';
+import configuration from 'src/config/configuration';
 
 export const grpcClientOptions: ClientOptions = {
   transport: Transport.GRPC,
   options: {
-    url: process.env.GRPC_URL,
+    url: configuration().grpc.url,
     package: 'scene',
     protoPath: join(__dirname, '..', 'proto/scene.proto'),
-    // loader: {
-    //   keepCase: false,
-    // }
+    loader: {
+      keepCase: false,
+    },
   },
 };

+ 29 - 4
src/scene/scene.d.ts

@@ -44,10 +44,10 @@ interface InitRequest {
 }
 
 interface RotateRequest {
-  actionType: number;
-  rotationAction: string;
-  traceId: string;
-  userId: string;
+  action_type: number;
+  rotation_action?: RotationActionType;
+  trace_id: string;
+  user_id: string;
 }
 
 interface MoveRequest {
@@ -129,3 +129,28 @@ interface EchoRequest {
   trace_id: string;
   user_id: string;
 }
+
+interface RTCEchoMessage {
+  echoMsg: string;
+}
+interface RTCEchoMessage {
+  echoMsg: string;
+}
+
+interface newUserStateType {
+  userType: number;
+}
+interface RotationActionType {
+  vertical_move: number;
+  horizontal_move: number;
+}
+
+interface RTCMessageRequest {
+  action_type: number;
+  echo_msg?: RTCEchoMessage;
+  getNewUserStateAction?: newUserStateType;
+  rotation_action?: RotationActionType;
+  sampleRate?: number;
+  trace_id: string;
+  user_id: string;
+}

+ 36 - 32
src/scene/scene.service.ts

@@ -9,6 +9,7 @@ import { statSync, createReadStream, readFileSync } from 'fs';
 import { Readable } from 'stream';
 import { BehaviorSubject } from 'rxjs';
 import * as streamBuffers from 'stream-buffers';
+import { ActionType } from './actionType';
 
 @Injectable()
 export class SceneService implements OnModuleInit {
@@ -36,40 +37,23 @@ export class SceneService implements OnModuleInit {
     return this.sceneGrpcService.getBreakPoint(request);
   }
 
+  test(request: TestRequest) {
+    return this.sceneGrpcService.test(request);
+  }
+
   init(request: string) {
     try {
-      console.log('request', this.sceneGrpcService);
+      // console.log('request', this.sceneGrpcService);
       const params = JSON.parse(request);
       // const requestData: InitRequest = {
       //   appId: params.appId
       // }
-      const demo_test: InitRequest = {
-        user_id: '92dd7e2f-cca9-495d-8f16-458e628ea827',
-        nick_name: 'Hello',
-        skin_id: 'ce098a8f-a7fc-4721-9c37-31bdbc580c59',
-        avatar_id: 'c961561e-78e5-4478-b158-944e3b9c9287',
-        room_id: 'c38187b6-d4af-44bb-8028-7ad1e5461cd8',
-        app_id: '2282e1b5-6129-4e0d-a30b-2339a1c761cd',
-        player: {
-          position: {
-            x: '0.0',
-            y: '0.0',
-            z: '0.0',
-          },
-          angle: {
-            pitch: 10,
-            yaw: 10,
-            roll: 10,
-          },
-        },
-      };
-      const name = {
-        name: 'Hello',
-      };
-      const initReply = this.sceneGrpcService.test(name);
-      // initReply.subscribe((val) => {
-      //   console.log('val', val);
-      // });
+      this.logger.log('init', request);
+      const rpcRequest: InitRequest = params;
+      const initReply = this.sceneGrpcService.init(rpcRequest);
+      initReply.subscribe((reply) => {
+        console.log('initReply', reply);
+      });
     } catch (error) {
       console.log('error', error);
     }
@@ -80,7 +64,10 @@ export class SceneService implements OnModuleInit {
   }
 
   rotate(request: RotateRequest) {
-    return this.sceneGrpcService.rotate(request);
+    const reply = this.sceneGrpcService.rotate(request);
+    reply.subscribe((res) => {
+      console.log('rotate-reply', res);
+    });
   }
 
   joystick(request: JoystickRequest) {
@@ -98,8 +85,25 @@ export class SceneService implements OnModuleInit {
     this.onSteaming.next(false);
   }
 
-  handleMessage(event: string | Buffer) {
-    console.log('get rtc message', event);
+  handleMessage(message: string | Buffer) {
+    try {
+      if (typeof message === 'string') {
+        const msg: RTCMessageRequest = JSON.parse(message);
+        switch (msg.action_type) {
+          case ActionType.rotate:
+            console.log('rotate', msg);
+            const rotateRequest: RotateRequest = msg;
+            this.rotate(rotateRequest);
+            break;
+
+          default:
+            break;
+        }
+      }
+      // console.log('get rtc message', message);
+    } catch (error) {
+      this.logger.error('handleMessage:rtc', error);
+    }
   }
   handleStartCountingFrame() {
     this._frameInteval = setInterval(async () => {
@@ -167,7 +171,7 @@ export class SceneService implements OnModuleInit {
     console.log('首屏--数据');
     const paths = path.join(__dirname, '../ws/video');
     // const clipPath = paths + `/1.v2.h264`;
-    const testClipPath = paths + `/2.h264`;
+    const testClipPath = paths + `/254.h264`;
     const metaData = {
       traceIds: [],
       vehicle: null,

+ 6 - 10
yarn.lock

@@ -1041,6 +1041,11 @@
     jest-matcher-utils "^27.0.0"
     pretty-format "^27.0.0"
 
+"@types/js-yaml@^4.0.5":
+  version "4.0.5"
+  resolved "https://registry.npmmirror.com/@types/js-yaml/-/js-yaml-4.0.5.tgz#738dd390a6ecc5442f35e7f03fa1431353f7e138"
+  integrity sha512-FhpRzf927MNQdRZP0J5DLIdTXhjLYzeUTmLAu69mnVksLH9CJY3IuSeEgbKUki7GQZm0WqDkGzyxju2EZGD2wA==
+
 "@types/json-schema@*", "@types/json-schema@^7.0.8", "@types/json-schema@^7.0.9":
   version "7.0.11"
   resolved "https://registry.npmmirror.com/@types/json-schema/-/json-schema-7.0.11.tgz"
@@ -1650,15 +1655,6 @@ bl@^4.0.3, bl@^4.1.0:
     inherits "^2.0.4"
     readable-stream "^3.4.0"
 
-bl@^5.0.0:
-  version "5.0.0"
-  resolved "https://registry.yarnpkg.com/bl/-/bl-5.0.0.tgz#6928804a41e9da9034868e1c50ca88f21f57aea2"
-  integrity sha512-8vxFNZ0pflFfi0WXA3WQXlj6CaMEwsmh63I1CNp0q+wWv8sD0ARx1KovSQd0l2GkwrMIOyedq0EF1FxI+RCZLQ==
-  dependencies:
-    buffer "^6.0.3"
-    inherits "^2.0.4"
-    readable-stream "^3.4.0"
-
 body-parser@1.19.2:
   version "1.19.2"
   resolved "https://registry.npmmirror.com/body-parser/-/body-parser-1.19.2.tgz"
@@ -3728,7 +3724,7 @@ js-yaml@^3.13.1:
 
 js-yaml@^4.1.0:
   version "4.1.0"
-  resolved "https://registry.npmmirror.com/js-yaml/-/js-yaml-4.1.0.tgz"
+  resolved "https://registry.npmmirror.com/js-yaml/-/js-yaml-4.1.0.tgz#c1fb65f8f5017901cdd2c951864ba18458a10602"
   integrity sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==
   dependencies:
     argparse "^2.0.1"