示例#1
0
def ReadUSBData(CSVPath,ClientID,client):
  # Read serial data from USB port
  #
  #   Define the PicAxe Divisors
  DivisorDict = dict.fromkeys(string.ascii_uppercase)
  for key in DivisorDict :
      DivisorDict[key] =	1
  DivisorDict['A'] =	10 # Soil Moisture
  DivisorDict['B'] =	10 # Temperature
  DivisorDict['S'] =	10 # Kihi-02 Moisture
  DivisorDict['T'] =	10 # Kihi-02 Temperature

  USBport = 'USB0'

  if (USBport in PiSerial() ):
        DoRead = True
        logging.info("USB port found: "+ USBport )
  else:
        Message = "Error looking for "+USBport
        CSV_Message = Message
        DoRead = ProcessError(CSVPath, ClientID, '', CSV_Message, Message)
        # Will try to read (twice) data anyway

  SerialDetails = {
    "DeviceName": "/dev/tty"+USBport,
    "ModuleType": "DRF126x",
    "BAUDrate": "2400",
    }
  # Could also include other parameters
  #  parity = serial.PARITY_NONE,
  #  stopbits = serial.STOPBITS_ONE,
  #  bytesize = serial.EIGHTBITS,
  # Default location of serial port on Pi models 3 and Zero
  #    SERIAL_PORT =        "/dev/ttyS0"
  # Other serial ports are  "/dev/ttyAMA0" & "/dev/serial0"
  # ModuleType can be Dorji DRF126x or DRF127x

  while DoRead :
      try :
        Value = GetSerialData(CSVPath,ClientID,SerialDetails)
    #    logging.info("Serial Loop: %s", Value)
        Status = Value["Status"]

        if Status == 0 :
            Error = "Invalid_Read"
            Save2CSV (CSVPath, ClientID, 'Error', Error)
        else :
            # Status is OK, so write the data ...
            Error = Value["Error"]
            Channel = Value["Channel"]
            Data = Value["Data"]
            ClientID = Value["ClientID"]
            Save2CSV (CSVPath, ClientID, Channel, Data)
            Save2Cayenne (client, Channel, Data, DivisorDict[Channel])

        Save2Cayenne (client, 'Stat', Status, 1)
      except :
          Message = "Exception reading LoRa Data from "+USBport
          CSV_Message = Message
          DoRead = ProcessError(CSVPath, ClientID, '', CSV_Message, Message)
示例#2
0
def ReadSerialData(CSVPath, ClientID, client):
    #   Define the PicAxe Divisors
    DivisorDict = dict.fromkeys(string.ascii_uppercase)
    for key in DivisorDict:
        DivisorDict[key] = 1
    DivisorDict['A'] = 10  # Soil Moisture
    DivisorDict['B'] = 10  # Temperature

    try:
        while True:
            Value = GetSerialData(CSVPath, ClientID)
            #    logging.info("Serial Loop: %s", Value)
            Channel = Value["Channel"]
            Data = Value["Data"]
            Status = Value["Status"]
            ClientID = Value["ClientID"]
            Error = Value["Error"]
            Save2Cayenne(client, 'Stat', Status, 1)
            #    logging.info("Wifi Loop: %s", Value)
            if Status == 0:
                Save2CSV(CSVPath, ClientID, 'Error', Error)
            else:
                # Status is OK, so write the data ...
                Save2CSV(CSVPath, ClientID, Channel, Data)
                Save2Cayenne(client, Channel, Data, DivisorDict[Channel])
    except:
        Message = "Exception reading LoRa Data"
        CSV_Message = Message
        ProcessError(CSVPath, ClientID, '', CSV_Message, Message)
示例#3
0
def ReadGPIOData(CSVPath,ClientID,client):
  # Read serial data from GPIO pins
  #
  #   Define the PicAxe Divisors
  DivisorDict = dict.fromkeys(string.ascii_uppercase)
  for key in DivisorDict :
      DivisorDict[key] =	1
  DivisorDict['A'] =	10 # Soil Moisture
  DivisorDict['B'] =	10 # Temperature
  DivisorDict['S'] =	10 # Kihi-02 Moisture
  DivisorDict['T'] =	10 # Kihi-02 Temperature
#  DivisorDict[','] =    1 # Battery voltage
  DoRead = True

  SerialDetails = {
    "DeviceName": "/dev/serial0",
    "ModuleType": "DRF127x",
  #  "ModuleType": "DRF126x",
    "BAUDrate": "2400",
    }
  # Could also include other parameters
  #  parity = serial.PARITY_NONE,
  #  stopbits = serial.STOPBITS_ONE,
  #  bytesize = serial.EIGHTBITS,
  # Default location of serial port on Pi models 3 and Zero
  #    SERIAL_PORT =        "/dev/ttyS0"
  # Other serial ports are  "/dev/ttyAMA0" & "/dev/serial0"
  # ModuleType can be Dorji DRF126x or DRF127x

#  while DoRead :
  try :
        Value = GetSerialData(CSVPath,ClientID,SerialDetails)
    #    logging.info("Serial Loop: %s", Value)
        Status = Value["Status"]

        if Status == 0 :
            Error = "Invalid_Read"
            Save2CSV (CSVPath, ClientID, 'Error', Error)
        else :
            # Status is OK, so write the data ...
 #           Error = Value["Error"]
            Channel =   Value["Channel"]
            Data =      Value["Data"]
            ClientID =  Value["ClientID"]
            RSSI =      Value["RSSI"]
            Save2CSV (CSVPath, ClientID, Channel, Data)
            Save2Cayenne (client, Channel, Data, DivisorDict[Channel])

            if not any ( { int(RSSI) <= 0, int(RSSI) >= 255 } ) : # Probably have a valid RSSI
                Channel = chr(22+ord('A')-1)
                # RSSI is Cayenne channel 22, PicAxe 22nd letter in alphabet
                Data = RSSI
                Save2CSV (CSVPath, ClientID, Channel, Data)
                Save2Cayenne (client, Channel, Data, 1)

        Save2Cayenne (client, 'Stat', Status, 1)
  except :
          Message = "Exception reading Serial Data from GPIO"
          CSV_Message = Message
          DoRead = ProcessError(CSVPath, ClientID, '', CSV_Message, Message)
示例#4
0
def ReadWifiThread(Freq, CSVPath, ClientID, client):
    while True:
        Value = GetWirelessStats()
        #    logging.info("Wifi Loop: %s", Value)
        Link = Value['wlan0']['link']
        Channel = 'WifiLnk'
        Save2CSV(CSVPath, ClientID, Channel, Link)
        Save2Cayenne(client, Channel, Link, 100)
        Level = Value['wlan0']['level']
        Channel = 'WifiLvl'
        Save2CSV(CSVPath, ClientID, Channel, Level)
        Save2Cayenne(client, Channel, Level, 100)
        time.sleep(Freq)
示例#5
0
def ReadCPUThread(Freq, CSVPath, ClientID, client):
    while True:
        Value = CPUTemperature().temperature
        #    logging.info("CPU  Loop: %s", Value)
        Channel = 'CPUtemp'
        Save2CSV(CSVPath, ClientID, Channel, Value)
        Save2Cayenne(client, Channel, Value, 1)
        time.sleep(Freq)
示例#6
0
def ReadTempThread(Freq, CSVPath, ClientID, client):
    while True:
        Value = ReadTemp()
        #    logging.info("Temp Loop: %s", Value)
        Channel = 'ExtTemp'
        Save2CSV(CSVPath, ClientID, Channel, Value)
        Save2Cayenne(client, Channel, Value, 1)
        time.sleep(Freq)
示例#7
0
def ReadWifiThread(Freq,CSVPath,ClientID,client):
  DoRead = True
  while DoRead :
    try:
      Value = GetWirelessStats()
#     logging.info("Wifi Loop: %s", Value)
      Link = Value['wlan0']['link']
      Channel = 'WifiLnk'
      Save2CSV (CSVPath, ClientID, Channel, Link)
      Save2Cayenne (client, Channel, Link, 100)
      Level = Value['wlan0']['level']
      Channel = 'WifiLvl'
      Save2CSV (CSVPath, ClientID, Channel, Level)
      Save2Cayenne (client, Channel, Level, 100)
      time.sleep(Freq)
    except :
       Message = "Exception reading Wifi Data"
       CSV_Message = Message
       DoRead = ProcessError(CSVPath, ClientID, '', CSV_Message, Message)
示例#8
0
def ReadCPUThread(Freq,CSVPath,ClientID,client):
  DoRead = True
  while DoRead :
    try:
      Value = CPUTemperature().temperature
#    logging.info("CPU  Loop: %s", Value)
      Channel = 'CPUtemp'
      Save2CSV (CSVPath, ClientID, Channel, Value)
      Save2Cayenne (client, Channel, Value, 1)
      time.sleep(Freq)
    except :
       Message = "Exception reading CPU Temperature"
       CSV_Message = Message
       DoRead = ProcessError(CSVPath, ClientID, '', CSV_Message, Message)
示例#9
0
def ReadDiskThread(Freq,CSVPath,ClientID,client):
  DoRead = True
  while DoRead :
    try:
      Value = round( DiskUsage().value,2)
#    logging.info("Disk Loop: %s", Value)
      Channel = 'DiskAvg'
      Save2CSV (CSVPath, ClientID, Channel, Value)
      Save2Cayenne (client, Channel, Value, 1)
      time.sleep(Freq)
    except :
      Message = "Exception reading Disk Usage"
      CSV_Message = Message
      DoRead = ProcessError(CSVPath, ClientID, '', CSV_Message, Message)
示例#10
0
def ReadTempThread(Freq,CSVPath,ClientID,client):
  DoRead = True
  while DoRead :
    try:
      Value = ReadTemp()
#    logging.info("Temp Loop: %s", Value)
      Channel = 'ExtTemp'
      Save2CSV (CSVPath, ClientID, Channel, Value)
      Save2Cayenne (client, Channel, Value, 1)
      time.sleep(Freq)
    except :
      Message = "Exception reading Onboard Temperature"
      CSV_Message = Message
      DoRead = ProcessError(CSVPath, ClientID, '', CSV_Message, Message)
示例#11
0
def ReadLoadThread(Freq,CSVPath,ClientID,client):
  DoRead = True
  while DoRead :
    try:
      Value = LoadAverage().load_average
#    logging.info("Load Loop: %s", Value)
      Channel = 'LoadAvg'
      Save2CSV (CSVPath, ClientID, Channel, Value)
      Save2Cayenne (client, Channel, Value, 1)
      time.sleep(Freq)
#      raise Exception('Test exception at line 79 of Thread2MQTT.py')
    except :
      Message = "Exception reading Load Average"
      CSV_Message = Message
      DoRead = ProcessError(CSVPath, ClientID, '', CSV_Message, Message)
示例#12
0
def ProcessError(CSVPath, ClientID, CayClient, CSV_Message, Message):
# Save Message to a file and Cayenne
    global LastError
    CurrentTime = datetime.datetime.now().isoformat()
    CSVPathFile = Save2CSV (CSVPath, ClientID, 'Exception', CSV_Message)
    CurrentTime = datetime.datetime.now().isoformat()
    LogPathFile = logging.getLoggerClass().root.handlers[0].baseFilename
    
    ErrorTime = datetime.datetime.now()
    ErrorGap    = ErrorTime - LastError['time']
#    logging.info( LastError )
#    logging.info( ErrorGap )
    
    if ErrorGap.days > 0: # Ages since last error
        Continue = True
        ResetCount = True
    elif ErrorGap.seconds > LastError['period']: # OK time since last error
        Continue = True
        ResetCount = True
    elif LastError['count'] < LastError['threshold']: # Still counting
        LastError['count'] += 1
        Continue = True
        ResetCount = False
    else:      # We have a problem
        Continue = False
        ResetCount = True
        
    if ResetCount:
        LastError = {
            'time'  : ErrorTime,
            'count' : 0
        }

    if not(Continue):
        Message = Message+' terminating thread'
        
    logging.exception(Message)
    os.system('tail -20 '+LogPathFile) # display last error if in foreground
    if CayClient :
        Save2Cayenne (CayClient, 'Stat', -1, 1)

    return(Continue)
示例#13
0
try:
 while SerialListen:
   with serial.Serial(SERIAL_PORT, BAUDRATE) as ser:
# Data processing
#      if DRF126x:
#         PacketIn = ser.read(8)
#         head1,head2,Device,Channel,Data,Cks,RSSI=struct.unpack("<ccccHBB",PacketIn)
#      else:
#         PacketIn = ser.read(7)
#         head1,head2,Device,Channel,Data,Cks     =struct.unpack("<ccccHB" ,PacketIn)
#         RSSI = 0
      Sync = ser.read_until(HEADIN)
# debugging      Sync = str(Sync)+"*"
      if not(Sync==HEADIN):
          print( "Extra Sync text!", Sync, "**************")
          Save2Cayenne (client, 'Stat', 1, 1)
          Save2CSV (CSVPath, MQTTCreds.get('Client ID'), 'Sync-Error', Sync)
#      print( "Header read:",Sync )

#      while (len(PacketIn) < 6):
      PacketIn = ser.read(5)
      print( PacketIn, len(PacketIn), 'l' )

      Device,Channel,Data,Cks=struct.unpack("<ccHB",PacketIn)
      if DRF126x :
          RSSI = ser.read(1)
      else:
          RSSI = 0

#      null, null, b8,    b9,  b10,b11,Cks=struct.unpack("<BBBBBBB",PacketIn) (eg of PicAxe line)
# Checksum processing
示例#14
0
client = cayenne.client.CayenneMQTTClient()
client.on_message = on_message
client.on_connect = on_connect

client.begin(CayenneParam.get('CayUsername'), \
   CayenneParam.get('CayPassword'), \
   CayenneParam.get('CayClientID'), \
   )

#   loglevel=logging.INFO)  # Logging doesn't seem to work in Python3
# For a secure connection use port 8883 when calling client.begin:
# client.begin(MQTT_USERNAME, MQTT_PASSWORD, MQTT_CLIENT_ID, port=8883, loglevel=logging.INFO)

SendData = True
# Save2Cayenne (client, 'Z', '123>') # Random experiement (didn't work)
try:
    while SendData:
        timestamp = time.time()
        Channel = 'CPUtemp'
        Data = CPUTemperature().temperature
        Save2CSV(CSVPath, CayenneParam.get('CayClientID'), Channel,
                 Data)  # Send a backup to a CSV file
        Save2Cayenne(client, Channel, Data)
        Save2Cayenne(client, 'Stat', 1)  # No errors at this point!
        time.sleep(INTERVAL)
        client.loop()
except:
    Message = 'Exception Processing Internal Data'
    ProcessError(CSVPath, CayenneParam.get('CayClientID'), \
         client, LOG_FILE, Message)
示例#15
0
try:
    while SerialListen:
        with serial.Serial(SERIAL_PORT, BAUDRATE) as ser:
            # Data processing
            #      if DRF126x:
            #         PacketIn = ser.read(8)
            #         head1,head2,Device,Channel,Data,Cks,RSSI=struct.unpack("<ccccHBB",PacketIn)
            #      else:
            #         PacketIn = ser.read(7)
            #         head1,head2,Device,Channel,Data,Cks     =struct.unpack("<ccccHB" ,PacketIn)
            #         RSSI = 0
            Sync = ser.read_until(HEADIN)
            # debugging      Sync = str(Sync)+"*"
            if not (Sync == HEADIN):
                print("Extra Sync text!", Sync, "**************")
                Save2Cayenne(client, 'Stat', 1, 1)
                Save2CSV(CSVPath, CayenneParam.get('CayClientID'),
                         'Sync-Error', Sync)
#      print( "Header read:",Sync )

#      while (len(PacketIn) < 6):
            PacketIn = ser.read(5)
            print(PacketIn, len(PacketIn), 'l')

            Device, Channel, Data, Cks = struct.unpack("<ccHB", PacketIn)
            if DRF126x:
                RSSI = ser.read(1)
            else:
                RSSI = 0

#      null, null, b8,    b9,  b10,b11,Cks=struct.unpack("<BBBBBBB",PacketIn) (eg of PicAxe line)
示例#16
0
client.on_connect = on_connect

client.begin(CayenneParam.get('CayUsername'), \
   CayenneParam.get('CayPassword'), \
   CayenneParam.get('CayClientID'), \
   )

CheckingQueue = True

while CheckingQueue:

    CayQueue = Queue(QueuePathFile, autosave=True)

    if not (CayQueue.empty()):
        CayPacket = CayQueue.get()

        Save2CSV (CSVPath, \
            CayPacket['CayClientID'], \
            CayPacket['Channel'], \
            CayPacket['Data'] \
                  ) # Send a backup to a CSV file

        Save2Cayenne (client, \
            CayPacket['Channel'], \
            CayPacket['Data'] \
                  ) # Send

#        client.loop()
#    CayQueue.task_done()
    time.sleep(1)
示例#17
0
# 	print(msg_body, target_temp, target_freq )

		if len (all_temp) == 5 or time.time() > (start_time + max_time_seconds) :
			repeatChecks = False
		else :
			timedata = time.time()
			while (time.time() < timedata + interval):
				time.sleep(1)

#	target_folders = { '28-0417019fa4ff':'A', '28-041671ea1aff':'B', '28-041701ae78ff':'C', '28-041701bcc3ff':'D' }
#	target_folders = { '28-0417019fa4ff':'A', '28-0416716607ff':'B', '28-041701bcc3ff':'C', '28-97aeeb1d64ff':'D', '28-041701ae78ff':'E' } # Corded plus
target_folders = { '28-0000032f8712':'A', '28-01131fa57571':'B', '28-031670e78aff':'C', '28-041670f565ff':'D', '28-97aeeb1d64ff':'E' } # skinks + Battery

#	{'28-97aeeb1d64ff': 22937, '28-0416716607ff': 22125, '28-0000032f9489': 22375, '28-52beeb1d64ff': 22687} # onboard sensors
#	all_temp = {'28-041701bcc3ff': 10625, '28-0417019fa4ff': 11125, '28-041671ea1aff': 9875, '28-041701ae78ff': 8562} # Sample data
for key in all_temp :
		Value   = int (all_temp[key]) / 1000 # Turn data to an int then scale back to degrees C
		Channel = target_folders[key]

		Save2CSV (CSVPath, ClientID, Channel, Value)
		Save2Cayenne (client, Channel, Value, 1)

print( all_temp  )

#	Timing for the Keep Going loop
#	timedata = time.time()
#	while (time.time() < timedata + keepInterval):
#		time.sleep(1)