Skip to content

Commit

Permalink
Init
Browse files Browse the repository at this point in the history
  • Loading branch information
identw committed Aug 20, 2020
0 parents commit 43f9420
Show file tree
Hide file tree
Showing 11 changed files with 1,208 additions and 0 deletions.
29 changes: 29 additions & 0 deletions .github/workflows/build.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
name: build
on:
push:
branches:
- master
jobs:
build:
name: build golang
runs-on: ubuntu-20.04
steps:
- name: clone
uses: actions/checkout@v2
- name: install depends
run: |
go mod download
mkdir artifacts
- name: build
run: |
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o artifacts/sms-mode-reader-amd64 .
CGO_ENABLED=0 GOOS=linux GOARCH=386 go build -o artifacts/sms-mode-reader-386 .
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -o artifacts/sms-mode-reader-arm8 .
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=7 go build -o artifacts/sms-mode-reader-arm7 .
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=6 go build -o artifacts/sms-mode-reader-arm6 .
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=5 go build -o artifacts/sms-mode-reader-arm5 .
- name: Save artifacts
uses: actions/upload-artifact@v2
with:
name: sms-mode-reader
path: artifacts/*
94 changes: 94 additions & 0 deletions .github/workflows/release.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
name: release
on:
push:
tags:
- 'v*'
jobs:
build_and_release:
name: build_and_release
runs-on: ubuntu-20.04
steps:
- name: Create Release
id: create_release
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tag_name: ${{ github.ref }}
release_name: Release ${{ github.ref }}
draft: false
prerelease: false
- name: clone
uses: actions/checkout@v2
- name: install depends
run: |
go mod download
mkdir artifacts
- name: build
run: |
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o artifacts/sms-modem-reader-amd64 .
CGO_ENABLED=0 GOOS=linux GOARCH=386 go build -o artifacts/sms-modem-reader-386 .
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -o artifacts/sms-modem-reader-arm64 .
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=7 go build -o artifacts/sms-modem-reader-arm7 .
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=6 go build -o artifacts/sms-modem-reader-arm6 .
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=5 go build -o artifacts/sms-modem-reader-arm5 .
- name: Upload relerase amd64
id: upload-release-asset-amd64
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: ./artifacts/sms-modem-reader-amd64
asset_name: sms-modem-reader-amd64
asset_content_type: application/x-elf
- name: Upload relerase 386
id: upload-release-asset-386
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: ./artifacts/sms-modem-reader-386
asset_name: sms-modem-reader-386
asset_content_type: application/x-elf
- name: Upload relerase arm64
id: upload-release-asset-arm64
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: ./artifacts/sms-modem-reader-arm64
asset_name: sms-modem-reader-arm64
asset_content_type: application/x-elf
- name: Upload relerase arm7
id: upload-release-asset-arm7
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: ./artifacts/sms-modem-reader-arm7
asset_name: sms-modem-reader-arm7
asset_content_type: application/x-elf
- name: Upload relerase arm6
id: upload-release-asset-arm6
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: ./artifacts/sms-modem-reader-arm6
asset_name: sms-modem-reader-arm6
asset_content_type: application/x-elf
- name: Upload relerase arm5
id: upload-release-asset-arm5
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: ./artifacts/sms-modem-reader-arm5
asset_name: sms-modem-reader-arm5
asset_content_type: application/x-elf
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/main
/sms-modem-reader
56 changes: 56 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# Sms modem reader
The application reads sms from the gsm huawei modem (tested on models: E173, E352b) using [AT commands](http://download-c.huawei.com/download/downloadCenter?downloadId=51047&version=120450&siteCode) and sends these sms to the specified webhook using the post request. It also periodically checks the balance and exports it to metrics on uri /metrics in prometheus format.

## Setup

## webhook
You can specify url using the environment variable `WEBHOOK_URL`. For example: `export WEBHOOK_URL=https://example.com/sms`

Requst type: `POST`
Content-type: `application/json`
Body: `{"message": "text sms"}`

## Check balance
The balance is checked using a USSD request, which can be specified through the environment variable `BALANCE_USSD`. The balance is read using a regular expression, which is specified using the environment variable `BALANCE_REGEXP` in the [golang regex syntax](https://golang.org/pkg/regexp/syntax/). The application tries to calculate the balance both from the response to the USSD request and from incoming sms. In regular expression, the first captured group will be considered the balance.

## Environment variables

* `METRIC_PORT` (default: "40111") - port for prometheus metrics
* `METRIC_LISTEN_IP` (default: "0.0.0.0") - ip address of the interface for prometheus metrics
* `BALANCE_USSD` (default: "*122#") - USSD request to check balance
* `BALANCE_REGEXP` (default: "^.*составляет ([0-9]+(\.[0-9]+)?) руб.*$") - regex to pull the current balance out of the message. The current balance will be the first captured group in the regular expression (that is, the first parentheses). The syntax used is https://golang.org/pkg/regexp/syntax/
* `INTERVAL_READ_SMS` (default: "10") - interval in seconds with which you want to check incoming sms
* `INTERVAL_CHECK_BALANCE` (default: "86400") - interval in seconds with which to check the current balance
* `WEBHOOK_URL` (default: "http://127.0.0.1/webhook") - url where sms messages will be sent
* `SERIAL_FILE` (default: "/dev/ttyUSB0") - serial port file
* `SERIAL_BAUD` (default: "9600") - serial port baud rate (bps)
* `SERIAL_STOP_BITS` (default: "1") - the number of stop bits. Possible values: "1", "2", "15"
* `SERIAL_PARITY` (default: "N") - indicates the presence and type of parity bit. Possible values: "N", "O", "E", "M", "S"
* `SERIAL_SIZE` (default: "8") - the number of bits that frame start and stop bits

## prometheus метрики
Metrics can be obtained at url: http://METRIC_LISTEN_IP:METRIC_PORT/metrics


| metric | type | description |
|--------------------------------|-------|------------------------------------------------------------------------------|
| sms_reader_balance | guage | current balance |
| sms_reader_balance_last_check | guage | unix timestamp last check |
| sms_reader_sms_last_status | guage | sms last read status, 0 - successful, 1 - failed to read |
| sms_reader_webhook_last_status | guage | status of the last submission to webhook, 0 - successful, 1 - failed to send |

Example metrics:
```
# HELP sms_reader_balance current balance
# TYPE sms_reader_balance gauge
sms_reader_balance 350.36
# HELP sms_reader_balance_last_check unix timestamp last check balance
# TYPE sms_reader_balance_last_check gauge
sms_reader_balance_last_check 1.597837689e+09
# HELP sms_reader_sms_last_status read sms correct, 1 = fail, 0 = success
# TYPE sms_reader_sms_last_status gauge
sms_reader_sms_last_status 0
# HELP sms_reader_webhook_last_status send webhook last send fail, 1 = fail, 0 = success
# TYPE sms_reader_webhook_last_status gauge
sms_reader_webhook_last_status 1
```
55 changes: 55 additions & 0 deletions README_ru.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# Sms modem reader
Приложение считывает sms из gsm модема huawei (протестировано на моделях: E173, E352b) c помощью [AT комманд](http://download-c.huawei.com/download/downloadCenter?downloadId=51047&version=120450&siteCode) и отправляет эти sms на указанный webhook c помощью post запроса. А также периодически проверяет баланс и экспортирует его в метрики на uri /metrics в формате prometheus.

## Установка

## webhook
Указать url можно с помощью переменной среды `WEBHOOK_URL`. Например: `export WEBHOOK_URL=https://example.com/sms`

Тип запроса: `POST`
Content-type: `application/json`
Тело: `{"message": "text sms"}`

## Проверка баланса
Баланс проверяется с помощью USSD запроса, который можно указать через переменную среды `BALANCE_USSD`. Считывается баланс с помощью регулярного выражения, которое указывается с помощью переменной среды `BALANCE_REGEXP` в синтаксисе [golang](https://golang.org/pkg/regexp/syntax/). Приложение пытается считать баланс как с ответа на USSD запрос, так и в приходящих sms. В регулярном выражении, балансом будет считаться первая захваченная группа.

## Переменные среды

* `METRIC_PORT` (умолчание: "40111") - порт для prometheus метрик
* `METRIC_LISTEN_IP` (умолчание: "0.0.0.0") - ip адрес интерфейса для prometheus метрик
* `BALANCE_USSD` (умолчание: "*122#") - ussd запрос для проверки баланса
* `BALANCE_REGEXP` (умолчание: "^.*составляет ([0-9]+(\.[0-9]+)?) руб.*$") - регулярное выражение, чтобы вытащить из сообщения текущий баланс. Текущим балансом будет считаться первая захваченная группа в регулярном выражении (то есть первые скобки). Используемый синтаксис - https://golang.org/pkg/regexp/syntax/
* `INTERVAL_READ_SMS` (умолчание: "10") - интервал в секундах, с которым требуется проверять приходящие sms
* `INTERVAL_CHECK_BALANCE` (умолчание: "86400") - интервал в секундах, с которым следует проверять текущий баланс
* `WEBHOOK_URL` (умолчание: "http://127.0.0.1/webhook") - url куда будут отправлены sms сообщения
* `SERIAL_FILE` (умолчание: "/dev/ttyUSB0") - файл последовательного порта
* `SERIAL_BAUD` (умолчание: "9600") - скорость передачи данных последовательного порта (bps)
* `SERIAL_STOP_BITS` (умолчание: "1") - количество стоповых битов. Возможные значения: "1", "2", "15"
* `SERIAL_PARITY` (умолчание: "N") - обозначение наличия и типа бита четности. Возможные значения: "N", "O", "E", "M", "S"
* `SERIAL_SIZE` (умолчание: "8") - количество битов, которые обрамляют стартовый и стоповый биты

## prometheus метрики
Метрики можно получить по url: http://METRIC_LISTEN_IP:METRIC_PORT/metrics.

| метрика | тип | описание |
|--------------------------------|-------|-----------------------------------------------------------------------------|
| sms_reader_balance | guage | текущий баланс |
| sms_reader_balance_last_check | guage | unix timestamp последней проверки |
| sms_reader_sms_last_status | guage | статус последнего чтения sms, 0 - успешно, 1 - не удалось прочитать |
| sms_reader_webhook_last_status | guage | статус последней отправки на webhook, 0 - успешно, 1 - не удалось отправить |

Пример метрик:
```
# HELP sms_reader_balance current balance
# TYPE sms_reader_balance gauge
sms_reader_balance 350.36
# HELP sms_reader_balance_last_check unix timestamp last check balance
# TYPE sms_reader_balance_last_check gauge
sms_reader_balance_last_check 1.597837689e+09
# HELP sms_reader_sms_last_status read sms correct, 1 = fail, 0 = success
# TYPE sms_reader_sms_last_status gauge
sms_reader_sms_last_status 0
# HELP sms_reader_webhook_last_status send webhook last send fail, 1 = fail, 0 = success
# TYPE sms_reader_webhook_last_status gauge
sms_reader_webhook_last_status 1
```
8 changes: 8 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module github.com/identw/sms-modem-reader

go 1.13

require (
github.com/prometheus/client_golang v1.7.1
github.com/tarm/serial v0.0.0-20180830185346-98f6abe2eb07
)
Loading

0 comments on commit 43f9420

Please sign in to comment.