Browse Source

first commit

pull/1/head
Bugra Isguzar 6 months ago
commit
efd852d153
6 changed files with 318 additions and 0 deletions
  1. 132
    0
      .gitignore
  2. 13
    0
      agent.py
  3. 92
    0
      core/__init__.py
  4. 1
    0
      core/modules/__init__.py
  5. 2
    0
      core/modules/healthcheck.py
  6. 78
    0
      install.sh

+ 132
- 0
.gitignore View File

@@ -0,0 +1,132 @@
.mqtt-structure

# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
.python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/


+ 13
- 0
agent.py View File

@@ -0,0 +1,13 @@
from core import Agent
from configparser import ConfigParser

if __name__ == "__main__":
configs = ConfigParser()
configs.read("/opt/sixfab/.env")
configs = configs["pms"]
agent = Agent(
configs["TOKEN"],
interval=configs["INTERVAL"],
)
agent.loop()

+ 92
- 0
core/__init__.py View File

@@ -0,0 +1,92 @@
import paho.mqtt.client as mqtt
import json
from .modules import *

MQTT_HOST = "beta.sixfab.com"
MQTT_PORT = 1883

COMMANDS = {"healthcheck": health_check}


class Agent(object):
def __init__(self, token: str, interval: int = 10, lwt: bool = True):
client = mqtt.Client()
self.client = client

client.username_pw_set(token, token)
client.user_data_set(token)

if lwt:
client.will_set("/device/{}/status".format(token), "offline", retain=True)
client.connect(MQTT_HOST, MQTT_PORT, 50)
client.on_connect = self.__on_connect
client.on_message = self.__on_message
client.on_disconnect = self.__on_disconnect
client.on_log = self.__on_log

def loop(self):
self.client.loop_forever()

def __on_message(self, client, userdata, msg):
"""
Triggering on mqtt message
Request Format:
{
"command": "",
"commandID": "", !!! OPTIONAL
"data": {}, !!! OPTIONAL
}


Response Format:
{
"command": "",
"commandID": "", !!! OPTIONAL
"response": {}, !!! OPTIONAL
}
"""
message = json.loads(msg.payload.decode())
command = message.get("command", None)
commandID = message.get("commandID", None)

if COMMANDS[command]:
response = json.dumps(
{
"command": command,
"commandID": commandID,
"response": COMMANDS[command](),
}
)

client.publish(
"/device/{userdata}/hive".format(userdata=userdata), response
)

else:
response = json.dumps(
{
"command": command,
"commandID": commandID,
"response": "Invalid command",
}
)
client.publish(
"/device/{userdata}/hive".format(userdata=userdata), response
)

def __on_connect(self, client, userdata, flags, rc):
print("Connected to the server")
self.client.subscribe("/device/{userdata}/directives".format(userdata=userdata))
self.client.publish(
"/device/{userdata}/status".format(userdata=userdata),
"online",
retain=True,
)

def __on_disconnect(self, client, userdata, rc):
print("Disconnected. Result Code: {rc}".format(rc=rc))

def __on_log(self, mqttc, obj, level, string):
print(string)

+ 1
- 0
core/modules/__init__.py View File

@@ -0,0 +1 @@
from .healthcheck import health_check

+ 2
- 0
core/modules/healthcheck.py View File

@@ -0,0 +1,2 @@
def health_check():
return 'I\'m here!'

+ 78
- 0
install.sh View File

@@ -0,0 +1,78 @@
cat << "EOF"
_____ _ __ _ _________ ___ _____
/ ___(_) / _| | | | ___ \ \/ |/ ___|
\ `--. ___ _| |_ __ _| |__ | |_/ / . . |\ `--.
`--. \ \ \/ / _/ _` | '_ \ | __/| |\/| | `--. \
/\__/ / |> <| || (_| | |_) | | | | | | |/\__/ /
\____/|_/_/\_\_| \__,_|_.__/ \_| \_| |_/\____/
EOF

TOKEN="asd"
INTERVAL="10"
AGENT_REPOSITORY="asd"

echo "Creating Sixfab root directory on /opt..."
sudo mkdir -p /opt/sixfab
echo "Root directory created."


echo "Looking for dependencies..."

# Check if git installed
if ! [ -x "$(command -v git)" ]; then
echo 'Git is not installed, installing...'
sudo apt-get install git >/dev/null
fi

# Check if python installed
if ! [ -x "$(command -v python3)" ]; then
echo 'Python3 is not installed, installing...'
sudo apt-get install python3 >/dev/null
fi

# Check if python installed
if ! [ -x "$(command -v pip3)" ]; then
echo 'Pip for python3 is not installed, installing...'
sudo apt-get install python3-pip >/dev/null
fi

echo "Cloning agent source..."
sudo git clone $AGENT_REPOSITORY /opt/sixfab/pms-agent >/dev/null
echo "Agent source cloned."

echo "Installing agent dependencies from PyPI..."
sudo pip3 install -r /opt/sixfab/pms-agent/requirements.txt

echo "Creating environment file..."
sudo touch /opt/sixfab/.env

echo "[pms]
TOKEN=$TOKEN
INTERVAL=$INTERVAL
" > /opt/sixfab/.env

echo "Environment file created."

echo "Initializing systemd service..."

sudo echo "[Unit]
Description=Sixfab PMS Agent
After=network.target

[Service]
ExecStart=/usr/bin/python3 -u agent.py
WorkingDirectory=/opt/sixfab/pms-agent
StandardOutput=inherit
StandardError=inherit
Restart=always
User=pi

[Install]
WantedBy=multi-user.target" > /etc/systemd/system/pms_agent.service

echo "Enabling and starting systemd service..."

sudo systemctl enable pms_agent
sudo systemctl start pms_agent

echo "Service initialized successfully."

Loading…
Cancel
Save