Python script boot - Debian - python

I'm a trying to start a program at boot but without success.
The program starts well but doesn't stay alive (it is supposed to be a infinite script).
But when I start the program normally I don't have any problem! I don't get why when I run at reboot it doesn't work.
I use a cron tab like this:
#reboot sudo python /bin/gestion.py &
I can show you my code:
import Adafruit_BBIO.GPIO as GPIO
import Adafruit_BBIO.PWM as PWM
import time
import socket
import threading
import sys
from os.path import expanduser
import datetime
print("DEBUT")
vitesse = 4
etat_moteur_droit = 0
etat_moteur_gauche = 0
data_thr = "Starting"
etat_thr = 1
HOST = '192.168.1.50' # Standard loopback interface address (localhost)
PORT = 65432 # Port to listen on (non-privileged ports are > 1023)
file = open('/home/log.txt', 'w')
file.write("It worked!\n" + str(datetime.datetime.now()))
file.close()
print("MID")
def main():
global data_thr
global etat_thr
global etat_moteur_droit
global etat_moteur_gauche
global vitesse
print("START")
etat_moteur_droit=0
setup_io()
# gestion_bonus(0)
# gestion_moteur_droit(4,0)
# gestion_moteur_gauche(4,0)
# avancer()
# time.sleep(3)
# tourner_a_gauche()
# time.sleep(3)
# tourner_a_droite()
# time.sleep(3)
# arreter()
x = threading.Thread(target=thread_serveur)
x.start()
while True:
try:
data_thr = data_thr.partition('\n')[0]
if(data_thr == ""):
etat_thr = 0
if(data_thr == "Fin thread"):
x = threading.Thread(target=thread_serveur)
x.start()
data_thr = "Fin thread step 2"
if(data_thr == "avance"):
avancer()
if(data_thr == "stop"):
arreter()
if(data_thr == "gauche"):
tourner_a_gauche()
if(data_thr == "droite"):
tourner_a_droite()
if(data_thr[:7] == "vitesse"):
vitesse = int(data_thr[8:10])
if(etat_moteur_droit == 1):
PWM.set_duty_cycle("P9_14", vitesse)
if(etat_moteur_gauche == 1):
PWM.set_duty_cycle("P8_19", vitesse)
except:
print("Erreur lors de reception message")
print("FIN")
file = open('/home/log.txt', 'w')
file.write("FIN!\n" + str(datetime.datetime.now()))
file.close()
def thread_serveur():
global data_thr
global etat_thr
connected = 0
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
while connected == 0:
try :
s.bind((HOST, PORT))
except socket.error:
pass
finally:
connected = 1
s.listen(1)
conn, addr = s.accept()
print('Connected by', addr)
timing = 0
start = time.time()
while etat_thr == 1:
try:
data_thr = conn.recv(1024)
if not data_thr:
break
if data_thr != "":
print(data_thr)
conn.sendall("Bien recu")
except:
print("Erreur lecture thread")
s.shutdown(socket.SHUT_RDWR)
s.close()
data_thr = "Fin thread"
def setup_io():
GPIO.setup("P9_17", GPIO.OUT)
GPIO.setup("P9_24", GPIO.OUT)
GPIO.setup("P9_23", GPIO.OUT)
PWM.start("P9_14", 0)
PWM.stop("P9_14")
PWM.start("P8_19", 0)
PWM.stop("P8_19")
PWM.cleanup()
def gestion_bonus(etat):
if(etat == 1):
GPIO.output("P9_17", GPIO.HIGH)
else:
GPIO.output("P9_17", GPIO.LOW)
GPIO.cleanup()
def gestion_moteur_droit(vitesse,enable):
global etat_moteur_droit
if(enable == 1 and etat_moteur_droit == 0):
PWM.start("P9_14", vitesse)
GPIO.output("P9_24",GPIO.HIGH)
etat_moteur_droit = 1
elif(enable == 1 and etat_moteur_droit == 1):
PWM.set_duty_cycle("P9_14", vitesse)
GPIO.output("P9_24",GPIO.HIGH)
elif(enable == 0):
PWM.stop("P9_14")
GPIO.output("P9_24",GPIO.LOW)
etat_moteur_droit =0
GPIO.cleanup()
def gestion_moteur_gauche(vitesse,enable):
global etat_moteur_gauche
if(enable == 1 and etat_moteur_gauche == 0):
PWM.start("P8_19", vitesse)
GPIO.output("P9_23",GPIO.HIGH)
etat_moteur_gauche = 1
elif(enable == 1 and etat_moteur_gauche == 1):
PWM.set_duty_cycle("P8_19", vitesse)
GPIO.output("P9_23",GPIO.HIGH)
elif(enable == 0):
PWM.stop("P8_19")
GPIO.output("P9_23",GPIO.LOW)
etat_moteur_gauche =0
GPIO.cleanup()
def avancer():
global vitesse
gestion_moteur_droit(vitesse,1)
gestion_moteur_gauche(vitesse,1)
def tourner_a_gauche():
global vitesse
gestion_moteur_droit(vitesse,1)
gestion_moteur_gauche(vitesse,0)
def tourner_a_droite():
global vitesse
gestion_moteur_droit(vitesse,0)
gestion_moteur_gauche(vitesse,1)
def arreter():
global vitesse
gestion_moteur_droit(vitesse,0)
gestion_moteur_gauche(vitesse,0)
if __name__ == "__main__":
main()
Can you help me please?

As I can see you are using some network service. Maybe when the cron run at #reboot, the network is not ready yet. It may worth a try to implement as service and run command on that way.
Example implementation
Create a file where the system daemon services can be found, e.g.: /lib/systemd/system/TestStartup.service. Example for content of member:
[Unit]
Description=Test service for startup
After=network.target
[Service]
User=root
ExecStart=/usr/bin/python /bin/gestion.py
Restart=on-failure
RestartSec=30
[Install]
WantedBy=multi-user.target
/usr/bin/pythn can be different as which version you are using and where it is installed on your machine, but you can check by whereis python command output:
ati#atihome:/lib/systemd/system$ whereis python
python: /usr/bin/python2.7 /usr/bin/python /usr/bin/python3.7 /usr/bin/python3.7m /usr/lib/python2.7 /usr/lib/python3.7 /etc/python2.7 /etc/python /etc/python3.7 /usr/local/lib/python2.7 /usr/local/lib/python3.7 /usr/share/python /usr/share/man/man1/python.1.gz
Then you need to reload system daemon and enable this service to allow to run after system startup. This service will start after Network is up. You can do by these commands:
systemctl daemon-reload
systemctl enable TestStartup (or how you named your member)
You can test, that start command is proper by this command:
systemctl start TestStartup
And check its status by this command:
systemctl status TestStartup
Then you can reboot the computer and check that it worked. I don't say that is is your solution for 100% but it may worth a try.

Related

How to start a new python script without ending the other one

I want to be able to open a new python script in a new terminal, without ending the other.
Im trying to create a server with one script dishing out all the clients to new scripts, but it wont work if the other script is ended.
is there a way to fix this?
here are some of my code
starter:
import socket; import time
import os
def clear():
os.system('cls' if os.name == 'nt' else 'clear')
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ip = socket.gethostbyname(socket.gethostname())
print(ip, "thats da ip")
port = 8080
print(port, "da port")
s.bind((ip, port))
print("binded")
def idk():
s.listen(1)
c, a = s.accept()
print(f"connection from {a}")
print("authenticating")
time.sleep(1)
g = c.recv(300).decode("utf-8")
if g == ">><<":
print("accepted")
time.sleep(3)
print("starting script")
time.sleep(2)
clear()
os.system("main.py")
print("script started")
while True:
e = open("connection_script", "r")
p = e.read()
e.close()
if p == "":
pass
else:
print(f"port is {p}")
print("sending port")
c.sendall(bytes(p, "utf-8"))
print("ending...")
time.sleep(2)
s.close()
else:
print("failed to pass")
time.sleep(1)
clear()
c, a = None
pass
idk()
the other script:
file_list = ">file<list<"
connection = "connection_script"
import time
import os
import socket
def_size = 0
req_size = 900
lv1_size = 1200
admin_size = 10000000000
wait_time = 1
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ip = socket.gethostbyname(socket.gethostname())
print(f"ip = {ip}")
time.sleep(1)
print("finding open port")
j = 0
while True:
j+=1
print(j)
try:
s.bind((ip, j))
port = j
break
except:
print("failed")
time.sleep(1)
def clear():
os.system('cls' if os.name == 'nt' else 'clear')
clear()
time.sleep(2)
print(f"port is {port}")
time.sleep(2)
clear()
print("opening connection for client")
time.sleep(1)
s.listen(1)
clear()
e = open(connection, "w")
e.write(str(port))
e.close()
time.sleep(0.1)
print("conection for client open")
time.sleep(wait_time)
e = open(connection, "w")
e.write("")
e.close()
c, a = s.accept()
print(f"connection made by {a}, conn is {c}")
time.sleep(1)
e = open("_file_list_", "r")
p = e.read()
e.close()
s.sendall(bytes(p, "utf-8"))
the client im using:
import socket
import time
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ip = "192.168.1.65"
port = 8080
s.connect((ip, port))
s.sendall(bytes(">><<", "utf-8"))
b = s.recv(300)
print(b)
s.close()
s.connect((ip, b))
while True:
print(s.recv(3000))
s.sendall(bytes(input(), "utf-8"))
Yo man if u r using PyCharm do this :
right click on the server script and press run
then go to the client script and press run
they should be running together
if u want to run multiple client scripts then in the "run" terminal on the left hand side there would be icons click the second one which states "modify run configurations"(only if u hover on it)
after clicking it on the right hand side of the "name" field there should be a checkbox which states "allow parrell run" ,click on that
now u will b able to run many client files at the same time
if u DONT have Pycharm do this(windows) :
go in the directry where u have saved ur files
press Shift+Right
there would be an option of open powershell here click that
then write "python "
and do the same thing for the other files
WORKS ONLY FOR PYTHON!!!!!!
If you are using windows you can open multiple "windows command prompt" and if you are using linux based os you can open multiple "Terminals".

Python version of Netcat (follow-up question)

This question is a follow-up of this topic.
The OP was very likely encountering "Connection Refused". I'm facing it now with the same
code:
#!/usr/bin/env python3
import sys, socket, subprocess, threading, getopt
listen = False
upload = False
command = False
execute = ''
target = ''
upload_dest = ''
port = 0
USAGE = '''
BHP Net Tool
Usage: bhpnet.py -t target_host -p port
-l --listen - listen on [host]:[port] for incoming
connections
-e --execute=file_to_run - execute the given file upon receiving
a connection
-c --command - initialize a command shell
-u --upload=destination - upon receiving connection upload a file
and write to [destination]
Examples:
bhpnet.py -t 192.168.0.1 -p 5555 -l -c
bhpnet.py -t 192.168.0.1 -p 5555 -l -u=c:\\target.exe
bhpnet.py -t 192.168.0.1 -p 5555 -l -e=\"cat /etc/passwd\"
echo "ABCDEF" | ./bhpnet.py -t 192.168.11.12 -p 135
'''
def usage():
print(USAGE)
sys.exit(0)
def main():
global listen
global port
global execute
global command
global upload_dest
global target
if not len(sys.argv[1:]):
usage()
try:
opts, args = getopt.getopt(sys.argv[1:], 'hle:t:p:cu:',['help','listen',
'execute','target','port','command','upload'])
except getopt.GetoptError as err:
print(str(err))
usage()
for o, a in opts:
if o in ('-h', '--help'):
usage()
elif o in ('-l', '--listen'):
listen = True
elif o in ('-e', '--execute'):
execute = a
elif o in ('-c', '--commandshell'):
command = True
elif o in ('-u', '--upload'):
upload_dest = a
elif o in ('-t', '--target'):
target = a
elif o in ('-p', '--port'):
port = int(a)
else:
assert False, 'Unhandled Option'
if not listen and len(target) and port > 0:
buffer = sys.stdin.read()
client_sender(buffer)
if listen:
server_loop()
def client_sender(buffer):
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
client.connect((target, port))
if len(buffer):
client.send(buffer)
while True:
recv_len = 1
response = ''
while recv_len:
data = client.recv(4096)
recv_len = len(data)
response += data
if recv_len < 4096:
break
print(response)
buffer = input('')
buffer += '\n'
client.send(buffer)
except Exception as e:
print(e) # here it prints out "Connection Refused"
print('[*] Exception ! Exiting ...')
client.close()
def server_loop():
global target
if not len(target):
target = '0.0.0.0'
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((target, port))
server.listen(5)
while True:
client_socket, addr = server.accept()
client_thread = threading.Thread(target=client_handler, args=(client_socket,))
client_thread.start()
def run_command(command):
command = command.rstrip()
try:
output = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True)
except:
output = 'Failed to execute command.\r\n'
return output
def client_handler(client_socket):
global upload
global execute
global command
if len(upload_dest):
file_buffer = ''
while True:
data = client_socket.recv(1024)
if not data:
break
else:
file_buffer += data
try:
with open(upload_dest, 'wb') as file_descriptor:
file_descriptor.write(file_buffer)
client_socket.send(b'Successfully saved file to {}.'.format(upload_dest))
except:
client_socket.send(b'Failed to save file to {}'.format(upload_dest))
if len(execute):
output = run_command(execute)
client_socket.send(output)
if command:
while True:
client_socket.send(b'<BHP:#> ')
cmd_buffer = ''
while '\n' not in cmd_buffer:
cmd_buffer += client_socket.recv(1024)
response = run_command(cmd_buffer)
client_socket.send(response)
main()
I'd like to ask more experienced network professsional why it could possibly throw "Connection Refused" if the port 9999 is open and firewall isn't blocking it ?
Running it like this:
server-side: ./netcat_repl.py -l -p 9999 -c
client-side: ./netcat_repl.py -t localhost -p 9999

python program stops after wifi connection discontinuity

I started learning Python two months ago and I have written a code for a Raspberry pi project. My problem is that the program stucks after some hours of operation. I think that in all cases, it stopped after some wifi connection drops. But I don't understand why the whole program stops if there something wrong with the wifi connection. It stops uploading values and renew the lcd screen messages it prints (I removed this and other stuff from the code in order to be more easy to read.)
The code starts at the startup (sudo python /home/pi/test.py &) and contains two Threads:
The "Control" thread reads temperature and humidity by using an i2c bus and a sensor am2315 and according to a temperature threshold, controls a relay through GPIO.
The "Thingspeak" thread reads the temperature threshold from a 'Thingspeak' channel and then uploads the measurements from the previous thread to 'Thingspeak'.
I really don't know what to do and how to search for any solutions.
Any help will be much appreciated.
#! /usr/bin/env python
from time import sleep
import datetime
import urllib2
import RPi.GPIO as GPIO
import threading
import smbus
from tentacle_pi.AM2315 import AM2315
import smtplib
import contextlib
sleep(120)
# Lock
tLock = threading.Lock()
# Global variables
tem_global = 0; hum_global = 0
tem_hi = 35; relay = 21
# GPIO setup
GPIO.setmode(GPIO.BCM)
GPIO.setup(relay, GPIO.OUT)
GPIO.output(relay, False)
sleep(1)
def Control():
global temg, humg, tem_hi, relay
# AM2315 setup
am = AM2315(0x5c,"/dev/i2c-1")
I2C_address = 0x70; I2C_bus_number = 1; i2c_channel_setup = 1
bus = smbus.SMBus(I2C_bus_number)
bus.write_byte(I2C_address, i2c_channel_setup)
sleep(1)
while True:
try:
tem_local, hum_local = am2315meas()
except:
tem_local = -1; hum_local = -1
tLock.acquire()
tem_global = tem_local; hum_global = hum_local
if tem_local < tem_hi:
GPIO.output(relay, True)
else:
GPIO.output(relay, False)
tLock.release()
sleep(150)
def Thingspeak():
global tem_global, hum_global, tem_hi
myAPI = "..."
channelID = "..."
baseURL = 'https://api.thingspeak.com/update?api_key=%s' % myAPI
while True:
sleep(30)
try:
# Reading value from thingspeak
tLock.acquire()
with contextlib.closing(urllib2.urlopen("https://api.thingspeak.com/channels/%s/fields/1/last?" % channelID)) as f_read:
tem_hi = float(fread.read())
t.Lock.release()
sleep(30)
# Uploading values to thingspeak
tLock.acquire()
with contextlib.closing(urllib2.urlopen(baseURL + "&field1=%s" % tem_global + "&field2=%s" % hum_global)) as f_upload:
pass
tLock.release()
except:
with open('/home/pi/errors.txt', mode='a') as file:
file.write('Network error recorded at %s.\n' % datetime.datetime.now())
file.close()
sleep(60)
continue
def Main():
t1 = threading.Thread(target=Thingspeak)
t2 = threading.Thread(target=Control)
t1.start()
t2.start()
t1.join()
t2.join()
GPIO.cleanup()
if __name__ == '__main__':
Main()
Problem solved. As James K Polk indicated, there was an error after the tLock.acquire(), every time the internet connection went off, causing deadlock of the program. Below is a corrected part of the code for anyone would be interested.
def Control():
global tem_global, hum_global, tem_hi, relay
# AM2315 setup
am = AM2315(0x5c,"/dev/i2c-1")
I2C_address = 0x70; I2C_bus_number = 1; i2c_channel_setup = 1
bus = smbus.SMBus(I2C_bus_number)
bus.write_byte(I2C_address, i2c_channel_setup)
sleep(1)
while True:
try:
tem_local, hum_local = am2315meas()
except:
tem_local = -1; hum_local = -1
with tLock:
tem_global = tem_local; hum_global = hum_local
if tem_local < tem_hi:
GPIO.output(relay, True)
else:
GPIO.output(relay, False)
sleep(150)
def Thingspeak():
global tem_global, hum_global, tem_hi
myAPI = "..."
channelID = "..."
baseURL = 'https://api.thingspeak.com/update?api_key=%s' % myAPI
while True:
sleep(30)
try:
# Reading value from thingspeak
with tLock:
with contextlib.closing(urllib2.urlopen("https://api.thingspeak.com/channels/%s/fields/1/last?" % channelID)) as f_read:
tem_hi = float(fread.read())
sleep(30)
# Uploading values to thingspeak
with tLock:
with contextlib.closing(urllib2.urlopen(baseURL + "&field1=%s" % tem_global + "&field2=%s" % hum_global)) as f_upload:
pass
except:
with open('/home/pi/errors.txt', mode='a') as file:
file.write('Network error recorded at %s.\n' % datetime.datetime.now())
sleep(60)
continue

Python socket OSError: [Errno 22] Invalid argument when closed

I'm struggling to gracefully close a script when the clients send the "stop" command.
As the script is wrote, it actually exit with the following error:
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner
self.run()
File "/usr/lib/python3.5/threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
File "server.py", line 248, in start_server
conn, addr = soc.accept()
File "/usr/lib/python3.5/socket.py", line 195, in accept
fd, addr = self._accept()
OSError: [Errno 22] Invalid argument
Any suggestion?
#!/usr/bin/python3
#################################################################################
# BLE PRESENCE FOR DOMOTICZ #
# #
# AUTHOR: MARCO BAGLIVO (ITALY) (https://github.com/mydomo) #
# #
#################################################################################
# BLE_SCAN LIBRARY IS A FORK OF https://github.com/flyinactor91/RasPi-iBeacons #
#################################################################################
#################################################################################
# INSTALL REQUIREMENTS ON UBUNTU SERVER 16.04: #
# #
# sudo apt-get install -y libbluetooth-dev bluez #
# sudo apt-get install python-dev python3-dev python3-setuptools python3-pip #
# sudo pip3 install pybluez #
# #
#################################################################################
import socket
from lib import ble_scan
from threading import Thread
import sys
import os
import time
import bluetooth._bluetooth as bluez
import signal
import subprocess
from collections import OrderedDict
##########- CONFIGURE SCRIPT -##########
socket_ip = '0.0.0.0'
socket_port = 12345
min_inval_between_batt_level_readings = 3600
##########- CONFIGURE TRANSLATIONS -##########
lang_SCAN_STOPPED = 'Scanning stopped by other function'
lang_READING_LOCK = 'Reading in progress...'
lang_READING_START = 'Reading started'
##########- START VARIABLE INITIALIZATION -##########
mode = ''
beacons_detected = ''
batt_lev_detected = ''
scan_beacon_data = True
ble_value = ''
devices_to_analize = {}
batt_lev_detected = {}
read_value_lock = False
##########- END VARIABLE INITIALIZATION -##########
##########- START FUNCTION THAT HANDLE CLIENT INPUT -##########
def socket_input_process(input_string):
global mode
global devices_to_analize
global lang_SCAN_STOPPED
global lang_READING_LOCK
global lang_READING_START
###- TRANSMIT BEACON DATA -###
# check if client requested "beacon_data"
if input_string == 'beacon_data':
# if beacon scanning function has being stopped in order to process one other request (ex.: battery level) warn the client
if scan_beacon_data == False:
return str(lang_SCAN_STOPPED)
# if beacon scanning function is active send the data to the client
if scan_beacon_data == True:
# set operative mode to beacon_data
mode = 'beacon_data'
# return beacons_detected ordered by timestamp ASC (tnx to: JkShaw - http://stackoverflow.com/questions/43715921/python3-ordering-a-complex-dict)
# return "just" the last 300 results to prevent the end of the socket buffer (each beacon data is about 45 bytes)
return str(sorted(beacons_detected.items(), key=lambda x: x[1][1], reverse=True)[:300])
###- TRANSMIT BATTERY LEVEL -###
# check if the request start with battery_level:
if input_string.startswith('battery_level:'):
# trim "battery_level:" from the request
string_devices_to_analize = input_string.replace("battery_level: ", "")
# split each MAC address in a list in order to be processed
devices_to_analize = string_devices_to_analize.split(',')
# set operative mode to battery_level
mode = 'battery_level'
# if the reading has already requested and there is no result ask to wait
if not batt_lev_detected and read_value_lock == True:
return str(lang_READING_LOCK)
# if the reading is requested for the first time start say that will start
elif not batt_lev_detected and read_value_lock == False:
return str(lang_READING_START)
# if is present a battery data send it
else:
return str(batt_lev_detected)
###- STOP RUNNING SERVICES -###
if input_string == 'stop':
killer.kill_now = True
print ('service stopping')
return str('Service stopping')
##########- END FUNCTION THAT HANDLE CLIENT INPUT -##########
##########- START FUNCTION THAT HANDLE SOCKET'S TRANSMISSION -##########
def client_thread(conn, ip, port, MAX_BUFFER_SIZE = 32768):
# the input is in bytes, so decode it
input_from_client_bytes = conn.recv(MAX_BUFFER_SIZE)
# MAX_BUFFER_SIZE is how big the message can be
# this is test if it's too big
siz = sys.getsizeof(input_from_client_bytes)
if siz >= MAX_BUFFER_SIZE:
print("The length of input is probably too long: {}".format(siz))
# decode input and strip the end of line
input_from_client = input_from_client_bytes.decode("utf8").rstrip()
res = socket_input_process(input_from_client)
#print("Result of processing {} is: {}".format(input_from_client, res))
vysl = res.encode("utf8") # encode the result string
conn.sendall(vysl) # send it to client
conn.close() # close connection
##########- END FUNCTION THAT HANDLE SOCKET'S TRANSMISSION -##########
def usb_dongle_reset():
process0 = subprocess.Popen("sudo hciconfig hci0 down", stdout=subprocess.PIPE, shell=True)
process0.communicate()
process1 = subprocess.Popen("sudo hciconfig hci0 reset", stdout=subprocess.PIPE, shell=True)
process1.communicate()
process2 = subprocess.Popen("sudo /etc/init.d/bluetooth restart", stdout=subprocess.PIPE, shell=True)
process2.communicate()
process3 = subprocess.Popen("sudo hciconfig hci0 up", stdout=subprocess.PIPE, shell=True)
process3.communicate()
def ble_scanner():
global beacons_detected
dev_id = 0
usb_dongle_reset()
try:
sock = bluez.hci_open_dev(dev_id)
#print ("ble thread started")
except:
print ("error accessing bluetooth device... restart in progress!")
usb_dongle_reset()
ble_scan.hci_le_set_scan_parameters(sock)
ble_scan.hci_enable_le_scan(sock)
beacons_detected = {}
while (scan_beacon_data == True) and (not killer.kill_now):
try:
returnedList = ble_scan.parse_events(sock, 25)
for beacon in returnedList:
MAC, RSSI, LASTSEEN = beacon.split(',')
beacons_detected[MAC] = [RSSI,LASTSEEN]
time.sleep(1)
except:
print ("failed restarting device... let's try again!")
usb_dongle_reset()
dev_id = 0
sock = bluez.hci_open_dev(dev_id)
ble_scan.hci_le_set_scan_parameters(sock)
ble_scan.hci_enable_le_scan(sock)
time.sleep(1)
def read_battery_level():
global scan_beacon_data
global mode
global batt_lev_detected
global read_value_lock
global min_inval_between_batt_level_readings
uuid_to_check = '0x2a19'
time_difference = 0
while (not killer.kill_now):
if mode == 'battery_level' and read_value_lock == False:
read_value_lock = True
#print ("Dispositivi da analizzare: " + str(devices_to_analize))
for device in devices_to_analize:
device_to_connect = device
#print ("Analizzo dispositivo: " + str(device))
# i'm reading the value stored
battery_level_moderator = str(batt_lev_detected.get(device, "Never"))
# cleaning the value stored
cleaned_battery_level_moderator = str(battery_level_moderator.replace("[", "").replace("]", "").replace(" ", "").replace("'", ""))
# assign the battery level and the timestamp to different variables
if cleaned_battery_level_moderator != "Never":
stored_batterylevel, stored_timestamp = cleaned_battery_level_moderator.split(',')
time_difference = int(time.time()) - int(stored_timestamp)
if (int(min_inval_between_batt_level_readings) <= int(time_difference)) or (str(cleaned_battery_level_moderator) == "Never") or (str(stored_batterylevel) == '255'):
scan_beacon_data = False
usb_dongle_reset()
#PUT HERE THE CODE TO READ THE BATTERY LEVEL
try:
handle_ble = os.popen("sudo hcitool lecc --random " + device_to_connect + " | awk '{print $3}'").read()
handle_ble_connect = os.popen("sudo hcitool ledc " + handle_ble).read()
#ble_value = int(os.popen("sudo gatttool -t random --char-read --uuid " + uuid_to_check + " -b " + device_to_connect + " | awk '{print $4}'").read() ,16)
ble_value = os.popen("sudo gatttool -t random --char-read --uuid " + uuid_to_check + " -b " + device_to_connect + " | awk '{print $4}'").read()
except:
ble_value = 'nd'
if ble_value != '':
ble_value = int(ble_value ,16)
if ble_value == '':
ble_value = '255'
time_checked = str(int(time.time()))
batt_lev_detected[device] = [ble_value,time_checked]
read_value_lock = False
#print (batt_lev_detected)
#AS SOON AS IT FINISH RESTART THE scan_beacon_data PROCESS
scan_beacon_data = True
mode = 'beacon_data'
Thread(target=ble_scanner).start()
time.sleep(1)
def start_server():
global soc
soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# this is for easy starting/killing the app
soc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
#print('Socket created')
try:
soc.bind((socket_ip, socket_port))
# print('Socket bind complete')
except socket.error as msg:
# print('Bind failed. Error : ' + str(sys.exc_info()))
sys.exit()
#Start listening on socket
soc.listen(10)
#print('Socket now listening')
# for handling task in separate jobs we need threading
#from threading import Thread
# this will make an infinite loop needed for
# not reseting server for every client
while (not killer.kill_now):
conn, addr = soc.accept()
ip, port = str(addr[0]), str(addr[1])
#print('Accepting connection from ' + ip + ':' + port)
try:
Thread(target=client_thread, args=(conn, ip, port)).start()
except:
print("Terible error!")
import traceback
traceback.print_exc()
soc.close()
def kill_socket():
global soc
global kill_now
kill_socket_switch = False
while (not kill_socket_switch):
if killer.kill_now:
print ("KILL_SOCKET PROVA A CHIUDERE IL SOCKET")
time.sleep(1)
soc.shutdown(socket.SHUT_RDWR)
soc.close()
kill_socket_switch = True
time.sleep(1)
### MAIN PROGRAM ###
class GracefulKiller:
kill_now = False
def __init__(self):
signal.signal(signal.SIGINT, self.exit_gracefully)
signal.signal(signal.SIGTERM, self.exit_gracefully)
def exit_gracefully(self,signum, frame):
global soc
self.kill_now = True
print ('Program stopping...')
if __name__ == '__main__':
killer = GracefulKiller()
Thread(target=start_server).start()
Thread(target=ble_scanner).start()
Thread(target=read_battery_level).start()
Thread(target=kill_socket).start()
# print ("End of the program. I was killed gracefully :)")

Run and log the output of 'ping' in a loop in a Python script

i wrote a simple agaent in python that all it dose is just cheacks for the internet connection.
When he finds out that ther is no connection he writes a log file to a text the hour and date and then just exit the program.
I want it to keep testing if there is a connection even if there is not how can i do this ? without the program exit
this is the code:
import os
import time
def Main():
ping =os.system('ping -n 1 -l 1000 8.8.8.8 ')
while ping ==0:
time.sleep(4)
ping = os.system('ping -n 1 -l 1000 8.8.8.8 ')
if ping ==1:
print 'no connection'
CT =time.strftime("%H:%M:%S %d/%m/%y")
alert=' No Connection'
f = open('logfile.txt','a+')
f.write('\n'+CT)
f.write(alert)
f.close()
if __name__ == "__main__":
Main()
Thanx a lot.
Wrap the Main call in an infinite loop?
if __name__ == "__main__":
while True:
Main()
time.sleep(1) # optional, as Main already contains a sleep time
This code should set you on your way. Just substitute the host with that of your choosing in the call to the LogPing object.
Check out the comments inline and please ask me if you have any questions.
from datetime import datetime
import os
import shlex
import subprocess
from time import sleep
class LogPing:
def __init__(self, host, count=1, timeout_seconds=10, logfile="ping_log.txt"):
self.host = host
self.count = count
self.timeout_seconds = timeout_seconds
self.logfile = logfile
self.output_blackhole = open(os.devnull, 'wb')
def _command(self):
command_string = "ping -c {count} -t {timeout} {host}".format(
count=self.count,
timeout=self.timeout_seconds,
host=self.host
)
try:
# we don't actually care about the output, just the return code,
# so trash the output. result == 0 on success
result = subprocess.check_call(
shlex.split(command_string),
stdout=self.output_blackhole,
stderr=subprocess.STDOUT
)
except subprocess.CalledProcessError:
# if here, that means that the host couldn't be reached for some reason.
result = -1
return result
def run(self):
ping_command_result = self._command()
if ping_command_result == 0:
status = "OK"
else:
status = "NOK"
# The time won't be exact, but close enough
message = "{status} : {time} : {host}\n".format(
status=status,
time=datetime.utcnow().strftime("%Y-%m-%d_%T"),
host=self.host
)
# open file in a context manager for writing, creating if not exists
# using a+ so that we append to the end of the last line.
with open(self.logfile, 'a+') as f:
f.write(message)
if __name__ == "__main__":
while True:
ping_instance = LogPing("example.org").run()
sleep(4)
If I understand yous correctly this will do its job:
import os
import time
def Main():
while True:
ping = os.system('ping -n 1 -l 1000 8.8.8.8 ')
if ping:
print 'no connection'
CT =time.strftime("%H:%M:%S %d/%m/%y")
alert=' No Connection'
with open('logfile.txt','a+') as f:
f.write('\n'+CT)
f.write(alert)
time.sleep(4)
if __name__ == "__main__":
Main()

Categories

Resources