コード例 #1
0
import json
import os
import sys
from mpi4py import MPI

from MainConfig import MainConfig
from CommandHelper import CommandHelper

if __name__ == "__main__":
    main_data = json.load(open('config.json'))
    main_config = MainConfig(main_data)

    comm = MPI.COMM_WORLD
    size = comm.Get_size()
    rank = comm.Get_rank()
    totals = []
    runs = 0

    one = os.path.isdir(main_config.out_dir)
    print(f'node {rank} {main_config.out_dir} exists {one}')

    if not one:
        try:
            os.makedirs(main_config.out_dir, exist_ok=True)
        except Exception as inst:
            print(type(inst))
            print(inst.args)
            print(inst)
            print(sys.exc_info()[0])

    if rank == 0:
コード例 #2
0
#!/usr/bin/env python

import simplejson as json
from MainConfig import MainConfig

print(MainConfig().CONFIG_PATH)

strjson = '{"key":"value"}'

jsonDict = None

try:
    jsonDict = json.loads(strjson)
except Exception as e:
    print(e)
print(jsonDict)

config = None
with open('/home/himanshu/DataLogger/app/config/config.json', 'r') as f:
    config = json.load(f)

with open('/home/himanshu/DataLogger/app/config/config.json', 'w') as f:
    config['mqtt_topic'] = 'new/topic'
    f.truncate()
    json.dump(config, f, indent=4)
コード例 #3
0
def main():
    imei = None
    mc = MainConfig().getConfig()

    #GsmUtility.resetModem()
    try:
        subprocess.call('hwclock -f /dev/rtc1 -s', shell=True)
    except Exception as e:
        self.LOG.error('Error syncing time: %s', e)

    try:
        imei = GsmUtility.getGsmImeiNumber()
    except Exception as e:
        print(e)

    try:
        ser = SerialConnection().getSerialConnection(
            connParams.get(ModbusConsts.BAUDRATE),
            connParams.get(ModbusConsts.PARITY),
            connParams.get(ModbusConsts.STOP_BITS),
            connParams.get(ModbusConsts.BYTE_SIZE))
        command = 'FA0600060001'
        crc = ModbusLib.get_modbus_crc(bytearray.fromhex(command))
        command = command + crc
        print('UPS command', command)
        commandResp = ModbusCommandSender().sendCommand(ser, command, 'RTU')
        if commandResp:
            print('UPS written successfully')
        else:
            print('Error  writing to UPS')
    except Exception as e:
        print('Error writing to UPS', e)

    GsmUtility.ImeiNumber = '0123456789' if imei is None else imei

    Status.deviceId = '0123456789' if mc.get(
        Constants.DEVICE_ID) is None else mc.get(Constants.DEVICE_ID)

    try:
        with open('/fw/DataLogger/app/version.info', 'r') as f:
            Status.fwVersion = f.readline()
            Status.fwVersion = Status.fwVersion.strip()
    except Exception as e:
        print('Error reading Firmware version: %s', e)

    recordTime = str(
        datetime.datetime.fromtimestamp(
            time.time()).strftime('%Y-%m-%d %H:%M:%S'))
    payload_type = 'xml' if mc.get(Constants.PAYLOAD_TYPE) is None else mc.get(
        Constants.PAYLOAD_TYPE)
    if payload_type == Constants.PAYLOAD_TYPE_XML:
        initialRecord = '<GATEWAY_ID V=\'' + str(
            Status.deviceId
        ) + '\'>' + '<DT V=\'' + recordTime + '\'>' + '<FW_VERSION V=\'' + str(
            Status.fwVersion) + '\'/></DT></GATEWAY_ID>'
    elif payload_type == Constants.PAYLOAD_TYPE_JSON:
        initialRecord = {}
        initialRecord['gateway_id'] = Status.deviceId
        initialRecord['dt'] = recordTime
        initialRecord['fw_version'] = Status.fwVersion
        initialRecord['imei'] = GsmUtility.ImeiNumber
        initialRecord = json.dumps(initialRecord)
    else:
        initialRecord = '<GATEWAY_ID V=\'' + str(
            Status.deviceId
        ) + '\'>' + '<DT V=\'' + recordTime + '\'>' + '<FW_VERSION V=\'' + str(
            Status.fwVersion) + '\'/></DT></GATEWAY_ID>'

    pq = PayloadQueue()
    pq.appendPayload(initialRecord)

    Status.modbusDevStatus = [0] * len(
        ModbusDeviceList().getModbusDeviceList())
    print('No of modbus devices ',
          len(ModbusDeviceList().getModbusDeviceList()))
    GPIO.setmode(GPIO.BOARD)
    GPIO.setup(15, GPIO.OUT)

    GPIO.setup(22, GPIO.OUT)

    GPIO.output(22, GPIO.HIGH)
    time.sleep(5)

    GPIO.setup(8, GPIO.OUT)
    GPIO.output(8, GPIO.HIGH)
    time.sleep(5)
    try:
        channel = mc.get(Constants.LORA_CHANNEL)
        channel = 23 if channel is None else channel
        result = LoraUtility.setChannel(channel)
        print('Lora Channel Result: ', result)
    except Exception as e:
        print(e)

    GPIO.output(8, GPIO.LOW)

    # Start the process monitor thread
    pm = ProcessMonitor.ProcessMonitor()
    pm.start()

    interval = int(mc.get(Constants.PERIODIC_INTERVAL))
    curtime = time.time()
    timeToSleep = interval - (curtime % interval)
    time.sleep(timeToSleep)

    # Start the PeriodicTimer
    pt = PeriodicTimer.PeriodicTimer()
    pt.start()

    time.sleep(1)

    # Start the modbus data acquisition service
    modbusDataService = ModbusDataService.ModbusDataService()
    modbusDataService.start()

    # Start the payload construction service
    messageComposer = MessageComposer.MessageComposer()
    messageComposer.start()

    # Start the Message sending service
    messageSender = MessageSender.MessageSender()
    messageSender.start()

    # Start the LED thread
    ledt = LedStatus.LedStatus()
    ledt.start()

    # Wait for the threads to complete
    while True:
        if Status.stop:
            MessageSender.stop = True
            MessageComposer.stop = True
            ModbusDataService.stop = True
            PeriodicTimer.stop = True
            ProcessMonitor.stop = True
            time.sleep(
                int(MainConfig().getConfig().get(Constants.PERIODIC_INTERVAL)))
            break
        else:
            time.sleep(
                int(MainConfig().getConfig().get(Constants.PERIODIC_INTERVAL)))
コード例 #4
0
    def constructXmlPayload(self):

        recordTime = PeriodicTimer.recordTimestamp
        mc = MainConfig().getConfig()
        if Constants.GATEWAY_ID in mc:
            xmlPayload = '<GATEWAY_ID V=\'' + mc.get(
                Constants.GATEWAY_ID) + '\'>'
        else:
            xmlPayload = '<GATEWAY_ID V=\'' + Status.deviceId + '\'>'
        xmlPayload = xmlPayload + '<DT V=\'' + recordTime + '\'>'
        #xmlPayload = xmlPayload + '<UID V=\'' + GsmUtility.ImeiNumber + '\'/>'
        modbusPayloadConstructed = False

        while True:
            if not InputDataQueue.modbusDataQueue.empty(
            ) and not modbusPayloadConstructed:
                modbusDataList = InputDataQueue.modbusDataQueue.get_nowait()
                modbusPayloadConstructed = True
                self.LOG.debug('Modbus data from queue: %s', modbusDataList)
                for modbusData in modbusDataList:
                    devCategory = modbusData.get(ModbusConsts.DEVICE_CATEGORY)
                    if ModbusConsts.CAT_INVERTER == devCategory:
                        inverterPayload = None
                        try:
                            inverterPayload = SolarInverterXml().getXmlPayload(
                                modbusData, recordTime)
                        except Exception as e:
                            self.LOG.error(
                                'Error Constructing inverter payload: %s', e)

                        if inverterPayload is not None:
                            xmlPayload = xmlPayload + inverterPayload

                    elif ModbusConsts.CAT_WST == devCategory:
                        wstPayload = None
                        try:
                            wstPayload = WeatherStationXml().getXmlPayload(
                                modbusData, recordTime)
                        except Exception as e:
                            self.LOG.error(
                                'Error constructing Weather Station payload: %s',
                                e)

                        if wstPayload is not None:
                            xmlPayload = xmlPayload + wstPayload

                    elif ModbusConsts.CAT_INVERTER_ABB33 == devCategory:
                        abbPayload = None
                        try:
                            abbPayload = AbbInverter33Xml().getXmlPayload(
                                modbusData, recordTime)
                        except Exception as e:
                            self.LOG.error(
                                'Error constructing Abb 33 KW inverter payload: %s',
                                e)

                        if abbPayload is not None:
                            xmlPayload = xmlPayload + abbPayload

                    elif ModbusConsts.CAT_INVERTER_ABB100 == devCategory:
                        abbPayload = None
                        try:
                            abbPayload = AbbInverter100Xml().getXmlPayload(
                                modbusData, recordTime)
                        except Exception as e:
                            self.LOG.error(
                                'Error constructing Abb 100 KW inverter payload: %s',
                                e)

                        if abbPayload is not None:
                            xmlPayload = xmlPayload + abbPayload

                InputDataQueue.modbusDataQueue.task_done()
            if PeriodicTimer.counter > 10 and not modbusPayloadConstructed:
                time.sleep(5.0)
            else:
                break

        xmlPayload = xmlPayload + '</DT>'
        xmlPayload = xmlPayload + '</GATEWAY_ID>'

        return xmlPayload