Commit 165e5deb authored by VCNguen's avatar VCNguen
Browse files

Initial commit

parents
Pipeline #2502 failed with stages
in 4 minutes and 3 seconds
hostDB='127.0.0.1'
userDB='user1'
passDB='Trung@789'
dataDB='test'
TOKEN_TL='1184469265:AAGgnSA0T1z3_PLNWMLu9LpB1fu6dCeNjyY'
from config import *
# convert format time and status in the values from kamera
def convSec2HMS(secondVar):
# if int(secondVar) is int :
h = (int(float(secondVar) // 3600))
m = int(float(secondVar)) - h*3600
m = m // 60
s = int(float(secondVar)) - h*3600 - m * 60
timeStr = str(h) + 'h ' + str(m) + 'm ' + str(s) + 's '
return timeStr
#--------------------------------------------------------------
def getProgStatus(val_Status):
status_str = ''
try:
pgst = int(val_Status[3:],16)
except Exception as e:
print('Error:',e)
return 'Error!'
if pgst & 1 :
status_str = 'running'
if pgst & 2 :
status_str = 'paused'
if pgst & 4 :
status_str = 'waiting'
if pgst & 16 :
status_str = 'waiting to start'
return status_str
#-----------------------------------
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
from dotenv import load_dotenv
import os
load_dotenv()
#-------------------------------------------------------------------------
TOKEN_TL = os.getenv('TOKEN_TL')
hostDB = os.getenv('hostDB')
userDB = os.getenv('userDB')
passDB = os.getenv('passDB')
dataDB = os.getenv('dataDB')
TIME_OFFSET = 20
TIMEOUT = 10
type_send = [1,2]
url_warn = 'http://192.168.3.16/simpac/warning/c3k_warn.plc'
url_info = 'http://192.168.3.16/simpac/info/c3k_frCVMV.plc'
url_auto = 'http://192.168.3.16/simpac/auto/c3k_auto.plc'
mes_error = 'Attention !\n \
Now the climate camera has a problem : {} \
\n Number: {} \
\n Type error : {} \
\n Quit notification: /quit'
mes_start = "'I have already remebered you, if admin alows, I will send alerts to you when the machine has errors'"
mes_status_dis = "Sorry, kamera is not working now !"
mes_help = "I have 5 commands:\n\b\b\b/start : Add you to the alert list.\n\
\b\b\b/stop : Delete you from the alert list.\n\
\b\b\b/status : Request the status\'s climate camera.\n\
\b\b\b/ups : Information about UPS.\n\
\b\b\b/help : About commands of the bot."
mes_stop = "I have already delete you from the alert list, I will not send alerts to you when the machine has errors"
mes_not_permi = "You don't have permission to request kamera information. Please contact admin"
mes_status_para = "This is parameters at the last time I checked kamera: \n\
- Number of checked : {} times \n\
- Last time checked : {}\n"
mes_admin = " There is a person, who wants to receive \
notification from the climate camera.\n - User_name : {} \n - Id : {}."
mes_UPS = "Status UPS: \n - Voltage: {}V\n - Capacity: {}%\n - {}"
mes_UPS_low = "The voltage or the capacity of the UPS is low!\n Need to charge now!\
\n Check server power /ups"
mes_UPS_powerOff = "Power Adapter Unplug or Power outage!\n Check server power /ups "
mes_powerOn = "Power on!"
mes_lost = 'Connect timeout, kamera is not working or disconnection!'
import mysql.connector
from datetime import datetime
import requests
from time import sleep
from config import *
#------------connect to DB-----------------------------------
conn = mysql.connector.connect(
host=hostDB,
user=userDB,
password=passDB,
database=dataDB
)
curs = conn.cursor()
conn.time_zone = "+03:00"
print("Connect DB successful!")
# --------------------------------------------------------------
def get_list_receive_id(type_user):
try:
type_user_permission = ''
for i in type_user:
type_user_permission += f'"{i}",'
type_user_permission = type_user_permission[:-1]
sql3 = f"SELECT user_id FROM alert_list WHERE permission IN ({type_user_permission});"
rows = sqlselect(sql3)
listchatid = []
# rows = (('1029731812',), ('251290036',), ('1343733841',), ('325253745',))
# using function for to get the element
if len(rows):
for i in rows:
listchatid.append(i[0])
return listchatid
except Exception as e:
print('Error get list id: ', e)
return ''
# --------------------------------------------------------------
def sqlselect(sql=str):
global conn
try:
conn = mysql.connector.connect(
host=hostDB,
user=userDB,
password=passDB,
database=dataDB
)
conn.time_zone = "+03:00"
curs = conn.cursor()
curs.execute(sql)
rows = curs.fetchall()
# print(rows)
return rows
except Exception as e:
print("Error sqlselect: ", sql)
return ''
# ----------------------get status bot -------------------
def getStatusBot():
try:
sql_dis = "SELECT status FROM admin_manager WHERE user_name = 'admin' ;"
rows_status = sqlselect(sql_dis)
if rows_status:
if rows_status[0][0]:
return True
else:
return False
except Exception as e:
print("Get status failed", e)
return ''
def write_user(chat_id, chat_user, permission):
try:
sql2 = "SELECT COUNT(*) FROM alert_list WHERE user_id={};".format(chat_id)
curs = conn.cursor()
curs.execute(sql2)
rows = curs.fetchone()
if rows and rows[0] > 0:
print("User has already existed !")
else:
sql1 = "INSERT INTO alert_list(user_id, user_name, permission, expiration) VALUES ({0},\'{1}\',\'{2}\',current_timestamp());".format(
chat_id, chat_user, permission
)
# print(sql1)
curs.execute(sql1)
conn.commit()
except Exception as e:
print('Error write user: ', e)
return ''
# ----------------------------------------------------------------------
def remove_user(chat_id):
global conn
try:
conn = mysql.connector.connect(
host=hostDB,
user=userDB,
password=passDB,
database=dataDB
)
sql1 = "DELETE FROM alert_list WHERE user_id={};".format(chat_id)
curs = conn.cursor()
curs.execute(sql1)
conn.commit()
except Exception as e:
print('Error remove user: ', e)
return ''
# -----------------------------------------------------------------
# --------------------------------------------------------------------
def check_time_permission(chat_id):
try:
sql_checktime = "SELECT expiration FROM alert_list WHERE user_id ={};".format(
chat_id)
rows = sqlselect(sql_checktime)
# print("rows: -------- ", rows[0][0])
if len(rows):
if rows[0][0] > datetime.now():
return True
else:
return False
except Exception as e:
print("Check time permission failed - ", e)
return ''
# --------------------------------------------------------------------------------------
def get_time_para():
try:
global conn
sql0 = "SELECT * FROM para_manager WHERE parameter in ('Time_cycle', 'Time_req') ;"
curs = conn.cursor()
curs.execute(sql0)
rows = curs.fetchall()
TIME_CYCLE = 0
TIME_REQ = 0
if len(rows) > 0:
# time between two circles
TIME_CYCLE = rows[0][3]
# time between two requests to web server kamera
TIME_REQ = rows[1][3]
TIME_CYCLE = float(TIME_CYCLE)
TIME_REQ = float(TIME_REQ)
return TIME_CYCLE, TIME_REQ
except Exception as e:
print("Error get time para: ", e)
return ''
# ---------------------------------------------------------------------------
def getInfoUPSfromDB():
try:
sqlUPS = 'SELECT * FROM power_record WHERE id = (SELECT MAX(id) FROM power_record);'
dataUPS = sqlselect(sqlUPS)
if len(dataUPS[0]):
voltage = dataUPS[0][2]
capacity = dataUPS[0][3]
status = dataUPS[0][4]
return voltage, capacity, status
return None
except Exception as e:
print('Error get Info UPS from DB:', e)
return ''
#-------------------------------------------------------------------
def checkPermissionUser(chat_id):
#check permission #check time
if chat_id in listUserPermission():
return True
else:
return False
#----------------------------------------------------------------------
def listUserPermission():
global type_send
list_user = get_list_receive_id(type_send)
list_user_permission=[]
for i in list_user:
if check_time_permission(i):
list_user_permission.append(i)
return list_user_permission
# ------------------------------------------------------------------
def send_message(chat_id,text='hello'):
url = f"https://api.telegram.org/bot{TOKEN_TL}/sendMessage"
payload = {'chat_id':chat_id,'text':text}
r = requests.post(url,json=payload)
return r
#---------------------------------------------------------------------------------
def send_many_message(list_user = [], mess='') :
# listchatid = get_list_receive_id(list_user_type)
list_user_sended = []
for chat_id in list_user:
send_message(chat_id, mess) #--> gui message cho ng dung
list_user_sended.append(chat_id)
sleep(0.1)
print(list_user_sended)
#------------------------------------------------------------------------
-- phpMyAdmin SQL Dump
-- version 4.0.4.2
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Feb 09, 2021 at 09:56 PM
-- Server version: 5.6.13
-- PHP Version: 5.4.17
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+03:00";
--
-- Database: `test`
--
CREATE DATABASE IF NOT EXISTS `data_bot` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `data_bot`;
-- --------------------------------------------------------
--
-- Table structure for table `admin_manager`
--
CREATE TABLE IF NOT EXISTS `admin_manager` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`user_name` varchar(50) NOT NULL,
`password` varchar(100) NOT NULL,
`status` tinyint(1) NOT NULL,
PRIMARY KEY (`user_name`),
UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
--
-- Dumping data for table `admin_manager`
--
INSERT INTO `admin_manager` (`id`, `user_name`, `password`, `status`) VALUES
(1, 'admin', 'pbkdf2:sha256:150000$D8JNnhoz$d01241d60f042c53b1721fbf95508f7439ace95e51ff471aa686e6e0bc377aca', 1);
--
-- Table structure for table `power_record`
--
CREATE TABLE IF NOT EXISTS `power_record` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`time_record` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`voltage` varchar(100) NOT NULL,
`capacity` varchar(100) NOT NULL,
`status` tinyint(1) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=0 ;
-- --------------------------------------------------------
--
-- Table structure for table `alert_list`
--
CREATE TABLE IF NOT EXISTS `alert_list` (
`user_id` varchar(50) CHARACTER SET cp1251 COLLATE cp1251_bin NOT NULL,
`time_create` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`user_name` varchar(50) CHARACTER SET cp1251 COLLATE cp1251_bin NOT NULL,
`permission` tinyint(1) NOT NULL,
`comment` varchar(200) CHARACTER SET cp1251 COLLATE cp1251_bin DEFAULT NULL,
`expiration` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `alert_list`
--
INSERT INTO `alert_list` (`user_id`, `time_create`, `user_name`, `permission`, `comment`, `expiration`) VALUES
('1343733841', '2020-10-28 18:43:35', 'nguyen van trung', 1, 'пользователь 1', '2022-12-06 21:01:00');
-- --------------------------------------------------------
--
-- Table structure for table `climate`
--
CREATE TABLE IF NOT EXISTS `climate` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`Time_request` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`Temperature` decimal(10,2) NOT NULL,
`Humidity` decimal(10,2) NOT NULL,
`Temperature_set` decimal(7,2) DEFAULT NULL,
`Humidity_set` decimal(7,2) DEFAULT NULL,
`Profile No.` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
`Profile Name` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
`Profile Cycles` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
`Active Cycles` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
`Total Loops` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
`Act Loops` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
`Segment` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
`Active Time` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
`Profile Time` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
`Total Time` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
`Segment Type` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
`Segment Total Time` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
`Segment Remain Time` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
`Status` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=0 ;
--
-- Table structure for table `para_manager`
--
CREATE TABLE IF NOT EXISTS `para_manager` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`parameter` varchar(50) DEFAULT NULL,
`on_message` tinyint(1) DEFAULT NULL,
`value` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=0 ;
--
-- Dumping data for table `para_manager`
--
INSERT INTO `para_manager` (`id`, `parameter`, `on_message`, `value`) VALUES
(1, 'id', 1, NULL),
(2, 'Time_request', 1, NULL),
(3, 'Temperature', 1, NULL),
(4, 'Temperature_set', 1, NULL),
(5, 'Humidity', 1, NULL),
(6, 'Humidity_set', 1, NULL),
(7, 'Profile No.', 1, NULL),
(8, 'Profile Name', 1, NULL),
(9, 'Profile Cycles', 0, NULL),
(10, 'Active Cycles', 0, NULL),
(11, 'Total Loops', 0, NULL),
(12, 'Act Loops', 0, NULL),
(13, 'Segment', 0, NULL),
(14, 'Active Time', 0, NULL),
(15, 'Profile Time', 0, NULL),
(16, 'Total Time', 0, NULL),
(17, 'Segment Type', 0, NULL),
(18, 'Segment Total Time', 0, NULL),
(19, 'Segment Remain Time', 0, NULL),
(20, 'Status', 0, NULL),
(21, 'Time_cycle', 0, '13'),
(22, 'Time_req', 0, '0.2');
#!/bin/bash
# launch this script with root privileges
echo "Install program Telegram Bot"
if [ $(id -u) != 0 ]
then
echo "You need to excuse this script with root privileges"
read -p "Press Enter key to exit"
exit 1
fi
###########################
# UPDATE AND UPGRADE OS
###########################
echo '###########################'
echo '# UPDATE AND UPGRADE OS #'
echo '###########################'
sudo apt update && apt upgrade -y &&
###########################
# install python 3 & pip
###########################
echo '###########################'
echo '# INSTALL PYTHON3 & PIP #'
echo '###########################'
sudo apt install -y python3-pip python3-dev build-essential libssl-dev libffi-dev python3-setuptools python3-venv &&
# curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
# python3 get-pip.py
pip3 --version
echo "Install successful Python3 and pip"
# if [ $? ]
# then
# echo "Error install pip, you need to install 'pip' manually!"
# fi
# install requirements.txt
# pip3 install -r requirements.txt &&
# if [ $? ]
# then
# echo "Check install requirement file - may be install manually"
# fi
########################
# install Nginx
########################
echo '###########################'
echo '# INSTALL NGINX #'
echo '###########################'
sudo apt install -y nginx &&
# if [ $(systemctl status nginx) != 0 ]
# then
# echo "S"
# read -p "Press Enter key to exit"
# exit 1
# fi
systemctl enable nginx &&
systemctl start nginx &&
echo "Install Nginx server successfully"
########################
# install Gunicorn
########################
echo '###########################'
echo '# INSTALL GUNICORN #'
echo '###########################'
sudo apt install -y python3-gunicorn &&
echo "Install Gunicorn successfully"
########################
# install mysql
########################
echo '###########################'
echo '# INSTALL MYSQL #'
echo '###########################'
sudo apt install -y mysql-client mysql-server &&
# config MySQL
sudo mysql_secure_installation &&
#
sudo systemctl start mysql &&
# create database
data1="data_bot"
sudo mysql -e "CREATE DATABASE $data1" &&
echo "########################"
echo "Dump database from file"
sudo mysql -p $data1 < data1.sql &&
echo "#############################"
echo "Create new user and password"
# enter name user and password
echo "Enter user name for the new acount of DataBase MySQL : "
read userDB
echo "Enter a password for new acount"
echo "Password must to have Upper letter,
Lower letter, number, symbol and at least 8 characters: "
read passDB
# create user in database
sudo mysql -e "CREATE USER IF NOT EXISTS '$userDB'@'localhost' IDENTIFIED BY '$passDB'";
sudo mysql -e "GRANT ALL PRIVILEGES ON *.* TO '$userDB'@'localhost';"
sudo mysql -e "FLUSH PRIVILEGES;"
# sudo systemctl start mysql
# restart mysql
sudo systemctl restart mysql &&
echo "Install successful MySQL"
# write username and password to the envirement file
echo "userDB='$userDB'">>.env.tmp
echo "passDB='$passDB'">>.env.tmp
host1="localhost" &&
echo "hostDB='$host1'">>.env.tmp &&
echo "dataDB='$data1'">>.env.tmp &&
########################
# CONFIG TO USE UPS
########################
echo '###########################'
echo '# CONFIG TO USE UPS #'
echo '###########################'
sudo apt install -y smbus &&
sudo apt install -y i2c-tools &&
# automatic launch I2C when restart
sudo echo 'i2c-dev'>>/etc/modules &&
# add user www-data to run I2C as administrator
sudo adduser www-data i2c &&
########################
# CONFIG TO USE USB MODEM
########################
echo '###########################'
echo '# CONFIG TO USE USB MODEM #'
echo '###########################'
# install driver
sudo apt -y install ppp usb-modeswitch
# add file to OS automatic recognize that usb-modem is a modem
# delete last line
sed '${/modeswitch_rules_end/d;}' /lib/udev/rules.d/40-usb_modeswitch.rules
# add in the last of the file 2 lines
echo "# Huawei E353/E3131">>/lib/udev/rules.d/40-usb_modeswitch.rules
echo "ATTR{idVendor}==\"12d1\", ATTR{idProduct}==\"1f01\", RUN +=\"usb_modeswitch '%b/%k'\"">>/lib/udev/rules.d/40-usb_modeswitch.rules
# config network
echo 'auto eth0'>>/etc/network/interfaces
echo 'allow-hotplug eth0'>>/etc/network/interfaces
echo 'iface eth0 inet dhcp'>>/etc/network/interfaces
echo 'metric 500'>>/etc/network/interfaces
# delete the line and enter a new line
sed -i '/ifupdown/d' /etc/NetworkManager/NetworkManager.conf &&
sed -i '/managed/d' /etc/NetworkManager/NetworkManager.conf &&
echo '[ifupdown]'>>/etc/NetworkManager/NetworkManager.conf &&
echo 'managed=false'>>/etc/NetworkManager/NetworkManager.conf
########################
########################
# copy all file to target forder
echo "Copy file....................................."
# create folder to target /var/www
mkdir /var/www/tele_bot
#copy
cp -av . /var/www/tele_bot/ && cd /var/www/tele_bot
chown -R www-data:www-data /var/www/tele_bot/.
# require user to register a telegram bot and save the token
echo "########################################################"
echo "You need to create a new telegram bot and save the TOKEN"
echo "Please enter Telegram-bot TOKEN:"
while [ true ]
do
read token
echo "Check TOKEN.................."
curl "https://api.telegram.org/bot$token/getUpdates" > respond
if grep -q true respond
then
echo "It is a correct Token"
echo "TOKEN_TL='$token'">>.env.tmp &&
break
else
echo -e "\n It is not a correct Token, please enter again:"
fi
done
rm respond
rm data1.sql
# rename envirement file
rm .env &&
mv .env.tmp .env &&
rm install.sh
########################
########################
# create virtual envirement to excute nginx
python3 -m venv venv
sudo apt install -y libxml2-dev libxslt-dev python3-dev &&
sudo apt install python3-lxml &&
sudo pip3 install -r requirements.txt &&
/var/www/tele_bot/venv/bin/pip install -r requirements.txt
# Configuring Nginx
# copy to folder /etc/nginx/sites-available
sudo cp -av /var/www/tele_bot/sites-available/telebot_web /etc/nginx/sites-available &&
sudo rm -r /var/www/tele_bot/sites-available &&
# Link the file to the sites-enabled directory to enable Nginx server block
sudo ln -s /etc/nginx/sites-available/telebot_web /etc/nginx/sites-enabled &&
rm /etc/nginx/sites-enabled/default &&