Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 47 additions & 31 deletions src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,22 @@
from sqlite_manager import *
from gpiozero import LED
from post_http import get_token

restart_button = LED(23)

send_pre = [5, 0, 1, 14, 0, 2, 0, 7, 1, 8]
MAX_ALL_FAIL_TOLERANCE = 5
RESTART_TIME = 3600


def refresh_token():
global token
log.info("Getting a brand new token")
token_timer = Timer(24*3600,refresh_token)
token_timer = Timer(24 * 3600, refresh_token)
token_timer.start()
token = get_token()


def restart_lora():
log.info("Restart LoRa module")
if args.production:
Expand All @@ -36,28 +40,31 @@ def restart_lora():
restart_button.on()
time.sleep(5)


def restart_script():
os.execv(sys.executable, ['python'] + sys.argv)
def post_thread():
os.execv(sys.executable, ['python'] + sys.argv)


def post_thread():
"""! Post meters information

"""
global counter
global post_time_s
global counter_restart
counter+=1
counter_restart+=1
log.info("Posting in %s s",str(post_time_s - counter + 1))
if counter == post_time_s :
post_json = load_json( node.id, node.key)
post_scada(post_json,args.production, token)
counter += 1
counter_restart += 1
log.info("Posting in %s s", str(post_time_s - counter + 1))
if counter == post_time_s:
post_json = load_json(node.id, node.key)
post_scada(post_json, args.production, token)
counter = 0
if counter_restart == RESTART_TIME:
restart_script()
post_timer = Timer(1.0,post_thread)

post_timer = Timer(1.0, post_thread)
post_timer.start()


def build_argparser():
"""! Set command line interface
Expand All @@ -66,8 +73,15 @@ def build_argparser():
"""
label = subprocess.check_output(["git", "describe"]).strip()
parser = argparse.ArgumentParser(description="To select production code")
parser.add_argument('-p','--production', action='store_true', default=False, help = "Create production code")
parser.add_argument('-v','--version', action='version', version=label.decode("utf-8"))
parser.add_argument('-p',
'--production',
action='store_true',
default=False,
help="Create production code")
parser.add_argument('-v',
'--version',
action='version',
version=label.decode("utf-8"))
return parser


Expand All @@ -91,7 +105,7 @@ def poll_loras(loras):
"""
log.info("Start polling")
lora_index = 0
fail_array = [False]*len(loras)
fail_array = [False] * len(loras)
for lora_dic in loras:
time.sleep(1)
lora = loranode(lora_dic)
Expand Down Expand Up @@ -137,40 +151,42 @@ def poll_loras(loras):
lora_index += 1
if False not in fail_array:
log.error("All nodes not responding!")
all_failed_counter+=1


all_failed_counter += 1

if all_failed_counter == MAX_ALL_FAIL_TOLERANCE:
log.debug("Maximum Fail Tolerance Reached")
restart_script()

time.sleep(5)
meter_updates = get_meter_updates(token)
for update in meter_updates:
time.sleep(3)

payload = get_modbus_adu_update(update.lora_id, update.function,update.address,update.value)

payload = get_modbus_adu_update(update.lora_id, update.function,
update.address, update.value)
unencripted_payload = payload
log.debug(payload)
dest_slave = payload[0]
if node.cipher:
payload = encrypt_md(payload, "CFB")
payload = encrypt_md(payload, "CFB")
result = node.send(payload, dest_slave)
log.debug("Result %s", str(list(result)))
log.info("Result code from sent [%d] ", result[6])

response = node.receive()
if response is None:
continue
continue
if node.cipher:
response = decrypt_md(response, "CFB")

log.debug("message received: %s", str(unencripted_payload))

if set(unencripted_payload) == set(response):
log.info("Wrote Coils Successfully")
else:
log.info("Something went wrong writing coils")


if __name__ == "__main__":
"""! Main program entry

Expand All @@ -184,7 +200,7 @@ def poll_loras(loras):
init_serial_port(node.lora_port)
restart_lora()
all_failed_counter = 0

if not node.init_lora():
log.error("Could not config LoRa")
os._exit(0)
Expand All @@ -195,16 +211,16 @@ def poll_loras(loras):
post_time_s = node.post_time
post_timer = Timer(1.0, post_thread)
post_timer.start()

token = ''
token_timer = Timer(1.0, refresh_token)
token_timer.start()

node.ser = serial.Serial(node.lora_port, timeout=14)
wtd_start.stop()
except Watchdog:
log.error("Reseting script due to wdt boot")
wtd = Watchdog(300) # 5min
wtd = Watchdog(300) # 5min
try:
while True:
poll_loras(node.loras)
Expand All @@ -221,4 +237,4 @@ def poll_loras(loras):
log.error("App Crashed!")
log.error("Problems? %s", sys.exc_info())
log.info("Restarting...")
os.execv(sys.executable, ['python'] + sys.argv)
os.execv(sys.executable, ['python'] + sys.argv)