Compare commits

..

1 Commits

Author SHA1 Message Date
03a21b1772 Update README.md 2023-08-08 10:28:17 +00:00
9 changed files with 233 additions and 1680 deletions

View File

@@ -1,12 +0,0 @@
stages: # List of stages for jobs, and their order of execution
- build
build-job: # This job runs in the build stage, which runs first.
stage: build
script:
- column=":"
- echo "${flow_id}"
- curl -X POST https://kestra.sectorq.eu/api/v1/executions/webhook/jaydee/ansible-all/${flow_id} -d '{"tag":["mqtt-srv"],"target":["morefine.home.lan"]}' -H "Content-Type${column} application/json"
rules:
- if: '$CI_COMMIT_MESSAGE =~ /build/'

View File

@@ -14,6 +14,7 @@ Already a pro? Just edit this README.md and make it your own. Want to make it ea
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
adsasd
cd existing_repo
git remote add origin https://gitlab.sectorq.eu/sectorq/mqtt_srv.git
git branch -M main

View File

@@ -1,14 +0,0 @@
{
"global":
{
"mykey": "prod/v1/install/"
},
"morefine":
{
"right": ["HDMI-A-0", "1920x1080"],
"tleft": ["DisplayPort-9", "1920x1080"],
"tright": ["DisplayPort-11", "1920x1080"],
"left": ["DisplayPort-10", "2560x1440"],
"mid": ["DisplayPort-0", "3440x1440"]
}
}

View File

@@ -17,34 +17,12 @@ import ctypes
import getopt
import random
import requests
import shutil
if os.path.exists("/etc/mqtt_srv/mqtt_srv.cfg"):
with open("/etc/mqtt_srv/mqtt_srv.cfg") as json_file:
config = json.load(json_file)
print(config)
else:
config = {}
#import psutil
stats = {}
VERSION = "1.0.37"
VERSION = "1.0.25"
curos = platform.system()
host = platform.node().lower().replace(".home.lan","")
if curos == "Windows":
log_path = "c:\\Program Files\\jaydee\\jaydee.log"
else:
log_path = "/tmp/mqtt_srv.log"
def writeLog(msg, svr="INFO"):
ts = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
ts2 = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
f = open(log_path, "a")
f.write(ts + " | " + svr + " | " + str(msg) + "\n")
f.close()
writeLog(host)
host = platform.node().lower()
print(host)
if curos == "Windows":
import winreg
def uptime():
@@ -86,12 +64,16 @@ def uptime():
string += str(seconds)
return string;
ts = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
ts2 = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
if os.path.exists(log_path):
shutil.move(log_path, log_path + "." + ts2)
def writeLog(msg, svr="INFO"):
ts = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
if curos == "Windows":
log_path = "c:\Program Files\jaydee\jaydee.log"
else:
log_path = "/tmp/mqtt_srv.log"
f = open(log_path, "a")
f.write(ts + " | " + svr + " | " + str(msg) + "\n")
f.close()
def check_router():
stats["uptime"] = uptime()
@@ -218,7 +200,7 @@ try:
opts, args = getopt.getopt(sys.argv[1:], "Sspmt:", ["command=", "help", "output="])
except getopt.GetoptError as err:
# print help information and exit:
writeLog(str(err)) # will print something like "option -a not recognized"
print(str(err)) # will print something like "option -a not recognized"
#usage()
sys.exit(2)
output = None
@@ -239,7 +221,7 @@ for o, a in opts:
_THR_VAL = sys.argv[3]
else:
_WIZZARD = True
MQTT_HOST = "mqtt.home.lan"
MQTT_HOST = "192.168.77.106"
MQTT_PORT = 1883
if _PUBLISH:
@@ -268,9 +250,9 @@ if _PUBLISH:
# result: [0, 1]
status = result[0]
if status == 0:
writeLog(f"Send `{_MESSAGE}` to topic `{_TOPIC}`")
print(f"Send `{_MESSAGE}` to topic `{_TOPIC}`")
else:
writeLog(f"Failed to send message to topic {_TOPIC}")
print(f"Failed to send message to topic {_TOPIC}")
client = connect_mqtt()
publish(client)
@@ -329,15 +311,12 @@ def get_ip():
finally:
s.close()
return IP
ex = 0
while ex == 0:
try:
IP = get_ip()
ex = 1
except:
time.sleep(5)
IP = get_ip()
print("OS : " + curos)
writeLog("OS : " + curos)
if curos != "Windows":
import autorandr
@@ -351,27 +330,28 @@ elif host == "SERVER":
mac = str(get_mac_address("enp2s0"))
elif host == "ASUS" and curos != "Windows":
mac = str(get_mac_address("enp3s0f1"))
elif host == "morefine" and curos != "Windows":
mac = str(get_mac_address("eno1"))
else:
mac = str(get_mac_address("Ethernet"))
print("MAC : " + mac)
writeLog("MAC : " + mac)
print("SYSTEM : " + host)
writeLog("SYSTEM : " + host)
print("IP : " + IP)
writeLog("IP : " + IP)
flag_connected = 0
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
print("Connected with result code " + str(rc))
writeLog("Connected with result code " + str(rc))
global flag_connected
flag_connected = 1
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
topic = "sectorq/systems/" + host.lower()
topic2 = "sectorq/systems/all"
MQTT_TOPIC = [(topic,0),(topic2,0)]
print(topic)
writeLog(topic)
time.sleep(1)
client.publish("sectorq/status", payload="{'action':'connect', 'system':'" + host.lower() + "', 'ip': '" + IP + "', 'mac':'" + mac + "', 'ver':'" + VERS + "'}", qos=0, retain=False)
@@ -379,21 +359,11 @@ def on_connect(client, userdata, flags, rc):
if host.lower() == "router":
check_router()
if host.lower() == "morefine":
myCmd =f'sudo XDG_RUNTIME_DIR=/run/user/1000 -u jd amixer set Master 100%'
# try:
# #percent = 20
# #output = subprocess.run(["pactl", "set-sink-volume", "@DEFAULT_SINK@", f"{percent}%"], check=True)
# writeLog(output)
# except subprocess.CalledProcessError as e:
# writeLog(e)
# writeLog("Failed to mute/unmute")
writeLog(myCmd)
output = subprocess.Popen(myCmd, shell=True)
if host.lower() == "nas":
cmnd = "/share/ZFS532_DATA/.qpkg/QKVM/usr/bin/virsh list --all"
writeLog(cmnd)
print("Getting VM info")
cmnd = "/share/ZFS530_DATA/.qpkg/QKVM/usr/bin/virsh list --all"
print(cmnd)
status, output = subprocess.getstatusoutput(cmnd)
l = 1
lines = output.splitlines()
@@ -403,26 +373,28 @@ def on_connect(client, userdata, flags, rc):
if l < 4:
continue
line = re.split(r" {2,}", i)
writeLog(str(line[0].strip()) + " " + str(line[1].strip()) + " " + str(line[2].strip()))
print(str(line[0].strip()) + " " + str(line[1].strip()) + " " + str(line[2].strip()))
VMS[str(line[1].strip())] = str(line[2].strip())
for m in VMS:
cmnd = "/share/ZFS532_DATA/.qpkg/QKVM/usr/bin/virsh domstate " + m
cmnd = "/share/ZFS530_DATA/.qpkg/QKVM/usr/bin/virsh domstate " + m
#out = subprocess.Popen(cmnd.split())
writeLog(cmnd)
print(cmnd)
status, output = subprocess.getstatusoutput(cmnd)
writeLog(output)
print(output)
if output.strip() == "running":
client.publish("sectorq/systems/nas/" + m, payload=1, qos=0, retain=True)
else:
client.publish("sectorq/systems/nas/" + m, payload=0, qos=0, retain=True)
client.subscribe(MQTT_TOPIC)
client.subscribe(topic)
def on_disconnect(client, userdata, rc):
print("disconnecting reason " +str(rc))
writeLog("disconnecting reason " +str(rc))
client.connected_flag=False
client.disconnect_flag=True
@@ -432,8 +404,8 @@ def on_disconnect(client, userdata, rc):
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
writeLog(msg.topic)
writeLog(msg.payload)
print(msg.topic)
print(msg.payload)
myObj = msg.payload.decode('utf-8')
# command = re.sub(r"^b\'|\'$", "", str(msg.payload))
# command = json.loads(msg.payload.decode("utf-8"))
@@ -441,36 +413,49 @@ def on_message(client, userdata, msg):
myObj = json.loads(msg.payload)
try:
writeLog(myObj["action"])
print(myObj["action"])
except:
print("Action not set")
writeLog("Action not set", "WARNING")
try:
print(myObj["cmd"])
writeLog(myObj["cmd"])
except:
print("Cmd not set")
writeLog("Cmd not set", "WARNING")
try:
print(myObj["target"])
writeLog(myObj["target"])
except:
print("Target Not Set")
writeLog("Target Not Set", "WARNING")
try:
print(myObj["status"])
writeLog(myObj["status"])
except:
print("Status Not Set")
writeLog("Status Not Set")
try:
print(myObj["command"])
writeLog(myObj["command"])
except:
print("Command Not Set")
writeLog("Command Not Set")
try:
print(myObj["cmd_line"])
writeLog(myObj["cmd_line"])
except:
print("Cmd_line Not Set")
writeLog("Cmd_line Not Set")
if myObj["cmd"] == "command":
print("Executing " + myObj["cmd_line"])
writeLog("Executing " + myObj["cmd_line"])
#os.system('start /b "' + myObj["cmd_line"] + '"')
try:
@@ -479,48 +464,48 @@ def on_message(client, userdata, msg):
# ctypes.windll.user32.MessageBoxW(0, myObj["cmd_line"], "Executed", 64)
except:
ctypes.windll.user32.MessageBoxW(0, "Your text", "Your title", 16)
print("Executed " + myObj["cmd_line"])
writeLog("Executed " + myObj["cmd_line"])
if myObj["cmd"] == "nas_cmd":
writeLog("Executing NAS")
#cmnd = "/share/ZFS530_DATA/.qpkg/QKVM/usr/bin/virsh domstate " + str(myObj["target"])
cmnd = "/share/ZFS532_DATA/.qpkg/QKVM/usr/bin/virsh domstate " + str(myObj["target"])
writeLog(cmnd)
print("Executing NAS")
cmnd = "/share/ZFS530_DATA/.qpkg/QKVM/usr/bin/virsh domstate " + str(myObj["target"])
print(cmnd)
status, output = subprocess.getstatusoutput(cmnd)
writeLog(output)
print(output)
cmd_type = myObj["command"]
if myObj["command"] == "start":
if output.strip() == "paused":
writeLog("System suspended")
print("System suspended")
cmd_type = "resume"
else:
writeLog("System Off")
print("System Off")
cmd_type = "start"
if myObj["command"] == "suspend":
cmd_type = "shutdown"
cmnd = "/share/ZFS532_DATA/.qpkg/QKVM/usr/bin/virsh " + cmd_type + " " + str(myObj["target"])
cmnd = "/share/ZFS530_DATA/.qpkg/QKVM/usr/bin/virsh " + cmd_type + " " + str(myObj["target"])
subprocess.Popen(cmnd.split())
writeLog(cmnd)
print(cmnd)
if myObj["command"] == "start":
try:
writeLog("sending")
print("sending")
client.publish("sectorq/systems/nas/" + str(myObj["target"]), payload=1, qos=0, retain=False)
except:
writeLog("failed to execute!")
print("failed to execute!")
client.publish("sectorq/systems/nas/" + str(myObj["target"]), payload="failed", qos=0, retain=False)
else:
try:
writeLog("sending")
print("sending")
client.publish("sectorq/systems/nas/" + str(myObj["target"]), payload=0, qos=0, retain=False)
except:
writeLog("failed to execute!")
print("failed to execute!")
client.publish("sectorq/systems/nas/" + str(myObj["target"]), payload="failed", qos=0, retain=False)
if myObj["cmd"] == "distrib":
writeLog("distributin313g")
print("distributin313g")
# os.startfile(sys.argv[0])
#sys.exit()
subprocess.Popen(['/bin/systemctl', 'restart', 'mqtt'])
@@ -629,6 +614,94 @@ def on_message(client, userdata, msg):
writeLog("Payload111114")
writeLog(output)
print(json.dumps(serv_d))
'''
if myObj["target"].lower() == "192.168.77.246":
dest_ip = "192.168.77.246"
elif myObj["target"].lower() == "192.168.77.106":
dest_ip = "192.168.77.106"
RULES = ["EMAIL993", "EMAIL995", "EMAIL143", "EMAIL25", "EMAIL993", "EMAIL465", "HTTPS", "HTTP"]
for i in RULES:
cmnd = "uci set firewall.{}.dest_ip={}".format(i,dest_ip)
writeLog(cmnd)
subprocess.Popen(cmnd.split())
#cmnd = "uci set dhcp.@dnsmasq[0].address=/mqtt_broker/" + dest_ip
#writeLog(cmnd)
#subprocess.Popen(cmnd.split())
time.sleep(1)
cmnd = "uci commit"
subprocess.Popen(cmnd.split())
writeLog("Starting " + myObj["target"].lower())
if myObj["target"].lower() == "192.168.77.246":
dest_ip = "192.168.77.246"
cmnd = "ssh root@192.168.77.246 'docker start mailu_resolver_1 mailu_redis_1 mailu_front_1 mailu_antispam_1 mailu_imap_1 mailu_admin_1 mailu_smtp_1 mailu_webmail_1 watchtower_watchtower_1 nginx-proxy-manager_db_1 nginx-proxy-manager_app_1 HomeAssistant webhub_client_1 dockermon_docker_mon_1 mosquitto_mosquitto_1 node-red_node-red_1 nextcloud_db_1 nextcloud_app_1'"
status, output = subprocess.getstatusoutput(cmnd)
elif myObj["target"].lower() == "192.168.77.106":
dest_ip = "192.168.77.106"
cmnd = "ssh root@192.168.77.246 'docker stop mailu_resolver_1 mailu_redis_1 mailu_front_1 mailu_antispam_1 mailu_imap_1 mailu_admin_1 mailu_smtp_1 mailu_webmail_1 watchtower_watchtower_1 nginx-proxy-manager_db_1 nginx-proxy-manager_app_1 HomeAssistant webhub_client_1 dockermon_docker_mon_1 mosquitto_mosquitto_1 node-red_node-red_1 nextcloud_db_1 nextcloud_app_1'"
status, output = subprocess.getstatusoutput(cmnd)
time.sleep(1)
cmnd = "/etc/init.d/firewall restart"
subprocess.Popen(cmnd.split())
#cmnd = "/etc/init.d/dnsmasq restart"
#subprocess.Popen(cmnd.split())
writeLog("reconfigure iot")
MQTT_BROKER = dest_ip
MQTT_USER = "jaydee"
MQTT_PASS = "jaydee1"
cmnd = "nmap -sP 192.168.77.*|grep \"Nmap scan report\"|egrep -o \"[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\""
#print(cmnd)
status, output = subprocess.getstatusoutput(cmnd)
# print(output)
ips = output.splitlines()
tasm_data = {}
for sys_ip in ips:
# print("Thsis is ip : " + sys_ip)
cmnd = "nmap " + sys_ip + " -p80|grep \"80/tcp open http\""
status, output = subprocess.getstatusoutput(cmnd)
# print("status of 80 : " + str(status))
if status == 0:
try:
# url = "http://" + sys_ip + "/cm?user=admin&password=l4c1j4yd33Du5l0&cmnd=STATUS+5"
url = "http://" + sys_ip + "/cm?cmnd=Backlog%20MqttHost%20" + MQTT_BROKER + "%3BMqttUser%20" + MQTT_USER + "%3BMqttPassword%20" + MQTT_PASS
print(url)
requests.get(url)
except:
#print(sys_ip + " : Not a tasmota!")
pass
else:
#print(sys_ip + " : Not a listening")
pass
time.sleep(1)
cmnd = "sed -i 's/^MQTT_HOST = .*/MQTT_HOST = \"" + dest_ip + "\"/' /root/mqtt_srv.py"
writeLog(cmnd)
status, output = subprocess.getstatusoutput(cmnd)
#for i in ;do uci set firewall.${i}.dest_ip=192.168.77.246;done;uci set firewall.HTTPS.dest_port='443';uci set firewall.HTTP.dest_port='80' ;uci commit;/etc/init.d/firewall restart
else:
pass
#cmnd = "/root/router_cmd.sh -t wireless -v 0"
print("Executed " + cmnd)
writeLog("Executed " + cmnd)
'''
if myObj["cmd"] == "banip":
if myObj["status"] == "ban":
@@ -651,8 +724,8 @@ def on_message(client, userdata, msg):
# os.startfile(sys.argv[0])
#sys.exit()
myCmd = 'c:\\Program Files\\RealVNC\\VNC Viewer\\vncviewer.exe C:\\Users\\jaydee\\' + myObj["target"].upper() + '.vnc'
print(myCmd)
writeLog(myCmd)
subprocess.Popen(myCmd.split())
if myObj["cmd"] == "getstats":
print("lalaa1")
@@ -664,57 +737,19 @@ def on_message(client, userdata, msg):
client.publish("sectorq/monitor/" + host.lower(), payload="{\"mb_temp\":0,\"mem_usage\":0,\"cpu_temp\":0,\"cpu_usage\":0,\"gpu_temp\":0,\"gpu_usage\":0}", qos=0, retain=False)
print("lalaa2")
if myObj["cmd"] == "openrgb":
myCmd = 'powershell.exe -windowstyle hidden -command Stop-ScheduledTask -TaskName "jaydee\\OpenRGB"'
writeLog(myCmd)
subprocess.Popen(myCmd.split())
time.sleep(2)
myCmd = 'powershell.exe -windowstyle hidden -command Start-ScheduledTask -TaskName "jaydee\\OpenRGB"'
writeLog(myCmd)
subprocess.Popen(myCmd.split())
if myObj["cmd"] == "hyperion":
myCmd = 'powershell.exe -windowstyle hidden -command Start-ScheduledTask -TaskName "jaydee\\hyperion"'
writeLog(myCmd)
subprocess.Popen(myCmd.split())
if myObj["cmd"] == "hyperiond":
myCmd = 'powershell.exe -windowstyle hidden -command Start-ScheduledTask -TaskName "jaydee\\hyperiond"'
writeLog(myCmd)
subprocess.Popen(myCmd.split())
if myObj["cmd"] == "assist":
writeLog("Starting Assist")
if curos == "Windows":
writeLog("Windows Vol Control")
if myObj['target'] == "start":
myCmd =f'powershell "& ""c:\\Program Files\\jaydee\\vol_control.ps1""" 0.2'
else:
myCmd =f'powershell "& ""c:\\Program Files\\jaydee\\vol_control.ps1""" 1'
else:
writeLog("Linux Vol Control")
if myObj['target'] == "start":
myCmd =f'sudo XDG_RUNTIME_DIR=/run/user/1000 -u jd amixer set Master 20%'
else:
myCmd =f'sudo XDG_RUNTIME_DIR=/run/user/1000 -u jd amixer set Master 100%'
# try:
# #percent = 20
# #output = subprocess.run(["pactl", "set-sink-volume", "@DEFAULT_SINK@", f"{percent}%"], check=True)
# writeLog(output)
# except subprocess.CalledProcessError as e:
# writeLog(e)
# writeLog("Failed to mute/unmute")
writeLog(myCmd)
output = subprocess.Popen(myCmd, shell=True)
writeLog(output)
if myObj["cmd"] == "display":
if curos == "Windows":
myCmd =f"powershell -w h -command \" Import-Module DisplayConfig ; Import-Clixml $home\\monitors\\{myObj['target']}.xml | Use-DisplayConfig -UpdateAdapterIds \""
if curos == "Windows1":
# os.startfile(sys.argv[0])
#sys.exit()
#print("reconfigure")
myCmd = 'MonitorSwitcher.exe -load:' + myObj["target"] + '.xml'
writeLog(myCmd)
#myCmd = f"MultiMonitorTool.exe /LoadConfig \"c:\\Program Files\\jaydee\\Monitors\\{myObj["target"]}.cfg\""
#writeLog(myCmd)
#print(myCmd)
output = subprocess.Popen(myCmd, shell=True)
#output = subprocess.Popen(myCmd.split())
writeLog(output)
#writeLog(os.path.realpath(__file__))
print("lalaa2")
#subprocess.Popen(r'"{}"'.format(myCmd), shell=True)
print("lalaa3")
subprocess.Popen(myCmd.split(), shell=True,cwd=r'c:\Progra~1\jaydee')
else:
'''
myCmd = ""
@@ -741,7 +776,7 @@ def on_message(client, userdata, msg):
'''
myCmd = ""
writeLog(myObj["target"])
if curos == "Windows1":
if curos == "Windows":
myCmd = "DisplayFusionCommand.exe -monitorloadprofile {}".format(myObj["target"])
@@ -749,77 +784,44 @@ def on_message(client, userdata, msg):
'''
mon1 = "HDMI-1-1"
mon2 = "HDMI-1-2"
mon3 = "DisplayPort-0"
mon4 = "DisplayPort-8"
mon3 = "DVI-I-2-1"
mon4 = "eDP-1-1"
'''
# right = ["HDMI-A-0", "1920x1080"]
# tleft = ["DisplayPort-6", "1920x1080"]
# tright = ["DisplayPort-8", "1920x1080"]
# left = ["DisplayPort-7", "2560x1440"]
# mid = ["DisplayPort-0", "3440x1440"]
mon1 = "HDMI-1"
mon2 = "HDMI-2"
mon3 = "DVI-I-2-1"
mon4 = "eDP-1"
right = config['morefine']['right']
tleft = config['morefine']['tleft']
tright = config['morefine']['tright']
left = config['morefine']['left']
mid = config['morefine']['mid']
myCmd = "bash /myapps/mqtt_srv/get_monitors.sh"
status, output = subprocess.getstatusoutput(myCmd)
f = open( "/tmp/monitors.txt" )
contents = f.read().splitlines()
f.close()
writeLog(contents)
for i in contents:
writeLog(i)
d = i.split(";")
if len(d) < 2:
continue
writeLog(d[1])
if d[1] == "DELL P3421W":
mid[0] = d[0]
elif d[1] == "VG27WQ":
left[0] = d[0]
elif d[1] == "PHL 243V5":
tleft[0] = d[0]
elif d[1] == "PHL 273V7":
tright[0] = d[0]
writeLog("dpc")
writeLog(contents)
#xrandr --output DisplayPort-1 --primary --auto --mode 3440x1440 --output HDMI-A-0 --auto --left-of DVI-I-1-1 --mode 1920x1080 --output DisplayPort-0 --auto --left-of DisplayPort-1 --mode 2560x1440 --output DVI-I-1-1 --above DisplayPort-1 --mode 1920x1080
if myObj["target"] == "mid":
myCmd = f"xrandr --output {mid[0]} --primary --auto --mode {mid[1]} --output {left[0]} --off --output {tleft[0]} --off --output {tright[0]} --off"
myCmd = "xrandr --output " + mon2 + " --primary --auto --mode 1920x1080 --output " + mon3 + " --off --output " +mon1 + " --off --output " + mon4 + " --off"
elif myObj["target"] == "left":
myCmd = f"xrandr --output {left[0]} --primary --auto --mode {left[1]} --output {mid[0]} --off --output {tleft[0]} --off --output {tright[0]} --off"
elif myObj["target"] == "all":
myCmd = f"xrandr --output {mid[0]} --primary --auto --mode {mid[1]} --pos 0x0 --output {tleft[0]} --auto --pos -1920x-1080 --mode {tleft[1]} --output {left[0]} --auto --left-of {mid[0]} --mode {left[1]} --output {tright[0]} --above {mid[0]} --mode {tright[1]}"
elif myObj["target"] == "midtright":
myCmd = f"xrandr --output {mid[0]} --primary --auto --mode {mid[1]} --pos 0x0 --output {tleft[0]} --off --output {left[0]} --off --output {tright[0]} --above {mid[0]} --mode {tright[1]}"
#myCmd = f"xrandr --output {mid[0]} --primary --auto --mode {mid[1]} --output {right[0]} --auto --right-of {mid[0]} --mode {right[1]} --output {left[0]} --auto --left-of {mid[0]} --mode {left[1]}"
elif myObj["target"] == "midleft":
myCmd = f"xrandr --output {mid[0]} --primary --auto --mode {mid[1]} --output {tleft[0]} --off --output {left[0]} --auto --left-of {mid[0]} --mode {left[1]} --output {tright[0]} --off"
elif myObj["target"] == "midtop":
myCmd = f"xrandr --output {mid[0]} --primary --auto --mode {mid[1]} --output {tright[0]} --auto --above {mid[0]} --mode {tright[1]} --output {left[0]} --off --output {tleft[0]} --off"
elif myObj["target"] == "midlefttleft":
myCmd = f"xrandr --output {mid[0]} --primary --auto --mode {mid[1]} --pos 0x0 --output {tright[0]} --off --output {left[0]} --auto --left-of {mid[0]} --mode {left[1]} --output {tleft[0]} --auto --pos -1920x-1080 --mode {tleft[1]}"
elif myObj["target"] == "lefttlefttright":
myCmd = f"xrandr --output {mid[0]} --off --output {tleft[0]} --auto --pos 640x-1080 --mode {tright[1]} --output {left[0]} --primary --auto --mode {left[1]} --pos 0x0 --output {tright[0]} --right-of {tleft[0]} --mode {tright[1]}"
elif myObj["target"] == "lefttleft":
myCmd = f"xrandr --output {mid[0]} --off --output {tleft[0]} --auto --pos 640x-1080 --mode {tright[1]} --output {left[0]} --primary --auto --mode {left[1]} --pos 0x0 --output {tright[0]} --off"
myCmd = "xrandr --output " + mon1 + " --primary --auto --mode 1920x1080 --output " + mon3 + " --off --output " +mon2 + " --off --output " + mon4 + " --off"
elif myObj["target"] == "all":
myCmd = "xrandr --output " + mon2 + " --primary --auto --mode 1920x1080 --output " + mon3 + " --auto --right-of " + mon2 + " --mode 1920x1080 --output " + mon1 + " --auto --left-of " + mon2 + " --mode 1920x1080 --output " + mon4 + " --auto --right-of " + mon2 + " --mode 1920x1080"
elif myObj["target"] == "midleft":
myCmd = "xrandr --output " + mon2 + " --primary --auto --mode 1920x1080 --output " + mon3 + " --off --output " + mon1 + " --auto --left-of " + mon2 + " --mode 1920x1080 --output " + mon4 + " --off"
elif myObj["target"] == "midtop":
myCmd = "xrandr --output " + mon2 + " --primary --auto --mode 1920x1080 --output " + mon3 + " --auto --right-of " + mon2 + " --mode 1920x1080 --output " + mon1 + " --off --output " + mon4 + " --off"
elif myObj["target"] == "midleftbuild":
myCmd = "xrandr --output " + mon2 + " --primary --auto --mode 1920x1080 --output " + mon3 + " --off --output " + mon1 + " --auto --left-of " + mon2 + " --mode 1920x1080 --output " + mon4 + " --auto --right-of " + mon2 + " --mode 1920x1080"
elif myObj["target"] == "midbuild":
myCmd = "xrandr --output " + mon2 + " --primary --auto --mode 1920x1080 --output " + mon3 + " --off --output " + mon1 + " --off --output " + mon4 + " --auto --right-of " + mon2 + " --mode 1920x1080"
elif myObj["target"] == "midlefttop":
myCmd = "xrandr --output " + mon2 + " --primary --auto --mode 1920x1080 --output " + mon3 + " --auto --right-of " + mon2 + " --mode 1920x1080 --output " + mon1 + " --auto --left-of " + mon2 + " --mode 1920x1080 --output " + mon4 + " --off"
elif myObj["target"] == "build":
myCmd = "xrandr --output " + mon2 + " --off --output " + mon3 + " --off --output " + mon1 + " --off --output " + mon4 + " --auto --mode 1920x1080"
else:
pass
writeLog(myCmd)
if myCmd != "":
print(myCmd)
writeLog("Executing : {myCmd}")
writeLog("Executing")
#subprocess.Popen(myCmd.split())
for i in [1,2,3]:
status, output = subprocess.getstatusoutput(myCmd)
writeLog(output)
writeLog(status)
time.sleep(1)
status, output = subprocess.getstatusoutput(myCmd)
writeLog(output)
writeLog(status)
if myObj["cmd"] == "display2":
# os.startfile(sys.argv[0])
#sys.exit()
@@ -848,11 +850,10 @@ def on_message(client, userdata, msg):
subprocess.Popen(['/usr/bin/xrandr'])
if myObj["cmd"] == "suspend":
writeLog("suspending")
print("suspending")
if curos == "Windows":
if host == "amd" or host == "amd1" or host == "morefine":
#os.system("shutdown /s /t 1")
os.system("shutdown /h")
if host == "amd" or host == "amd1":
os.system("shutdown /s /t 1")
else:
os.system("rundll32.exe powrprof.dll,SetSuspendState 0,1,0")
#cmnd = "psshutdown -d -t 1"
@@ -862,24 +863,16 @@ def on_message(client, userdata, msg):
#writeLog(output)
else:
if host == "nas" or host == "octopi":
cmnd = "/sbin/poweroff"
elif host in ["openmediavault", "omv","amd","rack"]:
cmnd = "poweroff"
elif host == "amd" or host == "ryzen":
cmnd = "systemctl suspend"
subprocess.Popen(["/sbin/poweroff"])
elif host == "openmediavault" or host == "omv":
subprocess.Popen(["poweroff"])
else:
#subprocess.Popen(["/bin/systemctl", "suspend", "-i"])
#subprocess.Popen(["sudo", "pm-suspend"])
cmnd = "pm-suspend"
writeLog(cmnd)
#subprocess.Popen(cmnd)
status, output = subprocess.getstatusoutput(cmnd)
print(output)
print(status)
status, output = subprocess.getstatusoutput(cmnd)
print(output)
print(status)
if myObj["cmd"] == "stats":
grep = subprocess.Popen(['grep', 'cpu', '/proc/stat'],
stdout=subprocess.PIPE,
@@ -926,7 +919,6 @@ def on_message(client, userdata, msg):
client.publish("sectorq/status/" + host, payload=jn, qos=0, retain=False)
except:
print("not a json!")
print(msg.payload)
client = mqtt.Client()
payload = '{"status": "off"}'
@@ -935,15 +927,7 @@ client.will_set("home-assistant/" + host.lower() + "/hwstats", payload=payload,
client.on_connect = on_connect
client.on_message = on_message
writeLog(MQTT_HOST)
connected = False
while not connected:
try:
client.connect(MQTT_HOST, MQTT_PORT, 25)
connected = True
except:
writeLog("Failed to connect repeating...")
time.sleep(10)
client.connect(MQTT_HOST, MQTT_PORT, 25)
# client.publish("sectorq/status", payload="{'action':'connect', 'system':'" + host + "', 'ip': '" + IP + "', 'mac':'" + mac + "', 'ver':'?'}", qos=0, retain=False)
@@ -970,18 +954,21 @@ def checkIfProcessRunning(processName):
if curos == "Windows":
print("WINDOWS")
#client.loop_forever()
client.loop_start()
NEXT_CHECK = 0
while True:
print("Version: {}".format(VERSION))
time.sleep(5)
try:
mtime = os.path.getmtime(sys.argv[0])
except OSError:
mtime = 0
print(mtime)
if NEXT_CHECK < int(time.time()):
NEXT_CHECK = int(time.time()) + 10
writeLog("Blalala : Next : " + str(NEXT_CHECK))
if curos == "Windows":
if checkIfProcessRunning("aida64.exe"):
aide_refs = {
@@ -998,6 +985,8 @@ if curos == "Windows":
#ks = ["TCPU", "TPCHDIO", "SMEMUTI", "SVIRTMEMUTI", "SCPUUTI", "FCPU", "TGPU1DIO", "SGPU1BIUTI"]
path = winreg.HKEY_CURRENT_USER
try:
key = winreg.OpenKeyEx(path, r"SOFTWARE\\FinalWire\\AIDA64\\SensorValues")
@@ -1044,29 +1033,8 @@ if curos == "Windows":
client.publish("sectorq/systems/" + host.lower() + "/stat", payload="on", qos=0, retain=True)
#print(json.dumps(stats))
#writeLog(json.dumps(stats))
writeLog(FILE_TIMESTAMP)
writeLog(mtime)
#writeLog(sys.argv[0])
if FILE_TIMESTAMP != mtime:
writeLog("Script updated ! restarting...")
#os.execv(sys.executable, ['python'] + sys.argv)
#os.system("/share/ZFS530_DATA/.qpkg/QPython39/bin/python3 mqtt_srv.py")
if host.lower() == "morefine":
mycmd = 'powershell -w h -command Start-ScheduledTask -TaskName "jaydee\\restart_mqtt_srv"'
writeLog(mycmd)
status,output = subprocess.Popen(mycmd.split(),shell=True)
if host.lower() == "router" or host.lower() == "omv":
#sys.stdout.flush()
#os.execv(sys.argv, "")
print("argv was",sys.argv)
print("sys.executable was", sys.executable)
print("restart now")
os.execv(sys.executable, ['python3'] + sys.argv)
#os.startfile(sys.argv[0])
sys.exit()
else:
print("Linux")
client.loop_start()
NEXT_CHECK = 0
@@ -1075,50 +1043,20 @@ else:
time.sleep(5)
try:
mtime = os.path.getmtime(sys.argv[0])
writeLog(sys.argv[0])
except OSError:
mtime = 0
#print(mtime)
if NEXT_CHECK < int(time.time()):
NEXT_CHECK = int(time.time()) + 20
#writeLog("Blalala : Next : " + str(NEXT_CHECK))
if host.lower() == "rpi5":
#writeLog("Blalala : AAA")
writeLog("Blalala : Next : " + str(NEXT_CHECK))
if host.lower() == "asus":
print(psutil.sensors_temperatures())
#print(psutil.sensors_fans())
sences = psutil.sensors_temperatures()
print("SENCES")
print(sences)
print("#"*40)
try:
cpu_data = sences["cpu_thermal"][0]
except:
try:
cpu_data = sences["k10temp"][0]
except:
cpu_data = "None"
writeLog(cpu_data)
print("CPUDATA")
print(cpu_data)
print("#"*40)
print("MBDATA")
try:
mb_data = sences["acpitz"][0]
print(mb_data)
print(mb_data.current)
mb_data = mb_data.current
except:
mb_data = 0
print("#"*40)
try:
print(psutil.sensors_fans())
fan_data = psutil.sensors_fans()["pwmfan"][0].current
except:
fan_data = "None"
cpu_data = sences["coretemp"][0]
mb_data = sences["acpitz"][0]
fan_data = psutil.sensors_fans()["asus"][0]
mem_data = psutil.virtual_memory()
swap_data = psutil.swap_memory()
#cpu_usage = psutil.cpu_percent(interval=1)
@@ -1139,68 +1077,7 @@ else:
#print(str(jn1["coretemp-isa-0000"]["Package id 0"]["temp1_input"]))
#print(str(jn1["asus-isa-0000"]["cpu_fan"]["fan1_input"]))
#client.publish("sectorq/monitor/" + host.lower(), payload="{\"mb_temp\":0,\"mem_usage\":0,\"cpu_temp\":0,\"cpu_usage\":0,\"gpu_temp\":0,\"gpu_usage\":0}", qos=0, retain=False)
writeLog('{"status":"on", "version":"' + VERSION + '","TCPU":"NA", "MB_TEMP":' + str(mb_data) + ', "MEM_UTIL":' + str(mem_data.percent) + ', "CPU_TEMP":' + str(cpu_data.current) + ', "GPU_TEMP":0, "GPU_UTIL":0, "FAN_CPU":"' + str(fan_data) + '", "VMEM_UTIL":' + str(swap_data.percent) + ', "CPU_UTIL":' + str(cpu_usage) + '}')
client.publish("home-assistant/" + host + "/hwstats", payload='{"status":"on", "version":"' + VERSION + '","TCPU":"NA", "MB_TEMP":' + str(mb_data) + ', "MEM_UTIL":' + str(mem_data.percent) + ', "CPU_TEMP":' + str(cpu_data.current) + ', "GPU_TEMP":0, "GPU_UTIL":0, "FAN_CPU":"' + str(fan_data) + '", "VMEM_UTIL":' + str(swap_data.percent) + ', "CPU_UTIL":' + str(cpu_usage) + '}', qos=0, retain=False)
client.publish("sectorq/systems/" + host.lower() + "/stat", payload="on", qos=0, retain=True)
if host.lower() == "asus" or host.lower() == "m-server" or host.lower() == "morefine" or host.lower() == "ryzen" or host.lower() == "amd" or host.lower() == "rack":
#writeLog("Blalala : AAA")
print(psutil.sensors_temperatures())
#print(psutil.sensors_fans())
sences = psutil.sensors_temperatures()
print("SENCES")
print(sences)
print("#"*40)
try:
cpu_data = sences["coretemp"][0]
except:
try:
cpu_data = sences["k10temp"][0]
except:
cpu_data = "None"
writeLog(cpu_data)
print("CPUDATA")
print(cpu_data)
print("#"*40)
print("MBDATA")
try:
mb_data = sences["acpitz"][0]
print(mb_data)
print(mb_data.current)
mb_data = mb_data.current
except:
mb_data = 0
print("#"*40)
try:
print(psutil.sensors_fans())
fan_data = psutil.sensors_fans()["asus"][0].current
except:
fan_data = "None"
mem_data = psutil.virtual_memory()
swap_data = psutil.swap_memory()
#cpu_usage = psutil.cpu_percent(interval=1)
load1, load5, load15 = psutil.getloadavg()
cpu_usage = round((load1/os.cpu_count()) * 100, 1)
print(mem_data)
print(mem_data.percent)
print(psutil.disk_usage('/'))
#print(psutil.virtual_memory())
#print(dict(psutil.virtual_memory()._asdict()))
#cmnd = "sensors -j|grep -v \"Can't read\""
#status, output = subprocess.getstatusoutput(cmnd)
#print(output)
#print(type(output))
#jn1 = json.loads(output)
#print(str(jn1["coretemp-isa-0000"]["Package id 0"]["temp1_input"]))
#print(str(jn1["asus-isa-0000"]["cpu_fan"]["fan1_input"]))
#client.publish("sectorq/monitor/" + host.lower(), payload="{\"mb_temp\":0,\"mem_usage\":0,\"cpu_temp\":0,\"cpu_usage\":0,\"gpu_temp\":0,\"gpu_usage\":0}", qos=0, retain=False)
writeLog('{"status":"on", "version":"' + VERSION + '","TCPU":"NA", "MB_TEMP":' + str(mb_data) + ', "MEM_UTIL":' + str(mem_data.percent) + ', "CPU_TEMP":' + str(cpu_data.current) + ', "GPU_TEMP":0, "GPU_UTIL":0, "FAN_CPU":"' + str(fan_data) + '", "VMEM_UTIL":' + str(swap_data.percent) + ', "CPU_UTIL":' + str(cpu_usage) + '}')
client.publish("home-assistant/" + host + "/hwstats", payload='{"status":"on", "version":"' + VERSION + '","TCPU":"NA", "MB_TEMP":' + str(mb_data) + ', "MEM_UTIL":' + str(mem_data.percent) + ', "CPU_TEMP":' + str(cpu_data.current) + ', "GPU_TEMP":0, "GPU_UTIL":0, "FAN_CPU":"' + str(fan_data) + '", "VMEM_UTIL":' + str(swap_data.percent) + ', "CPU_UTIL":' + str(cpu_usage) + '}', qos=0, retain=False)
client.publish("home-assistant/" + host + "/hwstats", payload='{"status":"on", "version":"' + VERSION + '","MB_TEMP":' + str(mb_data.current) + ', "MEM_UTIL":' + str(mem_data.percent) + ', "CPU_TEMP":' + str(cpu_data.current) + ', "GPU_TEMP":0, "GPU_UTIL":0, "FAN_CPU":' + str(fan_data.current) + ', "VMEM_UTIL":' + str(swap_data.percent) + ', "CPU_UTIL":' + str(cpu_usage) + '}', qos=0, retain=False)
client.publish("sectorq/systems/" + host.lower() + "/stat", payload="on", qos=0, retain=True)
elif host.lower() == "openmediavault" or host.lower() == "omv":
#print(psutil.sensors_temperatures())
@@ -1218,7 +1095,7 @@ else:
print("CPU Util : {}".format(cpu_usage))
print(mem_data)
print(mem_data.percent)
raid_data = psutil.disk_usage('/srv/dev-disk-by-uuid-2f843500-95b6-43b0-bea1-9b67032989b8')
raid_data = psutil.disk_usage('/srv/dev-disk-by-uuid-02fbe97a-cd9a-4511-8bd5-21f8516353ee')
#print(psutil.virtual_memory())
#print(dict(psutil.virtual_memory()._asdict()))
#cmnd = "sensors -j|grep -v \"Can't read\""
@@ -1242,14 +1119,13 @@ else:
#print(str(jn1["coretemp-isa-0000"]["Package id 0"]["temp1_input"]))
#print(str(jn1["asus-isa-0000"]["cpu_fan"]["fan1_input"]))
#client.publish("sectorq/monitor/" + host.lower(), payload="{\"mb_temp\":0,\"mem_usage\":0,\"cpu_temp\":0,\"cpu_usage\":0,\"gpu_temp\":0,\"gpu_usage\":0}", qos=0, retain=False)
client.publish("home-assistant/" + host + "/hwstats", payload='{"status":"on", "version":"' + VERSION + '","reboot":"' + str(reboot_pending) + '", "uptime":"' + str(sys_uptime) + '", "raid_usage": ' + str(disk_usage) + ',"rsync":"' + str(stat_rsync) +'", "MB_TEMP":' + str(mb_data.current) + ', "MEM_UTIL":' + str(mem_data.percent) + ', "CPU_TEMP":' + str(cpu_data.current) + ', "GPU_TEMP":0, "GPU_UTIL":0, "FAN_CPU":0, "VMEM_UTIL":' + str(swap_data.percent) + ', "CPU_UTIL":' + str(cpu_usage) + '}', qos=0, retain=False)
writeLog("lalal")
client.publish("home-assistant/" + host + "/hwstats", payload='{"version":"' + VERSION + '","reboot":"' + str(reboot_pending) + '", "uptime":"' + str(sys_uptime) + '", "raid_usage": ' + str(disk_usage) + ',"rsync":"' + str(stat_rsync) +'", "MB_TEMP":' + str(mb_data.current) + ', "MEM_UTIL":' + str(mem_data.percent) + ', "CPU_TEMP":' + str(cpu_data.current) + ', "GPU_TEMP":0, "GPU_UTIL":0, "FAN_CPU":0, "VMEM_UTIL":' + str(swap_data.percent) + ', "CPU_UTIL":' + str(cpu_usage) + '}', qos=0, retain=False)
elif host.lower() == "router":
check_router()
elif host.lower() == "nas":
#print("Getting VM info")
payload = {"status":"on"}
cmnd = "/share/ZFS532_DATA/.qpkg/QKVM/usr/bin/virsh list --all"
print("Getting VM info")
cmnd = "/share/ZFS530_DATA/.qpkg/QKVM/usr/bin/virsh list --all"
writeLog(cmnd)
status, output = subprocess.getstatusoutput(cmnd)
l = 1
@@ -1260,26 +1136,24 @@ else:
if l < 4:
continue
line = re.split(r" {2,}", i)
writeLog(str(line[0].strip()) + " " + str(line[1].strip()) + " " + str(line[2].strip()))
print(str(line[0].strip()) + " " + str(line[1].strip()) + " " + str(line[2].strip()))
VMS[str(line[1].strip())] = str(line[2].strip())
for m in VMS:
cmnd = "/share/ZFS532_DATA/.qpkg/QKVM/usr/bin/virsh domstate " + m
cmnd = "/share/ZFS530_DATA/.qpkg/QKVM/usr/bin/virsh domstate " + m
#out = subprocess.Popen(cmnd.split())
writeLog(cmnd)
status, output = subprocess.getstatusoutput(cmnd)
writeLog(output)
if output.strip() == "running":
payload[m] = 1
client.publish("sectorq/systems/nas/" + m, payload=1, qos=0, retain=True)
else:
payload[m] = 0
client.publish( "home-assistant/" + host + "/hwstats", payload=json.dumps(payload), qos=0, retain=True)
client.publish("sectorq/systems/nas/" + m, payload=0, qos=0, retain=True)
writeLog(FILE_TIMESTAMP)
writeLog(mtime)
if FILE_TIMESTAMP != mtime:
writeLog("Script updated ! restarting...")
#os.execv(sys.executable, ['python'] + sys.argv)

File diff suppressed because it is too large Load Diff

View File

@@ -1,15 +0,0 @@
[Unit]
Description=ROT13 demo service
Wants=network-online.target
After=network.target network-online.target
[Service]
Type=simple
User=root
Environment=XAUTHORITY=/home/jd/.Xauthority
Environment=DISPLAY=:0
#ExecStartPre=/bin/sleep 30
ExecStart=/myapps/mqtt_srv/venv/bin/python3 /myapps/mqtt_srv/mqtt_srv.py
[Install]
WantedBy=multi-user.target suspend.target hibernate.target hybrid-sleep.target suspend-then-hibernate.target

View File

@@ -1,28 +0,0 @@
#!/bin/bash
THIS_HOST=`uname -n`
case $1 in
"start")
echo "`date` : Starting service" >> /tmp/mqtt_srv.log
if [ "$THIS_HOST" == "nas" ]
then
echo "$?" >> /tmp/mqtt_srv.log
/share/Data/python/bin/python3 /usr/bin/mqtt_srv.py > /dev/null 2>&1 &
echo "$?" >> /tmp/mqtt_srv.log
else
python3 /jffs/scripts/mqtt_srv/mqtt_srv.py > /dev/null 2>&1 &
fi
cp /share/Data/nas_bash_history /root/.bash_history
;;
"stop")
echo lala1 >> /tmp/mqtt_srv.log
kill -9 `ps |grep -e "mqtt_srv.py"|grep -v grep|awk '{ print $1}'`
cp /root/.bash_history /share/Data/nas_bash_history
;;
"restart")
$0 stop
$0 start
;;
"status")
ps |grep -e "mqtt_srv.py"|grep -v grep
;;
esac

View File

@@ -1,44 +0,0 @@
# -*- mode: python ; coding: utf-8 -*-
block_cipher = None
a = Analysis(
['mqtt_srv.pyw'],
pathex=[],
binaries=[],
datas=[],
hiddenimports=[],
hookspath=[],
hooksconfig={},
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher,
noarchive=False,
)
pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)
exe = EXE(
pyz,
a.scripts,
a.binaries,
a.zipfiles,
a.datas,
[],
name='mqtt_srv',
debug=False,
bootloader_ignore_signals=False,
strip=False,
upx=True,
upx_exclude=[],
runtime_tmpdir=None,
console=True,
disable_windowed_traceback=False,
argv_emulation=False,
target_arch=None,
codesign_identity=None,
entitlements_file=None,
)

View File

@@ -1,6 +1,5 @@
ping3
requests
getmac
paho-mqtt<2.0.0
paho-mqtt
autorandr
psutil