# ts-b16-roller **Repository Path**: runzx/ts-b16-roller ## Basic Information - **Project Name**: ts-b16-roller - **Description**: No description available - **Primary Language**: Unknown - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2024-08-21 - **Last Updated**: 2024-08-21 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README ## ts-b16-roller 使用TypeScript开发的后端版通用控制器程序。原来的卷膜、拉幕、风机等单独由不同的控制器实现,当前客户需要一个柜子解决这些所有设备的控制,原始做法将导致柜子内要增加很多控制器。 1、一个控制器实现卷膜、拉幕、风机、照明等设备的控制 2、DO可通过配置文件自由配置 3、前端控制页面及接口兼容现有易种OS 4、控制器可实现tcp&loRa&RS485兼容控制 5、独立的设备配置页面,可执行入网设备查询&设备绑定 开发协议:[https://alidocs.dingtalk.com/i/nodes/m0Xw6OYE4D7VLOpE0qoRWRq13rbjgPM5# 「后端版通用控制器开发」](https://alidocs.dingtalk.com/i/nodes/m0Xw6OYE4D7VLOpE0qoRWRq13rbjgPM5) # Table of contents: - [Pre-reqs](#pre-reqs) - [Getting started](#getting-started) - [Deploying the app](#deploying-the-app) - [Pre-reqs](#Prerequisites) - [TypeScript + Node](#typescript--node) - [Getting TypeScript](#getting-typescript) - [Project Structure](#project-structure) - [Building the project](#building-the-project) - [Type Definition (`.d.ts`) Files](#type-definition-dts-files) - [Debugging](#debugging) - [Testing](#testing) - [ESLint](#eslint) - [Dependencies](#dependencies) - [`dependencies`](#dependencies) - [`devDependencies`](#devdependencies) # Pre-reqs To build and run this app locally you will need a few things: - Install [Node.js V10.24.1](https://nodejs.org/dist/latest-v10.x/) && npm install pm2 global ```shell eg. Raspberry Pi install $ wget https://nodejs.org/dist/latest-v10.x/node-v10.24.1-linux-armv7l.tar.xz $ tar -xvf node-v10.24.1-linux-armv7l.tar.xz $ sudo mv node-v10.24.1-linux-armv7l /usr/local/ $ sudo ln /usr/local/node-v10.24.1-linux-armv7l/bin/node /usr/local/bin/node $ sudo ln -s /usr/local/node-v10.24.1-linux-armv7l/bin/npm /usr/local/bin/npm $ sudo npm install pm2 -g ``` - Install [mariadb](https://mariadb.com/) OR install [Mysql](https://www.mysql.com/) AND [Redis-Server](https://redis.io/) nginx etc. ```shell $ sudo apt-get -y install git expect build-essential mariadb-server-10.0 redis-server i2c-tools python2.7 nginx ``` - Install [VS Code](https://code.visualstudio.com/) # Getting started - Clone the repository ``` git clone --depth=1 git@gitee.com:sharpqian/ts-b16-roller.git ``` - Install dependencies ``` cd npm install ``` - Configure your MySQL server update passwd ```bash # 1、ubuntu获取原始密码,Raspberry Pi使用root用户无需密码可登录 $ sudo cat /etc/mysql/debian.cnf $ mysql -u debian-sys-maint -p #这条指令的密码输入是输入第一条指令获得的信息中的 password得来 # 2、修改密码 #MYSQL8 USED use mysql; ALTER USER 'root'@'localhost' identified by 'XXXXXXXXXXXXXX'; #MYSQL5 USED update mysql.user set authentication_string=password('XXXXXXXXXXXXXX') where user='root' and Host ='localhost'; update user set plugin="mysql_native_password"; flush privileges; quit; #3、导入测试数据库(生产测试服务器) $ myql -u root -p #创建数据库并退出 create database mydb; quit; #导入测试数据库 $ mysql -u root -p mydb `npm: start` to run `npm start` for you. > **Note on editors!** - TypeScript has great support in [every editor](http://www.typescriptlang.org/index.html#download-links), but this project has been pre-configured for use with [VS Code](https://code.visualstudio.com/). Throughout the README We will try to call out specific places where VS Code really shines or where this project has been set up to take advantage of specific features. # Deploying the app There are many ways to deploy a Node app, and in general, nothing about the deployment process changes because you're using TypeScript. In this section, I'll walk you through how to deploy this app to Azure App Service using the extensions available in VS Code because I think it is the easiest and fastest way to get started, as well as the most friendly workflow from a developer's perspective. ## Prerequisites - ### Troubleshooting failed deployments Deployment can fail for various reasons, if you get stuck with a page that says *Service Unavailable* or some other error, [open an issue](https://gitee.com/sharpqian/ts-b16-roller/issues) and I'll try to help you resolve the problems. # TypeScript + Node In the next few sections I will call out everything that changes when adding TypeScript to an Express project. Note that all of this has already been set up for this project, but feel free to use this as a reference for converting other Node.js projects to TypeScript. ## Getting TypeScript TypeScript itself is simple to add to any project with `npm`. ``` npm install -D typescript ``` If you're using VS Code then you're good to go! VS Code will detect and use the TypeScript version you have installed in your `node_modules` folder. For other editors, make sure you have the corresponding [TypeScript plugin](http://www.typescriptlang.org/index.html#download-links). ## Project Structure The most obvious difference in a TypeScript + Node project is the folder structure. In a TypeScript project, it's best to have separate _source_ and _distributable_ files. TypeScript (`.ts`) files live in your `src` folder and after compilation are output as JavaScript (`.js`) in the `dist` folder. The `test` and `views` folders remain top level as expected. The full folder structure of this app is explained below: > **Note!** Make sure you have already built the app using `npm run build` | Name | Description | | ------------------------ | --------------------------------------------------------------------------------------------- | | **.vscode** | Contains VS Code specific settings | | **.github** | Contains GitHub settings and configurations, including the GitHub Actions workflows | | **dist** | Contains the distributable (or output) from your TypeScript build. This is the code you ship | | **node_modules** | Contains all your npm dependencies | | **src** | Contains your source code that will be compiled to the dist dir | | **src/device** | 包含了设备相关的控制接口 | | **src/doc** | 本项目相关的一些文档 | | **src/func** | 与前端交互相关的文件以及与数据库CURD接口 | | **src/lib** | 用到的库文件 | | **src/public/modbus** | MODBUS RTU库 | | **src**/index.ts | 程序入口文件 | | **test** | 测试文件夹 | | .mydb.sql | 测试使用的数据库 | | .settings.yaml | 本项目的配置文件信息 | | .copyStaticAssets.ts | Build script that copies settings.yanl libs to the dist folder | | package.json | File that contains npm dependencies as well as [build scripts](#what-if-a-library-isnt-on-definitelytyped) | | tsconfig.json | Config settings for compiling server code written in TypeScript | | tsconfig.tests.json | Config settings for compiling tests written in TypeScript | | .eslintrc | Config settings for ESLint code style checking | | .eslintignore | Config settings for paths to exclude from linting | ## Building the project It is rare for JavaScript projects not to have some kind of build pipeline these days, however Node projects typically have the least amount of build configuration. Because of this I've tried to keep the build as simple as possible. If you're concerned about compile time, the main watch task takes ~2s to refresh. ### Configuring TypeScript compilation TypeScript uses the file `tsconfig.json` to adjust project compile options. Let's dissect this project's `tsconfig.json`, starting with the `compilerOptions` which details how your project is compiled. ```json "compilerOptions": { "module": "commonjs", "esModuleInterop": true, "target": "es6", "noImplicitAny": true, "moduleResolution": "node", "sourceMap": true, "outDir": "dist", "baseUrl": ".", "paths": { "*": [ "node_modules/*", "src/types/*" ] } }, ``` | `compilerOptions` | Description | | ---------------------------------- | ------------------------------------------------------------------------------------------------------ | | `"module": "commonjs"` | The **output** module type (in your `.js` files). Node uses commonjs, so that is what we use | | `"esModuleInterop": true,` | Allows usage of an alternate module import syntax: `import foo from 'foo';` | | `"target": "es6"` | The output language level. Node supports ES6, so we can target that here | | `"noImplicitAny": true` | Enables a stricter setting which throws errors when something has a default `any` value | | `"moduleResolution": "node"` | TypeScript attempts to mimic Node's module resolution strategy. Read more [here](https://www.typescriptlang.org/docs/handbook/module-resolution.html#node) | | `"sourceMap": true` | We want source maps to be output along side our JavaScript. See the [debugging](#debugging) section | | `"outDir": "dist"` | Location to output `.js` files after compilation | | `"baseUrl": "."` | Part of configuring module resolution. See [path mapping section](#installing-dts-files-from-definitelytyped) | | `paths: {...}` | Part of configuring module resolution. See [path mapping section](#installing-dts-files-from-definitelytyped) | The rest of the file define the TypeScript project context. The project context is basically a set of options that determine which files are compiled when the compiler is invoked with a specific `tsconfig.json`. In this case, we use the following to define our project context: ```json "include": [ "src/**/*" ] ``` `include` takes an array of glob patterns of files to include in the compilation. This project is fairly simple and all of our .ts files are under the `src` folder. For more complex setups, you can include an `exclude` array of glob patterns that removes specific files from the set defined with `include`. There is also a `files` option which takes an array of individual file names which overrides both `include` and `exclude`. ### Running the build All the different build steps are orchestrated via [npm scripts](https://docs.npmjs.com/misc/scripts). Npm scripts basically allow us to call (and chain) terminal commands via npm. This is nice because most JavaScript tools have easy to use command line utilities allowing us to not need grunt or gulp to manage our builds. If you open `package.json`, you will see a `scripts` section with all the different scripts you can call. To call a script, simply run `npm run ` from the command line. You'll notice that npm scripts can call each other which makes it easy to compose complex builds out of simple individual build scripts. Below is a list of all the scripts this template has available: | Npm Script | Description | | ------------------------- | ------------------------------------------------------------------------------------------------- | | `build-ts` | Compiles all source `.ts` files to `.js` files in the `dist` folder | | `build` | Full build. Runs ALL build tasks (`build-sass`, `build-ts`, `lint`, `copy-static-assets`) code obfuscation | | `build-`code | Full build. Runs ALL build tasks (`build-sass`, `build-ts`, `lint`, `copy-static-assets`) no code obfuscation | | `copy-static-assets` | Calls script that copies JS libs, fonts, and images to dist directory | | `dev` | Develop debug mode for programmers | | `lint` | Runs ESLint on project files | | `serve` | Runs node on `dist/index.js` which is the apps entry point | | `start` | Does the same as 'npm run serve'. Can be invoked with `npm start` | | `test` | Runs tests using ts-node XX.ts | ## Type Definition (`.d.ts`) Files TypeScript uses `.d.ts` files to provide types for JavaScript libraries that were not written in TypeScript. This is great because once you have a `.d.ts` file, TypeScript can type check that library and provide you better help in your editor. The TypeScript community actively shares all the most up-to-date `.d.ts` files for popular libraries on a GitHub repository called [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types). Making sure that your `.d.ts` files are setup correctly is super important because once they're in place, you get an incredible amount of high quality type checking (and thus bug catching, IntelliSense, and other editor tools) for free. > **Note!** Because we're using `"noImplicitAny": true`, we are required to have a `.d.ts` file for **every** library we use. While you could set `noImplicitAny` to `false` to silence errors about missing `.d.ts` files, it is a best practice to have a `.d.ts` file for every library. (Even if the `.d.ts` file is [basically empty!](#writing-a-dts-file)) ### Installing `.d.ts` files from DefinitelyTyped For the most part, you'll find `.d.ts` files for the libraries you are using on DefinitelyTyped. These `.d.ts` files can be easily installed into your project by using the npm scope `@types`. For example, if we want the `.d.ts` file for jQuery, we can do so with `npm install --save-dev @types/jquery`. > **Note!** Be sure to add `--save-dev` (or `-D`) to your `npm install`. `.d.ts` files are project dependencies, but only used at compile time and thus should be dev dependencies. In this template, all the `.d.ts` files have already been added to `devDependencies` in `package.json`, so you will get everything you need after running your first `npm install`. Once `.d.ts` files have been installed using npm, you should see them in your `node_modules/@types` folder. The compiler will always look in this folder for `.d.ts` files when resolving JavaScript libraries. ### What if a library isn't on DefinitelyTyped? If you try to install a `.d.ts` file from `@types` and it isn't found, or you check DefinitelyTyped and cannot find a specific library, you will want to create your own `.d.ts file`. In the `src` folder of this project, you'll find the `types` folder which holds the `.d.ts` files that aren't on DefinitelyTyped (or weren't as of the time of this writing). #### Setting up TypeScript to look for `.d.ts` files in another folder The compiler knows to look in `node_modules/@types` by default, but to help the compiler find our own `.d.ts` files we have to configure path mapping in our `tsconfig.json`. Path mapping can get pretty confusing, but the basic idea is that the TypeScript compiler will look in specific places, in a specific order when resolving modules, and we have the ability to tell the compiler exactly how to do it. In the `tsconfig.json` for this project you'll see the following: ```json "baseUrl": ".", "paths": { "*": [ "node_modules/*", "src/types/*" ] } ``` This tells the TypeScript compiler that in addition to looking in `node_modules/@types` for every import (`*`) also look in our own `.d.ts` file location `` + `src/types/*`. So when we write something like: ```ts import * as flash from "express-flash"; ``` First the compiler will look for a `d.ts` file in `node_modules/@types` and then when it doesn't find one look in `src/types` and find our file `express-flash.d.ts`. #### Using `dts-gen` Unless you are familiar with `.d.ts` files, I strongly recommend trying to use the tool [dts-gen](https://github.com/Microsoft/dts-gen) first. The [README](https://github.com/Microsoft/dts-gen#dts-gen-a-typescript-definition-file-generator) does a great job explaining how to use the tool, and for most cases, you'll get an excellent scaffold of a `.d.ts` file to start with. In this project, `bcrypt-nodejs.d.ts`, `fbgraph.d.ts`, and `lusca.d.ts` were all generated using `dts-gen`. #### Writing a `.d.ts` file If generating a `.d.ts` using `dts-gen` isn't working, [you should tell me about it first](https://www.surveymonkey.com/r/LN2CV82), but then you can create your own `.d.ts` file. If you just want to silence the compiler for the time being, create a file called `.d.ts` in your `types` folder and then add this line of code: ```ts declare module ""; ``` If you want to invest some time into making a great `.d.ts` file that will give you great type checking and IntelliSense, the TypeScript website has great [docs on authoring `.d.ts` files](http://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html). #### Contributing to DefinitelyTyped The reason it's so easy to get great `.d.ts` files for most libraries is that developers like you contribute their work back to DefinitelyTyped. Contributing `.d.ts` files is a great way to get into the open source community if it's something you've never tried before, and as soon as your changes are accepted, every other developer in the world has access to your work. If you're interested in giving it a shot, check out the [guidance on DefinitelyTyped](https://github.com/definitelyTyped/DefinitelyTyped/#how-can-i-contribute). If you're not interested, [you should tell me why](https://www.surveymonkey.com/r/LN2CV82) so we can help make it easier in the future! ### Summary of `.d.ts` management In general if you stick to the following steps you should have minimal `.d.ts` issues; 1. After installing any npm package as a dependency or dev dependency, immediately try to install the `.d.ts` file via `@types`. 2. If the library has a `.d.ts` file on DefinitelyTyped, the installation will succeed, and you are done. If the install fails because the package doesn't exist, continue to step 3. 3. Make sure you project is [configured for supplying your own `d.ts` files](#setting-up-typescript-to-look-for-dts-files-in-another-folder) 4. Try to [generate a `.d.ts` file with dts-gen](#using-dts-gen). If it succeeds, you are done. If not, continue to step 5. 5. Create a file called `.d.ts` in your `types` folder. 6. Add the following code: ```ts declare module ""; ``` 7. At this point everything should compile with no errors, and you can either improve the types in the `.d.ts` file by following this [guide on authoring `.d.ts` files](http://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html) or continue with no types. 8. If you are still having issues, let me know by emailing me or pinging me on twitter, I will help you. ## Debugging Debugging TypeScript is exactly like debugging JavaScript with one caveat, you need source maps. ### Source maps Source maps allow you to drop break points in your TypeScript source code and have that break point be hit by the JavaScript that is being executed at runtime. > **Note!** - Source maps aren't specific to TypeScript. Anytime JavaScript is transformed (transpiled, compiled, optimized, minified, etc) you need source maps so that the code that is executed at runtime can be _mapped_ back to the source that generated it. The best part of source maps is when configured correctly, you don't even know they exist! So let's take a look at how we do that in this project. #### Configuring source maps First you need to make sure your `tsconfig.json` has source map generation enabled: ```json "compilerOptions" { "sourceMap": true } ``` With this option enabled, next to every `.js` file that the TypeScript compiler outputs there will be a `.map.js` file as well. This `.map.js` file provides the information necessary to map back to the source `.ts` file while debugging. > **Note!** - It is also possible to generate "inline" source maps using `"inlineSourceMap": true`. This is more common when writing client side code because some bundlers need inline source maps to preserve the mapping through the bundle. Because we are writing Node.js code, we don't have to worry about this. ### Using the debugger in VS Code Debugging is one of the places where VS Code really shines over other editors. Node.js debugging in VS Code is easy to set up and even easier to use. This project comes pre-configured with everything you need to get started. When you hit `F5` in VS Code, it looks for a top level `.vscode` folder with a `launch.json` file. You can debug in the following ways: * **Launch Program** - transpile typescript to javascript via npm build, then launch the app with the debugger attached on startup * **Attach by Process ID** - run the project in debug mode. This is mostly identical to the "Node.js: Attach by Process ID" template with one minor change. We added `"protocol": "inspector"` which tells VS Code that we're using the latest version of Node which uses a new debug protocol. * **Jest Current File** - have a Jest test file open and active in VSCode, then debug this specific file by setting break point. All tests are not run. * **Jest all** - run all tests, set a break point. In this file, you can tell VS Code exactly what you want to do: ```json [ { "name": "Launch Program", "type": "node", "program": "${workspaceFolder}/dist/server.js", "request": "launch", "preLaunchTask": "npm: build" }, { "type": "node", "request": "attach", "name": "Attach by Process ID", "processId": "${command:PickProcess}", "protocol": "inspector" }, { "type": "node", "request": "launch", "name": "Jest Current File", "program": "${workspaceFolder}/node_modules/.bin/jest", "args": [ "${fileBasenameNoExtension}", "--detectOpenHandles" ], "console": "integratedTerminal", "internalConsoleOptions": "neverOpen", "disableOptimisticBPs": true, "windows": { "program": "${workspaceFolder}/node_modules/jest/bin/jest", } }, { "type": "node", "request": "launch", "name": "Jest all", "runtimeExecutable": "npm", "runtimeArgs": [ "run-script", "test" ], "port": 9229, "skipFiles": [ "/**" ] }, ] ``` With this file in place, you can hit `F5` to attach a debugger. You will probably have multiple node processes running, so you need to find the one that shows `node dist/server.js`. Now just set your breakpoints and go! ## Testing For this project, I chose [Jest](https://facebook.github.io/jest/) as our test framework. While Mocha is probably more common, Mocha seems to be looking for a new maintainer and setting up TypeScript testing in Jest is wicked simple. ### Install the components To add TypeScript + Jest support, first install a few npm packages: ``` npm install -D jest ts-jest ``` `jest` is the testing framework itself, and `ts-jest` is just a simple function to make running TypeScript tests a little easier. ### Configure Jest Jest's configuration lives in `jest.config.js`, so let's open it up and add the following code: ```js module.exports = { globals: { 'ts-jest': { tsconfigFile: 'tsconfig.json' } }, moduleFileExtensions: [ 'ts', 'js' ], transform: { '^.+\\.(ts|tsx)$': './node_modules/ts-jest/preprocessor.js' }, testMatch: [ '**/test/**/*.test.(ts|js)' ], testEnvironment: 'node' }; ``` Basically we are telling Jest that we want it to consume all files that match the pattern `"**/test/**/*.test.(ts|js)"` (all `.test.ts`/`.test.js` files in the `test` folder), but we want to preprocess the `.ts` files first. This preprocess step is very flexible, but in our case, we just want to compile our TypeScript to JavaScript using our `tsconfig.json`. This all happens in memory when you run the tests, so there are no output `.js` test files for you to manage. ### Running tests Simply run `npm run test`. Note this will also generate a coverage report. ### Writing tests Writing tests for web apps has entire books dedicated to it and best practices are strongly influenced by personal style, so I'm deliberately avoiding discussing how or when to write tests in this guide. However, if prescriptive guidance on testing is something that you're interested in, [let me know](https://www.surveymonkey.com/r/LN2CV82), I'll do some homework and get back to you. ## ESLint ESLint is a code linter which mainly helps catch quickly minor code quality and style issues. ### ESLint rules Like most linters, ESLint has a wide set of configurable rules as well as support for custom rule sets. All rules are configured through `.eslintrc` configuration file. In this project, we are using a fairly basic set of rules with no additional custom rules. ### Running ESLint Like the rest of our build steps, we use npm scripts to invoke ESLint. To run ESLint you can call the main build script or just the ESLint task. ``` npm run build // runs full build including ESLint npm run lint // runs only ESLint ``` Notice that ESLint is not a part of the main watch task. If you are interested in seeing ESLint feedback as soon as possible, I strongly recommend the [VS Code ESLint extension](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint). ### VSCode Extensions To enhance your development experience while working in VSCode we also provide you a list of the suggested extensions for working with this project: ![Suggested Extensions In VSCode](https://user-images.githubusercontent.com/14539/34583539-6f290a30-f198-11e7-8804-30f40d418e20.png) - [VS Code ESLint extension](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint) - [Code Spell Checker](https://marketplace.visualstudio.com/items?itemName=streetsidesoftware.code-spell-checker) - [Azure Cosmos DB](https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-cosmosdb) - [Azure App Service](https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-azureappservice) # Dependencies Dependencies are managed through `package.json`. In that file you'll find two sections: ## `dependencies` | Package | Description | | ------------------------------- | --------------------------------------------------------------------- | | async | Utility library that provides asynchronous control flow. | | @serialport/parser-inter-byte-timeout | A transform stream that buffers data and emits it after not receiving any bytes for the specified amount of time or hitting a max buffer size | | crc | Module for calculating Cyclic Redundancy Check (CRC) for Node.js and the browser. | | ioredis | A robust, performance-focused and full-featured Redis client for Node.js. | | moment | Parse, validate, manipulate, and display dates | | mqtt | A library for the MQTT protocol | | sqlite3 | Asynchronous, non-blocking SQLite3 bindings | | yamljs | Standalone JavaScript YAML 1.2 Parser & Encoder. Works under node.js and all major browsers. Also brings command line YAML/JSON conversion tools. | | ts-node | TypeScript execution environment and REPL for node.js, with source map support | | mysql | A node.js driver for mysql. It is written in JavaScript, does not require compiling, and is 100% MIT licensed. | ## `devDependencies` | Package | Description | | ---------- | ------------------------------------------------------------ | | @types | Dependencies in this folder are `.d.ts` files used to provide types | | chai | Testing utility library that makes it easier to write tests | | cross-env | Run scripts that set and use environment variables across platforms | | jest | Testing library for JavaScript. | | sass | Allows to compile .scss files to .css | | nodemon | Utility that automatically restarts node process when it crashes | | mocha | simple, flexible, fun test framework | | ts-node | Enables directly running TS files. Used to run `copy-static-assets.ts` | | eslint | Linter for JavaScript and TypeScript files | | typescript | JavaScript compiler/type checker that boosts JavaScript productivity | To install or update these dependencies you can use `npm install` or `npm update`. ## License Copyright (c) KUNMING SHHOO Corporation. All rights reserved. Licensed under the [MIT](LICENSE) License.