Commit e3651a8c authored by wangdong's avatar wangdong

ls

parents
{
"comments": false,
"env": {
"main": {
"presets": [
["env", {
"targets": { "node": 7 }
}],
"stage-0"
]
},
"renderer": {
"presets": [
["env", {
"modules": false
}],
"stage-0"
]
},
"web": {
"presets": [
["env", {
"modules": false
}],
"stage-0"
]
}
},
"plugins": ["transform-runtime"]
}
'use strict'
process.env.NODE_ENV = 'production'
const { say } = require('cfonts')
const chalk = require('chalk')
const del = require('del')
const { spawn } = require('child_process')
const webpack = require('webpack')
const Multispinner = require('multispinner')
const mainConfig = require('./webpack.main.config')
const rendererConfig = require('./webpack.renderer.config')
const webConfig = require('./webpack.web.config')
const doneLog = chalk.bgGreen.white(' DONE ') + ' '
const errorLog = chalk.bgRed.white(' ERROR ') + ' '
const okayLog = chalk.bgBlue.white(' OKAY ') + ' '
const isCI = process.env.CI || false
if (process.env.BUILD_TARGET === 'clean') clean()
else if (process.env.BUILD_TARGET === 'web') web()
else build()
function clean () {
del.sync(['build/*', '!build/icons', '!build/icons/icon.*'])
console.log(`\n${doneLog}\n`)
process.exit()
}
function build () {
greeting()
del.sync(['dist/electron/*', '!.gitkeep'])
const tasks = ['main', 'renderer']
const m = new Multispinner(tasks, {
preText: 'building',
postText: 'process'
})
let results = ''
m.on('success', () => {
process.stdout.write('\x1B[2J\x1B[0f')
console.log(`\n\n${results}`)
console.log(`${okayLog}take it away ${chalk.yellow('`electron-builder`')}\n`)
process.exit()
})
pack(mainConfig).then(result => {
results += result + '\n\n'
m.success('main')
}).catch(err => {
m.error('main')
console.log(`\n ${errorLog}failed to build main process`)
console.error(`\n${err}\n`)
process.exit(1)
})
pack(rendererConfig).then(result => {
results += result + '\n\n'
m.success('renderer')
}).catch(err => {
m.error('renderer')
console.log(`\n ${errorLog}failed to build renderer process`)
console.error(`\n${err}\n`)
process.exit(1)
})
}
function pack (config) {
return new Promise((resolve, reject) => {
config.mode = 'production'
webpack(config, (err, stats) => {
if (err) reject(err.stack || err)
else if (stats.hasErrors()) {
let err = ''
stats.toString({
chunks: false,
colors: true
})
.split(/\r?\n/)
.forEach(line => {
err += ` ${line}\n`
})
reject(err)
} else {
resolve(stats.toString({
chunks: false,
colors: true
}))
}
})
})
}
function web () {
del.sync(['dist/web/*', '!.gitkeep'])
webConfig.mode = 'production'
webpack(webConfig, (err, stats) => {
if (err || stats.hasErrors()) console.log(err)
console.log(stats.toString({
chunks: false,
colors: true
}))
process.exit()
})
}
function greeting () {
const cols = process.stdout.columns
let text = ''
if (cols > 85) text = 'lets-build'
else if (cols > 60) text = 'lets-|build'
else text = false
if (text && !isCI) {
say(text, {
colors: ['yellow'],
font: 'simple3d',
space: false
})
} else console.log(chalk.yellow.bold('\n lets-build'))
console.log()
}
\ No newline at end of file
const hotClient = require('webpack-hot-middleware/client?noInfo=true&reload=true')
hotClient.subscribe(event => {
/**
* Reload browser when HTMLWebpackPlugin emits a new index.html
*
* Currently disabled until jantimon/html-webpack-plugin#680 is resolved.
* https://github.com/SimulatedGREG/electron-vue/issues/437
* https://github.com/jantimon/html-webpack-plugin/issues/680
*/
// if (event.action === 'reload') {
// window.location.reload()
// }
/**
* Notify `mainWindow` when `main` process is compiling,
* giving notice for an expected reload of the `electron` process
*/
if (event.action === 'compiling') {
document.body.innerHTML += `
<style>
#dev-client {
background: #4fc08d;
border-radius: 4px;
bottom: 20px;
box-shadow: 0 4px 5px 0 rgba(0, 0, 0, 0.14), 0 1px 10px 0 rgba(0, 0, 0, 0.12), 0 2px 4px -1px rgba(0, 0, 0, 0.3);
color: #fff;
font-family: 'Source Sans Pro', sans-serif;
left: 20px;
padding: 8px 12px;
position: absolute;
}
</style>
<div id="dev-client">
Compiling Main Process...
</div>
`
}
})
'use strict'
const chalk = require('chalk')
const electron = require('electron')
const path = require('path')
const { say } = require('cfonts')
const { spawn } = require('child_process')
const webpack = require('webpack')
const WebpackDevServer = require('webpack-dev-server')
const webpackHotMiddleware = require('webpack-hot-middleware')
const mainConfig = require('./webpack.main.config')
const rendererConfig = require('./webpack.renderer.config')
let electronProcess = null
let manualRestart = false
let hotMiddleware
function logStats (proc, data) {
let log = ''
log += chalk.yellow.bold(`┏ ${proc} Process ${new Array((19 - proc.length) + 1).join('-')}`)
log += '\n\n'
if (typeof data === 'object') {
data.toString({
colors: true,
chunks: false
}).split(/\r?\n/).forEach(line => {
log += ' ' + line + '\n'
})
} else {
log += ` ${data}\n`
}
log += '\n' + chalk.yellow.bold(`┗ ${new Array(28 + 1).join('-')}`) + '\n'
console.log(log)
}
function startRenderer () {
return new Promise((resolve, reject) => {
rendererConfig.entry.renderer = [path.join(__dirname, 'dev-client')].concat(rendererConfig.entry.renderer)
rendererConfig.mode = 'development'
const compiler = webpack(rendererConfig)
hotMiddleware = webpackHotMiddleware(compiler, {
log: false,
heartbeat: 2500
})
compiler.hooks.compilation.tap('compilation', compilation => {
compilation.hooks.htmlWebpackPluginAfterEmit.tapAsync('html-webpack-plugin-after-emit', (data, cb) => {
hotMiddleware.publish({ action: 'reload' })
cb()
})
})
compiler.hooks.done.tap('done', stats => {
logStats('Renderer', stats)
})
const server = new WebpackDevServer(
compiler,
{
contentBase: path.join(__dirname, '../'),
quiet: true,
before (app, ctx) {
app.use(hotMiddleware)
ctx.middleware.waitUntilValid(() => {
resolve()
})
}
}
)
server.listen(9080)
})
}
function startMain () {
return new Promise((resolve, reject) => {
mainConfig.entry.main = [path.join(__dirname, '../src/main/index.dev.js')].concat(mainConfig.entry.main)
mainConfig.mode = 'development'
const compiler = webpack(mainConfig)
compiler.hooks.watchRun.tapAsync('watch-run', (compilation, done) => {
logStats('Main', chalk.white.bold('compiling...'))
hotMiddleware.publish({ action: 'compiling' })
done()
})
compiler.watch({}, (err, stats) => {
if (err) {
console.log(err)
return
}
logStats('Main', stats)
if (electronProcess && electronProcess.kill) {
manualRestart = true
process.kill(electronProcess.pid)
electronProcess = null
startElectron()
setTimeout(() => {
manualRestart = false
}, 5000)
}
resolve()
})
})
}
function startElectron () {
var args = [
'--inspect=5858',
path.join(__dirname, '../dist/electron/main.js')
]
// detect yarn or npm and process commandline args accordingly
if (process.env.npm_execpath.endsWith('yarn.js')) {
args = args.concat(process.argv.slice(3))
} else if (process.env.npm_execpath.endsWith('npm-cli.js')) {
args = args.concat(process.argv.slice(2))
}
electronProcess = spawn(electron, args)
electronProcess.stdout.on('data', data => {
electronLog(data, 'blue')
})
electronProcess.stderr.on('data', data => {
electronLog(data, 'red')
})
electronProcess.on('close', () => {
if (!manualRestart) process.exit()
})
}
function electronLog (data, color) {
let log = ''
data = data.toString().split(/\r?\n/)
data.forEach(line => {
log += ` ${line}\n`
})
if (/[0-9A-z]+/.test(log)) {
console.log(
chalk[color].bold('┏ Electron -------------------') +
'\n\n' +
log +
chalk[color].bold('┗ ----------------------------') +
'\n'
)
}
}
function greeting () {
const cols = process.stdout.columns
let text = ''
if (cols > 104) text = 'electron-vue'
else if (cols > 76) text = 'electron-|vue'
else text = false
if (text) {
say(text, {
colors: ['yellow'],
font: 'simple3d',
space: false
})
} else console.log(chalk.yellow.bold('\n electron-vue'))
console.log(chalk.blue(' getting ready...') + '\n')
}
function init () {
greeting()
Promise.all([startRenderer(), startMain()])
.then(() => {
startElectron()
})
.catch(err => {
console.error(err)
})
}
init()
'use strict'
process.env.BABEL_ENV = 'main'
const path = require('path')
const { dependencies } = require('../package.json')
const webpack = require('webpack')
const MinifyPlugin = require("babel-minify-webpack-plugin")
let mainConfig = {
entry: {
main: path.join(__dirname, '../src/main/index.js')
},
externals: [
...Object.keys(dependencies || {})
],
module: {
rules: [
{
test: /\.js$/,
use: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.node$/,
use: 'node-loader'
}
]
},
node: {
__dirname: process.env.NODE_ENV !== 'production',
__filename: process.env.NODE_ENV !== 'production'
},
output: {
filename: '[name].js',
libraryTarget: 'commonjs2',
path: path.join(__dirname, '../dist/electron')
},
plugins: [
new webpack.NoEmitOnErrorsPlugin()
],
resolve: {
extensions: ['.js', '.json', '.node']
},
target: 'electron-main'
}
/**
* Adjust mainConfig for development settings
*/
if (process.env.NODE_ENV !== 'production') {
mainConfig.plugins.push(
new webpack.DefinePlugin({
'__static': `"${path.join(__dirname, '../static').replace(/\\/g, '\\\\')}"`
})
)
}
/**
* Adjust mainConfig for production settings
*/
if (process.env.NODE_ENV === 'production') {
mainConfig.plugins.push(
new MinifyPlugin(),
new webpack.DefinePlugin({
'process.env.NODE_ENV': '"production"'
})
)
}
module.exports = mainConfig
'use strict'
process.env.BABEL_ENV = 'renderer'
const path = require('path')
const { dependencies } = require('../package.json')
const webpack = require('webpack')
const MinifyPlugin = require("babel-minify-webpack-plugin")
const CopyWebpackPlugin = require('copy-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { VueLoaderPlugin } = require('vue-loader')
/**
* List of node_modules to include in webpack bundle
*
* Required for specific packages like Vue UI libraries
* that provide pure *.vue files that need compiling
* https://simulatedgreg.gitbooks.io/electron-vue/content/en/webpack-configurations.html#white-listing-externals
*/
let whiteListedModules = ['vue', 'element-ui']
let rendererConfig = {
devtool: '#cheap-module-eval-source-map',
entry: {
renderer: path.join(__dirname, '../src/renderer/main.js')
},
externals: [
...Object.keys(dependencies || {}).filter(d => !whiteListedModules.includes(d))
],
module: {
rules: [
{
test: /\.less$/,
use: ['vue-style-loader', 'css-loader', 'less-loader']
},
{
test: /\.css$/,
use: ['vue-style-loader', 'css-loader']
},
{
test: /\.html$/,
use: 'vue-html-loader'
},
{
test: /\.js$/,
use: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.node$/,
use: 'node-loader'
},
{
test: /\.vue$/,
use: {
loader: 'vue-loader',
options: {
extractCSS: process.env.NODE_ENV === 'production',
loaders: {
sass: 'vue-style-loader!css-loader!sass-loader?indentedSyntax=1',
scss: 'vue-style-loader!css-loader!sass-loader',
less: 'vue-style-loader!css-loader!less-loader'
}
}
}
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
use: {
loader: 'url-loader',
query: {
limit: 10000,
name: 'imgs/[name]--[folder].[ext]'
}
}
},
{
test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
loader: 'url-loader',
options: {
limit: 10000,
name: 'media/[name]--[folder].[ext]'
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
use: {
loader: 'url-loader',
query: {
limit: 10000,
name: 'fonts/[name]--[folder].[ext]'
}
}
}
]
},
node: {
__dirname: process.env.NODE_ENV !== 'production',
__filename: process.env.NODE_ENV !== 'production'
},
plugins: [
new VueLoaderPlugin(),
new MiniCssExtractPlugin({filename: 'styles.css'}),
new HtmlWebpackPlugin({
filename: 'index.html',
template: path.resolve(__dirname, '../src/index.ejs'),
minify: {
collapseWhitespace: true,
removeAttributeQuotes: true,
removeComments: true
},
nodeModules: process.env.NODE_ENV !== 'production'
? path.resolve(__dirname, '../node_modules')
: false
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin()
],
output: {
filename: '[name].js',
libraryTarget: 'commonjs2',
path: path.join(__dirname, '../dist/electron')
},
resolve: {
alias: {
'@': path.join(__dirname, '../src/renderer'),
'vue$': 'vue/dist/vue.esm.js'
},
extensions: ['.js', '.vue', '.json', '.css', '.node']
},
target: 'electron-renderer'
}
/**
* Adjust rendererConfig for development settings
*/
if (process.env.NODE_ENV !== 'production') {
rendererConfig.plugins.push(
new webpack.DefinePlugin({
'__static': `"${path.join(__dirname, '../static').replace(/\\/g, '\\\\')}"`
})
)
}
/**
* Adjust rendererConfig for production settings
*/
if (process.env.NODE_ENV === 'production') {
rendererConfig.devtool = ''
rendererConfig.plugins.push(
new MinifyPlugin(),
new CopyWebpackPlugin([
{
from: path.join(__dirname, '../static'),
to: path.join(__dirname, '../dist/electron/static'),
ignore: ['.*']
}
]),
new webpack.DefinePlugin({
'process.env.NODE_ENV': '"production"'
}),
new webpack.LoaderOptionsPlugin({
minimize: true
})
)
}
module.exports = rendererConfig
'use strict'
process.env.BABEL_ENV = 'web'
const path = require('path')
const webpack = require('webpack')
const MinifyPlugin = require("babel-minify-webpack-plugin")
const CopyWebpackPlugin = require('copy-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { VueLoaderPlugin } = require('vue-loader')
let webConfig = {
devtool: '#cheap-module-eval-source-map',
entry: {
web: path.join(__dirname, '../src/renderer/main.js')
},
module: {
rules: [
{
test: /\.less$/,
use: ['vue-style-loader', 'css-loader', 'less-loader']
},
{
test: /\.css$/,
use: ['vue-style-loader', 'css-loader']
},
{
test: /\.html$/,
use: 'vue-html-loader'
},
{
test: /\.js$/,
use: 'babel-loader',
include: [ path.resolve(__dirname, '../src/renderer') ],
exclude: /node_modules/
},
{
test: /\.vue$/,
use: {
loader: 'vue-loader',
options: {
extractCSS: true,
loaders: {
sass: 'vue-style-loader!css-loader!sass-loader?indentedSyntax=1',
scss: 'vue-style-loader!css-loader!sass-loader',
less: 'vue-style-loader!css-loader!less-loader'
}
}
}
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
use: {
loader: 'url-loader',
query: {
limit: 10000,
name: 'imgs/[name].[ext]'
}
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
use: {
loader: 'url-loader',
query: {
limit: 10000,
name: 'fonts/[name].[ext]'
}
}
}
]
},
plugins: [
new VueLoaderPlugin(),
new MiniCssExtractPlugin({filename: 'styles.css'}),
new HtmlWebpackPlugin({
filename: 'index.html',
template: path.resolve(__dirname, '../src/index.ejs'),
minify: {
collapseWhitespace: true,
removeAttributeQuotes: true,
removeComments: true
},
nodeModules: false
}),
new webpack.DefinePlugin({
'process.env.IS_WEB': 'true'
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin()
],
output: {
filename: '[name].js',
path: path.join(__dirname, '../dist/web')
},
resolve: {
alias: {
'@': path.join(__dirname, '../src/renderer'),
'vue$': 'vue/dist/vue.esm.js'
},
extensions: ['.js', '.vue', '.json', '.css']
},
target: 'web'
}
/**
* Adjust webConfig for production settings
*/
if (process.env.NODE_ENV === 'production') {
webConfig.devtool = ''
webConfig.plugins.push(
new MinifyPlugin(),
new CopyWebpackPlugin([
{
from: path.join(__dirname, '../static'),
to: path.join(__dirname, '../dist/web/static'),
ignore: ['.*']
}
]),
new webpack.DefinePlugin({
'process.env.NODE_ENV': '"production"'
}),
new webpack.LoaderOptionsPlugin({
minimize: true
})
)
}
module.exports = webConfig
.DS_Store
dist/electron/*
dist/web/*
build/*
!build/icons
node_modules/
npm-debug.log
npm-debug.log.*
thumbs.db
!.gitkeep
osx_image: xcode8.3
sudo: required
dist: trusty
language: c
matrix:
include:
- os: osx
- os: linux
env: CC=clang CXX=clang++ npm_config_clang=1
compiler: clang
cache:
directories:
- node_modules
- "$HOME/.electron"
- "$HOME/.cache"
addons:
apt:
packages:
- libgnome-keyring-dev
- icnsutils
before_install:
- mkdir -p /tmp/git-lfs && curl -L https://github.com/github/git-lfs/releases/download/v1.2.1/git-lfs-$([
"$TRAVIS_OS_NAME" == "linux" ] && echo "linux" || echo "darwin")-amd64-1.2.1.tar.gz
| tar -xz -C /tmp/git-lfs --strip-components 1 && /tmp/git-lfs/git-lfs pull
- if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then sudo apt-get install --no-install-recommends -y icnsutils graphicsmagick xz-utils; fi
install:
- nvm install 10
- curl -o- -L https://yarnpkg.com/install.sh | bash
- source ~/.bashrc
- npm install -g xvfb-maybe
- yarn
script:
- yarn run build
branches:
only:
- master
# slice
> A National Key Research Project AI
#### Build Setup
``` bash
# install dependencies
npm install
# serve with hot reload at localhost:9080
npm run dev
# build electron application for production
npm run build
```
---
This project was generated with [electron-vue](https://github.com/SimulatedGREG/electron-vue)@[45a3e22](https://github.com/SimulatedGREG/electron-vue/tree/45a3e224e7bb8fc71909021ccfdcfec0f461f634) using [vue-cli](https://github.com/vuejs/vue-cli). Documentation about the original structure can be found [here](https://simulatedgreg.gitbooks.io/electron-vue/content/index.html).
version: 0.1.{build}
branches:
only:
- master
image: Visual Studio 2017
platform:
- x64
cache:
- node_modules
- '%APPDATA%\npm-cache'
- '%USERPROFILE%\.electron'
- '%USERPROFILE%\AppData\Local\Yarn\cache'
init:
- git config --global core.autocrlf input
install:
- ps: Install-Product node 8 x64
- git reset --hard HEAD
- yarn
- node --version
build_script:
- yarn build
test: off
{
"name": "slice",
"version": "0.0.1",
"author": "wangdongMAC <897253127@qq.com>",
"description": "A National Key Research Project AI ",
"license": null,
"main": "./dist/electron/main.js",
"scripts": {
"build": "node .electron-vue/build.js && electron-builder",
"build:dir": "node .electron-vue/build.js && electron-builder --dir",
"build:clean": "cross-env BUILD_TARGET=clean node .electron-vue/build.js",
"build:web": "cross-env BUILD_TARGET=web node .electron-vue/build.js",
"dev": "node .electron-vue/dev-runner.js",
"pack": "npm run pack:main && npm run pack:renderer",
"pack:main": "cross-env NODE_ENV=production webpack --progress --colors --config .electron-vue/webpack.main.config.js",
"pack:renderer": "cross-env NODE_ENV=production webpack --progress --colors --config .electron-vue/webpack.renderer.config.js",
"postinstall": ""
},
"build": {
"productName": "slice",
"appId": "com.ustb-oai",
"directories": {
"output": "build"
},
"files": [
"dist/electron/**/*"
],
"dmg": {
"contents": [
{
"x": 410,
"y": 150,
"type": "link",
"path": "/Applications"
},
{
"x": 130,
"y": 150,
"type": "file"
}
]
},
"mac": {
"icon": "build/icons/icon.icns"
},
"win": {
"icon": "build/icons/icon.ico"
},
"linux": {
"icon": "build/icons"
}
},
"dependencies": {
"axios": "^0.21.1",
"chartjs": "^0.3.24",
"echart": "^0.1.3",
"echarts": "^5.0.2",
"element-ui": "^2.15.1",
"lodash": "^4.17.21",
"qs": "^6.10.1",
"ssh2": "^0.8.9",
"v-charts-v2": "^2.0.9",
"vue": "^2.5.16",
"vue-electron": "^1.0.6",
"vue-json-tree-view": "^2.1.6",
"vue-router": "^3.0.1",
"vue2-highcharts": "^1.2.5"
},
"devDependencies": {
"ajv": "^6.5.0",
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-minify-webpack-plugin": "^0.3.1",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-env": "^1.7.0",
"babel-preset-stage-0": "^6.24.1",
"babel-register": "^6.26.0",
"cfonts": "^2.1.2",
"chalk": "^2.4.1",
"copy-webpack-plugin": "^4.5.1",
"cross-env": "^5.1.6",
"css-loader": "^0.28.11",
"del": "^3.0.0",
"devtron": "^1.4.0",
"electron": "^2.0.4",
"electron-builder": "^20.19.2",
"electron-debug": "^1.5.0",
"electron-devtools-installer": "^2.2.4",
"file-loader": "^1.1.11",
"html-webpack-plugin": "^3.2.0",
"mini-css-extract-plugin": "0.4.0",
"multispinner": "^0.2.1",
"node-loader": "^0.6.0",
"style-loader": "^0.21.0",
"url-loader": "^1.0.1",
"vue-html-loader": "^1.2.4",
"vue-loader": "^15.2.4",
"vue-style-loader": "^4.1.0",
"vue-template-compiler": "^2.5.16",
"webpack": "^4.15.1",
"webpack-cli": "^3.0.8",
"webpack-dev-server": "^3.1.4",
"webpack-hot-middleware": "^2.22.2",
"webpack-merge": "^4.1.3"
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>slice</title>
<% if (htmlWebpackPlugin.options.nodeModules) { %>
<!-- Add `node_modules/` to global paths so `require` works properly in development -->
<script>
require('module').globalPaths.push('<%= htmlWebpackPlugin.options.nodeModules.replace(/\\/g, '\\\\') %>')
</script>
<% } %>
</head>
<body>
<div id="app"></div>
<!-- Set `__static` path to static files in production -->
<!-- webpack builds are automatically injected -->
</body>
</html>
/**
* This file is used specifically and only for development. It installs
* `electron-debug` & `vue-devtools`. There shouldn't be any need to
* modify this file, but it can be used to extend your development
* environment.
*/
/* eslint-disable */
// Install `electron-debug` with `devtron`
require('electron-debug')({ showDevTools: true })
// Install `vue-devtools`
require('electron').app.on('ready', () => {
let installExtension = require('electron-devtools-installer')
installExtension.default(installExtension.VUEJS_DEVTOOLS)
.then(() => {})
.catch(err => {
console.log('Unable to install `vue-devtools`: \n', err)
})
})
// Require `main` process to boot app
require('./index')
\ No newline at end of file
import { app, BrowserWindow,BrowserView, ipcMain,Menu,shell,screen,remote} from 'electron'
const isMac = process.platform === 'darwin'
let FlexRAN = false
const template = [
// { role: 'appMenu' }
...(isMac ? [{
label: app.name,
submenu: [
{ role: 'about' },
{ type: 'separator' },
{ role: 'services' },
{ type: 'separator' },
{ role: 'hide' },
{ role: 'hideothers' },
{ role: 'unhide' },
{ type: 'separator' },
{ role: 'quit' }
]
}] : []),
// { role: 'fileMenu' }
{
label: '查看',
submenu: [
{
label: 'FlexRAN Drone® Mosaic5G ',
click() {
//shell.openExternal('http://192.168.1.36');
if(!FlexRAN){
openFlexran()
FlexRAN = !FlexRAN
}
else{
closeFlexran()
FlexRAN = !FlexRAN
}
},
},
]
},
{
label: '远程连接',
submenu: [
{
label: 'OAI核心网',
click() {
createNewWindow("http://10.25.20.227:2222/ssh/host/192.168.1.12?autologin=1&user=root&pass=199710")
},
},
{
label: 'OAI基站',
click() {
createNewWindow("http://10.25.20.227:2222/ssh/host/192.168.1.193?autologin=1&user=root&pass=199710")
},
},
{
label: 'OAI-SIM',
click() {
createNewWindow("http://10.25.20.227:2222/ssh/host/192.168.1.212?autologin=1&user=root&pass=199710")
},
},
]
},
{
role: 'help',
submenu: [
{
label: 'Learn More',
click: async () => {
const { shell } = require('electron')
await shell.openExternal('https://electronjs.org')
}
}
]
}
]
/**
* Set `__static` path to static files in production
* https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-static-assets.html
*/
if (process.env.NODE_ENV !== 'development') {
global.__static = require('path').join(__dirname, '/static').replace(/\\/g, '\\\\')
}
let mainWindow,view,child
let newWindows=[]
const winURL = process.env.NODE_ENV === 'development'
? `http://localhost:9080`
: `file://${__dirname}/index.html`
function createNewWindow(url){
let win
/**
* Initial window options
*/
win = new BrowserWindow({
minWidth:400,
minHeight:600,
width: 400,
height: 600,
useContentSize: true,
webPreferences: {
nodeIntegration: true,
webSecurity: false
}
})
win.loadURL(url)
newWindows.push(win)
}
function createWindow () {
Menu.setApplicationMenu( Menu.buildFromTemplate(template));
/**
* Initial window options
*/
mainWindow = new BrowserWindow({
minWidth:1920,
minHeight:1000,
width: screen.getPrimaryDisplay().workAreaSize.width,
height: screen.getPrimaryDisplay().workAreaSize.height,
useContentSize: true,
webPreferences: {
nodeIntegration: true,
webSecurity: false
}
})
mainWindow.loadURL(winURL)
//mainWindow.isMaximized() ? mainWindow.unmaximize() : mainWindow.maximize()
mainWindow.on('closed', () => {
mainWindow = null
})
}
function openFlexran(){
view = new BrowserView()
mainWindow.setBrowserView(view)
console.log(mainWindow.getContentBounds())
view.setBounds({ x: 1364, y: 0, width: 556, height: mainWindow.getContentBounds()["height"] })
view.webContents.loadURL("http://10.25.20.227:2222/ssh/host/192.168.1.210?autologin=1&user=root&pass=199710")
view.setAutoResize({width:true,height:true, horizontal:true,vertical:true})
// child = new BrowserWindow({
// minWidth:1920,
// minHeight:1000,
// width: screen.getPrimaryDisplay().workAreaSize.width,
// height: screen.getPrimaryDisplay().workAreaSize.height,
// useContentSize: true,
// webPreferences: {
// nodeIntegration: true,
// webSecurity: false
// }
// })
// view1 = new BrowserView()
// child.setBrowserView(view1)
// console.log(child.getContentBounds())
// view1.setBounds({ x: 1364, y: 0, width: 556, height: child.getContentBounds()["height"] })
// view1.webContents.loadURL("http://10.25.20.227:2222/ssh/host/192.168.1.210?autologin=1&user=root&pass=199710")
// view1.setAutoResize({width:true,height:true, horizontal:true,vertical:true})
// child.loadURL("http://192.168.1.36")
}
function closeFlexran(){
view.setBounds({ x: 0, y: 0, width: 0, height: 0 })
}
app.on('ready', createWindow)
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if (mainWindow === null) {
createWindow()
}
})
app.on('resize', (e, cmd) => {
view.setBounds({ x: screen.getPrimaryDisplay().workAreaSize.width/2, y: 0, width: screen.getPrimaryDisplay().workAreaSize.width/2, height: screen.getPrimaryDisplay().workAreaSize.height/2 })
console.log("aaa")
})
/**
* Auto Updater
*
* Uncomment the following code below and install `electron-updater` to
* support auto updating. Code Signing with a valid certificate is required.
* https://simulatedgreg.gitbooks.io/electron-vue/content/en/using-electron-builder.html#auto-updating
*/
/*
import { autoUpdater } from 'electron-updater'
autoUpdater.on('update-downloaded', () => {
autoUpdater.quitAndInstall()
})
app.on('ready', () => {
if (process.env.NODE_ENV === 'production') autoUpdater.checkForUpdates()
})
*/
<template>
<div id="app">
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'slice'
}
</script>
<style>
/* CSS */
</style>
<template>
<div id="first">
<header><img src="~@/assets/ustb-oai.com.png" alt="electron-vue" width="400px" ></header>
<div id="wrapper">
<main>
<div id="left" class="left-side">
<slice-information></slice-information>
</div>
<div class="right-side">
<base-station-info></base-station-info>
</div>
</main>
</div>
</div>
</template>
<script>
import SystemInformation from './LandingPage/SystemInformation'
import SliceInformation from './sliceInfos/SliceInformation'
import BaseStationInfo from './sliceInfos/BaseStationInfo'
import UeLists from './sliceInfos/UeLists'
import * as flexranAPI from "../../utils/flexranAPI"
import {ipcRenderer} from 'electron'
export default {
name: 'landing-page',
components: { SystemInformation ,'slice-information':SliceInformation,"ue-lists":UeLists,"base-station-info":BaseStationInfo},
mounted(){
},
methods: {
open (link) {
this.$electron.shell.openExternal(link)
},
openFlexran () {
ipcRenderer.send('openFlexran')
},
closeFlexran () {
ipcRenderer.send('closeFlexran')
}
}
}
</script>
<style>
@import url('https://fonts.googleapis.com/css?family=Source+Sans+Pro');
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body { font-family: 'Source Sans Pro', sans-serif; }
img {
filter:grayscale(70%);
}
header {
margin-top: 15px;
}
#wrapper {
background:
radial-gradient(
ellipse at top left,
rgba(255, 255, 255, 1) 40%,
rgba(229, 229, 229, .9) 100%
);
height: 100vh;
padding: 15px 20px;
width: 100vw;
}
#left {
padding-right:10px ;
}
main {
display: flex;
justify-content: space-between;
margin-right: 556px;
}
main > div { flex-basis: 50%; }
.left-side {
display: flex;
flex-direction: column;
}
#first {
}
.doc button {
font-size: .8em;
cursor: pointer;
outline: none;
padding: 0.75em 2em;
border-radius: 2em;
display: inline-block;
color: #fff;
background-color: #4fc08d;
transition: all 0.15s ease;
box-sizing: border-box;
border: 1px solid #4fc08d;
}
.doc button.alt {
color: #42b983;
background-color: transparent;
}
</style>
<template>
<div>
<div class="title">Information</div>
<div class="items">
<div class="item">
<div class="name">Path:</div>
<div class="value">{{ path }}</div>
</div>
<div class="item">
<div class="name">Route Name:</div>
<div class="value">{{ name }}</div>
</div>
<div class="item">
<div class="name">Vue.js:</div>
<div class="value">{{ vue }}</div>
</div>
<div class="item">
<div class="name">Electron:</div>
<div class="value">{{ electron }}</div>
</div>
<div class="item">
<div class="name">Node:</div>
<div class="value">{{ node }}</div>
</div>
<div class="item">
<div class="name">Platform:</div>
<div class="value">{{ platform }}</div>
</div>
</div>
</div>
</template>
<script>
export default {
data () {
return {
electron: process.versions.electron,
name: this.$route.name,
node: process.versions.node,
path: this.$route.path,
platform: require('os').platform(),
vue: require('vue/package.json').version
}
}
}
</script>
<style scoped>
.title {
color: #888;
font-size: 18px;
font-weight: initial;
letter-spacing: .25px;
margin-top: 10px;
}
.items { margin-top: 8px; }
.item {
display: flex;
margin-bottom: 6px;
}
.item .name {
color: #6a6a6a;
margin-right: 6px;
}
.item .value {
color: #35495e;
font-weight: bold;
}
</style>
function dataHandler (newData, oldData) {
if (oldData) {
let chart = this.$data._chart
// Get new and old DataSet Labels
let newDatasetLabels = newData.datasets.map((dataset) => {
return dataset.label
})
let oldDatasetLabels = oldData.datasets.map((dataset) => {
return dataset.label
})
// Stringify 'em for easier compare
const oldLabels = JSON.stringify(oldDatasetLabels)
const newLabels = JSON.stringify(newDatasetLabels)
// Check if Labels are equal and if dataset length is equal
if (newLabels === oldLabels && oldData.datasets.length === newData.datasets.length) {
newData.datasets.forEach((dataset, i) => {
// Get new and old dataset keys
const oldDatasetKeys = Object.keys(oldData.datasets[i])
const newDatasetKeys = Object.keys(dataset)
// Get keys that aren't present in the new data
const deletionKeys = oldDatasetKeys.filter((key) => {
return key !== '_meta' && newDatasetKeys.indexOf(key) === -1
})
// Remove outdated key-value pairs
deletionKeys.forEach((deletionKey) => {
delete chart.data.datasets[i][deletionKey]
})
// Update attributes individually to avoid re-rendering the entire chart
for (const attribute in dataset) {
if (dataset.hasOwnProperty(attribute)) {
chart.data.datasets[i][attribute] = dataset[attribute]
}
}
})
if (newData.hasOwnProperty('labels')) {
chart.data.labels = newData.labels
this.$emit('labels:update')
}
if (newData.hasOwnProperty('xLabels')) {
chart.data.xLabels = newData.xLabels
this.$emit('xlabels:update')
}
if (newData.hasOwnProperty('yLabels')) {
chart.data.yLabels = newData.yLabels
this.$emit('ylabels:update')
}
chart.update()
this.$emit('chart:update')
} else {
if (chart) {
chart.destroy()
this.$emit('chart:destroy')
}
this.renderChart(this.chartData, this.options)
this.$emit('chart:render')
}
} else {
if (this.$data._chart) {
this.$data._chart.destroy()
this.$emit('chart:destroy')
}
this.renderChart(this.chartData, this.options)
this.$emit('chart:render')
}
}
export const reactiveData = {
data () {
return {
chartData: null
}
},
watch: {
'chartData': dataHandler
}
}
export const reactiveProp = {
props: {
chartData: {
type: Object,
required: true,
default: () => {}
}
},
watch: {
'chartData': dataHandler
}
}
export default {
reactiveData,
reactiveProp
}
<template>
<div>
<el-card>
<el-table
:data="dataList"
border stripe>
<el-table-column type="index" label="UE"></el-table-column>
<el-table-column
prop="rnti"
label="RNTI"
width="100">
</el-table-column>
<el-table-column
prop="Mbs"
label="速度">
</el-table-column>
<el-table-column
label="切片" >
<template slot-scope="scope" >
<el-tag size="medium" effect="dark">
{{scope.row.label}}
</el-tag>
</template>
</el-table-column>
<el-table-column
prop="imsi"
label="IMSI">
</el-table-column>
</el-table>
</el-card>
</div>
</template>
<script>
import Vue from "vue";
import vueJsonTreeView from "vue-json-tree-view";
import * as flexranAPI from "../../../utils/flexranAPI"
export default {
data(){
return{
dataList:[],
}
},
created(){
this.getDataList()
},
methods:{
getDataList(){
this.timeInterval = setInterval(async () => {
let res =await flexranAPI.GET_MAC_STATS({})
this.dataList=res.mac_stats[0].ue_list
console.log(this.dataList)
}, 1000);
}
}
}
</script>
<style lang="less" scoped>
</style>
<template>
<div>
<el-card>
<el-table :data="dataList" border stripe>
<el-table-column prop="id" label="网络切片ID"></el-table-column>
<el-table-column prop="label" label="切片类型" width="100">
</el-table-column>
<el-table-column label="吞吐量(Mps)">
<template slot-scope="scope">
{{ scope.row.ddqn.thrpt }}
</template>
</el-table-column>
<el-table-column label="时延(ms)">
<template slot-scope="scope">
{{ scope.row.ddqn.delay }}
</template>
</el-table-column>
<el-table-column label="PRB(x2)">
<template slot-scope="scope">
{{ scope.row.ddqn.mrb }}
</template>
</el-table-column>
<el-table-column label="RB使用情况">
<template slot-scope="scope">
{{ scope.row.ddqn.arb }}
</template>
</el-table-column>
</el-table>
</el-card>
</div>
</template>
<script>
import Vue from "vue";
import vueJsonTreeView from "vue-json-tree-view";
import * as flexranAPI from "../../../utils/flexranAPI";
Vue.use(vueJsonTreeView);
export default {
data() {
return {
dataList:[],
};
},
mounted() {
this.timeInterval = setInterval(() => {
flexranAPI.GET_MAC_STATS().then((result) => {
this.dataList = result.eNB_config[0].eNB.cellConfig[0].sliceConfig.dl.slices;
});
}, 1000);
},
};
</script>
<style scoped>
.title {
color: #888;
font-size: 18px;
font-weight: initial;
letter-spacing: 0.25px;
margin-top: 10px;
}
.items {
margin-top: 8px;
}
.item {
display: flex;
margin-bottom: 6px;
}
.item .name {
color: #6a6a6a;
margin-right: 6px;
}
.item .value {
color: #35495e;
font-weight: bold;
}
</style>
<template>
<div>
<div v-for="(item1, index1) in ue_list" :key="index1" v-bind="item1">
<el-popover
placement="right"
trigger="hover"
>
<div v-html="pingInfo"></div>
<div
style="margin: 10px"
@mouseover="hover = item1.imsi"
@mouseleave="hover = false"
slot="reference"
>
<span>
<tree-view
:data="{
rnti: item1.rnti,
imsi: item1.imsi,
sliceID: item1.dlSliceId,
label: item1.label,
Rate: item1.Mbs,
}"
:options="{
maxDepth: 2,
rootObjectKey: 'UE ' + index1,
modifiable: false,
slice_num: 1,
}"
/>
</span>
</div>
</el-popover>
</div>
</div>
</template>
<script>
import Vue from "vue";
import vueJsonTreeView from "vue-json-tree-view";
import * as flexranAPI from "../../../utils/flexranAPI";
import Tooltip from "element-ui";
Vue.use(vueJsonTreeView);
Vue.use(Tooltip);
export default {
data() {
return {
hover: false,
ue_list: [],
slice_conf: [],
pingInfo: "PING 172.16.0.x (172.16.0.x) 56(84) bytes of data.<br/>64 bytes from 172.16.0.6: icmp_seq=1 ttl=64 time=39.5 ms<br/>64 bytes from 172.16.0.6: icmp_seq=2 ttl=64 time=39.1 ms<br/>64 bytes from 172.16.0.6: icmp_seq=3 ttl=64 time=28.7 ms<br/>64 bytes from 172.16.0.6: icmp_seq=4 ttl=64 time=45.6 ms<br/><br/>--- 172.16.0.6 ping statistics ---<br/>4 packets transmitted, 4 received, 0% packet loss, time 242ms<br/>rtt min/avg/max/mdev = 28.799/38.307/45.687/6.068 ms<br/>",
visible:false
};
},
mounted() {
this.timeInterval = setInterval(() => {
flexranAPI.GET_MAC_STATS().then((result) => {
try {
this.slice_conf =
result.eNB_config[0].eNB.cellConfig[0].sliceConfig.dl;
this.ue_list = result.mac_stats[0].ue_list;
for (let i = 0; i < this.ue_list.length; i++) {
let slice_type = this.slice_conf.slices.filter(
(_item) => _item.id === this.ue_list[i].dlSliceId
);
this.ue_list[i].label = slice_type[0].label;
}
} catch (error) {
console.log(error);
}
});
}, 1000);
},
methods: {
async getping(imsi) {
this.timer = setInterval(() => {
flexranAPI.SEND_PING({ imsi: imsi }).then((result) => {
this.pingInfo = result.output.split("\n").join("<br/>");
});
}, 1000);
},
},
watch: {
hover: {
handler(newValue, oldValue) {
console.log(this.hover);
if (this.hover !== false) {
this.getping(this.hover);
}
if (this.hover == false) {
clearInterval(this.timer);
}
},
deep: true,
},
},
};
</script>
<style scoped>
.title {
color: #888;
font-size: 18px;
font-weight: initial;
letter-spacing: 0.25px;
margin-top: 10px;
}
.items {
margin-top: 8px;
}
.item {
display: flex;
margin-bottom: 6px;
}
.item .name {
color: #6a6a6a;
margin-right: 6px;
}
.item .value {
color: #35495e;
font-weight: bold;
}
</style>
import Vue from 'vue'
import axios from 'axios'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import App from './App'
import router from './router'
import {Table} from 'element-ui'
if (!process.env.IS_WEB) Vue.use(require('vue-electron'))
Vue.http = Vue.prototype.$http = axios
Vue.config.productionTip = false
Vue.use(Table);
Vue.use(ElementUI);
/* eslint-disable no-new */
new Vue({
components: { App },
router,
template: '<App/>'
}).$mount('#app')
import Vue from 'vue'
import Router from 'vue-router'
import BaseStationInfo from '../components/sliceInfos/BaseStationInfo'
Vue.use(Router)
// 渲染进程接收主进程的传参
const { ipcRenderer } = require('electron');
ipcRenderer.on('href', (event, arg) => {
if (arg) {
router.push({ path: arg });
}
});
export default new Router({
routes: [
{
path: '/',
name: 'landing-page',
component: require('@/components/LandingPage').default
},
{
path: '*',
redirect: '/'
}
]
})
import { service, request } from './network_services'
/**
* @description 获取MAC_Stats
* @param {Object} data NONE
*/
export function GET_MAC_STATS (data = {}) {
// 接口请求
return request({
url: 'http://192.168.1.12:8110/api/stats',
method: 'get',
data
})
}
/**
* @description 获取IPV4
* @param {Object} data {"imsi":"208920100001105"}
*/
export function GET_IPV4_IMSI (data = {}) {
// 接口请求
return request({
url: 'http://192.168.1.12:8110/api/getip',
method: 'post',
data
})
}
/**
* @description 获取IPV4
* @param {Object} data {"host":"172.16.0.8"}
*/
export function SEND_PING (data = {}) {
// 接口请求
return request({
url: 'http://192.168.1.12:8110/api/pingapp',
method: 'post',
data
})
}
/**
* @description Enables the ElasticMon logging framework. Note that this might notably fail because the endpoint is not configured properly or because logging is already active.
* @param {Object} data NONE
*/
export function ENABLE_ELASTIC (data = {}) {
// 接口请求
return request({
url: '/elasticmon/enable',
method: 'post',
data
})
}
/**
* @description This API endpoint changes the cell configuration of the eNodeB in the underlying agent, effectively resulting in soft-restart of the base station (only L1/L2/L3 will be restarted). The parameters are specified as a JSON file with the format of the cellConfig as contained in the agent configuration, but only the parametrs dlBandwidth, ulBandwidth, dlFreq, ulFreq end eutraBand are accepted.
* @param {Object} data {"dlBandwidth": 50,"ulBandwidth": 50, "dlFreq": 2650,"ulFreq": 2530, "eutraBand": 7};
* @param {Object} ENB_ID Default -1 for eNB 0
*/
export function CHANGE_CELL_CONF (data = {}, ENB_ID) {
// 接口请求
return request({
url: '/conf/enb/' + ENB_ID,
method: 'post',
data
})
}
/**
* @description This API endpoint triggers the base station to connect to a new MME (and therefore, to a new core network). The list of PLMNs should be configured such that the PLMN(s) served by this new CN are present in the RAN (either through eNB configuration, or dynamically through the corresponding north-bound call). Note that a registration with a subset of the PLMNs (e.g., to hide a PLMN from the CN) is not possible.
* @param {Object} data {
"mme": [
{
"s1Ip": "192.168.12.4"
}
]
}
* @param {Object} ENB_ID Default -1 for eNB 0
*/
export function ADD_NEW_MME (data = {}, ENB_ID) {
// 接口请求
return request({
url: '/mme/enb/' + ENB_ID,
method: 'post',
data
})
}
/**
* @description This API saves a list of IMSIs or regular expressions matching on IMSIs in order to auto-associate those to a particular slice when they connect. It is checked that the base station has a slice with the given slice ID. Whenever a UE whose IMSI is known (this might not always be the case, go to flight mode and exit to get it reliably) is not in the slice it was associated to, it will automatically be associated to this slice. When associating a new list to a slice which already has an association list, that list will be removed.
* @param {Object} data [
"^20895"
]
* @param {Object} ENB_ID Default -1 for eNB 0
*/
export function AUTO_SLICE_ASSOC (data = {}, ENB_ID, SLICE_ID) {
// 接口请求
return request({
url: '/auto_ue_slice_assoc/enb/' + ENB_ID + ' /slice/' + SLICE_ID + '/dl',
method: 'post',
data
})
}
/**
* @description This API endpoint changes the association of a UE in an underlying agent, specified as a JSON file with the format of the ueConfig as contained in the agent configuration. It can be used to changed the association of UEs using their current RNTI or IMSI. In the request, a slice ID and RNTI or IMSI must be present. The stats call should always be used after triggering this endpoint and sufficient time to verify the actions have been taken.
* @param {Object} data {
"ueConfig": [
{
"imsi": 208940100001115,
"dlSliceId": 3,
"ulSliceId": 3
}
]
}
* @param {Object} ENB_ID Default -1 for eNB 0
*/
export function CHANGE_SLICE_ASSOC (data = {}, ENB_ID) {
// 接口请求
return request({
url: '/ue_slice_assoc/enb/' + ENB_ID,
method: 'post',
data
})
}
/**
* @description This API endpoint deletes slices as specified in the JSON data in the body specified as a JSON file with the format of the sliceConfig as contained in the cellConfig of a agent configuration for a given agent. A valid slice ID must present. Slice 0 can not be removed. To remove the slice algorithm, consider posting the None slice algorithm instead.
* @param {Object} data {
"dl": {
"slices": [
{
"id": 3,
}
]
}
}
* @param {Object} ENB_ID Default -1 for eNB 0
*/
export function DELETE_SLICE (data = {}, ENB_ID) {
// 接口请求
return request({
url: '/slice/enb/' + ENB_ID,
method: 'delete',
data
})
}
/**
* @description This API endpoint posts a new slice configuration to an underlying agent, specified as a JSON file with the format of the sliceConfig as contained in the cellConfig of an agent configuration (for a description of the parameters, see below), or the scheduler to use if no slicing algorithm is chosen (None). It can be used to create arbitrary slices with an arbitrary ID or to change slices by specifying an ID for an existing slice. In the request, a slice ID must be present, as well as the slice parameters. The label is optional, and if no scheduler is given, the scheduler that was active when enabling slicing will be used. The stats call should always be used after triggering this endpoint and sufficient time to verify the actions have been taken. Note that the scheduler (within dl/ul) and the slices parameters are mutually exclusive, since the first only applies for no slicing algorithm (None), whereas the latter only applies if a slicing algorithm has been chosen.This API call has changed as of July 2020. For a description of how the old parameters can be reproduced in the new call, see Deprecated Slice ConfigurationRemarks on the Static slicing algorithm: this algorithm does not provide any sharing. Note that posLow/posHigh are in terms of resource block groups (RBG) in DL and resource blocks (RB) in UL. Furthermore, it is not checked that the channel bandwidth can actually accommodate this slice (posLow=100 and posHigh=110 are a valid entry, but they will never work, since LTE has a maximum bandwidth of 100RBs). Please refer to the stats call to check the amount of resource blocks as well as the resource block group size which will tell the applicable RB/RBG settings. Please also note that OAI reserves the first and last 1, 2, or 3 RBs (for bandwidths 25, 50, or 100RBs, respectively) for PUCCH, meaning that these first/last RBs should be spared out/they won't be given to the slice. Also, the minimum RB size in UL is 3!
* @param {Object} data {"dl":{"algorithm":"SCN19","slices":[
{"id":0,"scn19":{"typeid":1,"type":"static","posLow":0,"posHigh":8}},
{"id":2,"scn19":{"typeid":2,"type":"dynamic","kpsRequired":100,"kpsReference":1200}},
{"id":3,"scn19":{"typeid":2,"type":"dynamic","kpsRequired":1200,"kpsReference":1200}},
{"id":4,"scn19":{"typeid":2,"type":"dynamic","kpsRequired":500,"kpsReference":1200}}]}}
* @param {Object} ENB_ID Default -1 for eNB 0
*/
export function ADD_SLICE (data = {}, ENB_ID) {
// 接口请求
return request({
url: '/slice/enb/' + ENB_ID,
method: 'post',
data
})
}
\ No newline at end of file
import axios from 'axios'
import qs from 'qs'
import { get, isEmpty } from 'lodash'
axios.defaults.adapter = require('axios/lib/adapters/http');
function handleError (error) {
// 添加到日志
// 打印到控制台
// console.log(error)
}
/**
* @description 创建请求实例
*/
function createService () {
// 创建一个 axios 实例
const service = axios.create()
// 请求拦截
service.interceptors.request.use(
config => config,
error => {
// 发送失败
console.log(error)
return Promise.reject(error)
}
)
// 响应拦截
service.interceptors.response.use(
response => {
// http 状态码 200 情况
// 根据 前后端约定的 response.data.code 判断接口是否请求成功
// 例如 接口返回数据为
// {
// code: 0,
// msg: 'success',
// data: {
// list: [],
// count: 0
// }
// }
// 此时
// response.data.code :
// 0
// response.data.msg :
// 'success'
// response.data.data : (在调用接口)
// {
// list: [],
// count: 0
// }
// 默认约定 code 为 0 时代表成功
// 你也可以不使用这种方法,改为在下面的 http 错误拦截器里做处理
// 没有 code 视为非项目接口不作处理
if (response.data.code === undefined) {
return response.data
}
// 有 code 判断为项目接口请求
switch (response.data.code) {
// 返回响应内容
case 0: return response.data.data
// 例如在 code 401 情况下退回到登录页面
case 401: throw new Error('请重新登录')
// 根据需要添加其它判断
default: throw new Error(`${response.data.msg}: ${response.config.url}`)
}
},
error => {
const status = get(error, 'response.status')
switch (status) {
case 400: error.message = '请求错误'; break
case 401: error.message = '未授权,请登录'; break
case 403: error.message = '拒绝访问'; break
case 404: error.message = `请求地址出错: ${error.response.config.url}`; break
case 408: error.message = '请求超时'; break
case 500: error.message = '服务器内部错误'; break
case 501: error.message = '服务未实现'; break
case 502: error.message = '网关错误'; break
case 503: error.message = '服务不可用'; break
case 504: error.message = '网关超时'; break
case 505: error.message = 'HTTP版本不受支持'; break
case 204: error.message = 'Content-Type'; break
default: break
}
handleError(error)
//throw error
}
)
return service
}
function stringify (data) {
return qs.stringify(data, { allowDots: true, encode: false })
}
/**
* @description 创建请求方法
* @param {Object} service axios 实例
*/
function createRequest (service) {
return function (config) {
const token = ''
const configDefault = {
headers: {
'Content-Type': get(config, 'headers.Content-Type', 'application/json')
},
timeout: 5000,
baseURL: process.env.VUE_APP_API,
data: {}
}
const option = Object.assign(configDefault, config)
// 处理 get 请求的参数
// 请根据实际需要修改
if (!isEmpty(option.params)) {
option.url = option.url + '?' + stringify(option.params)
option.params = {}
}
// 当需要以 form 形式发送时 处理发送的数据
// 请根据实际需要修改
if (!isEmpty(option.data) && option.headers['Content-Type'] === 'application/x-www-form-urlencoded') {
option.data = stringify(option.data)
}
return service(option)
}
}
// 用于真实网络请求的实例和请求方法
export const service = createService()
export const request = createRequest(service)
\ No newline at end of file
This diff is collapsed.
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment