Skip to content

Commit

Permalink
basic client
Browse files Browse the repository at this point in the history
  • Loading branch information
medilies committed Oct 16, 2022
1 parent cbecade commit 6c837c6
Show file tree
Hide file tree
Showing 13 changed files with 2,191 additions and 2 deletions.
18 changes: 18 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
root = true

[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 4
trim_trailing_whitespace = true

[*.md]
trim_trailing_whitespace = false

[*.{yml,yaml}]
indent_size = 2

[docker-compose.yml]
indent_size = 4
10 changes: 10 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
MQTT_PROTOCOL="mqtt"
MQTT_HOST="localhost"
MQTT_PORT=1883
MQTT_USERNAME="medilies"
MQTT_PASSWORD="mqttjs"
MQTT_CLIENTID="medilies"

MQTT_CLEAN=false
MQTT_KEEPALIVE=300
MQTT_RECONNECTPERIOD=5000
130 changes: 130 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# Snowpack dependency directory (https://snowpack.dev/)
web_modules/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional stylelint cache
.stylelintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local

# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache

# Next.js build output
.next
out

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# vuepress v2.x temp and cache directory
.temp
.cache

# Docusaurus cache and generated files
.docusaurus

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

# Stores VSCode versions used for testing VSCode extensions
.vscode-test

# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
27 changes: 25 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,36 @@
# MQTT.JS client example

- Copy `.env.example` to `.env` and edit it.
## Setup

```bash
git clone https://github.com/medilies/mqttjs-client-example
```

```bash
cd mqttjs-client-example
```

```bash
npm install
```

```bash
cp .env.example .env
```

- Edit `.env`.
- Edit `sub_topics.json`.

## Usage

Start a broker. For example:

```bash
mosquitto -p 1883 -v
```

Start the client:

```bash
npm start
```
# mqttjs-client-example
20 changes: 20 additions & 0 deletions config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import * as fs from "fs";
import * as dotenv from "dotenv";

dotenv.config();

const mqtt = {
protocol: process.env.MQTT_PROTOCOL || "mqtt", // "mqtts"
host: process.env.MQTT_HOST || "localhost",
port: process.env.MQTT_PORT || 1884, // 8883
username: process.env.MQTT_USERNAME || "medilies",
password: process.env.MQTT_PASSWORD || "password",
clientId: process.env.MQTT_CLIENTID || "medilies",
clean: process.env.MQTT_CLEAN || false,
keepalive: process.env.MQTT_KEEPALIVE || 300,
reconnectPeriod: process.env.MQTT_RECONNECTPERIOD || 5 * 1000,
// ca: fs.readFileSync("path"),
// rejectUnauthorized: false,
};

export { mqtt };
36 changes: 36 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import * as config from "./config.js";

import * as fs from "fs";
import * as mqtt from "mqtt";

import * as mqttUtils from "./mqtt/utils.js";
import * as mqttLogger from "./mqtt/logger.js";

const subTopics = JSON.parse(fs.readFileSync("./sub_topics.json"));

const client = mqtt.connect(mqttUtils.formatConnectionOpts(config.mqtt));

console.log(client.options);

client.on("connect", () => {
mqttLogger.connect();

client.subscribe(subTopics, (err, grant) => {
if (err) mqttLogger.subscriptionError(err);
mqttLogger.subscribed(grant);
});
});

client.on("message", function (topic, message) {
// message is Buffer
console.log(message.toString());
// * most of logic is here when subscribing ...
});

// client.on("packetsend", mqttLogger.packetsend);
// client.on("packetreceive", mqttLogger.packetreceive);
client.on("reconnect", mqttLogger.reconnect);
client.on("close", mqttLogger.close);
client.on("offline", mqttLogger.offline);
client.on("end", mqttLogger.end);
client.on("error", mqttLogger.error);
75 changes: 75 additions & 0 deletions mqtt/logger.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import chalk from "chalk";

const log = console.log;

function dateStr() {
return new Date().toISOString() + " : ";
}

// ====================================================

const connect = () => {
log(dateStr() + chalk.bgGreen.bold("CONNECTED!"));
};

const reconnect = () => {
log(dateStr() + chalk.blueBright("RECONNECTING!"));
};

const close = () => {
log(dateStr() + chalk.bgGray("CLOSED!"));
};

const disconnect = () => {
log(dateStr() + chalk.bgGray("DISCONNECTED!"));
};

const offline = () => {
log(dateStr() + chalk.bgRed.bold("OFFLINE!"));
};

const error = (err) => {
console.error(dateStr() + chalk.yellow("ERROR!"));
// TODO: format err content
console.error(err);
};

const end = () => {
// ? throw
log(dateStr() + chalk.black.bgWhite("ENDED!"));
};

const packetsend = (packet) => {
log(dateStr() + chalk.gray("sent:"));
log(packet);
};

const packetreceive = (packet) => {
log(dateStr() + chalk.gray("recieved:"));
log(packet);
};

const subscribed = (topics) => {
log(dateStr() + chalk.bgBlue("SUBSCRIBED!"));
log(topics);
};

const subscriptionError = (data) => {
// ? throw
console.warn(dateStr() + chalk.bgYellow("SUBSCRIBE ERROR!"));
if (data) console.warn(data);
};

export {
connect,
reconnect,
close,
disconnect,
offline,
error,
end,
packetsend,
packetreceive,
subscribed,
subscriptionError,
};
15 changes: 15 additions & 0 deletions mqtt/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const formatConnectionOpts = (obj) => {
return {
protocol: obj.protocol,
host: obj.host,
port: obj.port,
username: obj.username,
password: obj.password,
clientId: obj.clientId,
clean: obj.clean.toLowerCase() === "true",
keepalive: parseInt(obj.keepalive),
reconnectPeriod: parseInt(obj.reconnectPeriod),
};
};

export { formatConnectionOpts };
Loading

0 comments on commit 6c837c6

Please sign in to comment.