Skip to content
Open
Show file tree
Hide file tree
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
7 changes: 4 additions & 3 deletions src/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,12 @@ def build_logger():

@return log register of information and the message
"""
logFormatter = logging.Formatter(logformat,datefmt = dateformat)
consoleFormatter = logging.Formatter("[%(levelname)-5.5s] [%(name)s] %(message)s")
logFormatter = logging.Formatter(logformat, datefmt=dateformat)
consoleFormatter = logging.Formatter(
"[%(levelname)-5.5s] [%(name)s] %(message)s")
log = logging.getLogger()

fileHandler = logging.FileHandler("{0}/{1}.log".format(".","logs"))
fileHandler = logging.FileHandler("{0}/{1}.log".format(".", "logs"))
fileHandler.setFormatter(logFormatter)
fileHandler.setLevel(logging.WARNING)
log.addHandler(fileHandler)
Expand Down
53 changes: 32 additions & 21 deletions src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,22 +16,23 @@
from sqlite_manager import *

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

def post_thread():


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

"""
global counter
global post_time_s
counter+=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)
counter += 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)
counter = 0
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 @@ -40,8 +41,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 Down Expand Up @@ -105,29 +113,32 @@ def poll_loras(loras):
meter_updates = get_meter_updates()
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 @@ -146,13 +157,13 @@ def poll_loras(loras):
energy_load(node.loras)
counter = 0
post_time_s = node.post_time
post_timer = Timer(1.0,post_thread)
post_timer = Timer(1.0, post_thread)
post_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 @@ -169,4 +180,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)
13 changes: 8 additions & 5 deletions src/modbus_process.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@
log = logging.getLogger('central')
ch = logging.NullHandler()
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
log.addHandler(ch)

def get_modbus_adu_update(id,function,address, value):

def get_modbus_adu_update(id, function, address, value):
"""! Organize and update the data unity
of the application and send it

Expand All @@ -22,10 +24,10 @@ def get_modbus_adu_update(id,function,address, value):
"""
adu = []
adu.append(id)
adu.append(5) #Write single coil
adu.append(5) #Write single coil
adu.append(0)
if function == "Reset":
adu.append(address) #TODO reset another address
adu.append(address) #TODO reset another address
else:
adu.append(address)
if value == True:
Expand All @@ -42,6 +44,7 @@ def get_modbus_adu_update(id,function,address, value):
log.debug("modbus adu to send: %s", str(adu))
return adu


def get_modbus_adu(id_slave, function_code, start_add, quantity):
"""! Organize the data in a list and return it

Expand All @@ -51,7 +54,7 @@ def get_modbus_adu(id_slave, function_code, start_add, quantity):
@param quantity quantity of data

@return adu list of data unity of application
"""
"""
if quantity > 125:
return None
adu = []
Expand Down
38 changes: 22 additions & 16 deletions src/post_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@
log = logging.getLogger('post')
ch = logging.NullHandler()
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
log.addHandler(ch)


def post_json(file, is_production):
"""! Get the status of the data

Expand All @@ -22,12 +24,10 @@ def post_json(file, is_production):
headers = {'Content-type': 'application/json'}
scada_url = 'https://postman-echo.com/post'
if is_production:
scada_url = "https://apimedidores.ciexpro.com/api/push/custom_create/"
log,debug(scada_url)
scada_url = "https://apimedidores.ciexpro.com/api/push/custom_create/"
log, debug(scada_url)
try:
r = requests.post(scada_url,
json=file,
headers=headers)
r = requests.post(scada_url, json=file, headers=headers)
log.info("Status code is : %s", str(r.status_code))
log.debug(str(r))
return r.status_code
Expand All @@ -45,7 +45,7 @@ def post_scada(data_dic, is_production):
@param is_production chech if there is a new data to add
"""
log.info("Posting to Scada")
success_code =201
success_code = 201
log.debug("Data to post: %s", str(data_dic))
r_code = post_json(data_dic, is_production)

Expand All @@ -66,29 +66,32 @@ def post_scada(data_dic, is_production):
with open("output/send_later.txt", "a") as file:
file.write(text)
file.close()


class MeterUpdate(object):
def __init__(self, object_dic):
self.lora_id =int(object_dic["meterid"][0:4],16)
self.address = int(object_dic["meterid"][4:6],16)
if self.address==0:
self.lora_id = int(object_dic["meterid"][0:4], 16)
self.address = int(object_dic["meterid"][4:6], 16)
if self.address == 0:
self.address = self.lora_id
if object_dic["isPowered"]:
self.function = "Relay"
self.value = object_dic["powerValue"]
else:
self.function = "Reset"
self.value = True

self.value = True


def get_meter_updates():
#get json from cloud
with open("json/states.json","r+") as status_file:
with open("json/states.json", "r+") as status_file:
status_dic = json.load(status_file)
updates = status_dic["updates"]
updates_list = []
#log.debug(status_dic)s

log.debug(updates)

for update in updates:
meter_update_object = MeterUpdate(update)
log.debug(meter_update_object.lora_id)
Expand All @@ -97,15 +100,18 @@ def get_meter_updates():
log.debug(meter_update_object.value)
updates_list.append(meter_update_object)
print(update["powerValue"])
update["powerValue"] = True if update["powerValue"]== False else False
update["powerValue"] = True if update[
"powerValue"] == False else False
#payload = get_modbus_adu_update(meter_update_object.lora_id, meter_update_object.function,meter_update_object.address,meter_update_object.value)
#log.debug(updates_list)
status_dic["updates"] = updates
status_file.seek(0)
status_file.truncate()
json.dump(status_dic, status_file)

return updates_list


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

Expand Down