def __get_GPGGA_GPVTG(self): try: # try opening the port self.port.open() enable_serial() gps_on(bit=1) sleep(30) self.port.flusInput() except: self.port = None printf('Unable to open port') traceback.print_exc( file=open("/media/mmcblk0p1/logs/system.log", "a+")) else: self.port.write(self.cmd['GPGGA']) sleep(1) GPGGA = self.port.readline() self.port.write(self.cmd['GPVTG']) sleep(1) GPVTG = self.port.readline() return GPGGA, GPVTG finally: # At every exit close the port, and turn off the GPS if self.port: self.port.close() gps_off(bit=1) disable_serial()
def put_to_inactive_sleep(): """ Send the system to sleep if no task is schedule in the nest 3 minute """ data = None with open("/media/mmcblk0p1/logs/schedule.log", "r") as schedule: data = schedule.read() data = data.split(",")[1] next_run = None now = datetime.datetime.now() if data: next_run = data.split(" ") # print(next_run) years, months, days = next_run[3].split("-") hours, minutes, seconds = next_run[4][0:-1].split(":") next_run = now.replace(year=int(years), month=int(months), day=int(days), hour=int(hours), minute=int(minutes), second=int(seconds)) time_interval = int(str(next_run - now).split(":")[1]) - 2 # print(interval) if time_interval < 3: pass elif no_task(): # if interval> 52: printf("No task in the next {0} minutes. Going on StandBy".format( time_interval)) with open("/media/mmcblk0p1/logs/slept.log", "w+") as slept: slept.write("1")
def get_nmea(self): """ Initiate the reading of the binex language from GPS module to Titron Take no argument Return None """ try: # try opening the port self.port.open() enable_serial() gps_on(bit=1) sleep(90) self.port.flusInput() except: self.port = None printf('An error occurred') traceback.print_exc( file=open("/media/mmcblk0p1/logs/system.log", "a+")) else: self.port.write(self.cmd['nmea'] + "\r") sleep(2) data = self.port.read(self.port.inWaiting()) writeFile('/media/mmcblk0p1/logs/gps_nmea.log', data, 'a+') sleep(2) return data.split("\n") finally: # At every exit close the port, and turn off the GPS if self.port: self.port.close() gps_off(bit=1) disable_serial()
def read_data(self): try: # Turn on Weather Station weather_on(1) sleep(60) # Read in the weather sensor data and write to an ascii text file port = serial.Serial("/dev/ttyS5") port.baudrate = 115200 port.timeout = 60 except: print("Problem with port 5 or problem with power to the vaisala") traceback.print_exc( file=open("/media/mmcblk0p1/logs/system.log", "a+")) else: t = 0 data = None # Read composite data message (all readings) every 10 seconds for 2 minutes and write to temporary ascii text file while t <= 120: with open( "/media/mmcblk0p1/logs/weather_data_ASCII_schedule.log", "a+") as raw_data: port.flushInput() data = port.readline() if data is None or data == "": printf( "Vaisala could not take reading. Got empty data") break raw_data.write(data) sleep(10) t = t + 10 finally: # Turn off Weather Station port.close() weather_off(1)
def clean_data(self): try: # put all the mesaurements into a matrix (array of arrays) float_array_final = [] string_array_final = [] with open("/media/mmcblk0p1/logs/weather_data_ASCII_schedule.log", "r") as f: for line in f: if "0R0" in line: string_array_raw = re.findall(r"[-+]?\d*\.\d+|\d+", line) for i in range(0, len(string_array_raw)): string_array_raw[i] = float(string_array_raw[i]) string_array_final = string_array_raw[2:] float_array_final.append(string_array_final) except: printf('Failed to acquire Wather station data or got empty array') traceback.print_exc( file=open("/media/mmcblk0p1/logs/system.log", "a+")) finally: # Erase the tempoerary ascii data file subprocess.call( "rm /media/mmcblk0p1/logs/weather_data_ASCII_schedule.log", shell=True) return string_array_final, float_array_final
def __toggle_1hour(): # set the power mode subprocess.call('echo 3 > /sys/class/gpio/wdt_ctl/data', shell=True) sleep(2) subprocess.call('echo 0 > /sys/class/gpio/wdt_ctl/data', shell=True) sleep(2) subprocess.call('echo 3 > /sys/class/gpio/wdt_ctl/data', shell=True) printf("Auto watchdog is set to 1 hour")
def get_binex(self): """ Initiate the reading of the binex language from GPS module to Titron Take no argument Return None """ printf('GPS data acquisition started') try: # try opening the port self.port.open() enable_serial() gps_on(bit=1) sleep(60) except: self.port = None print('An error occurred') traceback.print_exc( file=open("/media/mmcblk0p1/logs/system.log", "a+")) else: self.port.flushInput() self.sequence = 1 while self.sequence <= self.timeout * 60 / self.interval: self.port.write(self.cmd['binex'] + '\r') sleep(2) data = self.port.read(self.port.inWaiting()) writeFile('/media/mmcblk0p1/logs/gps_binex_data_temp.log', data, 'w+') try: subprocess.call( "cat /media/mmcblk0p1/logs/gps_binex_data_temp.log >> /media/mmcblk0p1/logs/gps_binex_data.log", shell=True) except: writeFile('/media/mmcblk0p1/logs/gps_binex.log', '', 'a+') subprocess.call( "cat /media/mmcblk0p1/logs/gps_binex_data_temp.log >> /media/mmcblk0p1/logs/gps_binex_data.log", shell=True) printf("An error occurred during file dumping!") traceback.print_exc( file=open("/media/mmcblk0p1/logs/system.log", "a+")) sleep(2) if self.port.inWaiting() != 0: data = self.port.read(self.port.inWaiting()) writeFile('/media/mmcblk0p1/logs/gps_binex_data_temp.log', data, 'w+') sleep(1) subprocess.call( "cat /media/mmcblk0p1/logs/gps_binex_data_temp.log >> /media/mmcblk0p1/logs/gps_binex.log", shell=True) sleep(self.interval - 5) self.sequence = self.sequence + 1 finally: # At every exit close the port, and turn off the GPS if self.port: self.port.close() subprocess.call("rm /media/mmcblk0p1/logs/gps_binex_data_temp.log", shell=True) gps_off(bit=1) disable_serial()
def average_data(self): # Call first two functions in correct order try: self.read_data() string_array_final, float_array_final = self.clean_data() # average the corresponding elements and output a sinlge array of numbers data_array_final = [] for j in range(0, len(string_array_final)): numbers_sum = 0 numbers_divide = 0 for k in range(0, len(float_array_final)): numbers_sum = numbers_sum + float_array_final[k][j] numbers_divide = numbers_sum / (len(float_array_final)) data_array_final.append(round(numbers_divide, 3)) # Write the averaged array elements to a final log file - append now = datetime.datetime.now() with open("/media/mmcblk0p1/logs/weather_data.log", "a+") as hourly: hourly.write("Current Date and Time: " + now.strftime("%Y-%m-%d %H:%M:%S\n")) hourly.write("Wind Direction Average (Degrees): " + str(data_array_final[0]) + ".\n") hourly.write("Wind Speed Average (m/s): " + str(data_array_final[1]) + ".\n") hourly.write("Air Temperature (C): " + str(data_array_final[2]) + ".\n") hourly.write("Relative Humidity (%RH): " + str(data_array_final[3]) + ".\n") hourly.write("Air Pressure (hPa): " + str(data_array_final[4]) + ".\n") hourly.write("Rain Accumulation (mm): " + str(data_array_final[5]) + ".\n") hourly.write("Rain Duration (s): " + str(data_array_final[6]) + ".\n") hourly.write("Rain Intensity (mm/h): " + str(data_array_final[7]) + ".\n") hourly.write("Rain Peak Intensity (mm/h): " + str(data_array_final[11]) + ".\n") hourly.write("Hail Accumulation (hits/cm^2): " + str(data_array_final[8]) + ".\n") hourly.write("Hail Duration (s): " + str(data_array_final[9]) + ".\n") hourly.write("Hail Intensity (hits/cm^2/hour): " + str(data_array_final[10]) + ".\n") hourly.write("Hail Peak Intensity (hits/cm^2/hour): " + str(data_array_final[12]) + ".\n") hourly.write("Vaisala Heating Temperature (C): " + str(data_array_final[13]) + ".\n") hourly.write("Vaisala Heating Voltage (V): " + str(data_array_final[14]) + ".\n") hourly.write("Vaisala Supply Voltage (V): " + str(data_array_final[15]) + ".\n\n\n") except: printf('Fail to parser vaisala data, maybe got an empty array') traceback.print_exc( file=open("/media/mmcblk0p1/logs/system.log", "a+"))
def readsolar(): solar_on() sleep(5) solar1 = open("/media/mmcblk0p1/logs/solar_temp1.log", "w+") solar1.close() # To read the battery voltage analog input: solar2 = open("/media/mmcblk0p1/logs/solar_temp2.log", "w+") solar2.close() t = 0 data = 0 # take voltage readings at a specific rate for a specified amount of time try: while t <= 30: # how long to take readings for (seconds) subprocess.call("echo 0 > /sys/class/gpio/mcp3208-gpio/index", shell=True) sleep(1) subprocess.call( 'cat /sys/class/gpio/mcp3208-gpio/data > /media/mmcblk0p1/logs/solar_temp1.log', shell=True) subprocess.call("echo 1 > /sys/class/gpio/mcp3208-gpio/index", shell=True) sleep(1) subprocess.call( 'cat /sys/class/gpio/mcp3208-gpio/data > /media/mmcblk0p1/logs/solar_temp2.log', shell=True) with open('/media/mmcblk0p1/logs/solar_temp1.log', "r") as solar_temp1: data1 = solar_temp1.read() data1 = int(data1, 16) # print(data1) with open("/media/mmcblk0p1/logs/solar_temp2.log", "r") as solar_temp2: data2 = solar_temp2.read() data2 = int(data2, 16) # print(data2) date = str(datetime.datetime.now()) data = date + ", " + str(data1) + ", " + str(data2) + "\n" data = str(data) # print(data) with open("/media/mmcblk0p1/logs/solar_data.log", "a+") as solar: solar.write(data + '\n') sleep(8) # set rate of readings in seconds t = t + 10 # keep time except: printf("Unable to read solar sensor") traceback.print_exc( file=open("/media/mmcblk0p1/logs/system.log", "a+")) # print(t) finally: solar_off() subprocess.call('rm /media/mmcblk0p1/logs/solar_temp1.log', shell=True) subprocess.call('rm /media/mmcblk0p1/logs/solar_temp2.log', shell=True)
def read(): try: port = ser('/dev/ttyS1') port.baudrate = 9600 port.timeout = 60 port.open() except: printf('Unable to open port') return None rev = port.read(port.inWaiting()) return rev
def power_up(bit): if bit: __toggle(bit-1) subprocess.call("echo 0xFF> /sys/class/gpio/pwr_ctl/data", shell=True) sleep(2) __toggle(bit) subprocess.call("echo 0xFF > /sys/class/gpio/pwr_ctl/data", shell=True) sleep(2) __toggle(2) subprocess.call("echo 0xFF > /sys/class/gpio/pwr_ctl/data", shell=True) printf("All devices powered on") __update_bit('0b11111111,0b11111111,0b11111111')
def gps_on(bit): """ Turn gps module power on after toggling the bit """ if bit: with open("/media/mmcblk0p1/logs/power_log.log", "r") as power_log: bit_string = power_log.read().split(',') bit_str = bit_string[0][0:8]+"1"+bit_string[0][9] __toggle(bit-1) subprocess.call( "echo {0} > /sys/class/gpio/pwr_ctl/data".format(hex(int(bit_str, 2))), shell=True) printf("gps turned on") __update_bit(bit_str + ','+bit_string[1]+','+bit_string[2])
def all_off(bit): if bit: bit_string = "0b00000000,0b00000000,0b00000000" __update_bit(bit_string) __toggle(bit-1) subprocess.call("echo 0x0> /sys/class/gpio/pwr_ctl/data", shell=True) sleep(1) __toggle(bit) subprocess.call("echo 0x0 > /sys/class/gpio/pwr_ctl/data", shell=True) sleep(1) __toggle(2) subprocess.call("echo 0x0 > /sys/class/gpio/pwr_ctl/data", shell=True) printf("Turning off all devices now!")
def V5_ENA_OFF(): """ Disabled 5 volt switch """ with open("/media/mmcblk0p1/logs/power_log.log", "r") as power_log: bit_string = power_log.read().split(',') bit_str = bit_string[2][0:9]+"0" __toggle(2) sleep(1) subprocess.call( "echo {0} > /sys/class/gpio/pwr_ctl/data".format(hex(int(bit_str, 2))), shell=True) printf("Disabled 5 volt switch") __update_bit(bit_string[0] + ','+bit_string[1]+','+bit_str)
def solar_off(): """ Disable 5 volt to solar sensor """ with open("/media/mmcblk0p1/logs/power_log.log", "r") as power_log: bit_string = power_log.read().split(',') bit_str = bit_string[2][0:6]+"0"+bit_string[2][7:] __toggle(2) sleep(1) subprocess.call( "echo {0} > /sys/class/gpio/pwr_ctl/data".format(hex(int(bit_str, 2))), shell=True) printf("solar sensor turned off") __update_bit(bit_string[0] + ','+bit_string[1]+','+bit_str)
def iridium_on(bit): """ Turn iridium module power on after toggling the bit """ if bit: with open("/media/mmcblk0p1/logs/power_log.log", "r") as power_log: bit_string = str(power_log.read()).split(",") bit_str = bit_string[1][0:5]+"1"+bit_string[1][6:] __toggle(bit) subprocess.call( "echo {0} > /sys/class/gpio/pwr_ctl/data".format(hex(int(bit_str, 2))), shell=True) printf("iridium turned on") __update_bit(bit_string[0] + ','+bit_str+','+bit_string[2])
def dts_off(bit): """ Turn windows/dts module power off after toggling the bit """ if bit: with open("/media/mmcblk0p1/logs/power_log.log", "r") as power_log: bit_string = power_log.read().split(",") bit_str = bit_string[0][0:3]+"0"+bit_string[0][4:] __toggle(bit-1) subprocess.call( "echo {0} > /sys/class/gpio/pwr_ctl/data".format(hex(int(bit_str, 2))), shell=True) printf("dts turned off") __update_bit(bit_str + ','+bit_string[1]+','+bit_string[2])
def disable_serial(): """ Enable serial communication """ with open("/media/mmcblk0p1/logs/power_log.log", "r") as power_log: bit_string = power_log.read().split(',') bit_str = bit_string[2][0:8]+"0"+bit_string[2][9:] __toggle(2) sleep(1) subprocess.call( "echo {0} > /sys/class/gpio/pwr_ctl/data".format(hex(int(bit_str, 2))), shell=True) printf("serial communication disable") __update_bit(bit_string[0] + ','+bit_string[1]+','+bit_str)
def modem_off(bit): """ Turn modem module power off after toggling the bit """ if bit: with open("/media/mmcblk0p1/logs/power_log.log", "r") as power_log: bit_string = power_log.read().split(',') bit_str = bit_string[1][0:6]+"0"+bit_string[1][7:] __toggle(bit) sleep(1) subprocess.call( "echo {0} > /sys/class/gpio/pwr_ctl/data".format(hex(int(bit_str, 2))), shell=True) printf("Modern turned off") __update_bit(bit_string[0] + ','+bit_str+','+bit_string[2])
def reboot(bit): if bit: bit_string = "0b00000000,0b00000000,0b00000000" __update_bit(bit_string) __toggle(bit-1) subprocess.call("echo 0x0> /sys/class/gpio/pwr_ctl/data", shell=True) sleep(2) __toggle(bit) subprocess.call("echo 0x0 > /sys/class/gpio/pwr_ctl/data", shell=True) sleep(2) __toggle(2) subprocess.call("echo 0x0 > /sys/class/gpio/pwr_ctl/data", shell=True) printf("Tritron is going down now for reboot!") sleep(2) subprocess.call("reboot", shell=True)
def power_down(bit): if bit: bit_string = "0b00000000,0b00000000,0b00000000" __update_bit(bit_string) __toggle(bit-1) subprocess.call("echo 0x0> /sys/class/gpio/pwr_ctl/data", shell=True) sleep(2) __toggle(bit) subprocess.call("echo 0x0 > /sys/class/gpio/pwr_ctl/data", shell=True) sleep(2) __toggle(2) subprocess.call("echo 0x0 > /sys/class/gpio/pwr_ctl/data", shell=True) printf("Tritron is going down now!") sleep(2) subprocess.call("shutdown -h now", shell=True)
def get_humidity(): data = 0 try: date = str(datetime.datetime.now()) call( 'cat /sys/class/hwmon/hwmon0/device/humidity1_input > /media/mmcblk0p1/logs/onboard_humid_temp.log', shell=True) sleep(1) with open('/media/mmcblk0p1/logs/onboard_humid_temp.log', 'r') as temp: data = float(temp.read()) / 1000 with open('/media/mmcblk0p1/logs/onboard_humid.log', 'a+') as humid: humid.write(date + ' ,' + str(data) + '\n') sleep(2) call('rm /media/mmcblk0p1/logs/onboard_humid_temp.log', shell=True) except: printf('Failed to acquire on board humidity') traceback.print_exc( file=open("/media/mmcblk0p1/logs/system.log", "a+"))
def kill(): """ Find the pid of the scheduler process and Kill the scheduler """ out = None try: p = Popen("top -n 1 | grep python | grep -v grep", stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True) out = p.communicate() out = out[0].replace(' ', '') st = out.find('root') pid = int(out[0:st - 1]) call("kill -2 {0}".format(pid), shell=True) except: printf("Schedule health: Failed to check schedule health") traceback.print_exc( file=open("/media/mmcblk0p1/logs/system.log", "a+"))
def send(message="Testing"): try: port = ser('/dev/ttyS1') port.baudrate = 9600 port.open() iridium_on(1) sbd_on(1) sleep(1) iridium_off(1) enable_serial() sleep(1) except: printf('Unable to open port') else: port.write(message + '\r') printf('sent SBD message: {0} {1}'.format(message, '\r')) sleep(60) finally: disable_serial() sbd_off(1) iridium_off(1)
def get_temperature(): data = 0 try: date = str(datetime.datetime.now()) subprocess.call( 'cat /sys/class/hwmon/hwmon0/device/temp1_input> /media/mmcblk0p1/logs/onboard_temperature_temp.log', shell=True) sleep(1) with open('/media/mmcblk0p1/logs/onboard_temperature_temp.log', 'r') as temp: data = float(temp.read()) / 1000 with open('/media/mmcblk0p1/logs/onboard_temperature.log', 'a+') as temp: temp.write(date + ' ,' + str(data) + '\n') sleep(2) call('rm /media/mmcblk0p1/logs/onboard_temperature_temp.log', shell=True) except Exception as err: printf('Failed to acquire on board temperature') traceback.print_exc( file=open("/media/mmcblk0p1/logs/system.log", "a+"))
def get_battery_voltage(): try: # get the voltage of the battery Vref_10 = 33 Vdividor = 4095 Vmultiplier = 7997 Vfinal_dividor = 10000 call('echo 4 > /sys/class/gpio/mcp3208-gpio/index', shell=True) sleep(1) p = Popen("cat /sys/class/gpio/mcp3208-gpio/data", stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True) out = p.communicate() volt = (((float(int('0x' + out[0], 16)) * Vref_10) / Vdividor) * Vmultiplier) / Vfinal_dividor return volt except: printf('Failed to acquire board input voltage') traceback.print_exc( file=open("/media/mmcblk0p1/logs/system.log", "a+"))
def get_battery_current(): try: # get the current of the battery dividor = 4095 # was 829 org multiplier = 790 final_dividor = 100 call('echo 5 > /sys/class/gpio/mcp3208-gpio/index', shell=True) sleep(1) p = Popen("cat /sys/class/gpio/mcp3208-gpio/data", stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True) out = p.communicate() curr = (float(int('0x' + out[0], 16)) * multiplier / dividor) / final_dividor return curr except: printf('Failed to acquire board input current') traceback.print_exc( file=open("/media/mmcblk0p1/logs/system.log", "a+"))
def cr_read(self): try: modem_on(1) is_on = is_on_checker(0, 5) if not is_on: # Turn on CR1000x cr1000_on(1) sleep(15) except: printf("Problem with port or problem with power to the CR1000") traceback.print_exc( file=open("/media/mmcblk0p1/logs/system.log", "a+")) else: # Read data device = CR1000.from_url('tcp:192.168.0.30:6785') data = device.get_data('Public') finally: if not is_on: # Turn off CR1000 cr1000_off(1) modem_off(1) return data
def write_file(self): try: labels, values = self.finddata() except Exception as err: printf('Unable to acquire cr1000x data with exception {0}'.format( err)) traceback.print_exc( file=open("/media/mmcblk0p1/logs/system.log", "a+")) else: therms = open("/media/mmcblk0p1/logs/thermdata.log", "a+") try: for i in range(len(labels)): therms.write(labels[i] + ': ' + values[i] + "\n") therms.close() except Exception as err: printf( 'failed to format cr1000x data with exception {1}. raw data {0}' .format(values, err)) traceback.print_exc( file=open("/media/mmcblk0p1/logs/system.log", "a+")) finally: cr1000_off(1) modem_off(1)
def get_schedule_health(): out = None try: p = Popen("top -n 1 | grep python | grep -v grep", stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True) out = p.communicate() out = out[0].replace(' ', '') st = out.find('root') out = int(out[st + 5:st + 10]) except: printf("Schedule health: Failed to check schedule health") traceback.print_exc( file=open("/media/mmcblk0p1/logs/system.log", "a+")) else: if out > 20000: printf("Self destrying schedule ram memory consumption above {0}". format(out)) kill() elif out < 15000: printf('Schedule health: Normal at {0} kb of ram'.format(out)) elif out >= 15000 and out < 17000: printf('Schedule health: warning at {0} kb of ram'.format(out)) elif out == None: printf('Schedule health: Scheduler not running') else: printf( 'Schedule health: critical at {0} kb of ram. Scheduler would be terminated at over 20000 kb' .format(out))