diff --git a/DHT22.py b/DHT22.py deleted file mode 100755 index 0bd269c..0000000 --- a/DHT22.py +++ /dev/null @@ -1,283 +0,0 @@ -#!/usr/bin/env python - -# 2014-07-11 DHT22.py - -import time -#import atexit - -import pigpio - -class sensor: - """ - A class to read relative humidity and temperature from the - DHT22 sensor. The sensor is also known as the AM2302. - - The sensor can be powered from the Pi 3V3 or the Pi 5V rail. - - Powering from the 3V3 rail is simpler and safer. You may need - to power from 5V if the sensor is connected via a long cable. - - For 3V3 operation connect pin 1 to 3V3 and pin 4 to ground. - - Connect pin 2 to a gpio. - - For 5V operation connect pin 1 to 5V and pin 4 to ground. - - The following pin 2 connection works for me. Use at YOUR OWN RISK. - - 5V--5K_resistor--+--10K_resistor--Ground - | - DHT22 pin 2 -----+ - | - gpio ------------+ - """ - - def __init__(self, pi, gpio, LED=None, power=None): - """ - Instantiate with the Pi and gpio to which the DHT22 output - pin is connected. - - Optionally a LED may be specified. This will be blinked for - each successful reading. - - Optionally a gpio used to power the sensor may be specified. - This gpio will be set high to power the sensor. If the sensor - locks it will be power cycled to restart the readings. - - Taking readings more often than about once every two seconds will - eventually cause the DHT22 to hang. A 3 second interval seems OK. - """ - - self.pi = pi - self.gpio = gpio - self.LED = LED - self.power = power - - if power is not None: - pi.write(power, 1) # Switch sensor on. - time.sleep(2) - - self.powered = True - - self.cb = None - - #atexit.register(self.cancel) - - self.bad_CS = 0 # Bad checksum count. - self.bad_SM = 0 # Short message count. - self.bad_MM = 0 # Missing message count. - self.bad_SR = 0 # Sensor reset count. - - # Power cycle if timeout > MAX_TIMEOUTS. - self.no_response = 0 - self.MAX_NO_RESPONSE = 2 - - self.rhum = -999 - self.temp = -999 - - self.tov = None - - self.high_tick = 0 - self.bit = 40 - - pi.set_pull_up_down(gpio, pigpio.PUD_OFF) - - pi.set_watchdog(gpio, 0) # Kill any watchdogs. - - self.cb = pi.callback(gpio, pigpio.EITHER_EDGE, self._cb) - - def _cb(self, gpio, level, tick): - """ - Accumulate the 40 data bits. Format into 5 bytes, humidity high, - humidity low, temperature high, temperature low, checksum. - """ - diff = pigpio.tickDiff(self.high_tick, tick) - - if level == 0: - - # Edge length determines if bit is 1 or 0. - - if diff >= 50: - val = 1 - if diff >= 200: # Bad bit? - self.CS = 256 # Force bad checksum. - else: - val = 0 - - if self.bit >= 40: # Message complete. - self.bit = 40 - - elif self.bit >= 32: # In checksum byte. - self.CS = (self.CS<<1) + val - - if self.bit == 39: - - # 40th bit received. - - self.pi.set_watchdog(self.gpio, 0) - - self.no_response = 0 - - total = self.hH + self.hL + self.tH + self.tL - - if (total & 255) == self.CS: # Is checksum ok? - - self.rhum = ((self.hH<<8) + self.hL) * 0.1 - - if self.tH & 128: # Negative temperature. - mult = -0.1 - self.tH = self.tH & 127 - else: - mult = 0.1 - - self.temp = ((self.tH<<8) + self.tL) * mult - - self.tov = time.time() - - if self.LED is not None: - self.pi.write(self.LED, 0) - - else: - - self.bad_CS += 1 - - elif self.bit >=24: # in temp low byte - self.tL = (self.tL<<1) + val - - elif self.bit >=16: # in temp high byte - self.tH = (self.tH<<1) + val - - elif self.bit >= 8: # in humidity low byte - self.hL = (self.hL<<1) + val - - elif self.bit >= 0: # in humidity high byte - self.hH = (self.hH<<1) + val - - else: # header bits - pass - - self.bit += 1 - - elif level == 1: - self.high_tick = tick - if diff > 250000: - self.bit = -2 - self.hH = 0 - self.hL = 0 - self.tH = 0 - self.tL = 0 - self.CS = 0 - - else: # level == pigpio.TIMEOUT: - self.pi.set_watchdog(self.gpio, 0) - if self.bit < 8: # Too few data bits received. - self.bad_MM += 1 # Bump missing message count. - self.no_response += 1 - if self.no_response > self.MAX_NO_RESPONSE: - self.no_response = 0 - self.bad_SR += 1 # Bump sensor reset count. - if self.power is not None: - self.powered = False - self.pi.write(self.power, 0) - time.sleep(2) - self.pi.write(self.power, 1) - time.sleep(2) - self.powered = True - elif self.bit < 39: # Short message receieved. - self.bad_SM += 1 # Bump short message count. - self.no_response = 0 - - else: # Full message received. - self.no_response = 0 - - def temperature(self): - """Return current temperature.""" - return self.temp - - def humidity(self): - """Return current relative humidity.""" - return self.rhum - - def staleness(self): - """Return time since measurement made.""" - if self.tov is not None: - return time.time() - self.tov - else: - return -999 - - def bad_checksum(self): - """Return count of messages received with bad checksums.""" - return self.bad_CS - - def short_message(self): - """Return count of short messages.""" - return self.bad_SM - - def missing_message(self): - """Return count of missing messages.""" - return self.bad_MM - - def sensor_resets(self): - """Return count of power cycles because of sensor hangs.""" - return self.bad_SR - - def trigger(self): - """Trigger a new relative humidity and temperature reading.""" - if self.powered: - if self.LED is not None: - self.pi.write(self.LED, 1) - - self.pi.write(self.gpio, pigpio.LOW) - time.sleep(0.017) # 17 ms - self.pi.set_mode(self.gpio, pigpio.INPUT) - self.pi.set_watchdog(self.gpio, 200) - - def cancel(self): - """Cancel the DHT22 sensor.""" - - self.pi.set_watchdog(self.gpio, 0) - - if self.cb != None: - self.cb.cancel() - self.cb = None - -if __name__ == "__main__": - - import time - - import pigpio - - import DHT22 - - # Intervals of about 2 seconds or less will eventually hang the DHT22. - INTERVAL=3 - - pi = pigpio.pi() - - s = DHT22.sensor(pi, 4) - - r = 0 - - next_reading = time.time() - - while True: - - r += 1 - - s.trigger() - - time.sleep(0.2) - - print("{} {} {} {:3.2f} {} {} {} {}".format( - r, s.humidity(), s.temperature(), s.staleness(), - s.bad_checksum(), s.short_message(), s.missing_message(), - s.sensor_resets())) - - next_reading += INTERVAL - - time.sleep(next_reading-time.time()) # Overall INTERVAL second polling. - - s.cancel() - - pi.stop() - diff --git a/HWcontrol.py b/HWcontrol.py old mode 100644 new mode 100755 index bdd2d98..45f7794 --- a/HWcontrol.py +++ b/HWcontrol.py @@ -2,6 +2,12 @@ #to kill python processes use -- pkill python +from __future__ import print_function +from __future__ import division +from builtins import str +from builtins import hex +from builtins import range +from past.utils import old_div import time import datetime import threading @@ -10,11 +16,9 @@ #import serial #import os import glob - - - import logging + logger = logging.getLogger("hydrosys4."+__name__) @@ -26,10 +30,19 @@ except ImportError: ISRPI=False else: + import sys, os + basepath=os.getcwd() + libpath="libraries/BMP/bmp180" # should be without the backslash at the beginning + sys.path.append(os.path.join(basepath, libpath)) # this adds new import paths to add modules + from grove_i2c_barometic_sensor_BMP180 import BMP085 + libpath="libraries/MotorHat" # should be without the backslash at the beginning + sys.path.append(os.path.join(basepath, libpath)) # this adds new import paths to add modules + from stepperDOUBLEmod import Adafruit_MotorHAT, Adafruit_DCMotor, Adafruit_StepperMotor + import Adafruit_DHT #humidity temperature sensor - import Adafruit_BMP.BMP085 as BMP085 #pressure sensor + #from Adafruit_MotorHAT import Adafruit_MotorHAT, Adafruit_DCMotor, Adafruit_StepperMotor - from stepperDOUBLEmod import Adafruit_MotorHAT, Adafruit_DCMotor, Adafruit_StepperMotor + import spidev import smbus import Hygro24_I2C @@ -40,7 +53,7 @@ ISRPI=True -HWCONTROLLIST=["tempsensor","humidsensor","pressuresensor","analogdigital","lightsensor","pulse","pinstate","servo","stepper","stepperstatus","photo","mail+info+link","mail+info","returnzero","stoppulse","readinputpin","hbridge","hbridgestatus","DS18B20","Hygro24_I2C","HX711","SlowWire","InterrFreqCounter"] +HWCONTROLLIST=["tempsensor","humidsensor","pressuresensor","analogdigital","lightsensor","pulse","pinstate","servo","stepper","stepperstatus","photo","mail+info+link","mail+info","returnzero","stoppulse","readinputpin","hbridge","hbridgestatus","DS18B20","Hygro24_I2C","HX711","SlowWire","InterrFreqCounter","WeatherAPI"] RPIMODBGPIOPINLIST=["2", "3", "4","5","6", "7", "8", "9", "10", "11", "12","13","14", "15", "16","17", "18", "19", "20","21","22", "23", "24", "25","26", "27"] NALIST=["N/A"] GPIOPLUSLIST=["I2C", "SPI"] @@ -195,9 +208,11 @@ def execute_task(cmd, message, recdata): elif cmd==HWCONTROLLIST[22]: # Interrupt frequency counter return get_InterruptFrequency_reading(cmd, message, recdata) + elif cmd==HWCONTROLLIST[23]: # weather API counter + return get_WeatherAPI_reading(cmd, message, recdata) else: - print "Command not found" + print("Command not found") recdata.append(cmd) recdata.append("e") recdata.append(0) @@ -224,7 +239,7 @@ def execute_task_fake(cmd, message, recdata): return True; else: - print "no fake command available" , cmd + print("no fake command available" , cmd) recdata.append(cmd) recdata.append("e") recdata.append(0) @@ -305,23 +320,23 @@ def get_DHT22_reading(cmd, message, recdata, DHT22_data): temperature=temperature*1.8+32 except: - print "error reading the DHT sensor (Humidity,Temperature)" + print("error reading the DHT sensor (Humidity,Temperature)") logger.error("error reading the DHT sensor (Humidity,Temperature)") # if reading OK, update status variable if (humidity is not None) and (temperature is not None): # further checks if (humidity>=0)and(humidity<=100)and(temperature>-20)and(temperature<200): - print 'Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity) - DHT22_data[element]['humidity']=('{:3.2f}'.format(humidity / 1.)) - DHT22_data[element]['temperature']=('{:3.2f}'.format(temperature / 1.)) + print('Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity)) + DHT22_data[element]['humidity']=('{:3.2f}'.format(old_div(humidity, 1.))) + DHT22_data[element]['temperature']=('{:3.2f}'.format(old_div(temperature, 1.))) DHT22_data[element]['lastupdate']=datetime.datetime.utcnow() successflag=1 else: - print 'Failed to get DHT22 reading' + print('Failed to get DHT22 reading') logger.error("Failed to get DHT22 reading, values in wrong range") else: - print 'Failed to get DHT22 reading' + print('Failed to get DHT22 reading') logger.error("Failed to get DHT22 reading") time.sleep(1) @@ -357,10 +372,24 @@ def get_DHT22_humidity(cmd, message, recdata, DHT22_data): def get_BMP180_pressure(cmd, message, recdata): successflag=0 Pressure=0 + + # Initialise the BMP085 and use STANDARD mode (default value) + # bmp = BMP085(0x77, debug=True) + # bmp = BMP085(0x77, 1) + + # To specify a different operating mode, uncomment one of the following: + # bmp = BMP085(0x77, 0) # ULTRALOWPOWER Mode + # bmp = BMP085(0x77, 1) # STANDARD Mode + # bmp = BMP085(0x77, 2) # HIRES Mode + bmp = BMP085(0x77, 3) # ULTRAHIRES Mode + + #temp = bmp.readTemperature() + try: - sensor = BMP085.BMP085(3) # 3 = High resolution mode - Pressure = '{0:0.2f}'.format(sensor.read_pressure()/float(100)) - successflag=1 + isok, Pressure = bmp.readPressure() + if isok: + Pressure = '{0:0.2f}'.format(Pressure/100) # the reading is in Hpa + successflag=1 except: #print " I2C bus reading error, BMP180 , pressure sensor " logger.error(" I2C bus reading error, BMP180 , pressure sensor ") @@ -369,7 +398,7 @@ def get_BMP180_pressure(cmd, message, recdata): recdata.append(Pressure) recdata.append(successflag) return True - + def get_BH1750_light(cmd, message, recdata): successflag=0 @@ -399,7 +428,7 @@ def get_BH1750_light(cmd, message, recdata): light=0 try: data = bus.read_i2c_block_data(DEVICE,ONE_TIME_HIGH_RES_MODE_1) - light = '{0:0.2f}'.format(((data[1] + (256 * data[0])) / 1.2)) + light = '{0:0.2f}'.format((old_div((data[1] + (256 * data[0])), 1.2))) successflag=1 except: #print " I2C bus reading error, BH1750 , light sensor " @@ -482,10 +511,10 @@ def get_DS18B20_temperature(cmd, message, recdata): temp_string = lines[1][equals_pos+2:] # takes the right part of the string try: - temperature = float(temp_string) / 1000.0 + temperature = old_div(float(temp_string), 1000.0) if (TemperatureUnit=="F") and (temperature is not None): temperature=temperature*1.8+32 - temperature=('{:3.2f}'.format(temperature / 1.)) + temperature=('{:3.2f}'.format(old_div(temperature, 1.))) successflag=1 except: @@ -534,7 +563,7 @@ def get_HX711_voltage(cmd, message, recdata): if (PINDATA<0)or(PINCLK<0): - print "HX711 PIN not valid", SensorAddress + print("HX711 PIN not valid", SensorAddress) # address not correct logger.error("HX711 PIN not valid: Pindata = %s Pinclk= %s", PINDATA_str,PINCLK_str) recdata.append(cmd) @@ -579,12 +608,12 @@ def get_HX711_voltage(cmd, message, recdata): averagefiltered, average = normalize_average(dataarray) - print "HX711 data Average: ",average , " Average filtered: ", averagefiltered + print("HX711 data Average: ",average , " Average filtered: ", averagefiltered) reading=averagefiltered - print "reading ", reading + print("reading ", reading) recdata.append(cmd) recdata.append(reading) @@ -618,7 +647,7 @@ def get_SlowWire_reading(cmd, message, recdata): if (PINDATA<0): - print "SlowWire PIN not valid" + print("SlowWire PIN not valid") # address not correct logger.error("SlowWire PIN not valid: Pindata = %s ", PINDATA_str) recdata.append(cmd) @@ -666,12 +695,12 @@ def get_SlowWire_reading(cmd, message, recdata): averagefiltered, average = normalize_average(dataarray) - print "SlowWire data Average: ",average , " Average filtered: ", averagefiltered + print("SlowWire data Average: ",average , " Average filtered: ", averagefiltered) reading=averagefiltered - print "reading ", reading + print("reading ", reading) recdata.append(cmd) recdata.append(reading) @@ -708,7 +737,7 @@ def get_Hygro24_capacity(cmd, message, recdata): else: SensorAddressInt = int(SensorAddress) except: - print "can't parse %s as an i2c address", SensorAddress + print("can't parse %s as an i2c address", SensorAddress) # address not correct logger.error("Hygro24_I2C address incorrect: %s", SensorAddress) recdata.append(cmd) @@ -722,7 +751,7 @@ def get_Hygro24_capacity(cmd, message, recdata): isOK , reading=chirp.read_capacity() # need to add control in case there is an error in reading - print "reading ", reading + print("reading ", reading) if isOK: successflag=1 @@ -779,7 +808,7 @@ def get_MCP3008_channel(cmd, message, recdata): if (waittime>=maxwait): #something wrog, wait too long, avoid initiate further processing - print "MCP3008 wait time EXCEEDED " + print("MCP3008 wait time EXCEEDED ") logger.warning("Wait Time exceeded, not able to read ADCdata Channel: %d", channel) return False @@ -824,8 +853,8 @@ def get_MCP3008_channel(cmd, message, recdata): # Function to convert data to voltage level, # rounded to specified number of decimal places. - voltsraw = (mean * refvoltage) / float(1023) - voltsnorm = (dataaverage * refvoltage) / float(1023) + voltsraw = old_div((mean * refvoltage), float(1023)) + voltsnorm = old_div((dataaverage * refvoltage), float(1023)) volts = round(voltsnorm,2) #print "MCP3008 chennel ", channel, " Average (volts): ",voltsraw , " Average Norm (v): ", voltsnorm @@ -833,7 +862,7 @@ def get_MCP3008_channel(cmd, message, recdata): spi.close() successflag=1 except: - print " DPI bus reading error, MCP3008 , AnalogDigitalConverter " + print(" DPI bus reading error, MCP3008 , AnalogDigitalConverter ") logger.error(" DPI bus reading error, MCP3008 , AnalogDigitalConverter ") recdata.append(cmd) @@ -854,18 +883,18 @@ def normalize_average(lst): """Calculates the standard deviation for a list of numbers.""" num_items = len(lst) if num_items>0: - mean = sum(lst) / float(num_items) + mean = old_div(sum(lst), float(num_items)) differences = [x - mean for x in lst] sq_differences = [d ** 2 for d in differences] ssd = sum(sq_differences) - variance = ssd / float(num_items) + variance = old_div(ssd, float(num_items)) sd = sqrt(variance) # use functions to adjust data, keep only the data inside the standard deviation final_list = [x for x in lst if ((x >= mean - sd) and (x <= mean + sd))] num_items_final = len(final_list) - normmean=sum(final_list) / float(num_items_final) + normmean=old_div(sum(final_list), float(num_items_final)) #print "discarded ", num_items-num_items_final , " mean difefrence ", normmean-mean @@ -1138,6 +1167,23 @@ def get_InterruptFrequency_reading(cmd, message, recdata): recdata.append(successflag) return True +def get_WeatherAPI_reading(cmd, message, recdata): + import weatherAPImod + successflag=1 + recdata.append(cmd) + + # here the reading + isok, reading=weatherAPImod.CalculateRainMultiplier() + if isok: + recdata.append(reading) + recdata.append(successflag) + else: + successflag=0 + recdata.append("e") + recdata.append(successflag) + return True + + def read_input_pin(cmd, message, recdata): @@ -1173,7 +1219,7 @@ def gpio_set_servo(cmd, message, recdata): previousduty=float(msgarray[5]) stepnumber=int(msgarray[6]) - step=(duty-previousduty)/stepnumber + step=old_div((duty-previousduty),stepnumber) GPIO_setup(str(PIN), "out") @@ -1234,7 +1280,7 @@ def gpio_set_hbridge(cmd, message, recdata , hbridge_data ): if hbridgebusy: - print "hbridge motor busy " + print("hbridge motor busy ") logger.warning("hbridge motor Busy, not proceeding ") recdata.append(cmd) recdata.append("e") @@ -1268,7 +1314,7 @@ def gpio_set_hbridge(cmd, message, recdata , hbridge_data ): except: - print "problem hbridge execution" + print("problem hbridge execution") logger.error("problem hbridge execution") recdata.append(cmd) recdata.append("e") @@ -1326,7 +1372,7 @@ def gpio_set_stepper(cmd, message, recdata , stepper_data): mh = Adafruit_MotorHAT() mh.reset() else: - print "Stepper busy " + print("Stepper busy ") logger.warning("Stepper Busy, not proceeding with stepper: %s", Interface) return False @@ -1335,31 +1381,32 @@ def gpio_set_stepper(cmd, message, recdata , stepper_data): # stepper is no busy, proceed - try: - # create a default object, no changes to I2C address or frequency - mh = Adafruit_MotorHAT() - - # set motor parameters - myStepper = mh.getStepper(200, Interface_Number) # 200 steps/rev, motor port #1 or #2 - myStepper.setSpeed(speed) # 30 RPM +# try: + # create a default object, no changes to I2C address or frequency + mh = Adafruit_MotorHAT() + + # set motor parameters + myStepper = mh.getStepper(200, Interface_Number) # 200 steps/rev, motor port #1 or #2 + myStepper.setSpeed(speed) # 30 RPM - #print "Double coil steps" - if direction=="FORWARD": - myStepper.step(steps, Adafruit_MotorHAT.FORWARD, Adafruit_MotorHAT.DOUBLE) - elif direction=="BACKWARD": - myStepper.step(steps, Adafruit_MotorHAT.BACKWARD, Adafruit_MotorHAT.DOUBLE) - - # turn off motors - mh.getMotor(1).run(Adafruit_MotorHAT.RELEASE) - mh.getMotor(2).run(Adafruit_MotorHAT.RELEASE) - mh.getMotor(3).run(Adafruit_MotorHAT.RELEASE) - mh.getMotor(4).run(Adafruit_MotorHAT.RELEASE) - - del mh + #print "Double coil steps" + if direction=="FORWARD": + myStepper.step(steps, Adafruit_MotorHAT.FORWARD, Adafruit_MotorHAT.DOUBLE) + elif direction=="BACKWARD": + myStepper.step(steps, Adafruit_MotorHAT.BACKWARD, Adafruit_MotorHAT.DOUBLE) + + # turn off motors + mh.getMotor(1).run(Adafruit_MotorHAT.RELEASE) + mh.getMotor(2).run(Adafruit_MotorHAT.RELEASE) + mh.getMotor(3).run(Adafruit_MotorHAT.RELEASE) + mh.getMotor(4).run(Adafruit_MotorHAT.RELEASE) + + del mh + try: write_status_data(stepper_data,Interface,"busyflag",False) except: - print "problem I2C stepper controller" + print("problem I2C stepper controller") logger.error("problem I2C stepper controller") write_status_data(stepper_data,Interface,"busyflag",False) return False @@ -1419,5 +1466,5 @@ def sendcommand(cmd, message, recdata): for i in range(0,30): get_DHT22_temperature_fake("tempsensor1", "" , recdata , DHT22_data ) time.sleep(0.4) - print DHT22_data['lastupdate'] + print(DHT22_data['lastupdate']) diff --git a/Hygro24_I2C.py b/Hygro24_I2C.py old mode 100644 new mode 100755 index ea4a6d5..aa5567d --- a/Hygro24_I2C.py +++ b/Hygro24_I2C.py @@ -1,9 +1,11 @@ #!/usr/bin/env python from __future__ import print_function +from builtins import hex +from builtins import object import smbus, time, sys, argparse -class ChirpAV: +class ChirpAV(object): def __init__(self, bus=1, address=0x20): self.bus_num = bus self.bus = smbus.SMBus(bus) @@ -159,13 +161,13 @@ def __repr__(self): if args.set_address: sa = args.set_address try: - if sa.startswith("0x"): - sa = int(sa, 16) - else: - sa = int(sa) + if sa.startswith("0x"): + sa = int(sa, 16) + else: + sa = int(sa) except ValueError: - parser.error("can't parse %s as an i2c address" % (args.set_address)) - raise SystemExit + parser.error("can't parse %s as an i2c address" % (args.set_address)) + raise SystemExit print("Setting the chirp's i2c address to 0x%x" % (sa)) chirp.set_address(sa) diff --git a/SlowWire.py b/SlowWire.py old mode 100644 new mode 100755 index 4be8643..9cc63c8 --- a/SlowWire.py +++ b/SlowWire.py @@ -3,7 +3,12 @@ """ #!/usr/bin/env python from __future__ import print_function +from __future__ import division +from builtins import hex +from builtins import range +from builtins import object +from past.utils import old_div import time # this is in python 2.7 which does not have the routine "time.perf_counter" in python 2.7 need a way to operate import sys import logging @@ -27,7 +32,7 @@ import RPi.GPIO as GPIO -class SlowWire: +class SlowWire(object): """ HX711 represents chip for reading load cells. """ @@ -63,7 +68,7 @@ def read_bytes(self): # return a tuple with boolean for OK and array of bytes ( GPIO.setup(self._dout_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) cyclewait=0.001 - numcycles=int(self._t_wait_sensor/cyclewait) + numcycles=int(old_div(self._t_wait_sensor,cyclewait)) print ("numero di cicli --------------------------->", numcycles) # Wait for sensor to pull pin low. @@ -195,7 +200,7 @@ def read_uint(self): def AddToCRC(self, b, crc): generator=0x1D crc ^= b - for i in xrange(8): + for i in range(8): if ((crc & 0x80) != 0): crc = (crc << 1) ^ generator else: @@ -211,3 +216,26 @@ def checkCRC(self, byteslist): # input is a list of bytes, the last byte should return True return False + + +if __name__ == '__main__': + + """ + This is an usage example, connected to GPIO PIN 17 (BCM) + """ + PINDATA=17 + GPIO.setmode(GPIO.BCM) + Sensor_bus = SlowWire(dout_pin=PINDATA) + + #print "Starting sample reading" + ReadingAttempt=3 + isok=False + while (ReadingAttempt>0)and(not isok): + + isok,datalist = Sensor_bus.read_uint() + if isok: + data=datalist[0] + print ("*************** SlowWire data: *********************** ",data) + else: + print ("error") + ReadingAttempt=ReadingAttempt-1 diff --git a/actuatordbmod.py b/actuatordbmod.py old mode 100644 new mode 100755 index 7f5a970..ecdf39b --- a/actuatordbmod.py +++ b/actuatordbmod.py @@ -2,7 +2,12 @@ """ utility for the planning database """ +from __future__ import print_function +from __future__ import division +from builtins import str +from builtins import range +from past.utils import old_div import logging import string from datetime import datetime,date,timedelta @@ -104,7 +109,7 @@ def getActuatorDataPeriod(selsensor,sensordata,enddate,pastdays): templist=[rowdata[0], value] sensordata.append(templist) except ValueError: - print "Error in database reading ",rowdata + print("Error in database reading ",rowdata) # sensor data -------------------------------------------- @@ -132,7 +137,7 @@ def getAllActuatorDataPeriodv2(enddate,pastdays): templist=[rowdata[0], value] sensordata.append(templist) except ValueError: - print "Error in database reading ",rowdata + print("Error in database reading ",rowdata) if len(sensordata)>0: outputallsensordata.append(sensordata) usedsensorlist.append(selsensor) @@ -190,11 +195,11 @@ def EvaluateDataPeriod(sensordata,startdate,enddate): summa=summa+number inde=inde+1 except ValueError: - print "Evaluation : Error in database reading ",dateref , " " ,data[1] + print("Evaluation : Error in database reading ",dateref , " " ,data[1]) if inde>0: - average=summa/inde + average=old_div(summa,inde) isok=True else: average=0 @@ -224,7 +229,7 @@ def SumProductDataPeriod(sensordata,startdate,enddate,timeinterval): try: sum=sum+float(data[1])*timeinterval except ValueError: - print data[1] + print(data[1]) return sum @@ -288,8 +293,8 @@ def consistencycheck(): sensordata=[] getsensordbdata("temp1",sensordata) getSensorDataPeriod("temp1",sensordata,datetime.now(),1) - print "data: " - print sensordata + print("data: ") + print(sensordata) rowvalue=[] teperatura=10 PHreading=10 diff --git a/advancedmod.py b/advancedmod.py old mode 100644 new mode 100755 index 929d978..fb0ceee --- a/advancedmod.py +++ b/advancedmod.py @@ -2,7 +2,9 @@ """ watering UI setting storage utilities """ +from __future__ import print_function +from builtins import str import logging import os import os.path @@ -27,7 +29,7 @@ if not filestoragemod.readfiledata(DATAFILENAME,data): #read watering setting file #read from default file filestoragemod.readfiledata(DEFDATAFILENAME,data) - print "Watering writing default calibration data" + print("Watering writing default calibration data") filestoragemod.savefiledata(DATAFILENAME,data) # end read data ----- diff --git a/autofertilizerdbmod.py b/autofertilizerdbmod.py old mode 100644 new mode 100755 index 2e3e7b8..2a7a059 --- a/autofertilizerdbmod.py +++ b/autofertilizerdbmod.py @@ -2,6 +2,7 @@ """ Auto watering UI setting storage utilities """ +from __future__ import print_function import logging import os @@ -30,7 +31,7 @@ if not filestoragemod.readfiledata(WTDATAFILENAME,WTdata): #read watering setting file #read from default file filestoragemod.readfiledata(DEFWTDATAFILENAME,WTdata) - print "Using Default config file" + print("Using Default config file") filestoragemod.savefiledata(WTDATAFILENAME,WTdata) # end read IOdata ----- @@ -165,7 +166,7 @@ def getrowdata(recordvalue,paramlist,index): #for parameters with array of integ for param in paramlist: try: datalist.append(int(ln[param][index])) - except Exception, e: + except Exception as e: #print 'Failed to load value ',param ,' set value to zero. Error: '+ str(e) datalist.append(0) diff --git a/autofertilizermod.py b/autofertilizermod.py old mode 100644 new mode 100755 index 6deb50a..0e6c935 --- a/autofertilizermod.py +++ b/autofertilizermod.py @@ -1,3 +1,4 @@ +from __future__ import print_function import logging from datetime import datetime, date ,timedelta import time @@ -46,20 +47,20 @@ def checkactivate(elementwater,durationwater): if waterok: # there is a corresponding doser element minwaterduration=hardwaremod.toint(autofertilizerdbmod.searchdata("element",element,"minactivationsec"),0) if not isschedulermode(element): #setup is not for scheduled time - print " Fertilizer " ,element ," set to autowater" - print " Check Water duration ", durationwater ,">", minwaterduration + print(" Fertilizer " ,element ," set to autowater") + print(" Check Water duration ", durationwater ,">", minwaterduration) if durationwater>minwaterduration: # watering time above the set threshold - print " OK Water duration " + print(" OK Water duration ") if statusdataDBmod.read_status_data(AUTO_data,element,"tobeactivated"): #if flag is ON - print " Activate ", element + print(" Activate ", element) durationfer=statusdataDBmod.read_status_data(AUTO_data,element,"duration") activatedoser(element,durationfer) time.sleep(durationfer) #this blocks the system (and watering activation) for n seconds ... not best practice else: - print " No pending request to activate ", element + print(" No pending request to activate ", element) def activatedoser(element, duration): - print element, " ",duration, " " , datetime.now() + print(element, " ",duration, " " , datetime.now()) logger.info('Doser Pulse, pulse time for ms = %s', duration) pulseok=hardwaremod.makepulse(element,duration) # salva su database @@ -83,10 +84,10 @@ def checkworkmode(element): def timelist(element): if isschedulermode(element): fertime=autofertilizerdbmod.searchdata("element",element,"time") - print "fertime " , fertime + print("fertime " , fertime) timelist=hardwaremod.separatetimestringint(fertime) else: - print "non scheduler mode " + print("non scheduler mode ") timelist=hardwaremod.separatetimestringint("00:20:00") # get up 0 minutes and check for doseractivation return timelist diff --git a/automationdbmod.py b/automationdbmod.py old mode 100644 new mode 100755 index 47c9aaf..15507c2 --- a/automationdbmod.py +++ b/automationdbmod.py @@ -2,6 +2,7 @@ """ Auto watering UI setting storage utilities """ +from __future__ import print_function import logging import os @@ -30,7 +31,7 @@ if not filestoragemod.readfiledata(WTDATAFILENAME,WTdata): #read watering setting file #read from default file filestoragemod.readfiledata(DEFWTDATAFILENAME,WTdata) - print "Watering writing default calibration data" + print("Watering writing default calibration data") filestoragemod.savefiledata(WTDATAFILENAME,WTdata) # end read IOdata ----- @@ -197,7 +198,7 @@ def getrowdata(recordvalue,paramlist,index): #for parameters with array of integ for param in paramlist: try: datalist.append(int(ln[param][index])) - except Exception, e: + except Exception as e: #print 'Failed to load value, set value to zero. Error: '+ str(e) datalist.append(0) diff --git a/automationmod.py b/automationmod.py old mode 100644 new mode 100755 index 21aa4df..204b5cf --- a/automationmod.py +++ b/automationmod.py @@ -1,3 +1,8 @@ +from __future__ import print_function +from __future__ import division +from builtins import str +from builtins import range +from past.utils import old_div import logging from datetime import datetime, time ,timedelta import hardwaremod @@ -62,7 +67,7 @@ def automationexecute(refsensor,element): if (workmode=="None"): # None case - print "No Action required, workmode set to None, element: " , element + print("No Action required, workmode set to None, element: " , element) logger.info("No Action required, workmode set to None, element: %s " , element) return @@ -103,11 +108,11 @@ def automationexecute(refsensor,element): # Calculated Variables if maxstepnumber<1: # not possible to proceed - print "No Action required, maxstepnumber <1, element: " , element + print("No Action required, maxstepnumber <1, element: " , element) logger.info("No Action required, maxstepnumber <1, element: %s " , element) return - interval=(sensormaxthreshold-sensorminthreshold)/maxstepnumber - actuatorinterval=(actuatormaxthreshold-actuatorminthreshold)/maxstepnumber + interval=old_div((sensormaxthreshold-sensorminthreshold),maxstepnumber) + actuatorinterval=old_div((actuatormaxthreshold-actuatorminthreshold),maxstepnumber) P=[] for I in range(0, maxstepnumber+1): P.append(actuatorminthreshold+I*actuatorinterval) @@ -118,18 +123,18 @@ def automationexecute(refsensor,element): # ------------------------ Automation alghoritm if workmode=="Full Auto": # check if inside the allowed time period - print "full Auto Mode" + print("full Auto Mode") logger.info('full auto mode --> %s', element) timeok=isNowInTimePeriod(starttime, endtime, datetime.now().time()) # don't use UTC here! - print "inside allowed time ", timeok , " starttime ", starttime , " endtime ", endtime + print("inside allowed time ", timeok , " starttime ", starttime , " endtime ", endtime) if timeok: logger.info('inside allowed time') isok,sensorvalue=sensorreading(sensor,averageminutes,mathoperation) # operation of sensor readings for a number of sample if isok: - print "Sensor Value ", sensorvalue + print("Sensor Value ", sensorvalue) if sensorminthreshold<=sensormaxthreshold: - print "Algorithm , element: " , element + print("Algorithm , element: " , element) logger.info("Forward algorithm , element: %s " , element) @@ -155,7 +160,7 @@ def automationexecute(refsensor,element): Inde=maxstepnumber mins=sensorminthreshold+(Inde-1)*interval if minssensorvalue: - print "INDE:",Inde + print("INDE:",Inde) value=P[Inde] # do relevant stuff CheckActivateNotify(element,waitingtime,value,mailtype,sensor,sensorvalue) @@ -198,10 +203,10 @@ def automationexecute(refsensor,element): logger.info('Outside allowed Time, Stop') elif workmode=="Emergency Activation": - print "Emergency Activation" + print("Emergency Activation") elif workmode=="Alert Only": - print "Alert Only" + print("Alert Only") @@ -213,7 +218,7 @@ def automationexecute(refsensor,element): if sensorvalue>sensormaxthreshold+interval: logger.info('sensor %s exceeding limits', sensor) textmessage="CRITICAL: "+ sensor + " reading " + str(sensorvalue) + " exceeding threshold limits, need to check the " + element - print textmessage + print(textmessage) #send alert mail notification alertcounter=statusdataDBmod.read_status_data(AUTO_data,element,"alertcounter") if alertcounter<2: @@ -226,7 +231,7 @@ def automationexecute(refsensor,element): if sensorvalue=waitingtime: # sufficient time between actions - print " Sufficient waiting time" + print(" Sufficient waiting time") logger.info('Sufficient waiting time') # action - print "Implement Actuator Value ", value + print("Implement Actuator Value ", value) logger.info('Procedure to start actuator %s, for value = %s', element, value) isok=activateactuator(element, value) @@ -327,7 +332,7 @@ def activateactuator(target, value): # return true in case the state change: ac def isNowInTimePeriod(startTime, endTime, nowTime): - print startTime," ", endTime," " , nowTime + print(startTime," ", endTime," " , nowTime) if startTime < endTime: return nowTime >= startTime and nowTime <= endTime else: #Over midnight @@ -341,7 +346,7 @@ def sensorreading(sensorname,MinutesOfAverage,operation): timelist=hardwaremod.gettimedata(sensorname) theinterval=timelist[1] # minutes if theinterval>0: - samplesnumber=int(MinutesOfAverage/theinterval+1) + samplesnumber=int(old_div(MinutesOfAverage,theinterval)+1) else: samplesnumber=1 theinterval=15 @@ -356,7 +361,7 @@ def sensorreading(sensorname,MinutesOfAverage,operation): quantity=quantitylist[operation] # sensor reading value logger.info('Sensor reading <%s>=<%s>',sensorname,str(quantity)) - print "sensor Reading ", sensorname, "=" , quantity + print("sensor Reading ", sensorname, "=" , quantity) return isok , quantity diff --git a/autowateringdbmod.py b/autowateringdbmod.py old mode 100644 new mode 100755 index 799d425..ce73cb0 --- a/autowateringdbmod.py +++ b/autowateringdbmod.py @@ -2,6 +2,7 @@ """ Auto watering UI setting storage utilities """ +from __future__ import print_function import logging import os @@ -30,7 +31,7 @@ if not filestoragemod.readfiledata(WTDATAFILENAME,WTdata): #read watering setting file #read from default file filestoragemod.readfiledata(DEFWTDATAFILENAME,WTdata) - print "Watering writing default calibration data" + print("Watering writing default calibration data") filestoragemod.savefiledata(WTDATAFILENAME,WTdata) # end read IOdata ----- @@ -175,7 +176,7 @@ def getrowdata(recordvalue,paramlist,index): #for parameters with array of integ for param in paramlist: try: datalist.append(int(ln[param][index])) - except Exception, e: + except Exception as e: #print 'Failed to load value, set value to zero. Error: '+ str(e) datalist.append(0) diff --git a/autowateringmod.py b/autowateringmod.py old mode 100644 new mode 100755 index 6759aa9..2c83b32 --- a/autowateringmod.py +++ b/autowateringmod.py @@ -1,3 +1,8 @@ +from __future__ import print_function +from __future__ import division +from builtins import str +from builtins import range +from past.utils import old_div import logging from datetime import datetime, time ,timedelta import hardwaremod @@ -15,7 +20,7 @@ # status array, required to check the ongoing actions within a watering cycle elementlist= autowateringdbmod.getelementlist() AUTO_data={} # dictionary of dictionary -AUTO_data["default"]={"cyclestartdate":datetime.now(),"lastwateringtime":datetime.now(),"cyclestatus":"done", "checkcounter":0, "alertcounter":0, "watercounter":0} +AUTO_data["default"]={"cyclestartdate":datetime.utcnow(),"lastwateringtime":datetime.utcnow()- timedelta(days=5),"cyclestatus":"done", "checkcounter":0, "alertcounter":0, "watercounter":0} allowwateringplan={} # define the flag that control the waterscheduling activation # cyclestartdate, datetime of the latest cycle start # cyclestatus, describe the status of the cycle: lowthreshold, rampup, done @@ -42,7 +47,7 @@ def cycleresetall(): global AUTO_data elementlist= autowateringdbmod.getelementlist() for element in elementlist: - AUTO_data[element]={"cyclestartdate":datetime.now(),"lastwateringtime":datetime.now(),"cyclestatus":"done", "checkcounter":0, "alertcounter":0, "watercounter":0} + cyclereset(element) def autowateringcheck(refsensor): @@ -59,14 +64,14 @@ def autowateringexecute(refsensor,element): sensor=autowateringdbmod.searchdata("element",element,"sensor") # check the sensor if refsensor==sensor: - print "auto watering check -----------------------------------------> ", element + print("auto watering check -----------------------------------------> ", element) logger.info('auto watering check --------------------------> %s', element) # check the watering mode modelist=["None", "Full Auto" , "Emergency Activation" , "Alert Only"] workmode=checkworkmode(element) if not(sensor in sensordbmod.gettablelist()): - print "Sensor does not exist " ,sensor , ", element: " , element + print("Sensor does not exist " ,sensor , ", element: " , element) logger.error("Sensor does not exist %s , element: %s " ,sensor, element) return "sensor not Exist" @@ -74,7 +79,7 @@ def autowateringexecute(refsensor,element): minthreshold=hardwaremod.tonumber(autowateringdbmod.searchdata("element",element,"threshold")[0],maxthreshold) # exit condition in case of data inconsistency if minthreshold>=maxthreshold: - print "Data inconsistency , element: " , element + print("Data inconsistency , element: " , element) logger.error("Data inconsistency , element: %s " , element) return "data inconsistency" @@ -100,10 +105,10 @@ def autowateringexecute(refsensor,element): # block the wateringplan activation as by definition of "Full Auto" allowwateringplan[element]=False # check if inside the allowed time period - print "full Auto Mode" + print("full Auto Mode") logger.info('full auto mode --> %s', element) timeok=isNowInTimePeriod(starttime, endtime, nowtime) - print "inside allowed time ", timeok , " starttime ", starttime , " endtime ", endtime + print("inside allowed time ", timeok , " starttime ", starttime , " endtime ", endtime) logger.info('full auto mode') if timeok: logger.info('inside allowed time') @@ -115,12 +120,12 @@ def autowateringexecute(refsensor,element): # wait to seek a more stable reading of hygrometer # check if time between watering events is larger that the waiting time (minutes) lastwateringtime=statusdataDBmod.read_status_data(AUTO_data,element,"lastwateringtime") - print ' Previous watering: ' , lastwateringtime , ' Now: ', datetime.now() - timedifference=sensordbmod.timediffinminutes(lastwateringtime,datetime.now()) - print 'Time interval between watering steps', timedifference ,'. threshold', waitingtime + print(' Previous watering: ' , lastwateringtime , ' Now: ', datetime.utcnow()) + timedifference=sensordbmod.timediffinminutes(lastwateringtime,datetime.utcnow()) + print('Time interval between watering steps', timedifference ,'. threshold', waitingtime) logger.info('Time interval between watering steps %d threshold %d', timedifference,waitingtime) if timedifference>waitingtime: - print " Sufficient waiting time" + print(" Sufficient waiting time") logger.info('Sufficient waiting time') # activate watering in case the maxstepnumber is not exceeded watercounter=statusdataDBmod.read_status_data(AUTO_data,element,"watercounter") @@ -132,7 +137,7 @@ def autowateringexecute(refsensor,element): textmessage="INFO: " + sensor + " value below the minimum threshold " + str(minthreshold) + ", activating the watering :" + element emailmod.sendallmail("alert", textmessage) statusdataDBmod.write_status_data(AUTO_data,element,"watercounter",watercounter+1) - statusdataDBmod.write_status_data(AUTO_data,element,"lastwateringtime",datetime.now()) + statusdataDBmod.write_status_data(AUTO_data,element,"lastwateringtime",datetime.utcnow()) else: # critical, sensor below minimum after all watering activations are done logger.info('Number of watering time per cycle has been exceeeded') @@ -149,7 +154,7 @@ def autowateringexecute(refsensor,element): alertcounter=statusdataDBmod.read_status_data(AUTO_data,element,"alertcounter") if alertcounter<1: textmessage="WARNING: Please consider to increase the amount of water per cycle, the "+ sensor + " value below the MINIMUM threshold " + str(minthreshold) + " still after activating the watering :" + element + " for " + str(maxstepnumber) + " times. System will automatically reset the watering cycle to allow more water" - print textmessage + print(textmessage) if (mailtype!="none"): #send alert mail notification emailmod.sendallmail("alert", textmessage) @@ -161,13 +166,13 @@ def autowateringexecute(refsensor,element): statusdataDBmod.write_status_data(AUTO_data,element,"watercounter",0) statusdataDBmod.write_status_data(AUTO_data,element,"checkcounter",-1) statusdataDBmod.write_status_data(AUTO_data,element,"alertcounter",0) - statusdataDBmod.write_status_data(AUTO_data,element,"cyclestartdate",datetime.now()) + statusdataDBmod.write_status_data(AUTO_data,element,"cyclestartdate",datetime.utcnow()) else: # slope not OK, probable hardware problem alertcounter=statusdataDBmod.read_status_data(AUTO_data,element,"alertcounter") if alertcounter<3: - textmessage="CRITICAL: Possible hardware problem, "+ sensor + " value below the MINIMUM threshold " + str(minthreshold) + " still after activating the watering :" + element + " for " + str(maxstepnumber) + " times" - print textmessage + textmessage="CRITICAL: Water line Disabled or Possible hardware problem, "+ sensor + " value below the MINIMUM threshold " + str(minthreshold) + " still after activating the watering :" + element + " for " + str(maxstepnumber) + " times" + print(textmessage) if (mailtype!="none"): #send alert mail notification emailmod.sendallmail("alert", textmessage) @@ -189,7 +194,7 @@ def autowateringexecute(refsensor,element): # wait to seek a more stable reading of hygrometer # check if time between watering events is larger that the waiting time (minutes) lastwateringtime=statusdataDBmod.read_status_data(AUTO_data,element,"lastwateringtime") - if sensordbmod.timediffinminutes(lastwateringtime,datetime.now())>waitingtime: + if sensordbmod.timediffinminutes(lastwateringtime,datetime.utcnow())>waitingtime: watercounter=statusdataDBmod.read_status_data(AUTO_data,element,"watercounter") if maxstepnumber>watercounter: #activate pump @@ -200,7 +205,7 @@ def autowateringexecute(refsensor,element): emailmod.sendallmail("alert", textmessage) statusdataDBmod.write_status_data(AUTO_data,element,"watercounter",watercounter+1) - statusdataDBmod.write_status_data(AUTO_data,element,"lastwateringtime",datetime.now()) + statusdataDBmod.write_status_data(AUTO_data,element,"lastwateringtime",datetime.utcnow()) else: # give up to reache the maximum threshold, proceed as done, send alert @@ -212,7 +217,7 @@ def autowateringexecute(refsensor,element): alertcounter=statusdataDBmod.read_status_data(AUTO_data,element,"alertcounter") if alertcounter<2: textmessage="INFO "+ sensor + " value below the Maximum threshold " + str(maxthreshold) + " still after activating the watering :" + element + " for " + str(maxstepnumber) + " times" - print textmessage + print(textmessage) if (mailtype!="none"): #send alert mail notification emailmod.sendallmail("alert", textmessage) @@ -224,7 +229,7 @@ def autowateringexecute(refsensor,element): statusdataDBmod.write_status_data(AUTO_data,element,"watercounter",0) statusdataDBmod.write_status_data(AUTO_data,element,"checkcounter",-1) statusdataDBmod.write_status_data(AUTO_data,element,"alertcounter",0) - statusdataDBmod.write_status_data(AUTO_data,element,"cyclestartdate",datetime.now()) + statusdataDBmod.write_status_data(AUTO_data,element,"cyclestartdate",datetime.utcnow()) @@ -245,7 +250,7 @@ def autowateringexecute(refsensor,element): # check if inside the allow time period logger.info('Emergency Mode') timeok=isNowInTimePeriod(starttime, endtime, nowtime) - print "inside allowed time ", timeok , " starttime ", starttime , " endtime ", endtime + print("inside allowed time ", timeok , " starttime ", starttime , " endtime ", endtime) if timeok: belowthr,valid=checkminthreshold(sensor,minthreshold,minaccepted,samplesminutes) if valid: @@ -254,7 +259,7 @@ def autowateringexecute(refsensor,element): # check if time between watering events is larger that the waiting time (minutes) lastwateringtime=statusdataDBmod.read_status_data(AUTO_data,element,"lastwateringtime") - if sensordbmod.timediffinminutes(lastwateringtime,datetime.now())>waitingtime: + if sensordbmod.timediffinminutes(lastwateringtime,datetime.utcnow())>waitingtime: # activate watering in case the maxstepnumber is not exceeded watercounter=statusdataDBmod.read_status_data(AUTO_data,element,"watercounter") if maxstepnumber>watercounter: @@ -266,7 +271,7 @@ def autowateringexecute(refsensor,element): emailmod.sendallmail("alert", textmessage) statusdataDBmod.write_status_data(AUTO_data,element,"watercounter",watercounter+1) - statusdataDBmod.write_status_data(AUTO_data,element,"lastwateringtime",datetime.now()) + statusdataDBmod.write_status_data(AUTO_data,element,"lastwateringtime",datetime.utcnow()) else: @@ -285,7 +290,7 @@ def autowateringexecute(refsensor,element): alertcounter=statusdataDBmod.read_status_data(AUTO_data,element,"alertcounter") if alertcounter<1: textmessage="WARNING: Please consider to increase the amount of water per cycle, the "+ sensor + " value below the MINIMUM threshold " + str(minthreshold) + " still after activating the watering :" + element + " for " + str(maxstepnumber) + " times. System will automatically reset the watering cycle to allow more water" - print textmessage + print(textmessage) if (mailtype!="none"): #send alert mail notification alertcounter emailmod.sendallmail("alert", textmessage) @@ -297,13 +302,13 @@ def autowateringexecute(refsensor,element): statusdataDBmod.write_status_data(AUTO_data,element,"watercounter",0) statusdataDBmod.write_status_data(AUTO_data,element,"checkcounter",-1) statusdataDBmod.write_status_data(AUTO_data,element,"alertcounter",0) - statusdataDBmod.write_status_data(AUTO_data,element,"cyclestartdate",datetime.now()) + statusdataDBmod.write_status_data(AUTO_data,element,"cyclestartdate",datetime.utcnow()) else: # slope not OK, probable hardware problem alertcounter=statusdataDBmod.read_status_data(AUTO_data,element,"alertcounter") if alertcounter<3: - textmessage="CRITICAL: Possible hardware problem, "+ sensor + " value below the MINIMUM threshold " + str(minthreshold) + " still after activating the watering :" + element + " for " + str(maxstepnumber) + " times" - print textmessage + textmessage="CRITICAL: Water line Disabled or Possible hardware problem, "+ sensor + " value below the MINIMUM threshold " + str(minthreshold) + " still after activating the watering :" + element + " for " + str(maxstepnumber) + " times" + print(textmessage) if (mailtype!="none"): #send alert mail notification emailmod.sendallmail("alert", textmessage) @@ -329,7 +334,7 @@ def autowateringexecute(refsensor,element): allowwateringplan[element]=True # check if inside the allow time period timeok=isNowInTimePeriod(starttime, endtime, nowtime) - print "inside allowed time ", timeok , " starttime ", starttime , " endtime ", endtime + print("inside allowed time ", timeok , " starttime ", starttime , " endtime ", endtime) if timeok: logger.info('Insede operative time') belowthr,valid=checkminthreshold(sensor,minthreshold,minaccepted,samplesminutes) @@ -341,7 +346,7 @@ def autowateringexecute(refsensor,element): # check if time between watering events is larger that the waiting time (minutes) lastwateringtime=statusdataDBmod.read_status_data(AUTO_data,element,"lastwateringtime") - if sensordbmod.timediffinminutes(lastwateringtime,datetime.now())>waitingtime: + if sensordbmod.timediffinminutes(lastwateringtime,datetime.utcnow())>waitingtime: # activate watering in case the maxstepnumber is not exceeded watercounter=statusdataDBmod.read_status_data(AUTO_data,element,"watercounter") if maxstepnumber>watercounter: @@ -353,7 +358,7 @@ def autowateringexecute(refsensor,element): textmessage="INFO: " + sensor + " value below the minimum threshold " + str(minthreshold) + ", activating the watering :" + element emailmod.sendallmail("alert", textmessage) statusdataDBmod.write_status_data(AUTO_data,element,"watercounter",watercounter+1) - statusdataDBmod.write_status_data(AUTO_data,element,"lastwateringtime",datetime.now()) + statusdataDBmod.write_status_data(AUTO_data,element,"lastwateringtime",datetime.utcnow()) else: @@ -373,7 +378,7 @@ def autowateringexecute(refsensor,element): alertcounter=statusdataDBmod.read_status_data(AUTO_data,element,"alertcounter") if alertcounter<1: textmessage="WARNING: Please consider to increase the amount of water per cycle, the "+ sensor + " value below the MINIMUM threshold " + str(minthreshold) + " still after activating the watering :" + element + " for " + str(maxstepnumber) + " times. System will automatically reset the watering cycle to allow more water" - print textmessage + print(textmessage) if (mailtype!="none"): #send alert mail notification emailmod.sendallmail("alert", textmessage) @@ -385,13 +390,13 @@ def autowateringexecute(refsensor,element): statusdataDBmod.write_status_data(AUTO_data,element,"watercounter",0) statusdataDBmod.write_status_data(AUTO_data,element,"checkcounter",-1) statusdataDBmod.write_status_data(AUTO_data,element,"alertcounter",0) - statusdataDBmod.write_status_data(AUTO_data,element,"cyclestartdate",datetime.now()) + statusdataDBmod.write_status_data(AUTO_data,element,"cyclestartdate",datetime.utcnow()) else: # slope not OK, probable hardware problem alertcounter=statusdataDBmod.read_status_data(AUTO_data,element,"alertcounter") if alertcounter<3: - textmessage="CRITICAL: Possible hardware problem, "+ sensor + " value below the MINIMUM threshold " + str(minthreshold) + " still after activating the watering :" + element + " for " + str(maxstepnumber) + " times" - print textmessage + textmessage="CRITICAL: Water line Disabled or Possible hardware problem, "+ sensor + " value below the MINIMUM threshold " + str(minthreshold) + " still after activating the watering :" + element + " for " + str(maxstepnumber) + " times" + print(textmessage) if (mailtype!="none"): #send alert mail notification emailmod.sendallmail("alert", textmessage) @@ -427,7 +432,7 @@ def autowateringexecute(refsensor,element): alertcounter=statusdataDBmod.read_status_data(AUTO_data,element,"alertcounter") if alertcounter<2: textmessage="WARNING "+ sensor + " value below the minimum threshold " + str(minthreshold) + " watering system: " + element - print textmessage + print(textmessage) if (mailtype!="none"): #send alert mail notification emailmod.sendallmail("alert", textmessage) @@ -446,22 +451,22 @@ def autowateringexecute(refsensor,element): else: # None case - print "No Action required, workmode set to None, element: " , element + print("No Action required, workmode set to None, element: " , element) logger.info("No Action required, workmode set to None, element: %s " , element) cyclestatus=statusdataDBmod.read_status_data(AUTO_data,element,"cyclestatus") if cyclestatus=="lowthreshold": checkcounter=statusdataDBmod.read_status_data(AUTO_data,element,"checkcounter") if checkcounter==1: - statusdataDBmod.write_status_data(AUTO_data,element,"cyclestartdate",datetime.now()) + statusdataDBmod.write_status_data(AUTO_data,element,"cyclestartdate",datetime.utcnow()) # implment alert message for the cycle exceeding days, and reset the cycle if workmode!="None": cyclestartdate=statusdataDBmod.read_status_data(AUTO_data,element,"cyclestartdate") - timedeltadays=sensordbmod.timediffdays(datetime.now(),cyclestartdate) + timedeltadays=sensordbmod.timediffdays(datetime.utcnow(),cyclestartdate) if (timedeltadays > maxdays): #the upper limit is set in case of abrupt time change textmessage="WARNING "+ sensor + " watering cycle is taking too many days, watering system: " + element + ". Reset watering cycle" - print textmessage + print(textmessage) # in case of full Auto, activate pump for minimum pulse period if workmode=="Full Auto": if (timedeltadays < maxdays+2): #the upper limit is set in case of abrupt time change @@ -471,13 +476,13 @@ def autowateringexecute(refsensor,element): if (mailtype!="warningonly")and(mailtype!="none"): emailmod.sendallmail("alert", textmessage) logger.error(textmessage) - logger.error("Cycle started %s, Now is %s ", cyclestartdate.strftime("%Y-%m-%d %H:%M:%S"), datetime.now().strftime("%Y-%m-%d %H:%M:%S")) + logger.error("Cycle started %s, Now is %s (UTC time) ", cyclestartdate.strftime("%Y-%m-%d %H:%M:%S"), datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")) # reset cycle statusdataDBmod.write_status_data(AUTO_data,element,"cyclestatus","done") statusdataDBmod.write_status_data(AUTO_data,element,"checkcounter",0) statusdataDBmod.write_status_data(AUTO_data,element,"watercounter",0) statusdataDBmod.write_status_data(AUTO_data,element,"alertcounter",0) - statusdataDBmod.write_status_data(AUTO_data,element,"cyclestartdate",datetime.now()) + statusdataDBmod.write_status_data(AUTO_data,element,"cyclestartdate",datetime.utcnow()) # implment Critical alert message in case the threshold is below the 0.5 of the minimum if workmode!="None": @@ -486,7 +491,7 @@ def autowateringexecute(refsensor,element): if belowthr: logger.info('sensor %s below half of the actual set threshold', sensor) textmessage="CRITICAL: Plant is dying, "+ sensor + " reading below half of the minimum threshold, need to check the " + element - print textmessage + print(textmessage) #send alert mail notification alertcounter=statusdataDBmod.read_status_data(AUTO_data,element,"alertcounter") if alertcounter<5: @@ -497,7 +502,7 @@ def autowateringexecute(refsensor,element): else: logger.info('sensor %s below valid data', sensor) textmessage="WARNING: "+ sensor + " below valid data range, need to check sensor" - print textmessage + print(textmessage) #send alert mail notification alertcounter=statusdataDBmod.read_status_data(AUTO_data,element,"alertcounter") if alertcounter<3: @@ -523,19 +528,19 @@ def checkminthreshold(sensor,minthreshold,minaccepted,samplesminutes): # check the hygrometer sensor levels sensorreadingaverage=sensorreading(sensor,samplesminutes) # if the average level after 4 measure (15 min each) is below threshold apply emergency - print " Min accepted threshold " , minaccepted + print(" Min accepted threshold " , minaccepted) if (sensorreadingaverage>minaccepted): if (sensorreadingaverage>minthreshold): logger.info('Soil moisture check, Sensor reading=%s > Minimum threshold=%s ', str(sensorreadingaverage), str(minthreshold)) - print 'Soil moisture check, Sensor reading=%s > Minimum threshold=%s ' + print('Soil moisture check, Sensor reading=%s > Minimum threshold=%s ') else: logger.warning('Soil moisture check, Sensor reading=%s < Minimum threshold=%s ', str(sensorreadingaverage), str(minthreshold)) logger.info('Start watering procedure ') - print 'Soil moisture check, activating watering procedure ' + print('Soil moisture check, activating watering procedure ') belowthr=True else: logger.warning('Sensor reading lower than acceptable values %s no action', str(sensorreadingaverage)) - print 'Sensor reading lower than acceptable values ', sensorreadingaverage ,' no action' + print('Sensor reading lower than acceptable values ', sensorreadingaverage ,' no action') validity=False return belowthr, validity @@ -543,21 +548,21 @@ def checkminthreshold(sensor,minthreshold,minaccepted,samplesminutes): def checkinclination(sensorname,startdate,enddate): # startdate is UTC now, need to be evaluated - print "Check inclination of the hygrometer curve after watering done " , sensorname + print("Check inclination of the hygrometer curve after watering done " , sensorname) logger.info('Check inclination of the hygrometer curve after watering done: %s', sensorname) logger.info('Start eveluation from %s to %s', startdate.strftime("%Y-%m-%d %H:%M:%S") , enddate.strftime("%Y-%m-%d %H:%M:%S")) - print "Start eveluation from " , startdate.strftime("%Y-%m-%d %H:%M:%S") , " to " , enddate.strftime("%Y-%m-%d %H:%M:%S") + print("Start eveluation from " , startdate.strftime("%Y-%m-%d %H:%M:%S") , " to " , enddate.strftime("%Y-%m-%d %H:%M:%S")) datax=[] datay=[] if sensorname: lenght=sensordbmod.getSensorDataPeriodXminutes(sensorname,datax,datay,startdate,enddate) - print "datax ", datax - print "datay ", datay + print("datax ", datax) + print("datay ", datay) if lenght>0: - avex=sum(datax)/float(lenght) - avey=sum(datay)/float(lenght) - print " Average: " , avex, " " , avey + avex=old_div(sum(datax),float(lenght)) + avey=old_div(sum(datay),float(lenght)) + print(" Average: " , avex, " " , avey) num=0 den=0 for inde in range(len(datax)): @@ -565,15 +570,15 @@ def checkinclination(sensorname,startdate,enddate): xy=(datax[inde]-avex)*(datay[inde]-avey) num=num+xy den=den+x2 - print " ----> Lenght " ,lenght , " num: ", num , " Den: ", den + print(" ----> Lenght " ,lenght , " num: ", num , " Den: ", den) if den>0.0001: # this is to avoid problem with division - slope=num/den + slope=old_div(num,den) logger.info('Inclination value: %.4f', slope) - print " Slope Value" , slope + print(" Slope Value" , slope) # here an arbitray min slope that should be reasonable for a working system yvolt=0.2 xminute=2*60 - minslope=yvolt/xminute # 0.2 volt per 2 hours + minslope=old_div(yvolt,xminute) # 0.2 volt per 2 hours if slope>minslope: logger.info('Inclination value %.4f above the min reference %.4f (0.2 volt per 2 hours), restaring watering cycle',slope,minslope) return True @@ -592,7 +597,7 @@ def sensorreading(sensorname,MinutesOfAverage): timelist=hardwaremod.gettimedata(sensorname) theinterval=timelist[1] # minutes if theinterval>0: - samplesnumber=int(MinutesOfAverage/theinterval+1) + samplesnumber=int(old_div(MinutesOfAverage,theinterval)+1) else: samplesnumber=1 # new procedure should be faster on database reading for large amount of data diff --git a/bash/install_hydrosys4 (copy).sh b/bash/install_hydrosys4 (copy).sh deleted file mode 100644 index 2c20608..0000000 --- a/bash/install_hydrosys4 (copy).sh +++ /dev/null @@ -1,803 +0,0 @@ -#!/bin/bash - - -#Debug enable next 3 lines -exec 5> install.txt -BASH_XTRACEFD="5" -set -x -# ------ end debug - - -function killpython() -{ - -sudo killall python - -} - - -function system_update_light() -{ - -# ---- system_update - -sudo apt-get -y update - -} - -function system_update() -{ - -# ---- remove unnecessary packages - -sudo apt-get remove --purge libreoffice-* -sudo apt-get remove --purge wolfram-engine - - -# ---- system_update - -sudo apt-get -y update -sudo apt-get -y upgrade - -} - -function system_update_UI() -{ - -while true; do - read -p "Do you wish to update the Raspbian system (y/n)?" yn - case $yn in - [Yy]* ) system_update; break;; - [Nn]* ) break;; - * ) echo "Please answer y or n.";; - esac -done - -} - -function install_dependencies() -{ - - -#--- start installing dependencies - -sudo apt-get -y install python-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo apt-get -y install python-pip || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install flask || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install apscheduler || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install pyserial || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(for the webcam support) -sudo apt-get -y install fswebcam || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(for the image thumbnail support) -sudo apt-get -y install libjpeg-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install Pillow || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(for external IP address, using DNS) -sudo apt-get -y install dnsutils || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(encryption) -sudo pip install pbkdf2 || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(web server) -sudo pip install tornado || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -} - -function enable_I2C() -{ - -# --- Enable I2C and Spi : -# /boot/config.txt - -sed -i 's/\(^.*#dtparam=i2c_arm=on.*$\)/dtparam=i2c_arm=on/' /boot/config.txt -sed -i 's/\(^.*#dtparam=spi=on.*$\)/dtparam=spi=on/' /boot/config.txt -sed -i 's/\(^.*#dtparam=i2s=on.*$\)/dtparam=i2s=on/' /boot/config.txt - -# --- Add modules: -# /etc/modules -aconf="/etc/modules" - -sed -i '/i2c-bcm2708/d' $aconf -sed -i -e "\$ai2c-bcm2708" $aconf - -sed -i '/i2c-dev/d' $aconf -sed -i -e "\$ai2c-dev" $aconf - -sed -i '/i2c-bcm2835/d' $aconf -sed -i -e "\$ai2c-bcm2835" $aconf - -sed -i '/rtc-ds1307/d' $aconf -sed -i -e "\$artc-ds1307" $aconf - -sed -i '/bcm2835-v4l2/d' $aconf -sed -i -e "\$abcm2835-v4l2" $aconf - - -# --- install I2C tools -sudo apt-get -y install git build-essential python-dev python-smbus || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo apt-get -y install -y i2c-tools || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -} - - -# --- enable raspicam - -############# MISSING ############## - -function modify_RClocal() -{ - -# --- Real Time Clock (RTC) -# /etc/rc.local - -autostart="yes" -# copy the below lines between # START and #END to rc.local -tmpfile=$(mktemp) -sudo sed '/#START/,/#END/d' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local -# Remove to growing plank lines. -sudo awk '!NF {if (++n <= 1) print; next}; {n=0;print}' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local -if [ "$autostart" == "yes" ]; then - if ! grep -Fq '#START HYDROSYS4 SECTION' /etc/rc.local; then - sudo sed -i '/exit 0/d' /etc/rc.local - sudo bash -c "cat >> /etc/rc.local" << EOF -#START HYDROSYS4 SECTION -# iptables -sudo iptables-restore < /home/pi/iptables.rules - -# clock -echo "HYDROSYS4-set HW clock ****************************************" -echo ds3231 0x68 > /sys/class/i2c-adapter/i2c-1/new_device || true -hwclock -s || true - -echo "HYDROSYS4-start system ****************************************" -cd /home/pi/env/autonom/ -sudo python /home/pi/env/autonom/bentornado.py & - -#END HYDROSYS4 SECTION - -exit 0 -EOF - else - tmpfile=$(mktemp) - sudo sed '/#START/,/#END/d' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local - # Remove to growing plank lines. - sudo awk '!NF {if (++n <= 1) print; next}; {n=0;print}' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local - fi - -fi - -sudo chown root:root /etc/rc.local -sudo chmod 755 /etc/rc.local -# end modification to RC.local - -} - - -### -- WIFI setup --- STANDARD - -function valid_ip() -{ - local ip=$1 - local stat=1 - - if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then - OIFS=$IFS - IFS='.' - ip=($ip) - IFS=$OIFS - [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \ - && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]] - stat=$? - fi - return $stat -} - - -input_UI () -{ - -echo "Hello, following initial setting is requested:" - -# IP part input - -IP="0" -while ! valid_ip $IP; do - read -p "Local IP address (range 192.168.0.100-192.168.1.200), to confirm press [ENTER] or modify: " -e -i 192.168.1.172 IP - if valid_ip $IP; then stat='good'; - else stat='bad'; echo "WRONG FORMAT, please enter a valid value for IP address" - fi - -done - echo "Confirmed IP address: "$IP - -PORT="" -while [[ ! $PORT =~ ^[0-9]+$ ]]; do -read -p "Local PORT, to confirm press [ENTER] or modify: " -e -i 5172 PORT - if [[ ! $PORT =~ ^[0-9]+$ ]]; - then echo "WRONG FORMAT, please enter a valid value for PORT"; - fi -done - echo "Confirmed PORT: "$PORT - -# Local WiFi AP name and password setting - -read -p "System WiFi AP name, to confirm press [ENTER] or modify: " -e -i Hydrosys4 WiFiAPname -echo "Confirmed Name: "$WiFiAPname - -read -p "System WiFi AP password, to confirm press [ENTER] or modify: " -e -i hydrosystem WiFiAPpsw -echo "Confirmed Password: "$WiFiAPpsw - -read -p "Do you want to change hostname? (y,n): " -e -i y ChangeHostName -echo "Confirmed Answer: "$ChangeHostName - -if [ "$ChangeHostName" == "y" ]; then - read -p "System Hostname, to confirm press [ENTER] or modify: " -e -i hydrosys4-172 NewHostName - echo "Confirmed Hostname: "$NewHostName -fi - -} - - -apply_newhostname () -{ - -# --- change system hostname -if [ "$ChangeHostName" == "y" ]; then - sudo hostnamectl set-hostname $NewHostName -fi - -} - - -ask_reboot () -{ - - -read -p "Do you want to reboot the system? (y,n): " -e -i y doreboot -echo "Confirmed Answer: "$doreboot - -if [ "$doreboot" == "y" ]; then - sudo reboot -fi - -} - - - - -install_MotorShieldlib () -{ - -# --- installing the python dev-library -sudo apt-get -y install build-essential python-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/MotorHat/master.zip" -if [ -f $aconf ]; then - cd /home/pi/env/autonom/libraries/MotorHat - unzip master.zip - cd Adafruit-Motor-HAT-Python-Library-master - sudo python setup.py install - cd /home/pi -else - cd /home/pi - sudo rm -r MotorHat - mkdir MotorHat - cd MotorHat - wget https://github.com/adafruit/Adafruit-Motor-HAT-Python-Library/archive/master.zip - unzip master.zip - cd Adafruit-Motor-HAT-Python-Library-master - sudo python setup.py install - cd /home/pi -fi -} - - - - -install_DHT22lib () -{ - -# --- installing the DHT22 Sensor libraries -sudo apt-get -y install build-essential python-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/DHT22/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/DHT22 - unzip master.zip - cd Adafruit_Python_DHT-master - # setup1plus is file that try to make the DTH22 work with both RaspberryPi zero,1 and model 2,3 - sudo python setup1plus.py install - cd /home/pi -else - cd /home/pi - sudo rm -r DHT22 - mkdir DHT22 - cd DHT22 - wget https://github.com/adafruit/Adafruit_Python_DHT/archive/master.zip - unzip master.zip - cd Adafruit_Python_DHT-master - sudo python setup.py install - cd /home/pi -fi -} - - -install_SPIlib () -{ - - -# --- INSTALL SPI library: - -sudo apt-get -y install python2.7-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/SPI/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/SPI - unzip master.zip - cd py-spidev-master - sudo python setup.py install - cd /home/pi -else - -cd /home/pi -sudo rm -r SPIDEV -mkdir SPIDEV -cd SPIDEV - -wget https://github.com/Gadgetoid/py-spidev/archive/master.zip - -unzip master.zip - -rm master.zip - -cd py-spidev-master - -sudo python setup.py install - -cd .. -cd .. - -fi -} - - -install_BMPlib () -{ - -# --- INSTALL BMP180 library (pressure sensor) - -sudo apt-get -y install build-essential python-dev python-smbus || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/BMP/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/BMP - unzip master.zip - cd Adafruit_Python_BMP-master - sudo python setup.py install - cd /home/pi -else - -cd /home/pi -sudo rm -r bmp180 -sudo mkdir bmp180 -cd bmp180 -wget https://github.com/adafruit/Adafruit_Python_BMP/archive/master.zip -cd Adafruit_Python_BMP-master -sudo python setup.py install -cd .. -cd .. - -fi -} - - -install_hydrosys4 () -{ -# --- INSTALL Hydrosys4 software -sudo apt-get -y install git || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - - -# check if file exist in local folder -aconf="/home/pi/env/autonom" -if [ -d $aconf ]; then # if the directory exist - cd /home/pi -else - cd /home/pi - sudo rm -r env - mkdir env - cd env - sudo rm -r autonom - git clone https://github.com/Hydrosys4/Master.git - sudo killall python - mv Master autonom - cd .. - -fi - -} - - - - - - -fn_hostapd () -{ - -sudo apt-get -y install hostapd || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -# unmask the service -sudo systemctl unmask hostapd.service - -# create hostapd.conf file -aconf="/etc/hostapd/hostapd.conf" -if [ -f $aconf ]; then - cp $aconf $aconf.1 - sudo rm $aconf - echo "remove file" -fi - - -sudo bash -c "cat >> $aconf" << EOF -# HERE-> {"name": "IPsetting", "LocalIPaddress": "$IP", "LocalPORT": "$PORT", "LocalAPSSID" : "$WiFiAPname"} -ieee80211n=1 -interface=wlan0 -ssid=$WiFiAPname -hw_mode=g -channel=6 -macaddr_acl=0 -auth_algs=1 -ignore_broadcast_ssid=0 -wpa=2 -wpa_passphrase=$WiFiAPpsw -wpa_key_mgmt=WPA-PSK -wpa_pairwise=TKIP -rsn_pairwise=CCMP -EOF - - -aconf="/etc/init.d/hostapd" -# Update hostapd main config file -sudo sed -i "s/\(^.*DAEMON_CONF=.*$\)/DAEMON_CONF=\/etc\/hostapd\/hostapd.conf/" $aconf - -aconf="/etc/default/hostapd" -# Update hostapd main config file -sudo sed -i "s/\(^.*DAEMON_CONF=.*$\)/DAEMON_CONF=\/etc\/hostapd\/hostapd.conf/" $aconf - -sudo systemctl enable hostapd.service - -} - - -fn_dnsmasq () -{ - -sudo apt-get -y install dnsmasq || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - - -# edit /etc/dnsmasq.conf file -aconf="/etc/dnsmasq.conf" - -# delete rows between #START and #END -sed -i '/^#START HYDROSYS4 SECTION/,/^#END HYDROSYS4 SECTION/{/^#START HYDROSYS4 SECTION/!{/^#END HYDROSYS4 SECTION/!d}}' $aconf -sed -i '/#START HYDROSYS4 SECTION/d' $aconf -sed -i '/#END HYDROSYS4 SECTION/d' $aconf - -# calculation of the range starting from assigned IP address -IFS="." read -a a <<< $IP -IFS="." read -a b <<< 0.0.0.1 -IFS="." read -a c <<< 0.0.0.9 -IPSTART="$[a[0]].$[a[1]].$[a[2]].$[a[3]+b[3]]" -IPEND="$[a[0]].$[a[1]].$[a[2]].$[a[3]+c[3]]" -if [[ a[3] -gt 244 ]]; then -IPSTART="$[a[0]].$[a[1]].$[a[2]].$[a[3]-c[3]]" -IPEND="$[a[0]].$[a[1]].$[a[2]].$[a[3]-b[3]]" -fi - -echo $IPSTART $IPEND - - - -# ----- - - - -sudo bash -c "cat >> $aconf" << EOF -#START HYDROSYS4 SECTION -interface=wlan0 -dhcp-range=$IPSTART,$IPEND,12h -#no-resolv -#END HYDROSYS4 SECTION -EOF - -sudo systemctl enable dnsmasq.service - - -} - - -fn_dhcpcd () -{ - -# edit /etc/dnsmasq.conf file -aconf="/etc/dhcpcd.conf" - -# delete rows between #START and #END -sed -i '/^#START HYDROSYS4 SECTION/,/^#END HYDROSYS4 SECTION/{/^#START HYDROSYS4 SECTION/!{/^#END HYDROSYS4 SECTION/!d}}' $aconf -sed -i '/#START HYDROSYS4 SECTION/d' $aconf -sed -i '/#END HYDROSYS4 SECTION/d' $aconf - - -sudo bash -c "cat >> $aconf" << EOF -#START HYDROSYS4 SECTION -profile static_wlan0 -static ip_address=$IP/24 -#static routers=192.168.1.1 -#static domain_name_servers=192.169.1.1 -# fallback to static profile on wlan0 -interface wlan0 -fallback static_wlan0 -#END HYDROSYS4 SECTION -EOF - - -} - -fn_ifnames () -{ -# this is to preserve the network interfaces names, becasue staring from debian stretch (9) the ifnames have new rules -# edit /etc/dnsmasq.conf file -aconf="/boot/cmdline.txt" - -APPEND=' net.ifnames=0' -echo "$(cat $aconf)$APPEND" > $aconf - -} - - - - - - - - - -install_mjpegstr () -{ -cd /home/pi - -sudo rm -r mjpg-streamer - -sudo apt-get -y install cmake libjpeg8-dev git - -sudo git clone https://github.com/jacksonliam/mjpg-streamer.git - -cd mjpg-streamer/mjpg-streamer-experimental - -sudo make - -sudo make install - -cd .. -cd .. - -} - - - -install_nginx () -{ -# this function is not used anymore -cd /home/pi - -sudo apt-get -y install nginx - -# create default file -aconf="/etc/nginx/sites-enabled/default" -if [ -f $aconf ]; then - cp $aconf /home/pi/$aconf.1 - sudo rm $aconf - echo "remove file" -fi - - -sudo bash -c "cat >> $aconf" << EOF -server { - # for a public HTTP server: - listen $PORT; - server_name localhost; - - access_log off; - error_log off; - - location / { - proxy_pass http://127.0.0.1:5020; - } - - location /stream { - rewrite ^/stream/(.*) /$1 break; - proxy_pass http://127.0.0.1:5022; - proxy_buffering off; - } - - location /favicon.ico { - alias /home/pi/env/autonom/static/favicon.ico; - } -} -EOF - -sudo service nginx start - -cd .. -cd .. - -} - - -install_squid3 () -{ -# this function is used to install the squid3 program used as reverse proxy -cd /home/pi - -sudo apt-get install squid3 -y || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -# add configuration to squid.conf, the file should already exist if installation is succesful -adir="/etc/squid3" -if [ -d $adir ]; then - aconf="/etc/squid3/squid.conf" -fi -adir="/etc/squid" -if [ -d $adir ]; then - aconf="/etc/squid/squid.conf" -fi - -if [ -f $aconf ]; then - cp $aconf $aconf.1 - sudo rm $aconf - echo "remove file" -fi - - - -sudo bash -c "cat >> $aconf" << EOF -# hydrosys4 configurations - -http_port $PORT accel defaultsite=hydrosys4 vhost - -acl Safe_ports port $PORT # unregistered ports - -acl videostream urlpath_regex \?action=stream - -cache_peer localhost parent 5020 0 no-query originserver name=server1 -cache_peer_access server1 deny videostream - -cache_peer localhost parent 5022 0 no-query originserver name=server2 -cache_peer_access server2 allow videostream -cache_peer_access server2 deny all - -http_access allow Safe_ports - -# default configurations - -# WELCOME TO SQUID 3.5.12 -acl SSL_ports port 443 -acl Safe_ports port 80 # http -acl Safe_ports port 21 # ftp -acl Safe_ports port 443 # https -acl Safe_ports port 70 # gopher -acl Safe_ports port 210 # wais -acl Safe_ports port 1025-65535 # unregistered ports -acl Safe_ports port 280 # http-mgmt -acl Safe_ports port 488 # gss-http -acl Safe_ports port 591 # filemaker -acl Safe_ports port 777 # multiling http -acl CONNECT method CONNECT -http_access deny !Safe_ports -http_access deny CONNECT !SSL_ports -http_access allow localhost manager -http_access deny manager -http_access allow localhost -http_access deny all -coredump_dir /var/spool/squid -refresh_pattern ^ftp: 1440 20% 10080 -refresh_pattern ^gopher: 1440 0% 1440 -refresh_pattern -i (/cgi-bin/|\?) 0 0% 0 -refresh_pattern (Release|Packages(.gz)*)$ 0 20% 2880 -refresh_pattern . 0 20% 4320 -EOF - -sudo service squid3 start - -cd .. -cd .. - -} - - - -edit_defaultnetworkdb () -{ - - -aconf="/home/pi/env/autonom/database/default/defnetwork.txt " - -# if file already exist then no action, otherwise create it -if [ -f $aconf ]; then - echo "network default file already exist" - else - sudo bash -c "cat >> $aconf" << EOF -{"name": "IPsetting", "LocalIPaddress": "192.168.0.172", "LocalPORT": "5012" , "LocalAPSSID" : "Hydrosys4"} -EOF - -fi - -} - -edit_networkdb () -{ - - -aconf="/home/pi/env/autonom/database/network.txt " - -# if file already exist then delete it -if [ -f $aconf ]; then - sudo rm $aconf - echo "remove file" -fi - -sudo bash -c "cat >> $aconf" << EOF -{"name": "IPsetting", "LocalIPaddress": "$IP", "LocalPORT": "$PORT", "LocalAPSSID" : "$WiFiAPname"} -EOF - - -} - - -iptables_blockports () -{ -sudo iptables -A INPUT -p tcp -s localhost --dport 5020 -j ACCEPT -sudo iptables -A INPUT -p tcp -s localhost --dport 5022 -j ACCEPT -sudo iptables -A INPUT -p tcp --dport 5020 -j DROP -sudo iptables -A INPUT -p tcp --dport 5022 -j DROP - -sudo iptables-save > /home/pi/iptables.rules - -} - - -# --- RUN the functions -killpython -input_UI -system_update_light -#system_update_UI -install_dependencies -enable_I2C -modify_RClocal -fn_hostapd -fn_dnsmasq -fn_dhcpcd -fn_ifnames -install_mjpegstr -#install_squid3 -install_nginx -install_hydrosys4 # this should be called before the DHT22 , SPI and BMP due to local library references -install_DHT22lib -install_SPIlib -install_BMPlib -install_MotorShieldlib -edit_defaultnetworkdb -#edit_networkdb -iptables_blockports -apply_newhostname -echo "installation is finished!!! " -ask_reboot diff --git a/bash/install_hydrosys4.sh b/bash/install_hydrosys4.sh old mode 100644 new mode 100755 index a23784b..24fef81 --- a/bash/install_hydrosys4.sh +++ b/bash/install_hydrosys4.sh @@ -11,7 +11,7 @@ set -x function killpython() { -sudo killall python +sudo killall python3 } @@ -61,28 +61,32 @@ function install_dependencies() #--- start installing dependencies -sudo apt-get -y install python-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo apt-get -y install python-pip || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install flask || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install apscheduler || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install pyserial || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} +sudo apt-get -y install python3-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} +sudo apt -y install python3-pip || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} +sudo pip3 install flask || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} +sudo pip3 install apscheduler || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} +sudo pip3 install pyserial || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} +sudo apt-get install python3-future #(for the webcam support) sudo apt-get -y install fswebcam || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} #(for the image thumbnail support) sudo apt-get -y install libjpeg-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install Pillow || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} +sudo apt install libopenjp2-7 +sudo pip3 install pillow || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} #(for external IP address, using DNS) sudo apt-get -y install dnsutils || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} #(encryption) -sudo pip install pbkdf2 || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} +sudo pip3 install pbkdf2 || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} #(web server) -sudo pip install tornado || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} +sudo pip3 install tornado || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} +#(GPIO) +sudo pip3 install RPi.GPIO } function enable_I2C() @@ -116,7 +120,7 @@ sed -i -e "\$abcm2835-v4l2" $aconf # --- install I2C tools -sudo apt-get -y install git build-essential python-dev python-smbus || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} +sudo apt-get -y install git build-essential python3-dev python3-smbus || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} sudo apt-get -y install -y i2c-tools || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} } @@ -153,7 +157,7 @@ hwclock -s || true echo "HYDROSYS4-start system ****************************************" cd /home/pi/env/autonom/ -sudo python /home/pi/env/autonom/bentornado.py & +sudo python3 /home/pi/env/autonom/bentornado.py & #END HYDROSYS4 SECTION @@ -272,33 +276,6 @@ fi -install_MotorShieldlib () -{ - -# --- installing the python dev-library -sudo apt-get -y install build-essential python-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/MotorHat/master.zip" -if [ -f $aconf ]; then - cd /home/pi/env/autonom/libraries/MotorHat - unzip master.zip - cd Adafruit-Motor-HAT-Python-Library-master - sudo python setup.py install - cd /home/pi -else - cd /home/pi - sudo rm -r MotorHat - mkdir MotorHat - cd MotorHat - wget https://github.com/adafruit/Adafruit-Motor-HAT-Python-Library/archive/master.zip - unzip master.zip - cd Adafruit-Motor-HAT-Python-Library-master - sudo python setup.py install - cd /home/pi -fi -} - @@ -306,28 +283,19 @@ install_DHT22lib () { # --- installing the DHT22 Sensor libraries -sudo apt-get -y install build-essential python-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} +sudo apt-get -y install build-essential python3-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -# check if file exist in local folder +# This is just going to install the lybrary present in local folder aconf="/home/pi/env/autonom/libraries/DHT22/master.zip" if [ -f $aconf ]; then cd /home/pi/env/autonom/libraries/DHT22 unzip master.zip cd Adafruit_Python_DHT-master - # setup1plus is file that try to make the DTH22 work with both RaspberryPi zero,1 and model 2,3 - sudo python setup1plus.py install - cd /home/pi -else - cd /home/pi - sudo rm -r DHT22 - mkdir DHT22 - cd DHT22 - wget https://github.com/adafruit/Adafruit_Python_DHT/archive/master.zip - unzip master.zip - cd Adafruit_Python_DHT-master - sudo python setup.py install + # setup1plus is file that make the DTH22 work with both RaspberryPi zero,1 and model 2,3 + sudo python3 setup1plus.py install cd /home/pi + fi } @@ -338,73 +306,14 @@ install_SPIlib () # --- INSTALL SPI library: -sudo apt-get -y install python2.7-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/SPI/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/SPI - unzip master.zip - cd py-spidev-master - sudo python setup.py install - cd /home/pi -else - -cd /home/pi -sudo rm -r SPIDEV -mkdir SPIDEV -cd SPIDEV - -wget https://github.com/Gadgetoid/py-spidev/archive/master.zip - -unzip master.zip - -rm master.zip - -cd py-spidev-master - -sudo python setup.py install +sudo apt-get -y install python3-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} +sudo pip3 install spidev -cd .. -cd .. - -fi } -install_BMPlib () -{ - -# --- INSTALL BMP180 library (pressure sensor) - -sudo apt-get -y install build-essential python-dev python-smbus || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/BMP/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/BMP - unzip master.zip - cd Adafruit_Python_BMP-master - sudo python setup.py install - cd /home/pi -else - -cd /home/pi -sudo rm -r bmp180 -sudo mkdir bmp180 -cd bmp180 -wget https://github.com/adafruit/Adafruit_Python_BMP/archive/master.zip -cd Adafruit_Python_BMP-master -sudo python setup.py install -cd .. -cd .. - -fi -} - install_hydrosys4 () { @@ -423,7 +332,7 @@ else cd env sudo rm -r autonom git clone https://github.com/Hydrosys4/Master.git - sudo killall python + sudo killall python3 mv Master autonom cd .. @@ -602,7 +511,7 @@ cd .. install_nginx () { -# this function is not used anymore +# this function is used cd /home/pi sudo apt-get -y install nginx @@ -651,7 +560,7 @@ cd .. install_squid3 () { -# this function is used to install the squid3 program used as reverse proxy +# this function is NOT USED cd /home/pi sudo apt-get install squid3 -y || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} @@ -798,8 +707,6 @@ install_nginx install_hydrosys4 # this should be called before the DHT22 , SPI and BMP due to local library references install_DHT22lib install_SPIlib -install_BMPlib -install_MotorShieldlib edit_defaultnetworkdb #edit_networkdb iptables_blockports diff --git a/bash/install_hydrosys4v24.sh b/bash/install_hydrosys4_old.sh old mode 100644 new mode 100755 similarity index 100% rename from bash/install_hydrosys4v24.sh rename to bash/install_hydrosys4_old.sh diff --git a/bash/install_hydrosys4v11.sh b/bash/install_hydrosys4v11.sh deleted file mode 100644 index 4ade433..0000000 --- a/bash/install_hydrosys4v11.sh +++ /dev/null @@ -1,652 +0,0 @@ -#!/bin/bash - - -#Debug enable next 3 lines -exec 5> install.txt -BASH_XTRACEFD="5" -set -x -# ------ end debug - - -function killpython() -{ - -sudo killall python - -} - - -function system_update() -{ - -# ---- remove unnecessary packages - -sudo apt-get remove --purge libreoffice-* -sudo apt-get remove --purge wolfram-engine - - -# ---- system_update - -sudo apt-get -y update -sudo apt-get -y upgrade - -} - - -function system_update_UI() -{ - -while true; do - read -p "Do you wish to update the Raspbian system (y/n)?" yn - case $yn in - [Yy]* ) system_update; break;; - [Nn]* ) break;; - * ) echo "Please answer y or n.";; - esac -done - -} - -function install_dependencies() -{ - - -#--- start installing dependencies - -sudo apt-get -y install python-dev -sudo apt-get -y install python-pip -sudo pip install flask -sudo pip install apscheduler -sudo pip install pyserial - -#(for the webcam support) -sudo apt-get -y install fswebcam - -#(for external IP address, using DNS) -sudo apt-get -y install dnsutils - -#(encryption) -sudo pip install pbkdf2 - -#(web server) -sudo pip install tornado - -} - -function enable_I2C() -{ - -# --- Enable I2C and Spi : -# /boot/config.txt - -sed -i 's/\(^.*#dtparam=i2c_arm=on.*$\)/dtparam=i2c_arm=on/' /boot/config.txt -sed -i 's/\(^.*#dtparam=spi=on.*$\)/dtparam=spi=on/' /boot/config.txt -sed -i 's/\(^.*#dtparam=i2s=on.*$\)/dtparam=i2s=on/' /boot/config.txt - -# --- Add modules: -# /etc/modules -aconf="/etc/modules" - -sed -i '/i2c-bcm2708/d' $aconf -sed -i -e "\$ai2c-bcm2708" $aconf - -sed -i '/i2c-dev/d' $aconf -sed -i -e "\$ai2c-dev" $aconf - -sed -i '/i2c-bcm2835/d' $aconf -sed -i -e "\$ai2c-bcm2835" $aconf - -sed -i '/rtc-ds1307/d' $aconf -sed -i -e "\$artc-ds1307" $aconf - -sed -i '/bcm2835-v4l2/d' $aconf -sed -i -e "\$abcm2835-v4l2" $aconf - - -# --- install I2C tools -sudo apt-get -y install git build-essential python-dev python-smbus -sudo apt-get -y install -y i2c-tools - -} - - -# --- enable raspicam - -############# MISSING ############## - -function modify_RClocal() -{ - -# --- Real Time Clock (RTC) -# /etc/rc.local - -autostart="yes" -# copy the below lines between # START and #END to rc.local -tmpfile=$(mktemp) -sudo sed '/#START/,/#END/d' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local -# Remove to growing plank lines. -sudo awk '!NF {if (++n <= 1) print; next}; {n=0;print}' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local -if [ "$autostart" == "yes" ]; then - if ! grep -Fq '#START HYDROSYS4 SECTION' /etc/rc.local; then - sudo sed -i '/exit 0/d' /etc/rc.local - sudo bash -c "cat >> /etc/rc.local" << EOF -#START HYDROSYS4 SECTION -# iptables -sudo iptables-restore < /home/pi/iptables.rules - -# clock -echo ds3231 0x68 > /sys/class/i2c-adapter/i2c-1/new_device || true -hwclock -s || true - -cd /home/pi/env/autonom/ -sudo python /home/pi/env/autonom/bentornado.py & - -#END HYDROSYS4 SECTION - -exit 0 -EOF - else - tmpfile=$(mktemp) - sudo sed '/#START/,/#END/d' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local - # Remove to growing plank lines. - sudo awk '!NF {if (++n <= 1) print; next}; {n=0;print}' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local - fi - -fi - -sudo chown root:root /etc/rc.local -sudo chmod 755 /etc/rc.local -# end modification to RC.local - -} - - -### -- WIFI setup --- STANDARD - -function valid_ip() -{ - local ip=$1 - local stat=1 - - if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then - OIFS=$IFS - IFS='.' - ip=($ip) - IFS=$OIFS - [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \ - && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]] - stat=$? - fi - return $stat -} - - -input_UI () -{ - -echo "Hello, following initial setting is requested:" - -# IP part input - -IP="0" -while ! valid_ip $IP; do - read -p "Local IP address (range 192.168.0.100-192.168.1.200), to confirm press [ENTER] or modify: " -e -i 192.168.0.172 IP - if valid_ip $IP; then stat='good'; - else stat='bad'; echo "WRONG FORMAT, please enter a valid value for IP address" - fi - -done - echo "Confirmed IP address: "$IP - -PORT="" -while [[ ! $PORT =~ ^[0-9]+$ ]]; do -read -p "Local PORT, to confirm press [ENTER] or modify: " -e -i 5012 PORT - if [[ ! $PORT =~ ^[0-9]+$ ]]; - then echo "WRONG FORMAT, please enter a valid value for PORT"; - fi -done - echo "Confirmed PORT: "$PORT - -# Local WiFi AP name and password setting - -read -p "System WiFi AP name, to confirm press [ENTER] or modify: " -e -i Hydrosys4 WiFiAPname -echo "Confirmed Name: "$WiFiAPname - -read -p "System WiFi AP password, to confirm press [ENTER] or modify: " -e -i hydrosystem WiFiAPpsw -echo "Confirmed Password: "$WiFiAPpsw - -} - - -install_DHT22lib () -{ - -# --- installing the DHT22 Sensor libraries -sudo apt-get -y install build-essential python-dev - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/DHT22/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/DHT22 - unzip master.zip - cd Adafruit_Python_DHT-master - # setup1+2 is file that try to make the DTH22 work with both RaspberryPi zero,1 and model 2,3 - sudo python setup1+2.py install - cd /home/pi -else - cd /home/pi - sudo rm -r DHT22 - mkdir DHT22 - cd DHT22 - wget https://github.com/adafruit/Adafruit_Python_DHT/archive/master.zip - unzip master.zip - cd Adafruit_Python_DHT-master - sudo python setup.py install - cd /home/pi -fi -} - - -install_SPIlib () -{ - - -# --- INSTALL SPI library: - -sudo apt-get -y install python2.7-dev - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/SPI/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/SPI - unzip master.zip - cd py-spidev-master - sudo python setup.py install - cd /home/pi -else - -cd /home/pi -sudo rm -r SPIDEV -mkdir SPIDEV -cd SPIDEV - -wget https://github.com/Gadgetoid/py-spidev/archive/master.zip - -unzip master.zip - -rm master.zip - -cd py-spidev-master - -sudo python setup.py install - -cd .. -cd .. - -fi -} - - -install_BMPlib () -{ - -# --- INSTALL BMP180 library (pressure sensor) - -sudo apt-get -y install build-essential python-dev python-smbus - - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/BMP/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/BMP - unzip master.zip - cd Adafruit_Python_BMP-master - sudo python setup.py install - cd /home/pi -else - -cd /home/pi -sudo rm -r bmp180 -sudo mkdir bmp180 -cd bmp180 -wget https://github.com/adafruit/Adafruit_Python_BMP/archive/master.zip -cd Adafruit_Python_BMP-master -sudo python setup.py install -cd .. -cd .. - -fi -} - - -install_hydrosys4 () -{ -# --- INSTALL Hydrosys4 software -sudo apt-get -y install git - - -# check if file exist in local folder -aconf="/home/pi/env/autonom" -if [ -d $aconf ]; then # if the directory exist - cd /home/pi -else - cd /home/pi - sudo rm -r env - mkdir env - cd env - sudo rm -r autonom - git clone https://github.com/Hydrosys4/Master.git - sudo killall python - mv Master autonom - cd .. - -fi - -} - - - - - - -fn_hostapd () -{ - -sudo apt-get -y install hostapd - - -# create hostapd.conf file -aconf="/etc/hostapd/hostapd.conf" -if [ -f $aconf ]; then - cp $aconf $aconf.1 - sudo rm $aconf - echo "remove file" -fi - - -sudo bash -c "cat >> $aconf" << EOF -# HERE-> {"name": "IPsetting", "LocalIPaddress": "$IP", "LocalPORT": "$PORT", "LocalAPSSID" : "$WiFiAPname"} -ieee80211n=1 -interface=wlan0 -ssid=$WiFiAPname -hw_mode=g -channel=6 -macaddr_acl=0 -auth_algs=1 -ignore_broadcast_ssid=0 -wpa=3 -wpa_passphrase=$WiFiAPpsw -wpa_key_mgmt=WPA-PSK -wpa_pairwise=TKIP -rsn_pairwise=CCMP -EOF - - -aconf="/etc/init.d/hostapd" -# Update hostapd main config file -sudo sed -i "s/\(^.*DAEMON_CONF=.*$\)/DAEMON_CONF=\/etc\/hostapd\/hostapd.conf/" $aconf - -sudo systemctl enable hostapd.service - -} - - -fn_dnsmasq () -{ - -sudo apt-get -y install dnsmasq - - -# edit /etc/dnsmasq.conf file -aconf="/etc/dnsmasq.conf" - -# delete rows between #START and #END -sed -i '/^#START HYDROSYS4 SECTION/,/^#END HYDROSYS4 SECTION/{/^#START HYDROSYS4 SECTION/!{/^#END HYDROSYS4 SECTION/!d}}' $aconf -sed -i '/#START HYDROSYS4 SECTION/d' $aconf -sed -i '/#END HYDROSYS4 SECTION/d' $aconf - - - -sudo bash -c "cat >> $aconf" << EOF -#START HYDROSYS4 SECTION -interface=wlan0 -dhcp-range=192.168.0.100,192.168.1.200,255.255.0.0,12h -#no-resolv -#END HYDROSYS4 SECTION -EOF - -sudo systemctl enable dnsmasq.service - - -} - - - - - - - - - - - - -install_mjpegstr () -{ -cd /home/pi - -sudo rm -r mjpg-streamer - -sudo apt-get -y install cmake libjpeg8-dev git - -sudo git clone https://github.com/jacksonliam/mjpg-streamer.git - -cd mjpg-streamer/mjpg-streamer-experimental - -sudo make - -sudo make install - -cd .. -cd .. - -} - - - -install_nginx () -{ -# this function is not used anymore -cd /home/pi - -sudo apt-get -y install nginx - -# create default file -aconf="/etc/nginx/sites-enabled/default" -if [ -f $aconf ]; then - cp $aconf /home/pi/$aconf.1 - sudo rm $aconf - echo "remove file" -fi - - -sudo bash -c "cat >> $aconf" << EOF -server { - # for a public HTTP server: - listen $PORT; - server_name localhost hydrosys4.local; - - access_log off; - error_log off; - - location / { - proxy_pass http://127.0.0.1:5020; - } - - location /stream { - rewrite ^/stream(.*) /$1 break; - proxy_pass http://127.0.0.1:5022; - proxy_buffering off; - } - - location /favicon.ico { - alias /home/pi/env/autonom/static/favicon.ico; - } -} -EOF - -sudo service nginx start - -cd .. -cd .. - -} - - -install_squid3 () -{ -# this function is used to install the squid3 program used as reverse proxy -cd /home/pi - -sudo apt-get install squid3 -y - -# add configuration to squid.conf, the file should already exist if installation is succesful -aconf="/etc/squid3/squid.conf" -if [ -f $aconf ]; then - cp $aconf $aconf.1 - sudo rm $aconf - echo "remove file" -fi - - -sudo bash -c "cat >> $aconf" << EOF -# WELCOME TO SQUID 3.5.12 - -# hydrosys4 configurations - -http_port 5012 accel defaultsite=hydrosys4 vhost - -acl Safe_ports port 5012 # unregistered ports - -acl videostream urlpath_regex \?action=stream - -cache_peer localhost parent 5020 0 no-query originserver name=server1 -cache_peer_access server1 deny videostream - -cache_peer localhost parent 5022 0 no-query originserver name=server2 -cache_peer_access server2 allow videostream -cache_peer_access server2 deny all - -http_access allow Safe_ports - -# default configurations - -# WELCOME TO SQUID 3.5.12 -acl SSL_ports port 443 -acl Safe_ports port 80 # http -acl Safe_ports port 21 # ftp -acl Safe_ports port 443 # https -acl Safe_ports port 70 # gopher -acl Safe_ports port 210 # wais -acl Safe_ports port 1025-65535 # unregistered ports -acl Safe_ports port 280 # http-mgmt -acl Safe_ports port 488 # gss-http -acl Safe_ports port 591 # filemaker -acl Safe_ports port 777 # multiling http -acl CONNECT method CONNECT -http_access deny !Safe_ports -http_access deny CONNECT !SSL_ports -http_access allow localhost manager -http_access deny manager -http_access allow localhost -http_access deny all -http_port 3128 -coredump_dir /var/spool/squid -refresh_pattern ^ftp: 1440 20% 10080 -refresh_pattern ^gopher: 1440 0% 1440 -refresh_pattern -i (/cgi-bin/|\?) 0 0% 0 -refresh_pattern (Release|Packages(.gz)*)$ 0 20% 2880 -refresh_pattern . 0 20% 4320 -EOF - -sudo service squid3 start - -cd .. -cd .. - -} - - - -edit_defaultnetworkdb () -{ - - -aconf="/home/pi/env/autonom/database/default/defnetwork.txt " - -# if file already exist then no action, otherwise create it -if [ -f $aconf ]; then - echo "network default file already exist" - else - sudo bash -c "cat >> $aconf" << EOF -{"name": "IPsetting", "LocalIPaddress": "192.168.0.172", "LocalPORT": "5012" , "LocalAPSSID" : "Hydrosys4"} -EOF - -fi - -} - -edit_networkdb () -{ - - -aconf="/home/pi/env/autonom/database/network.txt " - -# if file already exist then delete it -if [ -f $aconf ]; then - sudo rm $aconf - echo "remove file" -fi - -sudo bash -c "cat >> $aconf" << EOF -{"name": "IPsetting", "LocalIPaddress": "$IP", "LocalPORT": "$PORT", "LocalAPSSID" : "$WiFiAPname"} -EOF - - -} - - -iptables_blockports () -{ -sudo iptables -A INPUT -p tcp --dport 5020 -j DROP -sudo iptables -A INPUT -p tcp --dport 5022 -j DROP - -sudo iptables-save > /home/pi/iptables.rules - -} - - -# --- RUN the functions -killpython -input_UI -#system_update_UI -install_dependencies -enable_I2C -modify_RClocal -fn_hostapd -fn_dnsmasq -install_mjpegstr -install_squid3 -install_hydrosys4 # this should be called before the DHT22 , SPI and BMP due to local library references -install_DHT22lib -install_SPIlib -install_BMPlib -edit_defaultnetworkdb -edit_networkdb -iptables_blockports - -sudo apt-get -y install fswebcam - diff --git a/bash/install_hydrosys4v12.sh b/bash/install_hydrosys4v12.sh deleted file mode 100644 index 8d51baa..0000000 --- a/bash/install_hydrosys4v12.sh +++ /dev/null @@ -1,661 +0,0 @@ -#!/bin/bash - - -#Debug enable next 3 lines -exec 5> install.txt -BASH_XTRACEFD="5" -set -x -# ------ end debug - - -function killpython() -{ - -sudo killall python - -} - - -function system_update_light() -{ - -# ---- system_update - -sudo apt-get -y update - -} - -function system_update() -{ - -# ---- remove unnecessary packages - -sudo apt-get remove --purge libreoffice-* -sudo apt-get remove --purge wolfram-engine - - -# ---- system_update - -sudo apt-get -y update -sudo apt-get -y upgrade - -} - -function system_update_UI() -{ - -while true; do - read -p "Do you wish to update the Raspbian system (y/n)?" yn - case $yn in - [Yy]* ) system_update; break;; - [Nn]* ) break;; - * ) echo "Please answer y or n.";; - esac -done - -} - -function install_dependencies() -{ - - -#--- start installing dependencies - -sudo apt-get -y install python-dev -sudo apt-get -y install python-pip -sudo pip install flask -sudo pip install apscheduler -sudo pip install pyserial - -#(for the webcam support) -sudo apt-get -y install fswebcam - -#(for external IP address, using DNS) -sudo apt-get -y install dnsutils - -#(encryption) -sudo pip install pbkdf2 - -#(web server) -sudo pip install tornado - -} - -function enable_I2C() -{ - -# --- Enable I2C and Spi : -# /boot/config.txt - -sed -i 's/\(^.*#dtparam=i2c_arm=on.*$\)/dtparam=i2c_arm=on/' /boot/config.txt -sed -i 's/\(^.*#dtparam=spi=on.*$\)/dtparam=spi=on/' /boot/config.txt -sed -i 's/\(^.*#dtparam=i2s=on.*$\)/dtparam=i2s=on/' /boot/config.txt - -# --- Add modules: -# /etc/modules -aconf="/etc/modules" - -sed -i '/i2c-bcm2708/d' $aconf -sed -i -e "\$ai2c-bcm2708" $aconf - -sed -i '/i2c-dev/d' $aconf -sed -i -e "\$ai2c-dev" $aconf - -sed -i '/i2c-bcm2835/d' $aconf -sed -i -e "\$ai2c-bcm2835" $aconf - -sed -i '/rtc-ds1307/d' $aconf -sed -i -e "\$artc-ds1307" $aconf - -sed -i '/bcm2835-v4l2/d' $aconf -sed -i -e "\$abcm2835-v4l2" $aconf - - -# --- install I2C tools -sudo apt-get -y install git build-essential python-dev python-smbus -sudo apt-get -y install -y i2c-tools - -} - - -# --- enable raspicam - -############# MISSING ############## - -function modify_RClocal() -{ - -# --- Real Time Clock (RTC) -# /etc/rc.local - -autostart="yes" -# copy the below lines between # START and #END to rc.local -tmpfile=$(mktemp) -sudo sed '/#START/,/#END/d' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local -# Remove to growing plank lines. -sudo awk '!NF {if (++n <= 1) print; next}; {n=0;print}' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local -if [ "$autostart" == "yes" ]; then - if ! grep -Fq '#START HYDROSYS4 SECTION' /etc/rc.local; then - sudo sed -i '/exit 0/d' /etc/rc.local - sudo bash -c "cat >> /etc/rc.local" << EOF -#START HYDROSYS4 SECTION -# iptables -sudo iptables-restore < /home/pi/iptables.rules - -# clock -echo ds3231 0x68 > /sys/class/i2c-adapter/i2c-1/new_device || true -hwclock -s || true - -cd /home/pi/env/autonom/ -sudo python /home/pi/env/autonom/bentornado.py & - -#END HYDROSYS4 SECTION - -exit 0 -EOF - else - tmpfile=$(mktemp) - sudo sed '/#START/,/#END/d' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local - # Remove to growing plank lines. - sudo awk '!NF {if (++n <= 1) print; next}; {n=0;print}' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local - fi - -fi - -sudo chown root:root /etc/rc.local -sudo chmod 755 /etc/rc.local -# end modification to RC.local - -} - - -### -- WIFI setup --- STANDARD - -function valid_ip() -{ - local ip=$1 - local stat=1 - - if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then - OIFS=$IFS - IFS='.' - ip=($ip) - IFS=$OIFS - [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \ - && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]] - stat=$? - fi - return $stat -} - - -input_UI () -{ - -echo "Hello, following initial setting is requested:" - -# IP part input - -IP="0" -while ! valid_ip $IP; do - read -p "Local IP address (range 192.168.0.100-192.168.1.200), to confirm press [ENTER] or modify: " -e -i 192.168.0.172 IP - if valid_ip $IP; then stat='good'; - else stat='bad'; echo "WRONG FORMAT, please enter a valid value for IP address" - fi - -done - echo "Confirmed IP address: "$IP - -PORT="" -while [[ ! $PORT =~ ^[0-9]+$ ]]; do -read -p "Local PORT, to confirm press [ENTER] or modify: " -e -i 5012 PORT - if [[ ! $PORT =~ ^[0-9]+$ ]]; - then echo "WRONG FORMAT, please enter a valid value for PORT"; - fi -done - echo "Confirmed PORT: "$PORT - -# Local WiFi AP name and password setting - -read -p "System WiFi AP name, to confirm press [ENTER] or modify: " -e -i Hydrosys4 WiFiAPname -echo "Confirmed Name: "$WiFiAPname - -read -p "System WiFi AP password, to confirm press [ENTER] or modify: " -e -i hydrosystem WiFiAPpsw -echo "Confirmed Password: "$WiFiAPpsw - -} - - -install_DHT22lib () -{ - -# --- installing the DHT22 Sensor libraries -sudo apt-get -y install build-essential python-dev - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/DHT22/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/DHT22 - unzip master.zip - cd Adafruit_Python_DHT-master - # setup1+2 is file that try to make the DTH22 work with both RaspberryPi zero,1 and model 2,3 - sudo python setup1+2.py install - cd /home/pi -else - cd /home/pi - sudo rm -r DHT22 - mkdir DHT22 - cd DHT22 - wget https://github.com/adafruit/Adafruit_Python_DHT/archive/master.zip - unzip master.zip - cd Adafruit_Python_DHT-master - sudo python setup.py install - cd /home/pi -fi -} - - -install_SPIlib () -{ - - -# --- INSTALL SPI library: - -sudo apt-get -y install python2.7-dev - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/SPI/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/SPI - unzip master.zip - cd py-spidev-master - sudo python setup.py install - cd /home/pi -else - -cd /home/pi -sudo rm -r SPIDEV -mkdir SPIDEV -cd SPIDEV - -wget https://github.com/Gadgetoid/py-spidev/archive/master.zip - -unzip master.zip - -rm master.zip - -cd py-spidev-master - -sudo python setup.py install - -cd .. -cd .. - -fi -} - - -install_BMPlib () -{ - -# --- INSTALL BMP180 library (pressure sensor) - -sudo apt-get -y install build-essential python-dev python-smbus - - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/BMP/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/BMP - unzip master.zip - cd Adafruit_Python_BMP-master - sudo python setup.py install - cd /home/pi -else - -cd /home/pi -sudo rm -r bmp180 -sudo mkdir bmp180 -cd bmp180 -wget https://github.com/adafruit/Adafruit_Python_BMP/archive/master.zip -cd Adafruit_Python_BMP-master -sudo python setup.py install -cd .. -cd .. - -fi -} - - -install_hydrosys4 () -{ -# --- INSTALL Hydrosys4 software -sudo apt-get -y install git - - -# check if file exist in local folder -aconf="/home/pi/env/autonom" -if [ -d $aconf ]; then # if the directory exist - cd /home/pi -else - cd /home/pi - sudo rm -r env - mkdir env - cd env - sudo rm -r autonom - git clone https://github.com/Hydrosys4/Master.git - sudo killall python - mv Master autonom - cd .. - -fi - -} - - - - - - -fn_hostapd () -{ - -sudo apt-get -y install hostapd - - -# create hostapd.conf file -aconf="/etc/hostapd/hostapd.conf" -if [ -f $aconf ]; then - cp $aconf $aconf.1 - sudo rm $aconf - echo "remove file" -fi - - -sudo bash -c "cat >> $aconf" << EOF -# HERE-> {"name": "IPsetting", "LocalIPaddress": "$IP", "LocalPORT": "$PORT", "LocalAPSSID" : "$WiFiAPname"} -ieee80211n=1 -interface=wlan0 -ssid=$WiFiAPname -hw_mode=g -channel=6 -macaddr_acl=0 -auth_algs=1 -ignore_broadcast_ssid=0 -wpa=3 -wpa_passphrase=$WiFiAPpsw -wpa_key_mgmt=WPA-PSK -wpa_pairwise=TKIP -rsn_pairwise=CCMP -EOF - - -aconf="/etc/init.d/hostapd" -# Update hostapd main config file -sudo sed -i "s/\(^.*DAEMON_CONF=.*$\)/DAEMON_CONF=\/etc\/hostapd\/hostapd.conf/" $aconf - -sudo systemctl enable hostapd.service - -} - - -fn_dnsmasq () -{ - -sudo apt-get -y install dnsmasq - - -# edit /etc/dnsmasq.conf file -aconf="/etc/dnsmasq.conf" - -# delete rows between #START and #END -sed -i '/^#START HYDROSYS4 SECTION/,/^#END HYDROSYS4 SECTION/{/^#START HYDROSYS4 SECTION/!{/^#END HYDROSYS4 SECTION/!d}}' $aconf -sed -i '/#START HYDROSYS4 SECTION/d' $aconf -sed -i '/#END HYDROSYS4 SECTION/d' $aconf - - - -sudo bash -c "cat >> $aconf" << EOF -#START HYDROSYS4 SECTION -interface=wlan0 -dhcp-range=192.168.0.100,192.168.1.200,255.255.0.0,12h -#no-resolv -#END HYDROSYS4 SECTION -EOF - -sudo systemctl enable dnsmasq.service - - -} - - - - - - - - - - - - -install_mjpegstr () -{ -cd /home/pi - -sudo rm -r mjpg-streamer - -sudo apt-get -y install cmake libjpeg8-dev git - -sudo git clone https://github.com/jacksonliam/mjpg-streamer.git - -cd mjpg-streamer/mjpg-streamer-experimental - -sudo make - -sudo make install - -cd .. -cd .. - -} - - - -install_nginx () -{ -# this function is not used anymore -cd /home/pi - -sudo apt-get -y install nginx - -# create default file -aconf="/etc/nginx/sites-enabled/default" -if [ -f $aconf ]; then - cp $aconf /home/pi/$aconf.1 - sudo rm $aconf - echo "remove file" -fi - - -sudo bash -c "cat >> $aconf" << EOF -server { - # for a public HTTP server: - listen $PORT; - server_name localhost hydrosys4.local; - - access_log off; - error_log off; - - location / { - proxy_pass http://127.0.0.1:5020; - } - - location /stream { - rewrite ^/stream(.*) /$1 break; - proxy_pass http://127.0.0.1:5022; - proxy_buffering off; - } - - location /favicon.ico { - alias /home/pi/env/autonom/static/favicon.ico; - } -} -EOF - -sudo service nginx start - -cd .. -cd .. - -} - - -install_squid3 () -{ -# this function is used to install the squid3 program used as reverse proxy -cd /home/pi - -sudo apt-get install squid3 -y - -# add configuration to squid.conf, the file should already exist if installation is succesful -aconf="/etc/squid3/squid.conf" -if [ -f $aconf ]; then - cp $aconf $aconf.1 - sudo rm $aconf - echo "remove file" -fi - - -sudo bash -c "cat >> $aconf" << EOF -# WELCOME TO SQUID 3.5.12 - -# hydrosys4 configurations - -http_port 5012 accel defaultsite=hydrosys4 vhost - -acl Safe_ports port 5012 # unregistered ports - -acl videostream urlpath_regex \?action=stream - -cache_peer localhost parent 5020 0 no-query originserver name=server1 -cache_peer_access server1 deny videostream - -cache_peer localhost parent 5022 0 no-query originserver name=server2 -cache_peer_access server2 allow videostream -cache_peer_access server2 deny all - -http_access allow Safe_ports - -# default configurations - -# WELCOME TO SQUID 3.5.12 -acl SSL_ports port 443 -acl Safe_ports port 80 # http -acl Safe_ports port 21 # ftp -acl Safe_ports port 443 # https -acl Safe_ports port 70 # gopher -acl Safe_ports port 210 # wais -acl Safe_ports port 1025-65535 # unregistered ports -acl Safe_ports port 280 # http-mgmt -acl Safe_ports port 488 # gss-http -acl Safe_ports port 591 # filemaker -acl Safe_ports port 777 # multiling http -acl CONNECT method CONNECT -http_access deny !Safe_ports -http_access deny CONNECT !SSL_ports -http_access allow localhost manager -http_access deny manager -http_access allow localhost -http_access deny all -http_port 3128 -coredump_dir /var/spool/squid -refresh_pattern ^ftp: 1440 20% 10080 -refresh_pattern ^gopher: 1440 0% 1440 -refresh_pattern -i (/cgi-bin/|\?) 0 0% 0 -refresh_pattern (Release|Packages(.gz)*)$ 0 20% 2880 -refresh_pattern . 0 20% 4320 -EOF - -sudo service squid3 start - -cd .. -cd .. - -} - - - -edit_defaultnetworkdb () -{ - - -aconf="/home/pi/env/autonom/database/default/defnetwork.txt " - -# if file already exist then no action, otherwise create it -if [ -f $aconf ]; then - echo "network default file already exist" - else - sudo bash -c "cat >> $aconf" << EOF -{"name": "IPsetting", "LocalIPaddress": "192.168.0.172", "LocalPORT": "5012" , "LocalAPSSID" : "Hydrosys4"} -EOF - -fi - -} - -edit_networkdb () -{ - - -aconf="/home/pi/env/autonom/database/network.txt " - -# if file already exist then delete it -if [ -f $aconf ]; then - sudo rm $aconf - echo "remove file" -fi - -sudo bash -c "cat >> $aconf" << EOF -{"name": "IPsetting", "LocalIPaddress": "$IP", "LocalPORT": "$PORT", "LocalAPSSID" : "$WiFiAPname"} -EOF - - -} - - -iptables_blockports () -{ -sudo iptables -A INPUT -p tcp --dport 5020 -j DROP -sudo iptables -A INPUT -p tcp --dport 5022 -j DROP - -sudo iptables-save > /home/pi/iptables.rules - -} - - -# --- RUN the functions -killpython -input_UI -system_update_light -#system_update_UI -install_dependencies -enable_I2C -modify_RClocal -fn_hostapd -fn_dnsmasq -install_mjpegstr -install_squid3 -install_hydrosys4 # this should be called before the DHT22 , SPI and BMP due to local library references -install_DHT22lib -install_SPIlib -install_BMPlib -edit_defaultnetworkdb -edit_networkdb -iptables_blockports - -sudo apt-get -y install fswebcam - diff --git a/bash/install_hydrosys4v13.sh b/bash/install_hydrosys4v13.sh deleted file mode 100644 index f3b80a8..0000000 --- a/bash/install_hydrosys4v13.sh +++ /dev/null @@ -1,661 +0,0 @@ -#!/bin/bash - - -#Debug enable next 3 lines -exec 5> install.txt -BASH_XTRACEFD="5" -set -x -# ------ end debug - - -function killpython() -{ - -sudo killall python - -} - - -function system_update_light() -{ - -# ---- system_update - -sudo apt-get -y update - -} - -function system_update() -{ - -# ---- remove unnecessary packages - -sudo apt-get remove --purge libreoffice-* -sudo apt-get remove --purge wolfram-engine - - -# ---- system_update - -sudo apt-get -y update -sudo apt-get -y upgrade - -} - -function system_update_UI() -{ - -while true; do - read -p "Do you wish to update the Raspbian system (y/n)?" yn - case $yn in - [Yy]* ) system_update; break;; - [Nn]* ) break;; - * ) echo "Please answer y or n.";; - esac -done - -} - -function install_dependencies() -{ - - -#--- start installing dependencies - -sudo apt-get -y install python-dev || echo "ERROR --------------------------Installation failed ----------------" && exit -sudo apt-get -y install python-pip || echo "ERROR --------------------------Installation failed ----------------" && exit -sudo pip install flask || echo "ERROR --------------------------Installation failed ----------------" && exit -sudo pip install apscheduler || echo "ERROR --------------------------Installation failed ----------------" && exit -sudo pip install pyserial || echo "ERROR --------------------------Installation failed ----------------" && exit - -#(for the webcam support) -sudo apt-get -y install fswebcam || echo "ERROR --------------------------Installation failed ----------------" && exit - -#(for external IP address, using DNS) -sudo apt-get -y install dnsutils || echo "ERROR --------------------------Installation failed ----------------" && exit - -#(encryption) -sudo pip install pbkdf2 || echo "ERROR --------------------------Installation failed ----------------" && exit - -#(web server) -sudo pip install tornado || echo "ERROR --------------------------Installation failed ----------------" && exit - -} - -function enable_I2C() -{ - -# --- Enable I2C and Spi : -# /boot/config.txt - -sed -i 's/\(^.*#dtparam=i2c_arm=on.*$\)/dtparam=i2c_arm=on/' /boot/config.txt -sed -i 's/\(^.*#dtparam=spi=on.*$\)/dtparam=spi=on/' /boot/config.txt -sed -i 's/\(^.*#dtparam=i2s=on.*$\)/dtparam=i2s=on/' /boot/config.txt - -# --- Add modules: -# /etc/modules -aconf="/etc/modules" - -sed -i '/i2c-bcm2708/d' $aconf -sed -i -e "\$ai2c-bcm2708" $aconf - -sed -i '/i2c-dev/d' $aconf -sed -i -e "\$ai2c-dev" $aconf - -sed -i '/i2c-bcm2835/d' $aconf -sed -i -e "\$ai2c-bcm2835" $aconf - -sed -i '/rtc-ds1307/d' $aconf -sed -i -e "\$artc-ds1307" $aconf - -sed -i '/bcm2835-v4l2/d' $aconf -sed -i -e "\$abcm2835-v4l2" $aconf - - -# --- install I2C tools -sudo apt-get -y install git build-essential python-dev python-smbus || echo "ERROR --------------------------Installation failed ----------------" && exit -sudo apt-get -y install -y i2c-tools || echo "ERROR --------------------------Installation failed ----------------" && exit - -} - - -# --- enable raspicam - -############# MISSING ############## - -function modify_RClocal() -{ - -# --- Real Time Clock (RTC) -# /etc/rc.local - -autostart="yes" -# copy the below lines between # START and #END to rc.local -tmpfile=$(mktemp) -sudo sed '/#START/,/#END/d' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local -# Remove to growing plank lines. -sudo awk '!NF {if (++n <= 1) print; next}; {n=0;print}' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local -if [ "$autostart" == "yes" ]; then - if ! grep -Fq '#START HYDROSYS4 SECTION' /etc/rc.local; then - sudo sed -i '/exit 0/d' /etc/rc.local - sudo bash -c "cat >> /etc/rc.local" << EOF -#START HYDROSYS4 SECTION -# iptables -sudo iptables-restore < /home/pi/iptables.rules - -# clock -echo ds3231 0x68 > /sys/class/i2c-adapter/i2c-1/new_device || true -hwclock -s || true - -cd /home/pi/env/autonom/ -sudo python /home/pi/env/autonom/bentornado.py & - -#END HYDROSYS4 SECTION - -exit 0 -EOF - else - tmpfile=$(mktemp) - sudo sed '/#START/,/#END/d' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local - # Remove to growing plank lines. - sudo awk '!NF {if (++n <= 1) print; next}; {n=0;print}' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local - fi - -fi - -sudo chown root:root /etc/rc.local -sudo chmod 755 /etc/rc.local -# end modification to RC.local - -} - - -### -- WIFI setup --- STANDARD - -function valid_ip() -{ - local ip=$1 - local stat=1 - - if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then - OIFS=$IFS - IFS='.' - ip=($ip) - IFS=$OIFS - [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \ - && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]] - stat=$? - fi - return $stat -} - - -input_UI () -{ - -echo "Hello, following initial setting is requested:" - -# IP part input - -IP="0" -while ! valid_ip $IP; do - read -p "Local IP address (range 192.168.0.100-192.168.1.200), to confirm press [ENTER] or modify: " -e -i 192.168.0.172 IP - if valid_ip $IP; then stat='good'; - else stat='bad'; echo "WRONG FORMAT, please enter a valid value for IP address" - fi - -done - echo "Confirmed IP address: "$IP - -PORT="" -while [[ ! $PORT =~ ^[0-9]+$ ]]; do -read -p "Local PORT, to confirm press [ENTER] or modify: " -e -i 5012 PORT - if [[ ! $PORT =~ ^[0-9]+$ ]]; - then echo "WRONG FORMAT, please enter a valid value for PORT"; - fi -done - echo "Confirmed PORT: "$PORT - -# Local WiFi AP name and password setting - -read -p "System WiFi AP name, to confirm press [ENTER] or modify: " -e -i Hydrosys4 WiFiAPname -echo "Confirmed Name: "$WiFiAPname - -read -p "System WiFi AP password, to confirm press [ENTER] or modify: " -e -i hydrosystem WiFiAPpsw -echo "Confirmed Password: "$WiFiAPpsw - -} - - -install_DHT22lib () -{ - -# --- installing the DHT22 Sensor libraries -sudo apt-get -y install build-essential python-dev || echo "ERROR --------------------------Installation failed ----------------" && exit - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/DHT22/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/DHT22 - unzip master.zip - cd Adafruit_Python_DHT-master - # setup1+2 is file that try to make the DTH22 work with both RaspberryPi zero,1 and model 2,3 - sudo python setup1+2.py install - cd /home/pi -else - cd /home/pi - sudo rm -r DHT22 - mkdir DHT22 - cd DHT22 - wget https://github.com/adafruit/Adafruit_Python_DHT/archive/master.zip - unzip master.zip - cd Adafruit_Python_DHT-master - sudo python setup.py install - cd /home/pi -fi -} - - -install_SPIlib () -{ - - -# --- INSTALL SPI library: - -sudo apt-get -y install python2.7-dev || echo "ERROR --------------------------Installation failed ----------------" && exit - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/SPI/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/SPI - unzip master.zip - cd py-spidev-master - sudo python setup.py install - cd /home/pi -else - -cd /home/pi -sudo rm -r SPIDEV -mkdir SPIDEV -cd SPIDEV - -wget https://github.com/Gadgetoid/py-spidev/archive/master.zip - -unzip master.zip - -rm master.zip - -cd py-spidev-master - -sudo python setup.py install - -cd .. -cd .. - -fi -} - - -install_BMPlib () -{ - -# --- INSTALL BMP180 library (pressure sensor) - -sudo apt-get -y install build-essential python-dev python-smbus || echo "ERROR --------------------------Installation failed ----------------" && exit - - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/BMP/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/BMP - unzip master.zip - cd Adafruit_Python_BMP-master - sudo python setup.py install - cd /home/pi -else - -cd /home/pi -sudo rm -r bmp180 -sudo mkdir bmp180 -cd bmp180 -wget https://github.com/adafruit/Adafruit_Python_BMP/archive/master.zip -cd Adafruit_Python_BMP-master -sudo python setup.py install -cd .. -cd .. - -fi -} - - -install_hydrosys4 () -{ -# --- INSTALL Hydrosys4 software -sudo apt-get -y install git || echo "ERROR --------------------------Installation failed ----------------" && exit - - -# check if file exist in local folder -aconf="/home/pi/env/autonom" -if [ -d $aconf ]; then # if the directory exist - cd /home/pi -else - cd /home/pi - sudo rm -r env - mkdir env - cd env - sudo rm -r autonom - git clone https://github.com/Hydrosys4/Master.git - sudo killall python - mv Master autonom - cd .. - -fi - -} - - - - - - -fn_hostapd () -{ - -sudo apt-get -y install hostapd || echo "ERROR --------------------------Installation failed ----------------" && exit - - -# create hostapd.conf file -aconf="/etc/hostapd/hostapd.conf" -if [ -f $aconf ]; then - cp $aconf $aconf.1 - sudo rm $aconf - echo "remove file" -fi - - -sudo bash -c "cat >> $aconf" << EOF -# HERE-> {"name": "IPsetting", "LocalIPaddress": "$IP", "LocalPORT": "$PORT", "LocalAPSSID" : "$WiFiAPname"} -ieee80211n=1 -interface=wlan0 -ssid=$WiFiAPname -hw_mode=g -channel=6 -macaddr_acl=0 -auth_algs=1 -ignore_broadcast_ssid=0 -wpa=3 -wpa_passphrase=$WiFiAPpsw -wpa_key_mgmt=WPA-PSK -wpa_pairwise=TKIP -rsn_pairwise=CCMP -EOF - - -aconf="/etc/init.d/hostapd" -# Update hostapd main config file -sudo sed -i "s/\(^.*DAEMON_CONF=.*$\)/DAEMON_CONF=\/etc\/hostapd\/hostapd.conf/" $aconf - -sudo systemctl enable hostapd.service - -} - - -fn_dnsmasq () -{ - -sudo apt-get -y install dnsmasq || echo "ERROR --------------------------Installation failed ----------------" && exit - - -# edit /etc/dnsmasq.conf file -aconf="/etc/dnsmasq.conf" - -# delete rows between #START and #END -sed -i '/^#START HYDROSYS4 SECTION/,/^#END HYDROSYS4 SECTION/{/^#START HYDROSYS4 SECTION/!{/^#END HYDROSYS4 SECTION/!d}}' $aconf -sed -i '/#START HYDROSYS4 SECTION/d' $aconf -sed -i '/#END HYDROSYS4 SECTION/d' $aconf - - - -sudo bash -c "cat >> $aconf" << EOF -#START HYDROSYS4 SECTION -interface=wlan0 -dhcp-range=192.168.0.100,192.168.1.200,255.255.0.0,12h -#no-resolv -#END HYDROSYS4 SECTION -EOF - -sudo systemctl enable dnsmasq.service - - -} - - - - - - - - - - - - -install_mjpegstr () -{ -cd /home/pi - -sudo rm -r mjpg-streamer - -sudo apt-get -y install cmake libjpeg8-dev git - -sudo git clone https://github.com/jacksonliam/mjpg-streamer.git - -cd mjpg-streamer/mjpg-streamer-experimental - -sudo make - -sudo make install - -cd .. -cd .. - -} - - - -install_nginx () -{ -# this function is not used anymore -cd /home/pi - -sudo apt-get -y install nginx - -# create default file -aconf="/etc/nginx/sites-enabled/default" -if [ -f $aconf ]; then - cp $aconf /home/pi/$aconf.1 - sudo rm $aconf - echo "remove file" -fi - - -sudo bash -c "cat >> $aconf" << EOF -server { - # for a public HTTP server: - listen $PORT; - server_name localhost hydrosys4.local; - - access_log off; - error_log off; - - location / { - proxy_pass http://127.0.0.1:5020; - } - - location /stream { - rewrite ^/stream(.*) /$1 break; - proxy_pass http://127.0.0.1:5022; - proxy_buffering off; - } - - location /favicon.ico { - alias /home/pi/env/autonom/static/favicon.ico; - } -} -EOF - -sudo service nginx start - -cd .. -cd .. - -} - - -install_squid3 () -{ -# this function is used to install the squid3 program used as reverse proxy -cd /home/pi - -sudo apt-get install squid3 -y || echo "ERROR --------------------------Installation failed ----------------" && exit - -# add configuration to squid.conf, the file should already exist if installation is succesful -aconf="/etc/squid3/squid.conf" -if [ -f $aconf ]; then - cp $aconf $aconf.1 - sudo rm $aconf - echo "remove file" -fi - - -sudo bash -c "cat >> $aconf" << EOF -# WELCOME TO SQUID 3.5.12 - -# hydrosys4 configurations - -http_port 5012 accel defaultsite=hydrosys4 vhost - -acl Safe_ports port 5012 # unregistered ports - -acl videostream urlpath_regex \?action=stream - -cache_peer localhost parent 5020 0 no-query originserver name=server1 -cache_peer_access server1 deny videostream - -cache_peer localhost parent 5022 0 no-query originserver name=server2 -cache_peer_access server2 allow videostream -cache_peer_access server2 deny all - -http_access allow Safe_ports - -# default configurations - -# WELCOME TO SQUID 3.5.12 -acl SSL_ports port 443 -acl Safe_ports port 80 # http -acl Safe_ports port 21 # ftp -acl Safe_ports port 443 # https -acl Safe_ports port 70 # gopher -acl Safe_ports port 210 # wais -acl Safe_ports port 1025-65535 # unregistered ports -acl Safe_ports port 280 # http-mgmt -acl Safe_ports port 488 # gss-http -acl Safe_ports port 591 # filemaker -acl Safe_ports port 777 # multiling http -acl CONNECT method CONNECT -http_access deny !Safe_ports -http_access deny CONNECT !SSL_ports -http_access allow localhost manager -http_access deny manager -http_access allow localhost -http_access deny all -http_port 3128 -coredump_dir /var/spool/squid -refresh_pattern ^ftp: 1440 20% 10080 -refresh_pattern ^gopher: 1440 0% 1440 -refresh_pattern -i (/cgi-bin/|\?) 0 0% 0 -refresh_pattern (Release|Packages(.gz)*)$ 0 20% 2880 -refresh_pattern . 0 20% 4320 -EOF - -sudo service squid3 start - -cd .. -cd .. - -} - - - -edit_defaultnetworkdb () -{ - - -aconf="/home/pi/env/autonom/database/default/defnetwork.txt " - -# if file already exist then no action, otherwise create it -if [ -f $aconf ]; then - echo "network default file already exist" - else - sudo bash -c "cat >> $aconf" << EOF -{"name": "IPsetting", "LocalIPaddress": "192.168.0.172", "LocalPORT": "5012" , "LocalAPSSID" : "Hydrosys4"} -EOF - -fi - -} - -edit_networkdb () -{ - - -aconf="/home/pi/env/autonom/database/network.txt " - -# if file already exist then delete it -if [ -f $aconf ]; then - sudo rm $aconf - echo "remove file" -fi - -sudo bash -c "cat >> $aconf" << EOF -{"name": "IPsetting", "LocalIPaddress": "$IP", "LocalPORT": "$PORT", "LocalAPSSID" : "$WiFiAPname"} -EOF - - -} - - -iptables_blockports () -{ -sudo iptables -A INPUT -p tcp --dport 5020 -j DROP -sudo iptables -A INPUT -p tcp --dport 5022 -j DROP - -sudo iptables-save > /home/pi/iptables.rules - -} - - -# --- RUN the functions -killpython -input_UI -system_update_light -#system_update_UI -install_dependencies -enable_I2C -modify_RClocal -fn_hostapd -fn_dnsmasq -install_mjpegstr -install_squid3 -install_hydrosys4 # this should be called before the DHT22 , SPI and BMP due to local library references -install_DHT22lib -install_SPIlib -install_BMPlib -edit_defaultnetworkdb -edit_networkdb -iptables_blockports - -sudo apt-get -y install fswebcam - diff --git a/bash/install_hydrosys4v14.sh b/bash/install_hydrosys4v14.sh deleted file mode 100644 index b5918e8..0000000 --- a/bash/install_hydrosys4v14.sh +++ /dev/null @@ -1,660 +0,0 @@ -#!/bin/bash - - -#Debug enable next 3 lines -exec 5> install.txt -BASH_XTRACEFD="5" -set -x -# ------ end debug - - -function killpython() -{ - -sudo killall python - -} - - -function system_update_light() -{ - -# ---- system_update - -sudo apt-get -y update - -} - -function system_update() -{ - -# ---- remove unnecessary packages - -sudo apt-get remove --purge libreoffice-* -sudo apt-get remove --purge wolfram-engine - - -# ---- system_update - -sudo apt-get -y update -sudo apt-get -y upgrade - -} - -function system_update_UI() -{ - -while true; do - read -p "Do you wish to update the Raspbian system (y/n)?" yn - case $yn in - [Yy]* ) system_update; break;; - [Nn]* ) break;; - * ) echo "Please answer y or n.";; - esac -done - -} - -function install_dependencies() -{ - - -#--- start installing dependencies - -sudo apt-get -y install python-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo apt-get -y install python-pip || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install flask || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install apscheduler || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install pyserial || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(for the webcam support) -sudo apt-get -y install fswebcam || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(for external IP address, using DNS) -sudo apt-get -y install dnsutils || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(encryption) -sudo pip install pbkdf2 || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(web server) -sudo pip install tornado || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -} - -function enable_I2C() -{ - -# --- Enable I2C and Spi : -# /boot/config.txt - -sed -i 's/\(^.*#dtparam=i2c_arm=on.*$\)/dtparam=i2c_arm=on/' /boot/config.txt -sed -i 's/\(^.*#dtparam=spi=on.*$\)/dtparam=spi=on/' /boot/config.txt -sed -i 's/\(^.*#dtparam=i2s=on.*$\)/dtparam=i2s=on/' /boot/config.txt - -# --- Add modules: -# /etc/modules -aconf="/etc/modules" - -sed -i '/i2c-bcm2708/d' $aconf -sed -i -e "\$ai2c-bcm2708" $aconf - -sed -i '/i2c-dev/d' $aconf -sed -i -e "\$ai2c-dev" $aconf - -sed -i '/i2c-bcm2835/d' $aconf -sed -i -e "\$ai2c-bcm2835" $aconf - -sed -i '/rtc-ds1307/d' $aconf -sed -i -e "\$artc-ds1307" $aconf - -sed -i '/bcm2835-v4l2/d' $aconf -sed -i -e "\$abcm2835-v4l2" $aconf - - -# --- install I2C tools -sudo apt-get -y install git build-essential python-dev python-smbus || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo apt-get -y install -y i2c-tools || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -} - - -# --- enable raspicam - -############# MISSING ############## - -function modify_RClocal() -{ - -# --- Real Time Clock (RTC) -# /etc/rc.local - -autostart="yes" -# copy the below lines between # START and #END to rc.local -tmpfile=$(mktemp) -sudo sed '/#START/,/#END/d' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local -# Remove to growing plank lines. -sudo awk '!NF {if (++n <= 1) print; next}; {n=0;print}' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local -if [ "$autostart" == "yes" ]; then - if ! grep -Fq '#START HYDROSYS4 SECTION' /etc/rc.local; then - sudo sed -i '/exit 0/d' /etc/rc.local - sudo bash -c "cat >> /etc/rc.local" << EOF -#START HYDROSYS4 SECTION -# iptables -sudo iptables-restore < /home/pi/iptables.rules - -# clock -echo ds3231 0x68 > /sys/class/i2c-adapter/i2c-1/new_device || true -hwclock -s || true - -cd /home/pi/env/autonom/ -sudo python /home/pi/env/autonom/bentornado.py & - -#END HYDROSYS4 SECTION - -exit 0 -EOF - else - tmpfile=$(mktemp) - sudo sed '/#START/,/#END/d' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local - # Remove to growing plank lines. - sudo awk '!NF {if (++n <= 1) print; next}; {n=0;print}' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local - fi - -fi - -sudo chown root:root /etc/rc.local -sudo chmod 755 /etc/rc.local -# end modification to RC.local - -} - - -### -- WIFI setup --- STANDARD - -function valid_ip() -{ - local ip=$1 - local stat=1 - - if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then - OIFS=$IFS - IFS='.' - ip=($ip) - IFS=$OIFS - [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \ - && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]] - stat=$? - fi - return $stat -} - - -input_UI () -{ - -echo "Hello, following initial setting is requested:" - -# IP part input - -IP="0" -while ! valid_ip $IP; do - read -p "Local IP address (range 192.168.0.100-192.168.1.200), to confirm press [ENTER] or modify: " -e -i 192.168.0.172 IP - if valid_ip $IP; then stat='good'; - else stat='bad'; echo "WRONG FORMAT, please enter a valid value for IP address" - fi - -done - echo "Confirmed IP address: "$IP - -PORT="" -while [[ ! $PORT =~ ^[0-9]+$ ]]; do -read -p "Local PORT, to confirm press [ENTER] or modify: " -e -i 5012 PORT - if [[ ! $PORT =~ ^[0-9]+$ ]]; - then echo "WRONG FORMAT, please enter a valid value for PORT"; - fi -done - echo "Confirmed PORT: "$PORT - -# Local WiFi AP name and password setting - -read -p "System WiFi AP name, to confirm press [ENTER] or modify: " -e -i Hydrosys4 WiFiAPname -echo "Confirmed Name: "$WiFiAPname - -read -p "System WiFi AP password, to confirm press [ENTER] or modify: " -e -i hydrosystem WiFiAPpsw -echo "Confirmed Password: "$WiFiAPpsw - -} - - -install_DHT22lib () -{ - -# --- installing the DHT22 Sensor libraries -sudo apt-get -y install build-essential python-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/DHT22/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/DHT22 - unzip master.zip - cd Adafruit_Python_DHT-master - # setup1plus is file that try to make the DTH22 work with both RaspberryPi zero,1 and model 2,3 - sudo python setup1plus.py install - cd /home/pi -else - cd /home/pi - sudo rm -r DHT22 - mkdir DHT22 - cd DHT22 - wget https://github.com/adafruit/Adafruit_Python_DHT/archive/master.zip - unzip master.zip - cd Adafruit_Python_DHT-master - sudo python setup.py install - cd /home/pi -fi -} - - -install_SPIlib () -{ - - -# --- INSTALL SPI library: - -sudo apt-get -y install python2.7-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/SPI/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/SPI - unzip master.zip - cd py-spidev-master - sudo python setup.py install - cd /home/pi -else - -cd /home/pi -sudo rm -r SPIDEV -mkdir SPIDEV -cd SPIDEV - -wget https://github.com/Gadgetoid/py-spidev/archive/master.zip - -unzip master.zip - -rm master.zip - -cd py-spidev-master - -sudo python setup.py install - -cd .. -cd .. - -fi -} - - -install_BMPlib () -{ - -# --- INSTALL BMP180 library (pressure sensor) - -sudo apt-get -y install build-essential python-dev python-smbus || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/BMP/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/BMP - unzip master.zip - cd Adafruit_Python_BMP-master - sudo python setup.py install - cd /home/pi -else - -cd /home/pi -sudo rm -r bmp180 -sudo mkdir bmp180 -cd bmp180 -wget https://github.com/adafruit/Adafruit_Python_BMP/archive/master.zip -cd Adafruit_Python_BMP-master -sudo python setup.py install -cd .. -cd .. - -fi -} - - -install_hydrosys4 () -{ -# --- INSTALL Hydrosys4 software -sudo apt-get -y install git || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - - -# check if file exist in local folder -aconf="/home/pi/env/autonom" -if [ -d $aconf ]; then # if the directory exist - cd /home/pi -else - cd /home/pi - sudo rm -r env - mkdir env - cd env - sudo rm -r autonom - git clone https://github.com/Hydrosys4/Master.git - sudo killall python - mv Master autonom - cd .. - -fi - -} - - - - - - -fn_hostapd () -{ - -sudo apt-get -y install hostapd || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - - -# create hostapd.conf file -aconf="/etc/hostapd/hostapd.conf" -if [ -f $aconf ]; then - cp $aconf $aconf.1 - sudo rm $aconf - echo "remove file" -fi - - -sudo bash -c "cat >> $aconf" << EOF -# HERE-> {"name": "IPsetting", "LocalIPaddress": "$IP", "LocalPORT": "$PORT", "LocalAPSSID" : "$WiFiAPname"} -ieee80211n=1 -interface=wlan0 -ssid=$WiFiAPname -hw_mode=g -channel=6 -macaddr_acl=0 -auth_algs=1 -ignore_broadcast_ssid=0 -wpa=3 -wpa_passphrase=$WiFiAPpsw -wpa_key_mgmt=WPA-PSK -wpa_pairwise=TKIP -rsn_pairwise=CCMP -EOF - - -aconf="/etc/init.d/hostapd" -# Update hostapd main config file -sudo sed -i "s/\(^.*DAEMON_CONF=.*$\)/DAEMON_CONF=\/etc\/hostapd\/hostapd.conf/" $aconf - -sudo systemctl enable hostapd.service - -} - - -fn_dnsmasq () -{ - -sudo apt-get -y install dnsmasq || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - - -# edit /etc/dnsmasq.conf file -aconf="/etc/dnsmasq.conf" - -# delete rows between #START and #END -sed -i '/^#START HYDROSYS4 SECTION/,/^#END HYDROSYS4 SECTION/{/^#START HYDROSYS4 SECTION/!{/^#END HYDROSYS4 SECTION/!d}}' $aconf -sed -i '/#START HYDROSYS4 SECTION/d' $aconf -sed -i '/#END HYDROSYS4 SECTION/d' $aconf - - - -sudo bash -c "cat >> $aconf" << EOF -#START HYDROSYS4 SECTION -interface=wlan0 -dhcp-range=192.168.0.100,192.168.1.200,255.255.0.0,12h -#no-resolv -#END HYDROSYS4 SECTION -EOF - -sudo systemctl enable dnsmasq.service - - -} - - - - - - - - - - - - -install_mjpegstr () -{ -cd /home/pi - -sudo rm -r mjpg-streamer - -sudo apt-get -y install cmake libjpeg8-dev git - -sudo git clone https://github.com/jacksonliam/mjpg-streamer.git - -cd mjpg-streamer/mjpg-streamer-experimental - -sudo make - -sudo make install - -cd .. -cd .. - -} - - - -install_nginx () -{ -# this function is not used anymore -cd /home/pi - -sudo apt-get -y install nginx - -# create default file -aconf="/etc/nginx/sites-enabled/default" -if [ -f $aconf ]; then - cp $aconf /home/pi/$aconf.1 - sudo rm $aconf - echo "remove file" -fi - - -sudo bash -c "cat >> $aconf" << EOF -server { - # for a public HTTP server: - listen $PORT; - server_name localhost hydrosys4.local; - - access_log off; - error_log off; - - location / { - proxy_pass http://127.0.0.1:5020; - } - - location /stream { - rewrite ^/stream(.*) /$1 break; - proxy_pass http://127.0.0.1:5022; - proxy_buffering off; - } - - location /favicon.ico { - alias /home/pi/env/autonom/static/favicon.ico; - } -} -EOF - -sudo service nginx start - -cd .. -cd .. - -} - - -install_squid3 () -{ -# this function is used to install the squid3 program used as reverse proxy -cd /home/pi - -sudo apt-get install squid3 -y || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -# add configuration to squid.conf, the file should already exist if installation is succesful -aconf="/etc/squid3/squid.conf" -if [ -f $aconf ]; then - cp $aconf $aconf.1 - sudo rm $aconf - echo "remove file" -fi - - -sudo bash -c "cat >> $aconf" << EOF -# WELCOME TO SQUID 3.5.12 - -# hydrosys4 configurations - -http_port $PORT accel defaultsite=hydrosys4 vhost - -acl Safe_ports port $PORT # unregistered ports - -acl videostream urlpath_regex \?action=stream - -cache_peer localhost parent 5020 0 no-query originserver name=server1 -cache_peer_access server1 deny videostream - -cache_peer localhost parent 5022 0 no-query originserver name=server2 -cache_peer_access server2 allow videostream -cache_peer_access server2 deny all - -http_access allow Safe_ports - -# default configurations - -# WELCOME TO SQUID 3.5.12 -acl SSL_ports port 443 -acl Safe_ports port 80 # http -acl Safe_ports port 21 # ftp -acl Safe_ports port 443 # https -acl Safe_ports port 70 # gopher -acl Safe_ports port 210 # wais -acl Safe_ports port 1025-65535 # unregistered ports -acl Safe_ports port 280 # http-mgmt -acl Safe_ports port 488 # gss-http -acl Safe_ports port 591 # filemaker -acl Safe_ports port 777 # multiling http -acl CONNECT method CONNECT -http_access deny !Safe_ports -http_access deny CONNECT !SSL_ports -http_access allow localhost manager -http_access deny manager -http_access allow localhost -http_access deny all -coredump_dir /var/spool/squid -refresh_pattern ^ftp: 1440 20% 10080 -refresh_pattern ^gopher: 1440 0% 1440 -refresh_pattern -i (/cgi-bin/|\?) 0 0% 0 -refresh_pattern (Release|Packages(.gz)*)$ 0 20% 2880 -refresh_pattern . 0 20% 4320 -EOF - -sudo service squid3 start - -cd .. -cd .. - -} - - - -edit_defaultnetworkdb () -{ - - -aconf="/home/pi/env/autonom/database/default/defnetwork.txt " - -# if file already exist then no action, otherwise create it -if [ -f $aconf ]; then - echo "network default file already exist" - else - sudo bash -c "cat >> $aconf" << EOF -{"name": "IPsetting", "LocalIPaddress": "192.168.0.172", "LocalPORT": "5012" , "LocalAPSSID" : "Hydrosys4"} -EOF - -fi - -} - -edit_networkdb () -{ - - -aconf="/home/pi/env/autonom/database/network.txt " - -# if file already exist then delete it -if [ -f $aconf ]; then - sudo rm $aconf - echo "remove file" -fi - -sudo bash -c "cat >> $aconf" << EOF -{"name": "IPsetting", "LocalIPaddress": "$IP", "LocalPORT": "$PORT", "LocalAPSSID" : "$WiFiAPname"} -EOF - - -} - - -iptables_blockports () -{ -sudo iptables -A INPUT -p tcp --dport 5020 -j DROP -sudo iptables -A INPUT -p tcp --dport 5022 -j DROP - -sudo iptables-save > /home/pi/iptables.rules - -} - - -# --- RUN the functions -killpython -input_UI -system_update_light -#system_update_UI -install_dependencies -enable_I2C -modify_RClocal -fn_hostapd -fn_dnsmasq -install_mjpegstr -install_squid3 -install_hydrosys4 # this should be called before the DHT22 , SPI and BMP due to local library references -install_DHT22lib -install_SPIlib -install_BMPlib -edit_defaultnetworkdb -edit_networkdb -iptables_blockports - -sudo apt-get -y install fswebcam - diff --git a/bash/install_hydrosys4v15.sh b/bash/install_hydrosys4v15.sh deleted file mode 100644 index a776c09..0000000 --- a/bash/install_hydrosys4v15.sh +++ /dev/null @@ -1,686 +0,0 @@ -#!/bin/bash - - -#Debug enable next 3 lines -exec 5> install.txt -BASH_XTRACEFD="5" -set -x -# ------ end debug - - -function killpython() -{ - -sudo killall python - -} - - -function system_update_light() -{ - -# ---- system_update - -sudo apt-get -y update - -} - -function system_update() -{ - -# ---- remove unnecessary packages - -sudo apt-get remove --purge libreoffice-* -sudo apt-get remove --purge wolfram-engine - - -# ---- system_update - -sudo apt-get -y update -sudo apt-get -y upgrade - -} - -function system_update_UI() -{ - -while true; do - read -p "Do you wish to update the Raspbian system (y/n)?" yn - case $yn in - [Yy]* ) system_update; break;; - [Nn]* ) break;; - * ) echo "Please answer y or n.";; - esac -done - -} - -function install_dependencies() -{ - - -#--- start installing dependencies - -sudo apt-get -y install python-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo apt-get -y install python-pip || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install flask || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install apscheduler || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install pyserial || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(for the webcam support) -sudo apt-get -y install fswebcam || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(for external IP address, using DNS) -sudo apt-get -y install dnsutils || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(encryption) -sudo pip install pbkdf2 || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(web server) -sudo pip install tornado || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -} - -function enable_I2C() -{ - -# --- Enable I2C and Spi : -# /boot/config.txt - -sed -i 's/\(^.*#dtparam=i2c_arm=on.*$\)/dtparam=i2c_arm=on/' /boot/config.txt -sed -i 's/\(^.*#dtparam=spi=on.*$\)/dtparam=spi=on/' /boot/config.txt -sed -i 's/\(^.*#dtparam=i2s=on.*$\)/dtparam=i2s=on/' /boot/config.txt - -# --- Add modules: -# /etc/modules -aconf="/etc/modules" - -sed -i '/i2c-bcm2708/d' $aconf -sed -i -e "\$ai2c-bcm2708" $aconf - -sed -i '/i2c-dev/d' $aconf -sed -i -e "\$ai2c-dev" $aconf - -sed -i '/i2c-bcm2835/d' $aconf -sed -i -e "\$ai2c-bcm2835" $aconf - -sed -i '/rtc-ds1307/d' $aconf -sed -i -e "\$artc-ds1307" $aconf - -sed -i '/bcm2835-v4l2/d' $aconf -sed -i -e "\$abcm2835-v4l2" $aconf - - -# --- install I2C tools -sudo apt-get -y install git build-essential python-dev python-smbus || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo apt-get -y install -y i2c-tools || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -} - - -# --- enable raspicam - -############# MISSING ############## - -function modify_RClocal() -{ - -# --- Real Time Clock (RTC) -# /etc/rc.local - -autostart="yes" -# copy the below lines between # START and #END to rc.local -tmpfile=$(mktemp) -sudo sed '/#START/,/#END/d' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local -# Remove to growing plank lines. -sudo awk '!NF {if (++n <= 1) print; next}; {n=0;print}' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local -if [ "$autostart" == "yes" ]; then - if ! grep -Fq '#START HYDROSYS4 SECTION' /etc/rc.local; then - sudo sed -i '/exit 0/d' /etc/rc.local - sudo bash -c "cat >> /etc/rc.local" << EOF -#START HYDROSYS4 SECTION -# iptables -sudo iptables-restore < /home/pi/iptables.rules - -# clock -echo ds3231 0x68 > /sys/class/i2c-adapter/i2c-1/new_device || true -hwclock -s || true - -cd /home/pi/env/autonom/ -sudo python /home/pi/env/autonom/bentornado.py & - -#END HYDROSYS4 SECTION - -exit 0 -EOF - else - tmpfile=$(mktemp) - sudo sed '/#START/,/#END/d' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local - # Remove to growing plank lines. - sudo awk '!NF {if (++n <= 1) print; next}; {n=0;print}' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local - fi - -fi - -sudo chown root:root /etc/rc.local -sudo chmod 755 /etc/rc.local -# end modification to RC.local - -} - - -### -- WIFI setup --- STANDARD - -function valid_ip() -{ - local ip=$1 - local stat=1 - - if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then - OIFS=$IFS - IFS='.' - ip=($ip) - IFS=$OIFS - [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \ - && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]] - stat=$? - fi - return $stat -} - - -input_UI () -{ - -echo "Hello, following initial setting is requested:" - -# IP part input - -IP="0" -while ! valid_ip $IP; do - read -p "Local IP address (range 192.168.0.100-192.168.1.200), to confirm press [ENTER] or modify: " -e -i 192.168.0.172 IP - if valid_ip $IP; then stat='good'; - else stat='bad'; echo "WRONG FORMAT, please enter a valid value for IP address" - fi - -done - echo "Confirmed IP address: "$IP - -PORT="" -while [[ ! $PORT =~ ^[0-9]+$ ]]; do -read -p "Local PORT, to confirm press [ENTER] or modify: " -e -i 5012 PORT - if [[ ! $PORT =~ ^[0-9]+$ ]]; - then echo "WRONG FORMAT, please enter a valid value for PORT"; - fi -done - echo "Confirmed PORT: "$PORT - -# Local WiFi AP name and password setting - -read -p "System WiFi AP name, to confirm press [ENTER] or modify: " -e -i Hydrosys4 WiFiAPname -echo "Confirmed Name: "$WiFiAPname - -read -p "System WiFi AP password, to confirm press [ENTER] or modify: " -e -i hydrosystem WiFiAPpsw -echo "Confirmed Password: "$WiFiAPpsw - -} - - -install_DHT22lib () -{ - -# --- installing the DHT22 Sensor libraries -sudo apt-get -y install build-essential python-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/DHT22/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/DHT22 - unzip master.zip - cd Adafruit_Python_DHT-master - # setup1plus is file that try to make the DTH22 work with both RaspberryPi zero,1 and model 2,3 - sudo python setup1plus.py install - cd /home/pi -else - cd /home/pi - sudo rm -r DHT22 - mkdir DHT22 - cd DHT22 - wget https://github.com/adafruit/Adafruit_Python_DHT/archive/master.zip - unzip master.zip - cd Adafruit_Python_DHT-master - sudo python setup.py install - cd /home/pi -fi -} - - -install_SPIlib () -{ - - -# --- INSTALL SPI library: - -sudo apt-get -y install python2.7-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/SPI/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/SPI - unzip master.zip - cd py-spidev-master - sudo python setup.py install - cd /home/pi -else - -cd /home/pi -sudo rm -r SPIDEV -mkdir SPIDEV -cd SPIDEV - -wget https://github.com/Gadgetoid/py-spidev/archive/master.zip - -unzip master.zip - -rm master.zip - -cd py-spidev-master - -sudo python setup.py install - -cd .. -cd .. - -fi -} - - -install_BMPlib () -{ - -# --- INSTALL BMP180 library (pressure sensor) - -sudo apt-get -y install build-essential python-dev python-smbus || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/BMP/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/BMP - unzip master.zip - cd Adafruit_Python_BMP-master - sudo python setup.py install - cd /home/pi -else - -cd /home/pi -sudo rm -r bmp180 -sudo mkdir bmp180 -cd bmp180 -wget https://github.com/adafruit/Adafruit_Python_BMP/archive/master.zip -cd Adafruit_Python_BMP-master -sudo python setup.py install -cd .. -cd .. - -fi -} - - -install_hydrosys4 () -{ -# --- INSTALL Hydrosys4 software -sudo apt-get -y install git || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - - -# check if file exist in local folder -aconf="/home/pi/env/autonom" -if [ -d $aconf ]; then # if the directory exist - cd /home/pi -else - cd /home/pi - sudo rm -r env - mkdir env - cd env - sudo rm -r autonom - git clone https://github.com/Hydrosys4/Master.git - sudo killall python - mv Master autonom - cd .. - -fi - -} - - - - - - -fn_hostapd () -{ - -sudo apt-get -y install hostapd || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - - -# create hostapd.conf file -aconf="/etc/hostapd/hostapd.conf" -if [ -f $aconf ]; then - cp $aconf $aconf.1 - sudo rm $aconf - echo "remove file" -fi - - -sudo bash -c "cat >> $aconf" << EOF -# HERE-> {"name": "IPsetting", "LocalIPaddress": "$IP", "LocalPORT": "$PORT", "LocalAPSSID" : "$WiFiAPname"} -ieee80211n=1 -interface=wlan0 -ssid=$WiFiAPname -hw_mode=g -channel=6 -macaddr_acl=0 -auth_algs=1 -ignore_broadcast_ssid=0 -wpa=3 -wpa_passphrase=$WiFiAPpsw -wpa_key_mgmt=WPA-PSK -wpa_pairwise=TKIP -rsn_pairwise=CCMP -EOF - - -aconf="/etc/init.d/hostapd" -# Update hostapd main config file -sudo sed -i "s/\(^.*DAEMON_CONF=.*$\)/DAEMON_CONF=\/etc\/hostapd\/hostapd.conf/" $aconf - -sudo systemctl enable hostapd.service - -} - - -fn_dnsmasq () -{ - -sudo apt-get -y install dnsmasq || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - - -# edit /etc/dnsmasq.conf file -aconf="/etc/dnsmasq.conf" - -# delete rows between #START and #END -sed -i '/^#START HYDROSYS4 SECTION/,/^#END HYDROSYS4 SECTION/{/^#START HYDROSYS4 SECTION/!{/^#END HYDROSYS4 SECTION/!d}}' $aconf -sed -i '/#START HYDROSYS4 SECTION/d' $aconf -sed -i '/#END HYDROSYS4 SECTION/d' $aconf - -# calculation of the range starting from assigned IP address -IFS="." read -a a <<< $IP -IFS="." read -a b <<< 0.0.0.1 -IFS="." read -a c <<< 0.0.0.9 -IPSTART="$[a[0]].$[a[1]].$[a[2]].$[a[3]+b[3]]" -IPEND="$[a[0]].$[a[1]].$[a[2]].$[a[3]+c[3]]" -if [[ a[3] -gt 244 ]]; then -IPSTART="$[a[0]].$[a[1]].$[a[2]].$[a[3]-c[3]]" -IPEND="$[a[0]].$[a[1]].$[a[2]].$[a[3]-b[3]]" -fi - -echo $IPSTART $IPEND - - - -# ----- - - - -sudo bash -c "cat >> $aconf" << EOF -#START HYDROSYS4 SECTION -interface=wlan0 -dhcp-range=$IPSTART,$IPEND,12h -#no-resolv -#END HYDROSYS4 SECTION -EOF - -sudo systemctl enable dnsmasq.service - - -} - - - - - - - - - - - - -install_mjpegstr () -{ -cd /home/pi - -sudo rm -r mjpg-streamer - -sudo apt-get -y install cmake libjpeg8-dev git - -sudo git clone https://github.com/jacksonliam/mjpg-streamer.git - -cd mjpg-streamer/mjpg-streamer-experimental - -sudo make - -sudo make install - -cd .. -cd .. - -} - - - -install_nginx () -{ -# this function is not used anymore -cd /home/pi - -sudo apt-get -y install nginx - -# create default file -aconf="/etc/nginx/sites-enabled/default" -if [ -f $aconf ]; then - cp $aconf /home/pi/$aconf.1 - sudo rm $aconf - echo "remove file" -fi - - -sudo bash -c "cat >> $aconf" << EOF -server { - # for a public HTTP server: - listen $PORT; - server_name localhost hydrosys4.local; - - access_log off; - error_log off; - - location / { - proxy_pass http://127.0.0.1:5020; - } - - location /stream { - rewrite ^/stream(.*) /$1 break; - proxy_pass http://127.0.0.1:5022; - proxy_buffering off; - } - - location /favicon.ico { - alias /home/pi/env/autonom/static/favicon.ico; - } -} -EOF - -sudo service nginx start - -cd .. -cd .. - -} - - -install_squid3 () -{ -# this function is used to install the squid3 program used as reverse proxy -cd /home/pi - -sudo apt-get install squid3 -y || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -# add configuration to squid.conf, the file should already exist if installation is succesful -adir="/etc/squid3" -if [ -d $adir ]; then - aconf="/etc/squid3/squid.conf" -fi -adir="/etc/squid" -if [ -d $adir ]; then - aconf="/etc/squid/squid.conf" -fi - -aconf="/etc/squid3/squid.conf" -if [ -f $aconf ]; then - cp $aconf $aconf.1 - sudo rm $aconf - echo "remove file" -fi - - -sudo bash -c "cat >> $aconf" << EOF -# WELCOME TO SQUID 3.5.12 - -# hydrosys4 configurations - -http_port $PORT accel defaultsite=hydrosys4 vhost - -acl Safe_ports port $PORT # unregistered ports - -acl videostream urlpath_regex \?action=stream - -cache_peer localhost parent 5020 0 no-query originserver name=server1 -cache_peer_access server1 deny videostream - -cache_peer localhost parent 5022 0 no-query originserver name=server2 -cache_peer_access server2 allow videostream -cache_peer_access server2 deny all - -http_access allow Safe_ports - -# default configurations - -# WELCOME TO SQUID 3.5.12 -acl SSL_ports port 443 -acl Safe_ports port 80 # http -acl Safe_ports port 21 # ftp -acl Safe_ports port 443 # https -acl Safe_ports port 70 # gopher -acl Safe_ports port 210 # wais -acl Safe_ports port 1025-65535 # unregistered ports -acl Safe_ports port 280 # http-mgmt -acl Safe_ports port 488 # gss-http -acl Safe_ports port 591 # filemaker -acl Safe_ports port 777 # multiling http -acl CONNECT method CONNECT -http_access deny !Safe_ports -http_access deny CONNECT !SSL_ports -http_access allow localhost manager -http_access deny manager -http_access allow localhost -http_access deny all -coredump_dir /var/spool/squid -refresh_pattern ^ftp: 1440 20% 10080 -refresh_pattern ^gopher: 1440 0% 1440 -refresh_pattern -i (/cgi-bin/|\?) 0 0% 0 -refresh_pattern (Release|Packages(.gz)*)$ 0 20% 2880 -refresh_pattern . 0 20% 4320 -EOF - -sudo service squid3 start - -cd .. -cd .. - -} - - - -edit_defaultnetworkdb () -{ - - -aconf="/home/pi/env/autonom/database/default/defnetwork.txt " - -# if file already exist then no action, otherwise create it -if [ -f $aconf ]; then - echo "network default file already exist" - else - sudo bash -c "cat >> $aconf" << EOF -{"name": "IPsetting", "LocalIPaddress": "192.168.0.172", "LocalPORT": "5012" , "LocalAPSSID" : "Hydrosys4"} -EOF - -fi - -} - -edit_networkdb () -{ - - -aconf="/home/pi/env/autonom/database/network.txt " - -# if file already exist then delete it -if [ -f $aconf ]; then - sudo rm $aconf - echo "remove file" -fi - -sudo bash -c "cat >> $aconf" << EOF -{"name": "IPsetting", "LocalIPaddress": "$IP", "LocalPORT": "$PORT", "LocalAPSSID" : "$WiFiAPname"} -EOF - - -} - - -iptables_blockports () -{ -sudo iptables -A INPUT -p tcp --dport 5020 -j DROP -sudo iptables -A INPUT -p tcp --dport 5022 -j DROP - -sudo iptables-save > /home/pi/iptables.rules - -} - - -# --- RUN the functions -killpython -input_UI -system_update_light -#system_update_UI -install_dependencies -enable_I2C -modify_RClocal -fn_hostapd -fn_dnsmasq -install_mjpegstr -install_squid3 -install_hydrosys4 # this should be called before the DHT22 , SPI and BMP due to local library references -install_DHT22lib -install_SPIlib -install_BMPlib -edit_defaultnetworkdb -edit_networkdb -iptables_blockports - -sudo apt-get -y install fswebcam - diff --git a/bash/install_hydrosys4v16.sh b/bash/install_hydrosys4v16.sh deleted file mode 100644 index 3d378f1..0000000 --- a/bash/install_hydrosys4v16.sh +++ /dev/null @@ -1,678 +0,0 @@ -#!/bin/bash - - -#Debug enable next 3 lines -exec 5> install.txt -BASH_XTRACEFD="5" -set -x -# ------ end debug - - -function killpython() -{ - -sudo killall python - -} - - -function system_update_light() -{ - -# ---- system_update - -sudo apt-get -y update - -} - -function system_update() -{ - -# ---- remove unnecessary packages - -sudo apt-get remove --purge libreoffice-* -sudo apt-get remove --purge wolfram-engine - - -# ---- system_update - -sudo apt-get -y update -sudo apt-get -y upgrade - -} - -function system_update_UI() -{ - -while true; do - read -p "Do you wish to update the Raspbian system (y/n)?" yn - case $yn in - [Yy]* ) system_update; break;; - [Nn]* ) break;; - * ) echo "Please answer y or n.";; - esac -done - -} - -function install_dependencies() -{ - - -#--- start installing dependencies - -sudo apt-get -y install python-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo apt-get -y install python-pip || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install flask || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install apscheduler || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install pyserial || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(for the webcam support) -sudo apt-get -y install fswebcam || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(for the image thumbnail support) -sudo pip install Pillow || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(for external IP address, using DNS) -sudo apt-get -y install dnsutils || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(encryption) -sudo pip install pbkdf2 || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(web server) -sudo pip install tornado || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -} - -function enable_I2C() -{ - -# --- Enable I2C and Spi : -# /boot/config.txt - -sed -i 's/\(^.*#dtparam=i2c_arm=on.*$\)/dtparam=i2c_arm=on/' /boot/config.txt -sed -i 's/\(^.*#dtparam=spi=on.*$\)/dtparam=spi=on/' /boot/config.txt -sed -i 's/\(^.*#dtparam=i2s=on.*$\)/dtparam=i2s=on/' /boot/config.txt - -# --- Add modules: -# /etc/modules -aconf="/etc/modules" - -sed -i '/i2c-bcm2708/d' $aconf -sed -i -e "\$ai2c-bcm2708" $aconf - -sed -i '/i2c-dev/d' $aconf -sed -i -e "\$ai2c-dev" $aconf - -sed -i '/i2c-bcm2835/d' $aconf -sed -i -e "\$ai2c-bcm2835" $aconf - -sed -i '/rtc-ds1307/d' $aconf -sed -i -e "\$artc-ds1307" $aconf - -sed -i '/bcm2835-v4l2/d' $aconf -sed -i -e "\$abcm2835-v4l2" $aconf - - -# --- install I2C tools -sudo apt-get -y install git build-essential python-dev python-smbus || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo apt-get -y install -y i2c-tools || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -} - - -# --- enable raspicam - -############# MISSING ############## - -function modify_RClocal() -{ - -# --- Real Time Clock (RTC) -# /etc/rc.local - -autostart="yes" -# copy the below lines between # START and #END to rc.local -tmpfile=$(mktemp) -sudo sed '/#START/,/#END/d' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local -# Remove to growing plank lines. -sudo awk '!NF {if (++n <= 1) print; next}; {n=0;print}' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local -if [ "$autostart" == "yes" ]; then - if ! grep -Fq '#START HYDROSYS4 SECTION' /etc/rc.local; then - sudo sed -i '/exit 0/d' /etc/rc.local - sudo bash -c "cat >> /etc/rc.local" << EOF -#START HYDROSYS4 SECTION -# iptables -sudo iptables-restore < /home/pi/iptables.rules - -# clock -echo ds3231 0x68 > /sys/class/i2c-adapter/i2c-1/new_device || true -hwclock -s || true - -cd /home/pi/env/autonom/ -sudo python /home/pi/env/autonom/bentornado.py & - -#END HYDROSYS4 SECTION - -exit 0 -EOF - else - tmpfile=$(mktemp) - sudo sed '/#START/,/#END/d' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local - # Remove to growing plank lines. - sudo awk '!NF {if (++n <= 1) print; next}; {n=0;print}' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local - fi - -fi - -sudo chown root:root /etc/rc.local -sudo chmod 755 /etc/rc.local -# end modification to RC.local - -} - - -### -- WIFI setup --- STANDARD - -function valid_ip() -{ - local ip=$1 - local stat=1 - - if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then - OIFS=$IFS - IFS='.' - ip=($ip) - IFS=$OIFS - [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \ - && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]] - stat=$? - fi - return $stat -} - - -input_UI () -{ - -echo "Hello, following initial setting is requested:" - -# IP part input - -IP="0" -while ! valid_ip $IP; do - read -p "Local IP address (range 192.168.0.100-192.168.1.200), to confirm press [ENTER] or modify: " -e -i 192.168.0.172 IP - if valid_ip $IP; then stat='good'; - else stat='bad'; echo "WRONG FORMAT, please enter a valid value for IP address" - fi - -done - echo "Confirmed IP address: "$IP - -PORT="" -while [[ ! $PORT =~ ^[0-9]+$ ]]; do -read -p "Local PORT, to confirm press [ENTER] or modify: " -e -i 5012 PORT - if [[ ! $PORT =~ ^[0-9]+$ ]]; - then echo "WRONG FORMAT, please enter a valid value for PORT"; - fi -done - echo "Confirmed PORT: "$PORT - -# Local WiFi AP name and password setting - -read -p "System WiFi AP name, to confirm press [ENTER] or modify: " -e -i Hydrosys4 WiFiAPname -echo "Confirmed Name: "$WiFiAPname - -read -p "System WiFi AP password, to confirm press [ENTER] or modify: " -e -i hydrosystem WiFiAPpsw -echo "Confirmed Password: "$WiFiAPpsw - -} - - -install_DHT22lib () -{ - -# --- installing the DHT22 Sensor libraries -sudo apt-get -y install build-essential python-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/DHT22/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/DHT22 - unzip master.zip - cd Adafruit_Python_DHT-master - # setup1plus is file that try to make the DTH22 work with both RaspberryPi zero,1 and model 2,3 - sudo python setup1plus.py install - cd /home/pi -else - cd /home/pi - sudo rm -r DHT22 - mkdir DHT22 - cd DHT22 - wget https://github.com/adafruit/Adafruit_Python_DHT/archive/master.zip - unzip master.zip - cd Adafruit_Python_DHT-master - sudo python setup.py install - cd /home/pi -fi -} - - -install_SPIlib () -{ - - -# --- INSTALL SPI library: - -sudo apt-get -y install python2.7-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/SPI/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/SPI - unzip master.zip - cd py-spidev-master - sudo python setup.py install - cd /home/pi -else - -cd /home/pi -sudo rm -r SPIDEV -mkdir SPIDEV -cd SPIDEV - -wget https://github.com/Gadgetoid/py-spidev/archive/master.zip - -unzip master.zip - -rm master.zip - -cd py-spidev-master - -sudo python setup.py install - -cd .. -cd .. - -fi -} - - -install_BMPlib () -{ - -# --- INSTALL BMP180 library (pressure sensor) - -sudo apt-get -y install build-essential python-dev python-smbus || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/BMP/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/BMP - unzip master.zip - cd Adafruit_Python_BMP-master - sudo python setup.py install - cd /home/pi -else - -cd /home/pi -sudo rm -r bmp180 -sudo mkdir bmp180 -cd bmp180 -wget https://github.com/adafruit/Adafruit_Python_BMP/archive/master.zip -cd Adafruit_Python_BMP-master -sudo python setup.py install -cd .. -cd .. - -fi -} - - -install_hydrosys4 () -{ -# --- INSTALL Hydrosys4 software -sudo apt-get -y install git || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - - -# check if file exist in local folder -aconf="/home/pi/env/autonom" -if [ -d $aconf ]; then # if the directory exist - cd /home/pi -else - cd /home/pi - sudo rm -r env - mkdir env - cd env - sudo rm -r autonom - git clone https://github.com/Hydrosys4/Master.git - sudo killall python - mv Master autonom - cd .. - -fi - -} - - - - - - -fn_hostapd () -{ - -sudo apt-get -y install hostapd || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - - -# create hostapd.conf file -aconf="/etc/hostapd/hostapd.conf" -if [ -f $aconf ]; then - cp $aconf $aconf.1 - sudo rm $aconf - echo "remove file" -fi - - -sudo bash -c "cat >> $aconf" << EOF -# HERE-> {"name": "IPsetting", "LocalIPaddress": "$IP", "LocalPORT": "$PORT", "LocalAPSSID" : "$WiFiAPname"} -ieee80211n=1 -interface=wlan0 -ssid=$WiFiAPname -hw_mode=g -channel=6 -macaddr_acl=0 -auth_algs=1 -ignore_broadcast_ssid=0 -wpa=3 -wpa_passphrase=$WiFiAPpsw -wpa_key_mgmt=WPA-PSK -wpa_pairwise=TKIP -rsn_pairwise=CCMP -EOF - - -aconf="/etc/init.d/hostapd" -# Update hostapd main config file -sudo sed -i "s/\(^.*DAEMON_CONF=.*$\)/DAEMON_CONF=\/etc\/hostapd\/hostapd.conf/" $aconf - -sudo systemctl enable hostapd.service - -} - - -fn_dnsmasq () -{ - -sudo apt-get -y install dnsmasq || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - - -# edit /etc/dnsmasq.conf file -aconf="/etc/dnsmasq.conf" - -# delete rows between #START and #END -sed -i '/^#START HYDROSYS4 SECTION/,/^#END HYDROSYS4 SECTION/{/^#START HYDROSYS4 SECTION/!{/^#END HYDROSYS4 SECTION/!d}}' $aconf -sed -i '/#START HYDROSYS4 SECTION/d' $aconf -sed -i '/#END HYDROSYS4 SECTION/d' $aconf - -# calculation of the range starting from assigned IP address -IFS="." read -a a <<< $IP -IFS="." read -a b <<< 0.0.0.1 -IFS="." read -a c <<< 0.0.0.9 -IPSTART="$[a[0]].$[a[1]].$[a[2]].$[a[3]+b[3]]" -IPEND="$[a[0]].$[a[1]].$[a[2]].$[a[3]+c[3]]" -if [[ a[3] -gt 244 ]]; then -IPSTART="$[a[0]].$[a[1]].$[a[2]].$[a[3]-c[3]]" -IPEND="$[a[0]].$[a[1]].$[a[2]].$[a[3]-b[3]]" -fi - -echo $IPSTART $IPEND - - - -# ----- - - - -sudo bash -c "cat >> $aconf" << EOF -#START HYDROSYS4 SECTION -interface=wlan0 -dhcp-range=$IPSTART,$IPEND,12h -#no-resolv -#END HYDROSYS4 SECTION -EOF - -sudo systemctl enable dnsmasq.service - - -} - - - - - - - - - - - - -install_mjpegstr () -{ -cd /home/pi - -sudo rm -r mjpg-streamer - -sudo apt-get -y install cmake libjpeg8-dev git - -sudo git clone https://github.com/jacksonliam/mjpg-streamer.git - -cd mjpg-streamer/mjpg-streamer-experimental - -sudo make - -sudo make install - -cd .. -cd .. - -} - - - -install_nginx () -{ -# this function is not used anymore -cd /home/pi - -sudo apt-get -y install nginx - -# create default file -aconf="/etc/nginx/sites-enabled/default" -if [ -f $aconf ]; then - cp $aconf /home/pi/$aconf.1 - sudo rm $aconf - echo "remove file" -fi - - -sudo bash -c "cat >> $aconf" << EOF -server { - # for a public HTTP server: - listen $PORT; - server_name localhost hydrosys4.local; - - access_log off; - error_log off; - - location / { - proxy_pass http://127.0.0.1:5020; - } - - location /stream { - rewrite ^/stream(.*) /$1 break; - proxy_pass http://127.0.0.1:5022; - proxy_buffering off; - } - - location /favicon.ico { - alias /home/pi/env/autonom/static/favicon.ico; - } -} -EOF - -sudo service nginx start - -cd .. -cd .. - -} - - -install_squid3 () -{ -# this function is used to install the squid3 program used as reverse proxy -cd /home/pi - -sudo apt-get install squid3 -y || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -# add configuration to squid.conf, the file should already exist if installation is succesful -aconf="/etc/squid3/squid.conf" -if [ -f $aconf ]; then - cp $aconf $aconf.1 - sudo rm $aconf - echo "remove file" -fi - - -sudo bash -c "cat >> $aconf" << EOF -# WELCOME TO SQUID 3.5.12 - -# hydrosys4 configurations - -http_port $PORT accel defaultsite=hydrosys4 vhost - -acl Safe_ports port $PORT # unregistered ports - -acl videostream urlpath_regex \?action=stream - -cache_peer localhost parent 5020 0 no-query originserver name=server1 -cache_peer_access server1 deny videostream - -cache_peer localhost parent 5022 0 no-query originserver name=server2 -cache_peer_access server2 allow videostream -cache_peer_access server2 deny all - -http_access allow Safe_ports - -# default configurations - -# WELCOME TO SQUID 3.5.12 -acl SSL_ports port 443 -acl Safe_ports port 80 # http -acl Safe_ports port 21 # ftp -acl Safe_ports port 443 # https -acl Safe_ports port 70 # gopher -acl Safe_ports port 210 # wais -acl Safe_ports port 1025-65535 # unregistered ports -acl Safe_ports port 280 # http-mgmt -acl Safe_ports port 488 # gss-http -acl Safe_ports port 591 # filemaker -acl Safe_ports port 777 # multiling http -acl CONNECT method CONNECT -http_access deny !Safe_ports -http_access deny CONNECT !SSL_ports -http_access allow localhost manager -http_access deny manager -http_access allow localhost -http_access deny all -coredump_dir /var/spool/squid -refresh_pattern ^ftp: 1440 20% 10080 -refresh_pattern ^gopher: 1440 0% 1440 -refresh_pattern -i (/cgi-bin/|\?) 0 0% 0 -refresh_pattern (Release|Packages(.gz)*)$ 0 20% 2880 -refresh_pattern . 0 20% 4320 -EOF - -sudo service squid3 start - -cd .. -cd .. - -} - - - -edit_defaultnetworkdb () -{ - - -aconf="/home/pi/env/autonom/database/default/defnetwork.txt " - -# if file already exist then no action, otherwise create it -if [ -f $aconf ]; then - echo "network default file already exist" - else - sudo bash -c "cat >> $aconf" << EOF -{"name": "IPsetting", "LocalIPaddress": "192.168.0.172", "LocalPORT": "5012" , "LocalAPSSID" : "Hydrosys4"} -EOF - -fi - -} - -edit_networkdb () -{ - - -aconf="/home/pi/env/autonom/database/network.txt " - -# if file already exist then delete it -if [ -f $aconf ]; then - sudo rm $aconf - echo "remove file" -fi - -sudo bash -c "cat >> $aconf" << EOF -{"name": "IPsetting", "LocalIPaddress": "$IP", "LocalPORT": "$PORT", "LocalAPSSID" : "$WiFiAPname"} -EOF - - -} - - -iptables_blockports () -{ -sudo iptables -A INPUT -p tcp --dport 5020 -j DROP -sudo iptables -A INPUT -p tcp --dport 5022 -j DROP - -sudo iptables-save > /home/pi/iptables.rules - -} - - -# --- RUN the functions -killpython -input_UI -system_update_light -#system_update_UI -install_dependencies -enable_I2C -modify_RClocal -fn_hostapd -fn_dnsmasq -install_mjpegstr -install_squid3 -install_hydrosys4 # this should be called before the DHT22 , SPI and BMP due to local library references -install_DHT22lib -install_SPIlib -install_BMPlib -edit_defaultnetworkdb -edit_networkdb -iptables_blockports - diff --git a/bash/install_hydrosys4v17.sh b/bash/install_hydrosys4v17.sh deleted file mode 100644 index 0dabd43..0000000 --- a/bash/install_hydrosys4v17.sh +++ /dev/null @@ -1,686 +0,0 @@ -#!/bin/bash - - -#Debug enable next 3 lines -exec 5> install.txt -BASH_XTRACEFD="5" -set -x -# ------ end debug - - -function killpython() -{ - -sudo killall python - -} - - -function system_update_light() -{ - -# ---- system_update - -sudo apt-get -y update - -} - -function system_update() -{ - -# ---- remove unnecessary packages - -sudo apt-get remove --purge libreoffice-* -sudo apt-get remove --purge wolfram-engine - - -# ---- system_update - -sudo apt-get -y update -sudo apt-get -y upgrade - -} - -function system_update_UI() -{ - -while true; do - read -p "Do you wish to update the Raspbian system (y/n)?" yn - case $yn in - [Yy]* ) system_update; break;; - [Nn]* ) break;; - * ) echo "Please answer y or n.";; - esac -done - -} - -function install_dependencies() -{ - - -#--- start installing dependencies - -sudo apt-get -y install python-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo apt-get -y install python-pip || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install flask || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install apscheduler || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install pyserial || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(for the webcam support) -sudo apt-get -y install fswebcam || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(for the image thumbnail support) -sudo apt-get install libjpeg-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install Pillow || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(for external IP address, using DNS) -sudo apt-get -y install dnsutils || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(encryption) -sudo pip install pbkdf2 || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(web server) -sudo pip install tornado || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -} - -function enable_I2C() -{ - -# --- Enable I2C and Spi : -# /boot/config.txt - -sed -i 's/\(^.*#dtparam=i2c_arm=on.*$\)/dtparam=i2c_arm=on/' /boot/config.txt -sed -i 's/\(^.*#dtparam=spi=on.*$\)/dtparam=spi=on/' /boot/config.txt -sed -i 's/\(^.*#dtparam=i2s=on.*$\)/dtparam=i2s=on/' /boot/config.txt - -# --- Add modules: -# /etc/modules -aconf="/etc/modules" - -sed -i '/i2c-bcm2708/d' $aconf -sed -i -e "\$ai2c-bcm2708" $aconf - -sed -i '/i2c-dev/d' $aconf -sed -i -e "\$ai2c-dev" $aconf - -sed -i '/i2c-bcm2835/d' $aconf -sed -i -e "\$ai2c-bcm2835" $aconf - -sed -i '/rtc-ds1307/d' $aconf -sed -i -e "\$artc-ds1307" $aconf - -sed -i '/bcm2835-v4l2/d' $aconf -sed -i -e "\$abcm2835-v4l2" $aconf - - -# --- install I2C tools -sudo apt-get -y install git build-essential python-dev python-smbus || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo apt-get -y install -y i2c-tools || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -} - - -# --- enable raspicam - -############# MISSING ############## - -function modify_RClocal() -{ - -# --- Real Time Clock (RTC) -# /etc/rc.local - -autostart="yes" -# copy the below lines between # START and #END to rc.local -tmpfile=$(mktemp) -sudo sed '/#START/,/#END/d' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local -# Remove to growing plank lines. -sudo awk '!NF {if (++n <= 1) print; next}; {n=0;print}' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local -if [ "$autostart" == "yes" ]; then - if ! grep -Fq '#START HYDROSYS4 SECTION' /etc/rc.local; then - sudo sed -i '/exit 0/d' /etc/rc.local - sudo bash -c "cat >> /etc/rc.local" << EOF -#START HYDROSYS4 SECTION -# iptables -sudo iptables-restore < /home/pi/iptables.rules - -# clock -echo ds3231 0x68 > /sys/class/i2c-adapter/i2c-1/new_device || true -hwclock -s || true - -cd /home/pi/env/autonom/ -sudo python /home/pi/env/autonom/bentornado.py & - -#END HYDROSYS4 SECTION - -exit 0 -EOF - else - tmpfile=$(mktemp) - sudo sed '/#START/,/#END/d' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local - # Remove to growing plank lines. - sudo awk '!NF {if (++n <= 1) print; next}; {n=0;print}' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local - fi - -fi - -sudo chown root:root /etc/rc.local -sudo chmod 755 /etc/rc.local -# end modification to RC.local - -} - - -### -- WIFI setup --- STANDARD - -function valid_ip() -{ - local ip=$1 - local stat=1 - - if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then - OIFS=$IFS - IFS='.' - ip=($ip) - IFS=$OIFS - [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \ - && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]] - stat=$? - fi - return $stat -} - - -input_UI () -{ - -echo "Hello, following initial setting is requested:" - -# IP part input - -IP="0" -while ! valid_ip $IP; do - read -p "Local IP address (range 192.168.0.100-192.168.1.200), to confirm press [ENTER] or modify: " -e -i 192.168.0.172 IP - if valid_ip $IP; then stat='good'; - else stat='bad'; echo "WRONG FORMAT, please enter a valid value for IP address" - fi - -done - echo "Confirmed IP address: "$IP - -PORT="" -while [[ ! $PORT =~ ^[0-9]+$ ]]; do -read -p "Local PORT, to confirm press [ENTER] or modify: " -e -i 5012 PORT - if [[ ! $PORT =~ ^[0-9]+$ ]]; - then echo "WRONG FORMAT, please enter a valid value for PORT"; - fi -done - echo "Confirmed PORT: "$PORT - -# Local WiFi AP name and password setting - -read -p "System WiFi AP name, to confirm press [ENTER] or modify: " -e -i Hydrosys4 WiFiAPname -echo "Confirmed Name: "$WiFiAPname - -read -p "System WiFi AP password, to confirm press [ENTER] or modify: " -e -i hydrosystem WiFiAPpsw -echo "Confirmed Password: "$WiFiAPpsw - -} - - -install_DHT22lib () -{ - -# --- installing the DHT22 Sensor libraries -sudo apt-get -y install build-essential python-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/DHT22/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/DHT22 - unzip master.zip - cd Adafruit_Python_DHT-master - # setup1plus is file that try to make the DTH22 work with both RaspberryPi zero,1 and model 2,3 - sudo python setup1plus.py install - cd /home/pi -else - cd /home/pi - sudo rm -r DHT22 - mkdir DHT22 - cd DHT22 - wget https://github.com/adafruit/Adafruit_Python_DHT/archive/master.zip - unzip master.zip - cd Adafruit_Python_DHT-master - sudo python setup.py install - cd /home/pi -fi -} - - -install_SPIlib () -{ - - -# --- INSTALL SPI library: - -sudo apt-get -y install python2.7-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/SPI/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/SPI - unzip master.zip - cd py-spidev-master - sudo python setup.py install - cd /home/pi -else - -cd /home/pi -sudo rm -r SPIDEV -mkdir SPIDEV -cd SPIDEV - -wget https://github.com/Gadgetoid/py-spidev/archive/master.zip - -unzip master.zip - -rm master.zip - -cd py-spidev-master - -sudo python setup.py install - -cd .. -cd .. - -fi -} - - -install_BMPlib () -{ - -# --- INSTALL BMP180 library (pressure sensor) - -sudo apt-get -y install build-essential python-dev python-smbus || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/BMP/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/BMP - unzip master.zip - cd Adafruit_Python_BMP-master - sudo python setup.py install - cd /home/pi -else - -cd /home/pi -sudo rm -r bmp180 -sudo mkdir bmp180 -cd bmp180 -wget https://github.com/adafruit/Adafruit_Python_BMP/archive/master.zip -cd Adafruit_Python_BMP-master -sudo python setup.py install -cd .. -cd .. - -fi -} - - -install_hydrosys4 () -{ -# --- INSTALL Hydrosys4 software -sudo apt-get -y install git || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - - -# check if file exist in local folder -aconf="/home/pi/env/autonom" -if [ -d $aconf ]; then # if the directory exist - cd /home/pi -else - cd /home/pi - sudo rm -r env - mkdir env - cd env - sudo rm -r autonom - git clone https://github.com/Hydrosys4/Master.git - sudo killall python - mv Master autonom - cd .. - -fi - -} - - - - - - -fn_hostapd () -{ - -sudo apt-get -y install hostapd || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - - -# create hostapd.conf file -aconf="/etc/hostapd/hostapd.conf" -if [ -f $aconf ]; then - cp $aconf $aconf.1 - sudo rm $aconf - echo "remove file" -fi - - -sudo bash -c "cat >> $aconf" << EOF -# HERE-> {"name": "IPsetting", "LocalIPaddress": "$IP", "LocalPORT": "$PORT", "LocalAPSSID" : "$WiFiAPname"} -ieee80211n=1 -interface=wlan0 -ssid=$WiFiAPname -hw_mode=g -channel=6 -macaddr_acl=0 -auth_algs=1 -ignore_broadcast_ssid=0 -wpa=3 -wpa_passphrase=$WiFiAPpsw -wpa_key_mgmt=WPA-PSK -wpa_pairwise=TKIP -rsn_pairwise=CCMP -EOF - - -aconf="/etc/init.d/hostapd" -# Update hostapd main config file -sudo sed -i "s/\(^.*DAEMON_CONF=.*$\)/DAEMON_CONF=\/etc\/hostapd\/hostapd.conf/" $aconf - -sudo systemctl enable hostapd.service - -} - - -fn_dnsmasq () -{ - -sudo apt-get -y install dnsmasq || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - - -# edit /etc/dnsmasq.conf file -aconf="/etc/dnsmasq.conf" - -# delete rows between #START and #END -sed -i '/^#START HYDROSYS4 SECTION/,/^#END HYDROSYS4 SECTION/{/^#START HYDROSYS4 SECTION/!{/^#END HYDROSYS4 SECTION/!d}}' $aconf -sed -i '/#START HYDROSYS4 SECTION/d' $aconf -sed -i '/#END HYDROSYS4 SECTION/d' $aconf - -# calculation of the range starting from assigned IP address -IFS="." read -a a <<< $IP -IFS="." read -a b <<< 0.0.0.1 -IFS="." read -a c <<< 0.0.0.9 -IPSTART="$[a[0]].$[a[1]].$[a[2]].$[a[3]+b[3]]" -IPEND="$[a[0]].$[a[1]].$[a[2]].$[a[3]+c[3]]" -if [[ a[3] -gt 244 ]]; then -IPSTART="$[a[0]].$[a[1]].$[a[2]].$[a[3]-c[3]]" -IPEND="$[a[0]].$[a[1]].$[a[2]].$[a[3]-b[3]]" -fi - -echo $IPSTART $IPEND - - - -# ----- - - - -sudo bash -c "cat >> $aconf" << EOF -#START HYDROSYS4 SECTION -interface=wlan0 -dhcp-range=$IPSTART,$IPEND,12h -#no-resolv -#END HYDROSYS4 SECTION -EOF - -sudo systemctl enable dnsmasq.service - - -} - - - - - - - - - - - - -install_mjpegstr () -{ -cd /home/pi - -sudo rm -r mjpg-streamer - -sudo apt-get -y install cmake libjpeg8-dev git - -sudo git clone https://github.com/jacksonliam/mjpg-streamer.git - -cd mjpg-streamer/mjpg-streamer-experimental - -sudo make - -sudo make install - -cd .. -cd .. - -} - - - -install_nginx () -{ -# this function is not used anymore -cd /home/pi - -sudo apt-get -y install nginx - -# create default file -aconf="/etc/nginx/sites-enabled/default" -if [ -f $aconf ]; then - cp $aconf /home/pi/$aconf.1 - sudo rm $aconf - echo "remove file" -fi - - -sudo bash -c "cat >> $aconf" << EOF -server { - # for a public HTTP server: - listen $PORT; - server_name localhost hydrosys4.local; - - access_log off; - error_log off; - - location / { - proxy_pass http://127.0.0.1:5020; - } - - location /stream { - rewrite ^/stream(.*) /$1 break; - proxy_pass http://127.0.0.1:5022; - proxy_buffering off; - } - - location /favicon.ico { - alias /home/pi/env/autonom/static/favicon.ico; - } -} -EOF - -sudo service nginx start - -cd .. -cd .. - -} - - -install_squid3 () -{ -# this function is used to install the squid3 program used as reverse proxy -cd /home/pi - -sudo apt-get install squid3 -y || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -# add configuration to squid.conf, the file should already exist if installation is succesful -adir="/etc/squid3" -if [ -d $adir ]; then - aconf="/etc/squid3/squid.conf" -fi -adir="/etc/squid" -if [ -d $adir ]; then - aconf="/etc/squid/squid.conf" -fi - -if [ -f $aconf ]; then - cp $aconf $aconf.1 - sudo rm $aconf - echo "remove file" -fi - - - -sudo bash -c "cat >> $aconf" << EOF -# hydrosys4 configurations - -http_port $PORT accel defaultsite=hydrosys4 vhost - -acl Safe_ports port $PORT # unregistered ports - -acl videostream urlpath_regex \?action=stream - -cache_peer localhost parent 5020 0 no-query originserver name=server1 -cache_peer_access server1 deny videostream - -cache_peer localhost parent 5022 0 no-query originserver name=server2 -cache_peer_access server2 allow videostream -cache_peer_access server2 deny all - -http_access allow Safe_ports - -# default configurations - -# WELCOME TO SQUID 3.5.12 -acl SSL_ports port 443 -acl Safe_ports port 80 # http -acl Safe_ports port 21 # ftp -acl Safe_ports port 443 # https -acl Safe_ports port 70 # gopher -acl Safe_ports port 210 # wais -acl Safe_ports port 1025-65535 # unregistered ports -acl Safe_ports port 280 # http-mgmt -acl Safe_ports port 488 # gss-http -acl Safe_ports port 591 # filemaker -acl Safe_ports port 777 # multiling http -acl CONNECT method CONNECT -http_access deny !Safe_ports -http_access deny CONNECT !SSL_ports -http_access allow localhost manager -http_access deny manager -http_access allow localhost -http_access deny all -coredump_dir /var/spool/squid -refresh_pattern ^ftp: 1440 20% 10080 -refresh_pattern ^gopher: 1440 0% 1440 -refresh_pattern -i (/cgi-bin/|\?) 0 0% 0 -refresh_pattern (Release|Packages(.gz)*)$ 0 20% 2880 -refresh_pattern . 0 20% 4320 -EOF - -sudo service squid3 start - -cd .. -cd .. - -} - - - -edit_defaultnetworkdb () -{ - - -aconf="/home/pi/env/autonom/database/default/defnetwork.txt " - -# if file already exist then no action, otherwise create it -if [ -f $aconf ]; then - echo "network default file already exist" - else - sudo bash -c "cat >> $aconf" << EOF -{"name": "IPsetting", "LocalIPaddress": "192.168.0.172", "LocalPORT": "5012" , "LocalAPSSID" : "Hydrosys4"} -EOF - -fi - -} - -edit_networkdb () -{ - - -aconf="/home/pi/env/autonom/database/network.txt " - -# if file already exist then delete it -if [ -f $aconf ]; then - sudo rm $aconf - echo "remove file" -fi - -sudo bash -c "cat >> $aconf" << EOF -{"name": "IPsetting", "LocalIPaddress": "$IP", "LocalPORT": "$PORT", "LocalAPSSID" : "$WiFiAPname"} -EOF - - -} - - -iptables_blockports () -{ -sudo iptables -A INPUT -p tcp --dport 5020 -j DROP -sudo iptables -A INPUT -p tcp --dport 5022 -j DROP - -sudo iptables-save > /home/pi/iptables.rules - -} - - -# --- RUN the functions -killpython -input_UI -system_update_light -#system_update_UI -install_dependencies -enable_I2C -modify_RClocal -fn_hostapd -fn_dnsmasq -install_mjpegstr -install_squid3 -install_hydrosys4 # this should be called before the DHT22 , SPI and BMP due to local library references -install_DHT22lib -install_SPIlib -install_BMPlib -edit_defaultnetworkdb -edit_networkdb -iptables_blockports - diff --git a/bash/install_hydrosys4v18.sh b/bash/install_hydrosys4v18.sh deleted file mode 100644 index 1af818a..0000000 --- a/bash/install_hydrosys4v18.sh +++ /dev/null @@ -1,724 +0,0 @@ -#!/bin/bash - - -#Debug enable next 3 lines -exec 5> install.txt -BASH_XTRACEFD="5" -set -x -# ------ end debug - - -function killpython() -{ - -sudo killall python - -} - - -function system_update_light() -{ - -# ---- system_update - -sudo apt-get -y update - -} - -function system_update() -{ - -# ---- remove unnecessary packages - -sudo apt-get remove --purge libreoffice-* -sudo apt-get remove --purge wolfram-engine - - -# ---- system_update - -sudo apt-get -y update -sudo apt-get -y upgrade - -} - -function system_update_UI() -{ - -while true; do - read -p "Do you wish to update the Raspbian system (y/n)?" yn - case $yn in - [Yy]* ) system_update; break;; - [Nn]* ) break;; - * ) echo "Please answer y or n.";; - esac -done - -} - -function install_dependencies() -{ - - -#--- start installing dependencies - -sudo apt-get -y install python-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo apt-get -y install python-pip || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install flask || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install apscheduler || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install pyserial || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(for the webcam support) -sudo apt-get -y install fswebcam || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(for the image thumbnail support) -sudo apt-get install libjpeg-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install Pillow || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(for external IP address, using DNS) -sudo apt-get -y install dnsutils || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(encryption) -sudo pip install pbkdf2 || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(web server) -sudo pip install tornado || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -} - -function enable_I2C() -{ - -# --- Enable I2C and Spi : -# /boot/config.txt - -sed -i 's/\(^.*#dtparam=i2c_arm=on.*$\)/dtparam=i2c_arm=on/' /boot/config.txt -sed -i 's/\(^.*#dtparam=spi=on.*$\)/dtparam=spi=on/' /boot/config.txt -sed -i 's/\(^.*#dtparam=i2s=on.*$\)/dtparam=i2s=on/' /boot/config.txt - -# --- Add modules: -# /etc/modules -aconf="/etc/modules" - -sed -i '/i2c-bcm2708/d' $aconf -sed -i -e "\$ai2c-bcm2708" $aconf - -sed -i '/i2c-dev/d' $aconf -sed -i -e "\$ai2c-dev" $aconf - -sed -i '/i2c-bcm2835/d' $aconf -sed -i -e "\$ai2c-bcm2835" $aconf - -sed -i '/rtc-ds1307/d' $aconf -sed -i -e "\$artc-ds1307" $aconf - -sed -i '/bcm2835-v4l2/d' $aconf -sed -i -e "\$abcm2835-v4l2" $aconf - - -# --- install I2C tools -sudo apt-get -y install git build-essential python-dev python-smbus || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo apt-get -y install -y i2c-tools || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -} - - -# --- enable raspicam - -############# MISSING ############## - -function modify_RClocal() -{ - -# --- Real Time Clock (RTC) -# /etc/rc.local - -autostart="yes" -# copy the below lines between # START and #END to rc.local -tmpfile=$(mktemp) -sudo sed '/#START/,/#END/d' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local -# Remove to growing plank lines. -sudo awk '!NF {if (++n <= 1) print; next}; {n=0;print}' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local -if [ "$autostart" == "yes" ]; then - if ! grep -Fq '#START HYDROSYS4 SECTION' /etc/rc.local; then - sudo sed -i '/exit 0/d' /etc/rc.local - sudo bash -c "cat >> /etc/rc.local" << EOF -#START HYDROSYS4 SECTION -# iptables -sudo iptables-restore < /home/pi/iptables.rules - -# clock -echo ds3231 0x68 > /sys/class/i2c-adapter/i2c-1/new_device || true -hwclock -s || true - -cd /home/pi/env/autonom/ -sudo python /home/pi/env/autonom/bentornado.py & - -#END HYDROSYS4 SECTION - -exit 0 -EOF - else - tmpfile=$(mktemp) - sudo sed '/#START/,/#END/d' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local - # Remove to growing plank lines. - sudo awk '!NF {if (++n <= 1) print; next}; {n=0;print}' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local - fi - -fi - -sudo chown root:root /etc/rc.local -sudo chmod 755 /etc/rc.local -# end modification to RC.local - -} - - -### -- WIFI setup --- STANDARD - -function valid_ip() -{ - local ip=$1 - local stat=1 - - if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then - OIFS=$IFS - IFS='.' - ip=($ip) - IFS=$OIFS - [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \ - && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]] - stat=$? - fi - return $stat -} - - -input_UI () -{ - -echo "Hello, following initial setting is requested:" - -# IP part input - -IP="0" -while ! valid_ip $IP; do - read -p "Local IP address (range 192.168.0.100-192.168.1.200), to confirm press [ENTER] or modify: " -e -i 192.168.0.172 IP - if valid_ip $IP; then stat='good'; - else stat='bad'; echo "WRONG FORMAT, please enter a valid value for IP address" - fi - -done - echo "Confirmed IP address: "$IP - -PORT="" -while [[ ! $PORT =~ ^[0-9]+$ ]]; do -read -p "Local PORT, to confirm press [ENTER] or modify: " -e -i 5012 PORT - if [[ ! $PORT =~ ^[0-9]+$ ]]; - then echo "WRONG FORMAT, please enter a valid value for PORT"; - fi -done - echo "Confirmed PORT: "$PORT - -# Local WiFi AP name and password setting - -read -p "System WiFi AP name, to confirm press [ENTER] or modify: " -e -i Hydrosys4 WiFiAPname -echo "Confirmed Name: "$WiFiAPname - -read -p "System WiFi AP password, to confirm press [ENTER] or modify: " -e -i hydrosystem WiFiAPpsw -echo "Confirmed Password: "$WiFiAPpsw - -} - - -install_DHT22lib () -{ - -# --- installing the DHT22 Sensor libraries -sudo apt-get -y install build-essential python-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/DHT22/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/DHT22 - unzip master.zip - cd Adafruit_Python_DHT-master - # setup1plus is file that try to make the DTH22 work with both RaspberryPi zero,1 and model 2,3 - sudo python setup1plus.py install - cd /home/pi -else - cd /home/pi - sudo rm -r DHT22 - mkdir DHT22 - cd DHT22 - wget https://github.com/adafruit/Adafruit_Python_DHT/archive/master.zip - unzip master.zip - cd Adafruit_Python_DHT-master - sudo python setup.py install - cd /home/pi -fi -} - - -install_SPIlib () -{ - - -# --- INSTALL SPI library: - -sudo apt-get -y install python2.7-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/SPI/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/SPI - unzip master.zip - cd py-spidev-master - sudo python setup.py install - cd /home/pi -else - -cd /home/pi -sudo rm -r SPIDEV -mkdir SPIDEV -cd SPIDEV - -wget https://github.com/Gadgetoid/py-spidev/archive/master.zip - -unzip master.zip - -rm master.zip - -cd py-spidev-master - -sudo python setup.py install - -cd .. -cd .. - -fi -} - - -install_BMPlib () -{ - -# --- INSTALL BMP180 library (pressure sensor) - -sudo apt-get -y install build-essential python-dev python-smbus || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/BMP/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/BMP - unzip master.zip - cd Adafruit_Python_BMP-master - sudo python setup.py install - cd /home/pi -else - -cd /home/pi -sudo rm -r bmp180 -sudo mkdir bmp180 -cd bmp180 -wget https://github.com/adafruit/Adafruit_Python_BMP/archive/master.zip -cd Adafruit_Python_BMP-master -sudo python setup.py install -cd .. -cd .. - -fi -} - - -install_hydrosys4 () -{ -# --- INSTALL Hydrosys4 software -sudo apt-get -y install git || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - - -# check if file exist in local folder -aconf="/home/pi/env/autonom" -if [ -d $aconf ]; then # if the directory exist - cd /home/pi -else - cd /home/pi - sudo rm -r env - mkdir env - cd env - sudo rm -r autonom - git clone https://github.com/Hydrosys4/Master.git - sudo killall python - mv Master autonom - cd .. - -fi - -} - - - - - - -fn_hostapd () -{ - -sudo apt-get -y install hostapd || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - - -# create hostapd.conf file -aconf="/etc/hostapd/hostapd.conf" -if [ -f $aconf ]; then - cp $aconf $aconf.1 - sudo rm $aconf - echo "remove file" -fi - - -sudo bash -c "cat >> $aconf" << EOF -# HERE-> {"name": "IPsetting", "LocalIPaddress": "$IP", "LocalPORT": "$PORT", "LocalAPSSID" : "$WiFiAPname"} -ieee80211n=1 -interface=wlan0 -ssid=$WiFiAPname -hw_mode=g -channel=6 -macaddr_acl=0 -auth_algs=1 -ignore_broadcast_ssid=0 -wpa=3 -wpa_passphrase=$WiFiAPpsw -wpa_key_mgmt=WPA-PSK -wpa_pairwise=TKIP -rsn_pairwise=CCMP -EOF - - -aconf="/etc/init.d/hostapd" -# Update hostapd main config file -sudo sed -i "s/\(^.*DAEMON_CONF=.*$\)/DAEMON_CONF=\/etc\/hostapd\/hostapd.conf/" $aconf - -sudo systemctl enable hostapd.service - -} - - -fn_dnsmasq () -{ - -sudo apt-get -y install dnsmasq || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - - -# edit /etc/dnsmasq.conf file -aconf="/etc/dnsmasq.conf" - -# delete rows between #START and #END -sed -i '/^#START HYDROSYS4 SECTION/,/^#END HYDROSYS4 SECTION/{/^#START HYDROSYS4 SECTION/!{/^#END HYDROSYS4 SECTION/!d}}' $aconf -sed -i '/#START HYDROSYS4 SECTION/d' $aconf -sed -i '/#END HYDROSYS4 SECTION/d' $aconf - -# calculation of the range starting from assigned IP address -IFS="." read -a a <<< $IP -IFS="." read -a b <<< 0.0.0.1 -IFS="." read -a c <<< 0.0.0.9 -IPSTART="$[a[0]].$[a[1]].$[a[2]].$[a[3]+b[3]]" -IPEND="$[a[0]].$[a[1]].$[a[2]].$[a[3]+c[3]]" -if [[ a[3] -gt 244 ]]; then -IPSTART="$[a[0]].$[a[1]].$[a[2]].$[a[3]-c[3]]" -IPEND="$[a[0]].$[a[1]].$[a[2]].$[a[3]-b[3]]" -fi - -echo $IPSTART $IPEND - - - -# ----- - - - -sudo bash -c "cat >> $aconf" << EOF -#START HYDROSYS4 SECTION -interface=wlan0 -dhcp-range=$IPSTART,$IPEND,12h -#no-resolv -#END HYDROSYS4 SECTION -EOF - -sudo systemctl enable dnsmasq.service - - -} - - -fn_dhcpcd () -{ - -# edit /etc/dnsmasq.conf file -aconf="/etc/dhcpcd.conf" - -# delete rows between #START and #END -sed -i '/^#START HYDROSYS4 SECTION/,/^#END HYDROSYS4 SECTION/{/^#START HYDROSYS4 SECTION/!{/^#END HYDROSYS4 SECTION/!d}}' $aconf -sed -i '/#START HYDROSYS4 SECTION/d' $aconf -sed -i '/#END HYDROSYS4 SECTION/d' $aconf - - -sudo bash -c "cat >> $aconf" << EOF -#START HYDROSYS4 SECTION -profile static_wlan0 -static ip_address=192.168.1.152/24 -#static routers=192.168.1.1 -#static domain_name_servers=192.169.1.1 -# fallback to static profile on wlan0 -interface wlan0 -fallback static_wlan0 -#END HYDROSYS4 SECTION -EOF - - -} - -fn_ifnames () -{ -# this is to preserve the network interfaces names, becasue staring from debian stretch (9) the ifnames have new rules -# edit /etc/dnsmasq.conf file -aconf="/boot/cmdline.txt" - -APPEND=' net.ifnames=0' -echo "$(cat $aconf)$APPEND" > $aconf - -} - - - - - - - - - -install_mjpegstr () -{ -cd /home/pi - -sudo rm -r mjpg-streamer - -sudo apt-get -y install cmake libjpeg8-dev git - -sudo git clone https://github.com/jacksonliam/mjpg-streamer.git - -cd mjpg-streamer/mjpg-streamer-experimental - -sudo make - -sudo make install - -cd .. -cd .. - -} - - - -install_nginx () -{ -# this function is not used anymore -cd /home/pi - -sudo apt-get -y install nginx - -# create default file -aconf="/etc/nginx/sites-enabled/default" -if [ -f $aconf ]; then - cp $aconf /home/pi/$aconf.1 - sudo rm $aconf - echo "remove file" -fi - - -sudo bash -c "cat >> $aconf" << EOF -server { - # for a public HTTP server: - listen $PORT; - server_name localhost hydrosys4.local; - - access_log off; - error_log off; - - location / { - proxy_pass http://127.0.0.1:5020; - } - - location /stream { - rewrite ^/stream(.*) /$1 break; - proxy_pass http://127.0.0.1:5022; - proxy_buffering off; - } - - location /favicon.ico { - alias /home/pi/env/autonom/static/favicon.ico; - } -} -EOF - -sudo service nginx start - -cd .. -cd .. - -} - - -install_squid3 () -{ -# this function is used to install the squid3 program used as reverse proxy -cd /home/pi - -sudo apt-get install squid3 -y || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -# add configuration to squid.conf, the file should already exist if installation is succesful -adir="/etc/squid3" -if [ -d $adir ]; then - aconf="/etc/squid3/squid.conf" -fi -adir="/etc/squid" -if [ -d $adir ]; then - aconf="/etc/squid/squid.conf" -fi - -if [ -f $aconf ]; then - cp $aconf $aconf.1 - sudo rm $aconf - echo "remove file" -fi - - - -sudo bash -c "cat >> $aconf" << EOF -# hydrosys4 configurations - -http_port $PORT accel defaultsite=hydrosys4 vhost - -acl Safe_ports port $PORT # unregistered ports - -acl videostream urlpath_regex \?action=stream - -cache_peer localhost parent 5020 0 no-query originserver name=server1 -cache_peer_access server1 deny videostream - -cache_peer localhost parent 5022 0 no-query originserver name=server2 -cache_peer_access server2 allow videostream -cache_peer_access server2 deny all - -http_access allow Safe_ports - -# default configurations - -# WELCOME TO SQUID 3.5.12 -acl SSL_ports port 443 -acl Safe_ports port 80 # http -acl Safe_ports port 21 # ftp -acl Safe_ports port 443 # https -acl Safe_ports port 70 # gopher -acl Safe_ports port 210 # wais -acl Safe_ports port 1025-65535 # unregistered ports -acl Safe_ports port 280 # http-mgmt -acl Safe_ports port 488 # gss-http -acl Safe_ports port 591 # filemaker -acl Safe_ports port 777 # multiling http -acl CONNECT method CONNECT -http_access deny !Safe_ports -http_access deny CONNECT !SSL_ports -http_access allow localhost manager -http_access deny manager -http_access allow localhost -http_access deny all -coredump_dir /var/spool/squid -refresh_pattern ^ftp: 1440 20% 10080 -refresh_pattern ^gopher: 1440 0% 1440 -refresh_pattern -i (/cgi-bin/|\?) 0 0% 0 -refresh_pattern (Release|Packages(.gz)*)$ 0 20% 2880 -refresh_pattern . 0 20% 4320 -EOF - -sudo service squid3 start - -cd .. -cd .. - -} - - - -edit_defaultnetworkdb () -{ - - -aconf="/home/pi/env/autonom/database/default/defnetwork.txt " - -# if file already exist then no action, otherwise create it -if [ -f $aconf ]; then - echo "network default file already exist" - else - sudo bash -c "cat >> $aconf" << EOF -{"name": "IPsetting", "LocalIPaddress": "192.168.0.172", "LocalPORT": "5012" , "LocalAPSSID" : "Hydrosys4"} -EOF - -fi - -} - -edit_networkdb () -{ - - -aconf="/home/pi/env/autonom/database/network.txt " - -# if file already exist then delete it -if [ -f $aconf ]; then - sudo rm $aconf - echo "remove file" -fi - -sudo bash -c "cat >> $aconf" << EOF -{"name": "IPsetting", "LocalIPaddress": "$IP", "LocalPORT": "$PORT", "LocalAPSSID" : "$WiFiAPname"} -EOF - - -} - - -iptables_blockports () -{ -sudo iptables -A INPUT -p tcp --dport 5020 -j DROP -sudo iptables -A INPUT -p tcp --dport 5022 -j DROP - -sudo iptables-save > /home/pi/iptables.rules - -} - - -# --- RUN the functions -killpython -input_UI -system_update_light -#system_update_UI -install_dependencies -enable_I2C -modify_RClocal -fn_hostapd -fn_dnsmasq -fn_dhcpcd -fn_ifnames -install_mjpegstr -install_squid3 -install_hydrosys4 # this should be called before the DHT22 , SPI and BMP due to local library references -install_DHT22lib -install_SPIlib -install_BMPlib -edit_defaultnetworkdb -edit_networkdb -iptables_blockports - diff --git a/bash/install_hydrosys4v19.sh b/bash/install_hydrosys4v19.sh deleted file mode 100644 index 1af818a..0000000 --- a/bash/install_hydrosys4v19.sh +++ /dev/null @@ -1,724 +0,0 @@ -#!/bin/bash - - -#Debug enable next 3 lines -exec 5> install.txt -BASH_XTRACEFD="5" -set -x -# ------ end debug - - -function killpython() -{ - -sudo killall python - -} - - -function system_update_light() -{ - -# ---- system_update - -sudo apt-get -y update - -} - -function system_update() -{ - -# ---- remove unnecessary packages - -sudo apt-get remove --purge libreoffice-* -sudo apt-get remove --purge wolfram-engine - - -# ---- system_update - -sudo apt-get -y update -sudo apt-get -y upgrade - -} - -function system_update_UI() -{ - -while true; do - read -p "Do you wish to update the Raspbian system (y/n)?" yn - case $yn in - [Yy]* ) system_update; break;; - [Nn]* ) break;; - * ) echo "Please answer y or n.";; - esac -done - -} - -function install_dependencies() -{ - - -#--- start installing dependencies - -sudo apt-get -y install python-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo apt-get -y install python-pip || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install flask || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install apscheduler || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install pyserial || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(for the webcam support) -sudo apt-get -y install fswebcam || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(for the image thumbnail support) -sudo apt-get install libjpeg-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install Pillow || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(for external IP address, using DNS) -sudo apt-get -y install dnsutils || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(encryption) -sudo pip install pbkdf2 || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(web server) -sudo pip install tornado || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -} - -function enable_I2C() -{ - -# --- Enable I2C and Spi : -# /boot/config.txt - -sed -i 's/\(^.*#dtparam=i2c_arm=on.*$\)/dtparam=i2c_arm=on/' /boot/config.txt -sed -i 's/\(^.*#dtparam=spi=on.*$\)/dtparam=spi=on/' /boot/config.txt -sed -i 's/\(^.*#dtparam=i2s=on.*$\)/dtparam=i2s=on/' /boot/config.txt - -# --- Add modules: -# /etc/modules -aconf="/etc/modules" - -sed -i '/i2c-bcm2708/d' $aconf -sed -i -e "\$ai2c-bcm2708" $aconf - -sed -i '/i2c-dev/d' $aconf -sed -i -e "\$ai2c-dev" $aconf - -sed -i '/i2c-bcm2835/d' $aconf -sed -i -e "\$ai2c-bcm2835" $aconf - -sed -i '/rtc-ds1307/d' $aconf -sed -i -e "\$artc-ds1307" $aconf - -sed -i '/bcm2835-v4l2/d' $aconf -sed -i -e "\$abcm2835-v4l2" $aconf - - -# --- install I2C tools -sudo apt-get -y install git build-essential python-dev python-smbus || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo apt-get -y install -y i2c-tools || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -} - - -# --- enable raspicam - -############# MISSING ############## - -function modify_RClocal() -{ - -# --- Real Time Clock (RTC) -# /etc/rc.local - -autostart="yes" -# copy the below lines between # START and #END to rc.local -tmpfile=$(mktemp) -sudo sed '/#START/,/#END/d' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local -# Remove to growing plank lines. -sudo awk '!NF {if (++n <= 1) print; next}; {n=0;print}' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local -if [ "$autostart" == "yes" ]; then - if ! grep -Fq '#START HYDROSYS4 SECTION' /etc/rc.local; then - sudo sed -i '/exit 0/d' /etc/rc.local - sudo bash -c "cat >> /etc/rc.local" << EOF -#START HYDROSYS4 SECTION -# iptables -sudo iptables-restore < /home/pi/iptables.rules - -# clock -echo ds3231 0x68 > /sys/class/i2c-adapter/i2c-1/new_device || true -hwclock -s || true - -cd /home/pi/env/autonom/ -sudo python /home/pi/env/autonom/bentornado.py & - -#END HYDROSYS4 SECTION - -exit 0 -EOF - else - tmpfile=$(mktemp) - sudo sed '/#START/,/#END/d' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local - # Remove to growing plank lines. - sudo awk '!NF {if (++n <= 1) print; next}; {n=0;print}' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local - fi - -fi - -sudo chown root:root /etc/rc.local -sudo chmod 755 /etc/rc.local -# end modification to RC.local - -} - - -### -- WIFI setup --- STANDARD - -function valid_ip() -{ - local ip=$1 - local stat=1 - - if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then - OIFS=$IFS - IFS='.' - ip=($ip) - IFS=$OIFS - [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \ - && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]] - stat=$? - fi - return $stat -} - - -input_UI () -{ - -echo "Hello, following initial setting is requested:" - -# IP part input - -IP="0" -while ! valid_ip $IP; do - read -p "Local IP address (range 192.168.0.100-192.168.1.200), to confirm press [ENTER] or modify: " -e -i 192.168.0.172 IP - if valid_ip $IP; then stat='good'; - else stat='bad'; echo "WRONG FORMAT, please enter a valid value for IP address" - fi - -done - echo "Confirmed IP address: "$IP - -PORT="" -while [[ ! $PORT =~ ^[0-9]+$ ]]; do -read -p "Local PORT, to confirm press [ENTER] or modify: " -e -i 5012 PORT - if [[ ! $PORT =~ ^[0-9]+$ ]]; - then echo "WRONG FORMAT, please enter a valid value for PORT"; - fi -done - echo "Confirmed PORT: "$PORT - -# Local WiFi AP name and password setting - -read -p "System WiFi AP name, to confirm press [ENTER] or modify: " -e -i Hydrosys4 WiFiAPname -echo "Confirmed Name: "$WiFiAPname - -read -p "System WiFi AP password, to confirm press [ENTER] or modify: " -e -i hydrosystem WiFiAPpsw -echo "Confirmed Password: "$WiFiAPpsw - -} - - -install_DHT22lib () -{ - -# --- installing the DHT22 Sensor libraries -sudo apt-get -y install build-essential python-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/DHT22/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/DHT22 - unzip master.zip - cd Adafruit_Python_DHT-master - # setup1plus is file that try to make the DTH22 work with both RaspberryPi zero,1 and model 2,3 - sudo python setup1plus.py install - cd /home/pi -else - cd /home/pi - sudo rm -r DHT22 - mkdir DHT22 - cd DHT22 - wget https://github.com/adafruit/Adafruit_Python_DHT/archive/master.zip - unzip master.zip - cd Adafruit_Python_DHT-master - sudo python setup.py install - cd /home/pi -fi -} - - -install_SPIlib () -{ - - -# --- INSTALL SPI library: - -sudo apt-get -y install python2.7-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/SPI/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/SPI - unzip master.zip - cd py-spidev-master - sudo python setup.py install - cd /home/pi -else - -cd /home/pi -sudo rm -r SPIDEV -mkdir SPIDEV -cd SPIDEV - -wget https://github.com/Gadgetoid/py-spidev/archive/master.zip - -unzip master.zip - -rm master.zip - -cd py-spidev-master - -sudo python setup.py install - -cd .. -cd .. - -fi -} - - -install_BMPlib () -{ - -# --- INSTALL BMP180 library (pressure sensor) - -sudo apt-get -y install build-essential python-dev python-smbus || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/BMP/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/BMP - unzip master.zip - cd Adafruit_Python_BMP-master - sudo python setup.py install - cd /home/pi -else - -cd /home/pi -sudo rm -r bmp180 -sudo mkdir bmp180 -cd bmp180 -wget https://github.com/adafruit/Adafruit_Python_BMP/archive/master.zip -cd Adafruit_Python_BMP-master -sudo python setup.py install -cd .. -cd .. - -fi -} - - -install_hydrosys4 () -{ -# --- INSTALL Hydrosys4 software -sudo apt-get -y install git || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - - -# check if file exist in local folder -aconf="/home/pi/env/autonom" -if [ -d $aconf ]; then # if the directory exist - cd /home/pi -else - cd /home/pi - sudo rm -r env - mkdir env - cd env - sudo rm -r autonom - git clone https://github.com/Hydrosys4/Master.git - sudo killall python - mv Master autonom - cd .. - -fi - -} - - - - - - -fn_hostapd () -{ - -sudo apt-get -y install hostapd || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - - -# create hostapd.conf file -aconf="/etc/hostapd/hostapd.conf" -if [ -f $aconf ]; then - cp $aconf $aconf.1 - sudo rm $aconf - echo "remove file" -fi - - -sudo bash -c "cat >> $aconf" << EOF -# HERE-> {"name": "IPsetting", "LocalIPaddress": "$IP", "LocalPORT": "$PORT", "LocalAPSSID" : "$WiFiAPname"} -ieee80211n=1 -interface=wlan0 -ssid=$WiFiAPname -hw_mode=g -channel=6 -macaddr_acl=0 -auth_algs=1 -ignore_broadcast_ssid=0 -wpa=3 -wpa_passphrase=$WiFiAPpsw -wpa_key_mgmt=WPA-PSK -wpa_pairwise=TKIP -rsn_pairwise=CCMP -EOF - - -aconf="/etc/init.d/hostapd" -# Update hostapd main config file -sudo sed -i "s/\(^.*DAEMON_CONF=.*$\)/DAEMON_CONF=\/etc\/hostapd\/hostapd.conf/" $aconf - -sudo systemctl enable hostapd.service - -} - - -fn_dnsmasq () -{ - -sudo apt-get -y install dnsmasq || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - - -# edit /etc/dnsmasq.conf file -aconf="/etc/dnsmasq.conf" - -# delete rows between #START and #END -sed -i '/^#START HYDROSYS4 SECTION/,/^#END HYDROSYS4 SECTION/{/^#START HYDROSYS4 SECTION/!{/^#END HYDROSYS4 SECTION/!d}}' $aconf -sed -i '/#START HYDROSYS4 SECTION/d' $aconf -sed -i '/#END HYDROSYS4 SECTION/d' $aconf - -# calculation of the range starting from assigned IP address -IFS="." read -a a <<< $IP -IFS="." read -a b <<< 0.0.0.1 -IFS="." read -a c <<< 0.0.0.9 -IPSTART="$[a[0]].$[a[1]].$[a[2]].$[a[3]+b[3]]" -IPEND="$[a[0]].$[a[1]].$[a[2]].$[a[3]+c[3]]" -if [[ a[3] -gt 244 ]]; then -IPSTART="$[a[0]].$[a[1]].$[a[2]].$[a[3]-c[3]]" -IPEND="$[a[0]].$[a[1]].$[a[2]].$[a[3]-b[3]]" -fi - -echo $IPSTART $IPEND - - - -# ----- - - - -sudo bash -c "cat >> $aconf" << EOF -#START HYDROSYS4 SECTION -interface=wlan0 -dhcp-range=$IPSTART,$IPEND,12h -#no-resolv -#END HYDROSYS4 SECTION -EOF - -sudo systemctl enable dnsmasq.service - - -} - - -fn_dhcpcd () -{ - -# edit /etc/dnsmasq.conf file -aconf="/etc/dhcpcd.conf" - -# delete rows between #START and #END -sed -i '/^#START HYDROSYS4 SECTION/,/^#END HYDROSYS4 SECTION/{/^#START HYDROSYS4 SECTION/!{/^#END HYDROSYS4 SECTION/!d}}' $aconf -sed -i '/#START HYDROSYS4 SECTION/d' $aconf -sed -i '/#END HYDROSYS4 SECTION/d' $aconf - - -sudo bash -c "cat >> $aconf" << EOF -#START HYDROSYS4 SECTION -profile static_wlan0 -static ip_address=192.168.1.152/24 -#static routers=192.168.1.1 -#static domain_name_servers=192.169.1.1 -# fallback to static profile on wlan0 -interface wlan0 -fallback static_wlan0 -#END HYDROSYS4 SECTION -EOF - - -} - -fn_ifnames () -{ -# this is to preserve the network interfaces names, becasue staring from debian stretch (9) the ifnames have new rules -# edit /etc/dnsmasq.conf file -aconf="/boot/cmdline.txt" - -APPEND=' net.ifnames=0' -echo "$(cat $aconf)$APPEND" > $aconf - -} - - - - - - - - - -install_mjpegstr () -{ -cd /home/pi - -sudo rm -r mjpg-streamer - -sudo apt-get -y install cmake libjpeg8-dev git - -sudo git clone https://github.com/jacksonliam/mjpg-streamer.git - -cd mjpg-streamer/mjpg-streamer-experimental - -sudo make - -sudo make install - -cd .. -cd .. - -} - - - -install_nginx () -{ -# this function is not used anymore -cd /home/pi - -sudo apt-get -y install nginx - -# create default file -aconf="/etc/nginx/sites-enabled/default" -if [ -f $aconf ]; then - cp $aconf /home/pi/$aconf.1 - sudo rm $aconf - echo "remove file" -fi - - -sudo bash -c "cat >> $aconf" << EOF -server { - # for a public HTTP server: - listen $PORT; - server_name localhost hydrosys4.local; - - access_log off; - error_log off; - - location / { - proxy_pass http://127.0.0.1:5020; - } - - location /stream { - rewrite ^/stream(.*) /$1 break; - proxy_pass http://127.0.0.1:5022; - proxy_buffering off; - } - - location /favicon.ico { - alias /home/pi/env/autonom/static/favicon.ico; - } -} -EOF - -sudo service nginx start - -cd .. -cd .. - -} - - -install_squid3 () -{ -# this function is used to install the squid3 program used as reverse proxy -cd /home/pi - -sudo apt-get install squid3 -y || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -# add configuration to squid.conf, the file should already exist if installation is succesful -adir="/etc/squid3" -if [ -d $adir ]; then - aconf="/etc/squid3/squid.conf" -fi -adir="/etc/squid" -if [ -d $adir ]; then - aconf="/etc/squid/squid.conf" -fi - -if [ -f $aconf ]; then - cp $aconf $aconf.1 - sudo rm $aconf - echo "remove file" -fi - - - -sudo bash -c "cat >> $aconf" << EOF -# hydrosys4 configurations - -http_port $PORT accel defaultsite=hydrosys4 vhost - -acl Safe_ports port $PORT # unregistered ports - -acl videostream urlpath_regex \?action=stream - -cache_peer localhost parent 5020 0 no-query originserver name=server1 -cache_peer_access server1 deny videostream - -cache_peer localhost parent 5022 0 no-query originserver name=server2 -cache_peer_access server2 allow videostream -cache_peer_access server2 deny all - -http_access allow Safe_ports - -# default configurations - -# WELCOME TO SQUID 3.5.12 -acl SSL_ports port 443 -acl Safe_ports port 80 # http -acl Safe_ports port 21 # ftp -acl Safe_ports port 443 # https -acl Safe_ports port 70 # gopher -acl Safe_ports port 210 # wais -acl Safe_ports port 1025-65535 # unregistered ports -acl Safe_ports port 280 # http-mgmt -acl Safe_ports port 488 # gss-http -acl Safe_ports port 591 # filemaker -acl Safe_ports port 777 # multiling http -acl CONNECT method CONNECT -http_access deny !Safe_ports -http_access deny CONNECT !SSL_ports -http_access allow localhost manager -http_access deny manager -http_access allow localhost -http_access deny all -coredump_dir /var/spool/squid -refresh_pattern ^ftp: 1440 20% 10080 -refresh_pattern ^gopher: 1440 0% 1440 -refresh_pattern -i (/cgi-bin/|\?) 0 0% 0 -refresh_pattern (Release|Packages(.gz)*)$ 0 20% 2880 -refresh_pattern . 0 20% 4320 -EOF - -sudo service squid3 start - -cd .. -cd .. - -} - - - -edit_defaultnetworkdb () -{ - - -aconf="/home/pi/env/autonom/database/default/defnetwork.txt " - -# if file already exist then no action, otherwise create it -if [ -f $aconf ]; then - echo "network default file already exist" - else - sudo bash -c "cat >> $aconf" << EOF -{"name": "IPsetting", "LocalIPaddress": "192.168.0.172", "LocalPORT": "5012" , "LocalAPSSID" : "Hydrosys4"} -EOF - -fi - -} - -edit_networkdb () -{ - - -aconf="/home/pi/env/autonom/database/network.txt " - -# if file already exist then delete it -if [ -f $aconf ]; then - sudo rm $aconf - echo "remove file" -fi - -sudo bash -c "cat >> $aconf" << EOF -{"name": "IPsetting", "LocalIPaddress": "$IP", "LocalPORT": "$PORT", "LocalAPSSID" : "$WiFiAPname"} -EOF - - -} - - -iptables_blockports () -{ -sudo iptables -A INPUT -p tcp --dport 5020 -j DROP -sudo iptables -A INPUT -p tcp --dport 5022 -j DROP - -sudo iptables-save > /home/pi/iptables.rules - -} - - -# --- RUN the functions -killpython -input_UI -system_update_light -#system_update_UI -install_dependencies -enable_I2C -modify_RClocal -fn_hostapd -fn_dnsmasq -fn_dhcpcd -fn_ifnames -install_mjpegstr -install_squid3 -install_hydrosys4 # this should be called before the DHT22 , SPI and BMP due to local library references -install_DHT22lib -install_SPIlib -install_BMPlib -edit_defaultnetworkdb -edit_networkdb -iptables_blockports - diff --git a/bash/install_hydrosys4v20.sh b/bash/install_hydrosys4v20.sh deleted file mode 100644 index ea24bc5..0000000 --- a/bash/install_hydrosys4v20.sh +++ /dev/null @@ -1,755 +0,0 @@ -#!/bin/bash - - -#Debug enable next 3 lines -exec 5> install.txt -BASH_XTRACEFD="5" -set -x -# ------ end debug - - -function killpython() -{ - -sudo killall python - -} - - -function system_update_light() -{ - -# ---- system_update - -sudo apt-get -y update - -} - -function system_update() -{ - -# ---- remove unnecessary packages - -sudo apt-get remove --purge libreoffice-* -sudo apt-get remove --purge wolfram-engine - - -# ---- system_update - -sudo apt-get -y update -sudo apt-get -y upgrade - -} - -function system_update_UI() -{ - -while true; do - read -p "Do you wish to update the Raspbian system (y/n)?" yn - case $yn in - [Yy]* ) system_update; break;; - [Nn]* ) break;; - * ) echo "Please answer y or n.";; - esac -done - -} - -function install_dependencies() -{ - - -#--- start installing dependencies - -sudo apt-get -y install python-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo apt-get -y install python-pip || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install flask || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install apscheduler || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install pyserial || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(for the webcam support) -sudo apt-get -y install fswebcam || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(for the image thumbnail support) -sudo apt-get -y install libjpeg-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install Pillow || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(for external IP address, using DNS) -sudo apt-get -y install dnsutils || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(encryption) -sudo pip install pbkdf2 || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(web server) -sudo pip install tornado || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -} - -function enable_I2C() -{ - -# --- Enable I2C and Spi : -# /boot/config.txt - -sed -i 's/\(^.*#dtparam=i2c_arm=on.*$\)/dtparam=i2c_arm=on/' /boot/config.txt -sed -i 's/\(^.*#dtparam=spi=on.*$\)/dtparam=spi=on/' /boot/config.txt -sed -i 's/\(^.*#dtparam=i2s=on.*$\)/dtparam=i2s=on/' /boot/config.txt - -# --- Add modules: -# /etc/modules -aconf="/etc/modules" - -sed -i '/i2c-bcm2708/d' $aconf -sed -i -e "\$ai2c-bcm2708" $aconf - -sed -i '/i2c-dev/d' $aconf -sed -i -e "\$ai2c-dev" $aconf - -sed -i '/i2c-bcm2835/d' $aconf -sed -i -e "\$ai2c-bcm2835" $aconf - -sed -i '/rtc-ds1307/d' $aconf -sed -i -e "\$artc-ds1307" $aconf - -sed -i '/bcm2835-v4l2/d' $aconf -sed -i -e "\$abcm2835-v4l2" $aconf - - -# --- install I2C tools -sudo apt-get -y install git build-essential python-dev python-smbus || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo apt-get -y install -y i2c-tools || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -} - - -# --- enable raspicam - -############# MISSING ############## - -function modify_RClocal() -{ - -# --- Real Time Clock (RTC) -# /etc/rc.local - -autostart="yes" -# copy the below lines between # START and #END to rc.local -tmpfile=$(mktemp) -sudo sed '/#START/,/#END/d' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local -# Remove to growing plank lines. -sudo awk '!NF {if (++n <= 1) print; next}; {n=0;print}' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local -if [ "$autostart" == "yes" ]; then - if ! grep -Fq '#START HYDROSYS4 SECTION' /etc/rc.local; then - sudo sed -i '/exit 0/d' /etc/rc.local - sudo bash -c "cat >> /etc/rc.local" << EOF -#START HYDROSYS4 SECTION -# iptables -sudo iptables-restore < /home/pi/iptables.rules - -# clock -echo ds3231 0x68 > /sys/class/i2c-adapter/i2c-1/new_device || true -hwclock -s || true - -cd /home/pi/env/autonom/ -sudo python /home/pi/env/autonom/bentornado.py & - -#END HYDROSYS4 SECTION - -exit 0 -EOF - else - tmpfile=$(mktemp) - sudo sed '/#START/,/#END/d' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local - # Remove to growing plank lines. - sudo awk '!NF {if (++n <= 1) print; next}; {n=0;print}' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local - fi - -fi - -sudo chown root:root /etc/rc.local -sudo chmod 755 /etc/rc.local -# end modification to RC.local - -} - - -### -- WIFI setup --- STANDARD - -function valid_ip() -{ - local ip=$1 - local stat=1 - - if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then - OIFS=$IFS - IFS='.' - ip=($ip) - IFS=$OIFS - [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \ - && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]] - stat=$? - fi - return $stat -} - - -input_UI () -{ - -echo "Hello, following initial setting is requested:" - -# IP part input - -IP="0" -while ! valid_ip $IP; do - read -p "Local IP address (range 192.168.0.100-192.168.1.200), to confirm press [ENTER] or modify: " -e -i 192.168.1.172 IP - if valid_ip $IP; then stat='good'; - else stat='bad'; echo "WRONG FORMAT, please enter a valid value for IP address" - fi - -done - echo "Confirmed IP address: "$IP - -PORT="" -while [[ ! $PORT =~ ^[0-9]+$ ]]; do -read -p "Local PORT, to confirm press [ENTER] or modify: " -e -i 5172 PORT - if [[ ! $PORT =~ ^[0-9]+$ ]]; - then echo "WRONG FORMAT, please enter a valid value for PORT"; - fi -done - echo "Confirmed PORT: "$PORT - -# Local WiFi AP name and password setting - -read -p "System WiFi AP name, to confirm press [ENTER] or modify: " -e -i Hydrosys4 WiFiAPname -echo "Confirmed Name: "$WiFiAPname - -read -p "System WiFi AP password, to confirm press [ENTER] or modify: " -e -i hydrosystem WiFiAPpsw -echo "Confirmed Password: "$WiFiAPpsw - -} - -install_MotorShieldlib () -{ - -# --- installing the python dev-library -sudo apt-get -y install build-essential python-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/MotorHat/master.zip" -if [ -f $aconf ]; then - cd /home/pi/env/autonom/libraries/MotorHat - unzip master.zip - cd Adafruit-Motor-HAT-Python-Library-master - sudo python setup.py install - cd /home/pi -else - cd /home/pi - sudo rm -r MotorHat - mkdir MotorHat - cd MotorHat - wget https://github.com/adafruit/Adafruit-Motor-HAT-Python-Library/archive/master.zip - unzip master.zip - cd Adafruit-Motor-HAT-Python-Library-master - sudo python setup.py install - cd /home/pi -fi -} - - - - -install_DHT22lib () -{ - -# --- installing the DHT22 Sensor libraries -sudo apt-get -y install build-essential python-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/DHT22/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/DHT22 - unzip master.zip - cd Adafruit_Python_DHT-master - # setup1plus is file that try to make the DTH22 work with both RaspberryPi zero,1 and model 2,3 - sudo python setup1plus.py install - cd /home/pi -else - cd /home/pi - sudo rm -r DHT22 - mkdir DHT22 - cd DHT22 - wget https://github.com/adafruit/Adafruit_Python_DHT/archive/master.zip - unzip master.zip - cd Adafruit_Python_DHT-master - sudo python setup.py install - cd /home/pi -fi -} - - -install_SPIlib () -{ - - -# --- INSTALL SPI library: - -sudo apt-get -y install python2.7-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/SPI/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/SPI - unzip master.zip - cd py-spidev-master - sudo python setup.py install - cd /home/pi -else - -cd /home/pi -sudo rm -r SPIDEV -mkdir SPIDEV -cd SPIDEV - -wget https://github.com/Gadgetoid/py-spidev/archive/master.zip - -unzip master.zip - -rm master.zip - -cd py-spidev-master - -sudo python setup.py install - -cd .. -cd .. - -fi -} - - -install_BMPlib () -{ - -# --- INSTALL BMP180 library (pressure sensor) - -sudo apt-get -y install build-essential python-dev python-smbus || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/BMP/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/BMP - unzip master.zip - cd Adafruit_Python_BMP-master - sudo python setup.py install - cd /home/pi -else - -cd /home/pi -sudo rm -r bmp180 -sudo mkdir bmp180 -cd bmp180 -wget https://github.com/adafruit/Adafruit_Python_BMP/archive/master.zip -cd Adafruit_Python_BMP-master -sudo python setup.py install -cd .. -cd .. - -fi -} - - -install_hydrosys4 () -{ -# --- INSTALL Hydrosys4 software -sudo apt-get -y install git || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - - -# check if file exist in local folder -aconf="/home/pi/env/autonom" -if [ -d $aconf ]; then # if the directory exist - cd /home/pi -else - cd /home/pi - sudo rm -r env - mkdir env - cd env - sudo rm -r autonom - git clone https://github.com/Hydrosys4/Master.git - sudo killall python - mv Master autonom - cd .. - -fi - -} - - - - - - -fn_hostapd () -{ - -sudo apt-get -y install hostapd || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - - -# create hostapd.conf file -aconf="/etc/hostapd/hostapd.conf" -if [ -f $aconf ]; then - cp $aconf $aconf.1 - sudo rm $aconf - echo "remove file" -fi - - -sudo bash -c "cat >> $aconf" << EOF -# HERE-> {"name": "IPsetting", "LocalIPaddress": "$IP", "LocalPORT": "$PORT", "LocalAPSSID" : "$WiFiAPname"} -ieee80211n=1 -interface=wlan0 -ssid=$WiFiAPname -hw_mode=g -channel=6 -macaddr_acl=0 -auth_algs=1 -ignore_broadcast_ssid=0 -wpa=2 -wpa_passphrase=$WiFiAPpsw -wpa_key_mgmt=WPA-PSK -wpa_pairwise=TKIP -rsn_pairwise=CCMP -EOF - - -aconf="/etc/init.d/hostapd" -# Update hostapd main config file -sudo sed -i "s/\(^.*DAEMON_CONF=.*$\)/DAEMON_CONF=\/etc\/hostapd\/hostapd.conf/" $aconf - -sudo systemctl enable hostapd.service - -} - - -fn_dnsmasq () -{ - -sudo apt-get -y install dnsmasq || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - - -# edit /etc/dnsmasq.conf file -aconf="/etc/dnsmasq.conf" - -# delete rows between #START and #END -sed -i '/^#START HYDROSYS4 SECTION/,/^#END HYDROSYS4 SECTION/{/^#START HYDROSYS4 SECTION/!{/^#END HYDROSYS4 SECTION/!d}}' $aconf -sed -i '/#START HYDROSYS4 SECTION/d' $aconf -sed -i '/#END HYDROSYS4 SECTION/d' $aconf - -# calculation of the range starting from assigned IP address -IFS="." read -a a <<< $IP -IFS="." read -a b <<< 0.0.0.1 -IFS="." read -a c <<< 0.0.0.9 -IPSTART="$[a[0]].$[a[1]].$[a[2]].$[a[3]+b[3]]" -IPEND="$[a[0]].$[a[1]].$[a[2]].$[a[3]+c[3]]" -if [[ a[3] -gt 244 ]]; then -IPSTART="$[a[0]].$[a[1]].$[a[2]].$[a[3]-c[3]]" -IPEND="$[a[0]].$[a[1]].$[a[2]].$[a[3]-b[3]]" -fi - -echo $IPSTART $IPEND - - - -# ----- - - - -sudo bash -c "cat >> $aconf" << EOF -#START HYDROSYS4 SECTION -interface=wlan0 -dhcp-range=$IPSTART,$IPEND,12h -#no-resolv -#END HYDROSYS4 SECTION -EOF - -sudo systemctl enable dnsmasq.service - - -} - - -fn_dhcpcd () -{ - -# edit /etc/dnsmasq.conf file -aconf="/etc/dhcpcd.conf" - -# delete rows between #START and #END -sed -i '/^#START HYDROSYS4 SECTION/,/^#END HYDROSYS4 SECTION/{/^#START HYDROSYS4 SECTION/!{/^#END HYDROSYS4 SECTION/!d}}' $aconf -sed -i '/#START HYDROSYS4 SECTION/d' $aconf -sed -i '/#END HYDROSYS4 SECTION/d' $aconf - - -sudo bash -c "cat >> $aconf" << EOF -#START HYDROSYS4 SECTION -profile static_wlan0 -static ip_address=$IP/24 -#static routers=192.168.1.1 -#static domain_name_servers=192.169.1.1 -# fallback to static profile on wlan0 -interface wlan0 -fallback static_wlan0 -#END HYDROSYS4 SECTION -EOF - - -} - -fn_ifnames () -{ -# this is to preserve the network interfaces names, becasue staring from debian stretch (9) the ifnames have new rules -# edit /etc/dnsmasq.conf file -aconf="/boot/cmdline.txt" - -APPEND=' net.ifnames=0' -echo "$(cat $aconf)$APPEND" > $aconf - -} - - - - - - - - - -install_mjpegstr () -{ -cd /home/pi - -sudo rm -r mjpg-streamer - -sudo apt-get -y install cmake libjpeg8-dev git - -sudo git clone https://github.com/jacksonliam/mjpg-streamer.git - -cd mjpg-streamer/mjpg-streamer-experimental - -sudo make - -sudo make install - -cd .. -cd .. - -} - - - -install_nginx () -{ -# this function is not used anymore -cd /home/pi - -sudo apt-get -y install nginx - -# create default file -aconf="/etc/nginx/sites-enabled/default" -if [ -f $aconf ]; then - cp $aconf /home/pi/$aconf.1 - sudo rm $aconf - echo "remove file" -fi - - -sudo bash -c "cat >> $aconf" << EOF -server { - # for a public HTTP server: - listen $PORT; - server_name localhost hydrosys4.local; - - access_log off; - error_log off; - - location / { - proxy_pass http://127.0.0.1:5020; - } - - location /stream { - rewrite ^/stream(.*) /$1 break; - proxy_pass http://127.0.0.1:5022; - proxy_buffering off; - } - - location /favicon.ico { - alias /home/pi/env/autonom/static/favicon.ico; - } -} -EOF - -sudo service nginx start - -cd .. -cd .. - -} - - -install_squid3 () -{ -# this function is used to install the squid3 program used as reverse proxy -cd /home/pi - -sudo apt-get install squid3 -y || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -# add configuration to squid.conf, the file should already exist if installation is succesful -adir="/etc/squid3" -if [ -d $adir ]; then - aconf="/etc/squid3/squid.conf" -fi -adir="/etc/squid" -if [ -d $adir ]; then - aconf="/etc/squid/squid.conf" -fi - -if [ -f $aconf ]; then - cp $aconf $aconf.1 - sudo rm $aconf - echo "remove file" -fi - - - -sudo bash -c "cat >> $aconf" << EOF -# hydrosys4 configurations - -http_port $PORT accel defaultsite=hydrosys4 vhost - -acl Safe_ports port $PORT # unregistered ports - -acl videostream urlpath_regex \?action=stream - -cache_peer localhost parent 5020 0 no-query originserver name=server1 -cache_peer_access server1 deny videostream - -cache_peer localhost parent 5022 0 no-query originserver name=server2 -cache_peer_access server2 allow videostream -cache_peer_access server2 deny all - -http_access allow Safe_ports - -# default configurations - -# WELCOME TO SQUID 3.5.12 -acl SSL_ports port 443 -acl Safe_ports port 80 # http -acl Safe_ports port 21 # ftp -acl Safe_ports port 443 # https -acl Safe_ports port 70 # gopher -acl Safe_ports port 210 # wais -acl Safe_ports port 1025-65535 # unregistered ports -acl Safe_ports port 280 # http-mgmt -acl Safe_ports port 488 # gss-http -acl Safe_ports port 591 # filemaker -acl Safe_ports port 777 # multiling http -acl CONNECT method CONNECT -http_access deny !Safe_ports -http_access deny CONNECT !SSL_ports -http_access allow localhost manager -http_access deny manager -http_access allow localhost -http_access deny all -coredump_dir /var/spool/squid -refresh_pattern ^ftp: 1440 20% 10080 -refresh_pattern ^gopher: 1440 0% 1440 -refresh_pattern -i (/cgi-bin/|\?) 0 0% 0 -refresh_pattern (Release|Packages(.gz)*)$ 0 20% 2880 -refresh_pattern . 0 20% 4320 -EOF - -sudo service squid3 start - -cd .. -cd .. - -} - - - -edit_defaultnetworkdb () -{ - - -aconf="/home/pi/env/autonom/database/default/defnetwork.txt " - -# if file already exist then no action, otherwise create it -if [ -f $aconf ]; then - echo "network default file already exist" - else - sudo bash -c "cat >> $aconf" << EOF -{"name": "IPsetting", "LocalIPaddress": "192.168.0.172", "LocalPORT": "5012" , "LocalAPSSID" : "Hydrosys4"} -EOF - -fi - -} - -edit_networkdb () -{ - - -aconf="/home/pi/env/autonom/database/network.txt " - -# if file already exist then delete it -if [ -f $aconf ]; then - sudo rm $aconf - echo "remove file" -fi - -sudo bash -c "cat >> $aconf" << EOF -{"name": "IPsetting", "LocalIPaddress": "$IP", "LocalPORT": "$PORT", "LocalAPSSID" : "$WiFiAPname"} -EOF - - -} - - -iptables_blockports () -{ -sudo iptables -A INPUT -p tcp --dport 5020 -j DROP -sudo iptables -A INPUT -p tcp --dport 5022 -j DROP - -sudo iptables-save > /home/pi/iptables.rules - -} - - -# --- RUN the functions -killpython -input_UI -system_update_light -#system_update_UI -install_dependencies -enable_I2C -modify_RClocal -fn_hostapd -fn_dnsmasq -fn_dhcpcd -fn_ifnames -install_mjpegstr -install_squid3 -install_hydrosys4 # this should be called before the DHT22 , SPI and BMP due to local library references -install_DHT22lib -install_SPIlib -install_BMPlib -install_MotorShieldlib -edit_defaultnetworkdb -#edit_networkdb -iptables_blockports - -echo "installation is finished!!! " diff --git a/bash/install_hydrosys4v21.sh b/bash/install_hydrosys4v21.sh deleted file mode 100644 index 8a9e25b..0000000 --- a/bash/install_hydrosys4v21.sh +++ /dev/null @@ -1,757 +0,0 @@ -#!/bin/bash - - -#Debug enable next 3 lines -exec 5> install.txt -BASH_XTRACEFD="5" -set -x -# ------ end debug - - -function killpython() -{ - -sudo killall python - -} - - -function system_update_light() -{ - -# ---- system_update - -sudo apt-get -y update - -} - -function system_update() -{ - -# ---- remove unnecessary packages - -sudo apt-get remove --purge libreoffice-* -sudo apt-get remove --purge wolfram-engine - - -# ---- system_update - -sudo apt-get -y update -sudo apt-get -y upgrade - -} - -function system_update_UI() -{ - -while true; do - read -p "Do you wish to update the Raspbian system (y/n)?" yn - case $yn in - [Yy]* ) system_update; break;; - [Nn]* ) break;; - * ) echo "Please answer y or n.";; - esac -done - -} - -function install_dependencies() -{ - - -#--- start installing dependencies - -sudo apt-get -y install python-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo apt-get -y install python-pip || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install flask || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install apscheduler || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install pyserial || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(for the webcam support) -sudo apt-get -y install fswebcam || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(for the image thumbnail support) -sudo apt-get -y install libjpeg-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install Pillow || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(for external IP address, using DNS) -sudo apt-get -y install dnsutils || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(encryption) -sudo pip install pbkdf2 || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(web server) -sudo pip install tornado || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -} - -function enable_I2C() -{ - -# --- Enable I2C and Spi : -# /boot/config.txt - -sed -i 's/\(^.*#dtparam=i2c_arm=on.*$\)/dtparam=i2c_arm=on/' /boot/config.txt -sed -i 's/\(^.*#dtparam=spi=on.*$\)/dtparam=spi=on/' /boot/config.txt -sed -i 's/\(^.*#dtparam=i2s=on.*$\)/dtparam=i2s=on/' /boot/config.txt - -# --- Add modules: -# /etc/modules -aconf="/etc/modules" - -sed -i '/i2c-bcm2708/d' $aconf -sed -i -e "\$ai2c-bcm2708" $aconf - -sed -i '/i2c-dev/d' $aconf -sed -i -e "\$ai2c-dev" $aconf - -sed -i '/i2c-bcm2835/d' $aconf -sed -i -e "\$ai2c-bcm2835" $aconf - -sed -i '/rtc-ds1307/d' $aconf -sed -i -e "\$artc-ds1307" $aconf - -sed -i '/bcm2835-v4l2/d' $aconf -sed -i -e "\$abcm2835-v4l2" $aconf - - -# --- install I2C tools -sudo apt-get -y install git build-essential python-dev python-smbus || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo apt-get -y install -y i2c-tools || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -} - - -# --- enable raspicam - -############# MISSING ############## - -function modify_RClocal() -{ - -# --- Real Time Clock (RTC) -# /etc/rc.local - -autostart="yes" -# copy the below lines between # START and #END to rc.local -tmpfile=$(mktemp) -sudo sed '/#START/,/#END/d' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local -# Remove to growing plank lines. -sudo awk '!NF {if (++n <= 1) print; next}; {n=0;print}' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local -if [ "$autostart" == "yes" ]; then - if ! grep -Fq '#START HYDROSYS4 SECTION' /etc/rc.local; then - sudo sed -i '/exit 0/d' /etc/rc.local - sudo bash -c "cat >> /etc/rc.local" << EOF -#START HYDROSYS4 SECTION -# iptables -sudo iptables-restore < /home/pi/iptables.rules - -# clock -echo "HYDROSYS4-set HW clock ****************************************" -echo ds3231 0x68 > /sys/class/i2c-adapter/i2c-1/new_device || true -hwclock -s || true - -echo "HYDROSYS4-start system ****************************************" -cd /home/pi/env/autonom/ -sudo python /home/pi/env/autonom/bentornado.py & - -#END HYDROSYS4 SECTION - -exit 0 -EOF - else - tmpfile=$(mktemp) - sudo sed '/#START/,/#END/d' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local - # Remove to growing plank lines. - sudo awk '!NF {if (++n <= 1) print; next}; {n=0;print}' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local - fi - -fi - -sudo chown root:root /etc/rc.local -sudo chmod 755 /etc/rc.local -# end modification to RC.local - -} - - -### -- WIFI setup --- STANDARD - -function valid_ip() -{ - local ip=$1 - local stat=1 - - if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then - OIFS=$IFS - IFS='.' - ip=($ip) - IFS=$OIFS - [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \ - && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]] - stat=$? - fi - return $stat -} - - -input_UI () -{ - -echo "Hello, following initial setting is requested:" - -# IP part input - -IP="0" -while ! valid_ip $IP; do - read -p "Local IP address (range 192.168.0.100-192.168.1.200), to confirm press [ENTER] or modify: " -e -i 192.168.1.172 IP - if valid_ip $IP; then stat='good'; - else stat='bad'; echo "WRONG FORMAT, please enter a valid value for IP address" - fi - -done - echo "Confirmed IP address: "$IP - -PORT="" -while [[ ! $PORT =~ ^[0-9]+$ ]]; do -read -p "Local PORT, to confirm press [ENTER] or modify: " -e -i 5172 PORT - if [[ ! $PORT =~ ^[0-9]+$ ]]; - then echo "WRONG FORMAT, please enter a valid value for PORT"; - fi -done - echo "Confirmed PORT: "$PORT - -# Local WiFi AP name and password setting - -read -p "System WiFi AP name, to confirm press [ENTER] or modify: " -e -i Hydrosys4 WiFiAPname -echo "Confirmed Name: "$WiFiAPname - -read -p "System WiFi AP password, to confirm press [ENTER] or modify: " -e -i hydrosystem WiFiAPpsw -echo "Confirmed Password: "$WiFiAPpsw - -} - -install_MotorShieldlib () -{ - -# --- installing the python dev-library -sudo apt-get -y install build-essential python-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/MotorHat/master.zip" -if [ -f $aconf ]; then - cd /home/pi/env/autonom/libraries/MotorHat - unzip master.zip - cd Adafruit-Motor-HAT-Python-Library-master - sudo python setup.py install - cd /home/pi -else - cd /home/pi - sudo rm -r MotorHat - mkdir MotorHat - cd MotorHat - wget https://github.com/adafruit/Adafruit-Motor-HAT-Python-Library/archive/master.zip - unzip master.zip - cd Adafruit-Motor-HAT-Python-Library-master - sudo python setup.py install - cd /home/pi -fi -} - - - - -install_DHT22lib () -{ - -# --- installing the DHT22 Sensor libraries -sudo apt-get -y install build-essential python-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/DHT22/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/DHT22 - unzip master.zip - cd Adafruit_Python_DHT-master - # setup1plus is file that try to make the DTH22 work with both RaspberryPi zero,1 and model 2,3 - sudo python setup1plus.py install - cd /home/pi -else - cd /home/pi - sudo rm -r DHT22 - mkdir DHT22 - cd DHT22 - wget https://github.com/adafruit/Adafruit_Python_DHT/archive/master.zip - unzip master.zip - cd Adafruit_Python_DHT-master - sudo python setup.py install - cd /home/pi -fi -} - - -install_SPIlib () -{ - - -# --- INSTALL SPI library: - -sudo apt-get -y install python2.7-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/SPI/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/SPI - unzip master.zip - cd py-spidev-master - sudo python setup.py install - cd /home/pi -else - -cd /home/pi -sudo rm -r SPIDEV -mkdir SPIDEV -cd SPIDEV - -wget https://github.com/Gadgetoid/py-spidev/archive/master.zip - -unzip master.zip - -rm master.zip - -cd py-spidev-master - -sudo python setup.py install - -cd .. -cd .. - -fi -} - - -install_BMPlib () -{ - -# --- INSTALL BMP180 library (pressure sensor) - -sudo apt-get -y install build-essential python-dev python-smbus || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/BMP/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/BMP - unzip master.zip - cd Adafruit_Python_BMP-master - sudo python setup.py install - cd /home/pi -else - -cd /home/pi -sudo rm -r bmp180 -sudo mkdir bmp180 -cd bmp180 -wget https://github.com/adafruit/Adafruit_Python_BMP/archive/master.zip -cd Adafruit_Python_BMP-master -sudo python setup.py install -cd .. -cd .. - -fi -} - - -install_hydrosys4 () -{ -# --- INSTALL Hydrosys4 software -sudo apt-get -y install git || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - - -# check if file exist in local folder -aconf="/home/pi/env/autonom" -if [ -d $aconf ]; then # if the directory exist - cd /home/pi -else - cd /home/pi - sudo rm -r env - mkdir env - cd env - sudo rm -r autonom - git clone https://github.com/Hydrosys4/Master.git - sudo killall python - mv Master autonom - cd .. - -fi - -} - - - - - - -fn_hostapd () -{ - -sudo apt-get -y install hostapd || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - - -# create hostapd.conf file -aconf="/etc/hostapd/hostapd.conf" -if [ -f $aconf ]; then - cp $aconf $aconf.1 - sudo rm $aconf - echo "remove file" -fi - - -sudo bash -c "cat >> $aconf" << EOF -# HERE-> {"name": "IPsetting", "LocalIPaddress": "$IP", "LocalPORT": "$PORT", "LocalAPSSID" : "$WiFiAPname"} -ieee80211n=1 -interface=wlan0 -ssid=$WiFiAPname -hw_mode=g -channel=6 -macaddr_acl=0 -auth_algs=1 -ignore_broadcast_ssid=0 -wpa=2 -wpa_passphrase=$WiFiAPpsw -wpa_key_mgmt=WPA-PSK -wpa_pairwise=TKIP -rsn_pairwise=CCMP -EOF - - -aconf="/etc/init.d/hostapd" -# Update hostapd main config file -sudo sed -i "s/\(^.*DAEMON_CONF=.*$\)/DAEMON_CONF=\/etc\/hostapd\/hostapd.conf/" $aconf - -sudo systemctl enable hostapd.service - -} - - -fn_dnsmasq () -{ - -sudo apt-get -y install dnsmasq || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - - -# edit /etc/dnsmasq.conf file -aconf="/etc/dnsmasq.conf" - -# delete rows between #START and #END -sed -i '/^#START HYDROSYS4 SECTION/,/^#END HYDROSYS4 SECTION/{/^#START HYDROSYS4 SECTION/!{/^#END HYDROSYS4 SECTION/!d}}' $aconf -sed -i '/#START HYDROSYS4 SECTION/d' $aconf -sed -i '/#END HYDROSYS4 SECTION/d' $aconf - -# calculation of the range starting from assigned IP address -IFS="." read -a a <<< $IP -IFS="." read -a b <<< 0.0.0.1 -IFS="." read -a c <<< 0.0.0.9 -IPSTART="$[a[0]].$[a[1]].$[a[2]].$[a[3]+b[3]]" -IPEND="$[a[0]].$[a[1]].$[a[2]].$[a[3]+c[3]]" -if [[ a[3] -gt 244 ]]; then -IPSTART="$[a[0]].$[a[1]].$[a[2]].$[a[3]-c[3]]" -IPEND="$[a[0]].$[a[1]].$[a[2]].$[a[3]-b[3]]" -fi - -echo $IPSTART $IPEND - - - -# ----- - - - -sudo bash -c "cat >> $aconf" << EOF -#START HYDROSYS4 SECTION -interface=wlan0 -dhcp-range=$IPSTART,$IPEND,12h -#no-resolv -#END HYDROSYS4 SECTION -EOF - -sudo systemctl enable dnsmasq.service - - -} - - -fn_dhcpcd () -{ - -# edit /etc/dnsmasq.conf file -aconf="/etc/dhcpcd.conf" - -# delete rows between #START and #END -sed -i '/^#START HYDROSYS4 SECTION/,/^#END HYDROSYS4 SECTION/{/^#START HYDROSYS4 SECTION/!{/^#END HYDROSYS4 SECTION/!d}}' $aconf -sed -i '/#START HYDROSYS4 SECTION/d' $aconf -sed -i '/#END HYDROSYS4 SECTION/d' $aconf - - -sudo bash -c "cat >> $aconf" << EOF -#START HYDROSYS4 SECTION -profile static_wlan0 -static ip_address=$IP/24 -#static routers=192.168.1.1 -#static domain_name_servers=192.169.1.1 -# fallback to static profile on wlan0 -interface wlan0 -fallback static_wlan0 -#END HYDROSYS4 SECTION -EOF - - -} - -fn_ifnames () -{ -# this is to preserve the network interfaces names, becasue staring from debian stretch (9) the ifnames have new rules -# edit /etc/dnsmasq.conf file -aconf="/boot/cmdline.txt" - -APPEND=' net.ifnames=0' -echo "$(cat $aconf)$APPEND" > $aconf - -} - - - - - - - - - -install_mjpegstr () -{ -cd /home/pi - -sudo rm -r mjpg-streamer - -sudo apt-get -y install cmake libjpeg8-dev git - -sudo git clone https://github.com/jacksonliam/mjpg-streamer.git - -cd mjpg-streamer/mjpg-streamer-experimental - -sudo make - -sudo make install - -cd .. -cd .. - -} - - - -install_nginx () -{ -# this function is not used anymore -cd /home/pi - -sudo apt-get -y install nginx - -# create default file -aconf="/etc/nginx/sites-enabled/default" -if [ -f $aconf ]; then - cp $aconf /home/pi/$aconf.1 - sudo rm $aconf - echo "remove file" -fi - - -sudo bash -c "cat >> $aconf" << EOF -server { - # for a public HTTP server: - listen $PORT; - server_name localhost hydrosys4.local; - - access_log off; - error_log off; - - location / { - proxy_pass http://127.0.0.1:5020; - } - - location /stream { - rewrite ^/stream(.*) /$1 break; - proxy_pass http://127.0.0.1:5022; - proxy_buffering off; - } - - location /favicon.ico { - alias /home/pi/env/autonom/static/favicon.ico; - } -} -EOF - -sudo service nginx start - -cd .. -cd .. - -} - - -install_squid3 () -{ -# this function is used to install the squid3 program used as reverse proxy -cd /home/pi - -sudo apt-get install squid3 -y || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -# add configuration to squid.conf, the file should already exist if installation is succesful -adir="/etc/squid3" -if [ -d $adir ]; then - aconf="/etc/squid3/squid.conf" -fi -adir="/etc/squid" -if [ -d $adir ]; then - aconf="/etc/squid/squid.conf" -fi - -if [ -f $aconf ]; then - cp $aconf $aconf.1 - sudo rm $aconf - echo "remove file" -fi - - - -sudo bash -c "cat >> $aconf" << EOF -# hydrosys4 configurations - -http_port $PORT accel defaultsite=hydrosys4 vhost - -acl Safe_ports port $PORT # unregistered ports - -acl videostream urlpath_regex \?action=stream - -cache_peer localhost parent 5020 0 no-query originserver name=server1 -cache_peer_access server1 deny videostream - -cache_peer localhost parent 5022 0 no-query originserver name=server2 -cache_peer_access server2 allow videostream -cache_peer_access server2 deny all - -http_access allow Safe_ports - -# default configurations - -# WELCOME TO SQUID 3.5.12 -acl SSL_ports port 443 -acl Safe_ports port 80 # http -acl Safe_ports port 21 # ftp -acl Safe_ports port 443 # https -acl Safe_ports port 70 # gopher -acl Safe_ports port 210 # wais -acl Safe_ports port 1025-65535 # unregistered ports -acl Safe_ports port 280 # http-mgmt -acl Safe_ports port 488 # gss-http -acl Safe_ports port 591 # filemaker -acl Safe_ports port 777 # multiling http -acl CONNECT method CONNECT -http_access deny !Safe_ports -http_access deny CONNECT !SSL_ports -http_access allow localhost manager -http_access deny manager -http_access allow localhost -http_access deny all -coredump_dir /var/spool/squid -refresh_pattern ^ftp: 1440 20% 10080 -refresh_pattern ^gopher: 1440 0% 1440 -refresh_pattern -i (/cgi-bin/|\?) 0 0% 0 -refresh_pattern (Release|Packages(.gz)*)$ 0 20% 2880 -refresh_pattern . 0 20% 4320 -EOF - -sudo service squid3 start - -cd .. -cd .. - -} - - - -edit_defaultnetworkdb () -{ - - -aconf="/home/pi/env/autonom/database/default/defnetwork.txt " - -# if file already exist then no action, otherwise create it -if [ -f $aconf ]; then - echo "network default file already exist" - else - sudo bash -c "cat >> $aconf" << EOF -{"name": "IPsetting", "LocalIPaddress": "192.168.0.172", "LocalPORT": "5012" , "LocalAPSSID" : "Hydrosys4"} -EOF - -fi - -} - -edit_networkdb () -{ - - -aconf="/home/pi/env/autonom/database/network.txt " - -# if file already exist then delete it -if [ -f $aconf ]; then - sudo rm $aconf - echo "remove file" -fi - -sudo bash -c "cat >> $aconf" << EOF -{"name": "IPsetting", "LocalIPaddress": "$IP", "LocalPORT": "$PORT", "LocalAPSSID" : "$WiFiAPname"} -EOF - - -} - - -iptables_blockports () -{ -sudo iptables -A INPUT -p tcp --dport 5020 -j DROP -sudo iptables -A INPUT -p tcp --dport 5022 -j DROP - -sudo iptables-save > /home/pi/iptables.rules - -} - - -# --- RUN the functions -killpython -input_UI -system_update_light -#system_update_UI -install_dependencies -enable_I2C -modify_RClocal -fn_hostapd -fn_dnsmasq -fn_dhcpcd -fn_ifnames -install_mjpegstr -install_squid3 -install_hydrosys4 # this should be called before the DHT22 , SPI and BMP due to local library references -install_DHT22lib -install_SPIlib -install_BMPlib -install_MotorShieldlib -edit_defaultnetworkdb -#edit_networkdb -iptables_blockports - -echo "installation is finished!!! " diff --git a/bash/install_hydrosys4v22.sh b/bash/install_hydrosys4v22.sh deleted file mode 100644 index 09e31b9..0000000 --- a/bash/install_hydrosys4v22.sh +++ /dev/null @@ -1,782 +0,0 @@ -#!/bin/bash - - -#Debug enable next 3 lines -exec 5> install.txt -BASH_XTRACEFD="5" -set -x -# ------ end debug - - -function killpython() -{ - -sudo killall python - -} - - -function system_update_light() -{ - -# ---- system_update - -sudo apt-get -y update - -} - -function system_update() -{ - -# ---- remove unnecessary packages - -sudo apt-get remove --purge libreoffice-* -sudo apt-get remove --purge wolfram-engine - - -# ---- system_update - -sudo apt-get -y update -sudo apt-get -y upgrade - -} - -function system_update_UI() -{ - -while true; do - read -p "Do you wish to update the Raspbian system (y/n)?" yn - case $yn in - [Yy]* ) system_update; break;; - [Nn]* ) break;; - * ) echo "Please answer y or n.";; - esac -done - -} - -function install_dependencies() -{ - - -#--- start installing dependencies - -sudo apt-get -y install python-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo apt-get -y install python-pip || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install flask || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install apscheduler || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install pyserial || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(for the webcam support) -sudo apt-get -y install fswebcam || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(for the image thumbnail support) -sudo apt-get -y install libjpeg-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install Pillow || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(for external IP address, using DNS) -sudo apt-get -y install dnsutils || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(encryption) -sudo pip install pbkdf2 || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(web server) -sudo pip install tornado || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -} - -function enable_I2C() -{ - -# --- Enable I2C and Spi : -# /boot/config.txt - -sed -i 's/\(^.*#dtparam=i2c_arm=on.*$\)/dtparam=i2c_arm=on/' /boot/config.txt -sed -i 's/\(^.*#dtparam=spi=on.*$\)/dtparam=spi=on/' /boot/config.txt -sed -i 's/\(^.*#dtparam=i2s=on.*$\)/dtparam=i2s=on/' /boot/config.txt - -# --- Add modules: -# /etc/modules -aconf="/etc/modules" - -sed -i '/i2c-bcm2708/d' $aconf -sed -i -e "\$ai2c-bcm2708" $aconf - -sed -i '/i2c-dev/d' $aconf -sed -i -e "\$ai2c-dev" $aconf - -sed -i '/i2c-bcm2835/d' $aconf -sed -i -e "\$ai2c-bcm2835" $aconf - -sed -i '/rtc-ds1307/d' $aconf -sed -i -e "\$artc-ds1307" $aconf - -sed -i '/bcm2835-v4l2/d' $aconf -sed -i -e "\$abcm2835-v4l2" $aconf - - -# --- install I2C tools -sudo apt-get -y install git build-essential python-dev python-smbus || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo apt-get -y install -y i2c-tools || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -} - - -# --- enable raspicam - -############# MISSING ############## - -function modify_RClocal() -{ - -# --- Real Time Clock (RTC) -# /etc/rc.local - -autostart="yes" -# copy the below lines between # START and #END to rc.local -tmpfile=$(mktemp) -sudo sed '/#START/,/#END/d' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local -# Remove to growing plank lines. -sudo awk '!NF {if (++n <= 1) print; next}; {n=0;print}' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local -if [ "$autostart" == "yes" ]; then - if ! grep -Fq '#START HYDROSYS4 SECTION' /etc/rc.local; then - sudo sed -i '/exit 0/d' /etc/rc.local - sudo bash -c "cat >> /etc/rc.local" << EOF -#START HYDROSYS4 SECTION -# iptables -sudo iptables-restore < /home/pi/iptables.rules - -# clock -echo "HYDROSYS4-set HW clock ****************************************" -echo ds3231 0x68 > /sys/class/i2c-adapter/i2c-1/new_device || true -hwclock -s || true - -echo "HYDROSYS4-start system ****************************************" -cd /home/pi/env/autonom/ -sudo python /home/pi/env/autonom/bentornado.py & - -#END HYDROSYS4 SECTION - -exit 0 -EOF - else - tmpfile=$(mktemp) - sudo sed '/#START/,/#END/d' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local - # Remove to growing plank lines. - sudo awk '!NF {if (++n <= 1) print; next}; {n=0;print}' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local - fi - -fi - -sudo chown root:root /etc/rc.local -sudo chmod 755 /etc/rc.local -# end modification to RC.local - -} - - -### -- WIFI setup --- STANDARD - -function valid_ip() -{ - local ip=$1 - local stat=1 - - if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then - OIFS=$IFS - IFS='.' - ip=($ip) - IFS=$OIFS - [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \ - && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]] - stat=$? - fi - return $stat -} - - -input_UI () -{ - -echo "Hello, following initial setting is requested:" - -# IP part input - -IP="0" -while ! valid_ip $IP; do - read -p "Local IP address (range 192.168.0.100-192.168.1.200), to confirm press [ENTER] or modify: " -e -i 192.168.1.172 IP - if valid_ip $IP; then stat='good'; - else stat='bad'; echo "WRONG FORMAT, please enter a valid value for IP address" - fi - -done - echo "Confirmed IP address: "$IP - -PORT="" -while [[ ! $PORT =~ ^[0-9]+$ ]]; do -read -p "Local PORT, to confirm press [ENTER] or modify: " -e -i 5172 PORT - if [[ ! $PORT =~ ^[0-9]+$ ]]; - then echo "WRONG FORMAT, please enter a valid value for PORT"; - fi -done - echo "Confirmed PORT: "$PORT - -# Local WiFi AP name and password setting - -read -p "System WiFi AP name, to confirm press [ENTER] or modify: " -e -i Hydrosys4 WiFiAPname -echo "Confirmed Name: "$WiFiAPname - -read -p "System WiFi AP password, to confirm press [ENTER] or modify: " -e -i hydrosystem WiFiAPpsw -echo "Confirmed Password: "$WiFiAPpsw - -read -p "Do you want to change hostname? (y,n): " -e -i y ChangeHostName -echo "Confirmed Answer: "$ChangeHostName - -if [ "$ChangeHostName" == "y" ]; then - read -p "System Hostname, to confirm press [ENTER] or modify: " -e -i hydrosys4-172 NewHostName - echo "Confirmed Hostname: "$NewHostName -fi - -} - - -apply_newhostname () -{ - -# --- change system hostname -if [ "$ChangeHostName" == "y" ]; then - sudo hostnamectl set-hostname $NewHostName -fi - -} - - - - - - - -install_MotorShieldlib () -{ - -# --- installing the python dev-library -sudo apt-get -y install build-essential python-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/MotorHat/master.zip" -if [ -f $aconf ]; then - cd /home/pi/env/autonom/libraries/MotorHat - unzip master.zip - cd Adafruit-Motor-HAT-Python-Library-master - sudo python setup.py install - cd /home/pi -else - cd /home/pi - sudo rm -r MotorHat - mkdir MotorHat - cd MotorHat - wget https://github.com/adafruit/Adafruit-Motor-HAT-Python-Library/archive/master.zip - unzip master.zip - cd Adafruit-Motor-HAT-Python-Library-master - sudo python setup.py install - cd /home/pi -fi -} - - - - -install_DHT22lib () -{ - -# --- installing the DHT22 Sensor libraries -sudo apt-get -y install build-essential python-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/DHT22/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/DHT22 - unzip master.zip - cd Adafruit_Python_DHT-master - # setup1plus is file that try to make the DTH22 work with both RaspberryPi zero,1 and model 2,3 - sudo python setup1plus.py install - cd /home/pi -else - cd /home/pi - sudo rm -r DHT22 - mkdir DHT22 - cd DHT22 - wget https://github.com/adafruit/Adafruit_Python_DHT/archive/master.zip - unzip master.zip - cd Adafruit_Python_DHT-master - sudo python setup.py install - cd /home/pi -fi -} - - -install_SPIlib () -{ - - -# --- INSTALL SPI library: - -sudo apt-get -y install python2.7-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/SPI/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/SPI - unzip master.zip - cd py-spidev-master - sudo python setup.py install - cd /home/pi -else - -cd /home/pi -sudo rm -r SPIDEV -mkdir SPIDEV -cd SPIDEV - -wget https://github.com/Gadgetoid/py-spidev/archive/master.zip - -unzip master.zip - -rm master.zip - -cd py-spidev-master - -sudo python setup.py install - -cd .. -cd .. - -fi -} - - -install_BMPlib () -{ - -# --- INSTALL BMP180 library (pressure sensor) - -sudo apt-get -y install build-essential python-dev python-smbus || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/BMP/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/BMP - unzip master.zip - cd Adafruit_Python_BMP-master - sudo python setup.py install - cd /home/pi -else - -cd /home/pi -sudo rm -r bmp180 -sudo mkdir bmp180 -cd bmp180 -wget https://github.com/adafruit/Adafruit_Python_BMP/archive/master.zip -cd Adafruit_Python_BMP-master -sudo python setup.py install -cd .. -cd .. - -fi -} - - -install_hydrosys4 () -{ -# --- INSTALL Hydrosys4 software -sudo apt-get -y install git || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - - -# check if file exist in local folder -aconf="/home/pi/env/autonom" -if [ -d $aconf ]; then # if the directory exist - cd /home/pi -else - cd /home/pi - sudo rm -r env - mkdir env - cd env - sudo rm -r autonom - git clone https://github.com/Hydrosys4/Master.git - sudo killall python - mv Master autonom - cd .. - -fi - -} - - - - - - -fn_hostapd () -{ - -sudo apt-get -y install hostapd || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - - -# create hostapd.conf file -aconf="/etc/hostapd/hostapd.conf" -if [ -f $aconf ]; then - cp $aconf $aconf.1 - sudo rm $aconf - echo "remove file" -fi - - -sudo bash -c "cat >> $aconf" << EOF -# HERE-> {"name": "IPsetting", "LocalIPaddress": "$IP", "LocalPORT": "$PORT", "LocalAPSSID" : "$WiFiAPname"} -ieee80211n=1 -interface=wlan0 -ssid=$WiFiAPname -hw_mode=g -channel=6 -macaddr_acl=0 -auth_algs=1 -ignore_broadcast_ssid=0 -wpa=2 -wpa_passphrase=$WiFiAPpsw -wpa_key_mgmt=WPA-PSK -wpa_pairwise=TKIP -rsn_pairwise=CCMP -EOF - - -aconf="/etc/init.d/hostapd" -# Update hostapd main config file -sudo sed -i "s/\(^.*DAEMON_CONF=.*$\)/DAEMON_CONF=\/etc\/hostapd\/hostapd.conf/" $aconf - -sudo systemctl enable hostapd.service - -} - - -fn_dnsmasq () -{ - -sudo apt-get -y install dnsmasq || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - - -# edit /etc/dnsmasq.conf file -aconf="/etc/dnsmasq.conf" - -# delete rows between #START and #END -sed -i '/^#START HYDROSYS4 SECTION/,/^#END HYDROSYS4 SECTION/{/^#START HYDROSYS4 SECTION/!{/^#END HYDROSYS4 SECTION/!d}}' $aconf -sed -i '/#START HYDROSYS4 SECTION/d' $aconf -sed -i '/#END HYDROSYS4 SECTION/d' $aconf - -# calculation of the range starting from assigned IP address -IFS="." read -a a <<< $IP -IFS="." read -a b <<< 0.0.0.1 -IFS="." read -a c <<< 0.0.0.9 -IPSTART="$[a[0]].$[a[1]].$[a[2]].$[a[3]+b[3]]" -IPEND="$[a[0]].$[a[1]].$[a[2]].$[a[3]+c[3]]" -if [[ a[3] -gt 244 ]]; then -IPSTART="$[a[0]].$[a[1]].$[a[2]].$[a[3]-c[3]]" -IPEND="$[a[0]].$[a[1]].$[a[2]].$[a[3]-b[3]]" -fi - -echo $IPSTART $IPEND - - - -# ----- - - - -sudo bash -c "cat >> $aconf" << EOF -#START HYDROSYS4 SECTION -interface=wlan0 -dhcp-range=$IPSTART,$IPEND,12h -#no-resolv -#END HYDROSYS4 SECTION -EOF - -sudo systemctl enable dnsmasq.service - - -} - - -fn_dhcpcd () -{ - -# edit /etc/dnsmasq.conf file -aconf="/etc/dhcpcd.conf" - -# delete rows between #START and #END -sed -i '/^#START HYDROSYS4 SECTION/,/^#END HYDROSYS4 SECTION/{/^#START HYDROSYS4 SECTION/!{/^#END HYDROSYS4 SECTION/!d}}' $aconf -sed -i '/#START HYDROSYS4 SECTION/d' $aconf -sed -i '/#END HYDROSYS4 SECTION/d' $aconf - - -sudo bash -c "cat >> $aconf" << EOF -#START HYDROSYS4 SECTION -profile static_wlan0 -static ip_address=$IP/24 -#static routers=192.168.1.1 -#static domain_name_servers=192.169.1.1 -# fallback to static profile on wlan0 -interface wlan0 -fallback static_wlan0 -#END HYDROSYS4 SECTION -EOF - - -} - -fn_ifnames () -{ -# this is to preserve the network interfaces names, becasue staring from debian stretch (9) the ifnames have new rules -# edit /etc/dnsmasq.conf file -aconf="/boot/cmdline.txt" - -APPEND=' net.ifnames=0' -echo "$(cat $aconf)$APPEND" > $aconf - -} - - - - - - - - - -install_mjpegstr () -{ -cd /home/pi - -sudo rm -r mjpg-streamer - -sudo apt-get -y install cmake libjpeg8-dev git - -sudo git clone https://github.com/jacksonliam/mjpg-streamer.git - -cd mjpg-streamer/mjpg-streamer-experimental - -sudo make - -sudo make install - -cd .. -cd .. - -} - - - -install_nginx () -{ -# this function is not used anymore -cd /home/pi - -sudo apt-get -y install nginx - -# create default file -aconf="/etc/nginx/sites-enabled/default" -if [ -f $aconf ]; then - cp $aconf /home/pi/$aconf.1 - sudo rm $aconf - echo "remove file" -fi - - -sudo bash -c "cat >> $aconf" << EOF -server { - # for a public HTTP server: - listen $PORT; - server_name localhost hydrosys4.local; - - access_log off; - error_log off; - - location / { - proxy_pass http://127.0.0.1:5020; - } - - location /stream { - rewrite ^/stream(.*) /$1 break; - proxy_pass http://127.0.0.1:5022; - proxy_buffering off; - } - - location /favicon.ico { - alias /home/pi/env/autonom/static/favicon.ico; - } -} -EOF - -sudo service nginx start - -cd .. -cd .. - -} - - -install_squid3 () -{ -# this function is used to install the squid3 program used as reverse proxy -cd /home/pi - -sudo apt-get install squid3 -y || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -# add configuration to squid.conf, the file should already exist if installation is succesful -adir="/etc/squid3" -if [ -d $adir ]; then - aconf="/etc/squid3/squid.conf" -fi -adir="/etc/squid" -if [ -d $adir ]; then - aconf="/etc/squid/squid.conf" -fi - -if [ -f $aconf ]; then - cp $aconf $aconf.1 - sudo rm $aconf - echo "remove file" -fi - - - -sudo bash -c "cat >> $aconf" << EOF -# hydrosys4 configurations - -http_port $PORT accel defaultsite=hydrosys4 vhost - -acl Safe_ports port $PORT # unregistered ports - -acl videostream urlpath_regex \?action=stream - -cache_peer localhost parent 5020 0 no-query originserver name=server1 -cache_peer_access server1 deny videostream - -cache_peer localhost parent 5022 0 no-query originserver name=server2 -cache_peer_access server2 allow videostream -cache_peer_access server2 deny all - -http_access allow Safe_ports - -# default configurations - -# WELCOME TO SQUID 3.5.12 -acl SSL_ports port 443 -acl Safe_ports port 80 # http -acl Safe_ports port 21 # ftp -acl Safe_ports port 443 # https -acl Safe_ports port 70 # gopher -acl Safe_ports port 210 # wais -acl Safe_ports port 1025-65535 # unregistered ports -acl Safe_ports port 280 # http-mgmt -acl Safe_ports port 488 # gss-http -acl Safe_ports port 591 # filemaker -acl Safe_ports port 777 # multiling http -acl CONNECT method CONNECT -http_access deny !Safe_ports -http_access deny CONNECT !SSL_ports -http_access allow localhost manager -http_access deny manager -http_access allow localhost -http_access deny all -coredump_dir /var/spool/squid -refresh_pattern ^ftp: 1440 20% 10080 -refresh_pattern ^gopher: 1440 0% 1440 -refresh_pattern -i (/cgi-bin/|\?) 0 0% 0 -refresh_pattern (Release|Packages(.gz)*)$ 0 20% 2880 -refresh_pattern . 0 20% 4320 -EOF - -sudo service squid3 start - -cd .. -cd .. - -} - - - -edit_defaultnetworkdb () -{ - - -aconf="/home/pi/env/autonom/database/default/defnetwork.txt " - -# if file already exist then no action, otherwise create it -if [ -f $aconf ]; then - echo "network default file already exist" - else - sudo bash -c "cat >> $aconf" << EOF -{"name": "IPsetting", "LocalIPaddress": "192.168.0.172", "LocalPORT": "5012" , "LocalAPSSID" : "Hydrosys4"} -EOF - -fi - -} - -edit_networkdb () -{ - - -aconf="/home/pi/env/autonom/database/network.txt " - -# if file already exist then delete it -if [ -f $aconf ]; then - sudo rm $aconf - echo "remove file" -fi - -sudo bash -c "cat >> $aconf" << EOF -{"name": "IPsetting", "LocalIPaddress": "$IP", "LocalPORT": "$PORT", "LocalAPSSID" : "$WiFiAPname"} -EOF - - -} - - -iptables_blockports () -{ -sudo iptables -A INPUT -p tcp --dport 5020 -j DROP -sudo iptables -A INPUT -p tcp --dport 5022 -j DROP - -sudo iptables-save > /home/pi/iptables.rules - -} - - -# --- RUN the functions -killpython -input_UI -system_update_light -#system_update_UI -install_dependencies -enable_I2C -modify_RClocal -fn_hostapd -fn_dnsmasq -fn_dhcpcd -fn_ifnames -install_mjpegstr -install_squid3 -install_hydrosys4 # this should be called before the DHT22 , SPI and BMP due to local library references -install_DHT22lib -install_SPIlib -install_BMPlib -install_MotorShieldlib -edit_defaultnetworkdb -#edit_networkdb -iptables_blockports -apply_newhostname -echo "installation is finished!!! " diff --git a/bash/install_hydrosys4v23.sh b/bash/install_hydrosys4v23.sh deleted file mode 100644 index 2c20608..0000000 --- a/bash/install_hydrosys4v23.sh +++ /dev/null @@ -1,803 +0,0 @@ -#!/bin/bash - - -#Debug enable next 3 lines -exec 5> install.txt -BASH_XTRACEFD="5" -set -x -# ------ end debug - - -function killpython() -{ - -sudo killall python - -} - - -function system_update_light() -{ - -# ---- system_update - -sudo apt-get -y update - -} - -function system_update() -{ - -# ---- remove unnecessary packages - -sudo apt-get remove --purge libreoffice-* -sudo apt-get remove --purge wolfram-engine - - -# ---- system_update - -sudo apt-get -y update -sudo apt-get -y upgrade - -} - -function system_update_UI() -{ - -while true; do - read -p "Do you wish to update the Raspbian system (y/n)?" yn - case $yn in - [Yy]* ) system_update; break;; - [Nn]* ) break;; - * ) echo "Please answer y or n.";; - esac -done - -} - -function install_dependencies() -{ - - -#--- start installing dependencies - -sudo apt-get -y install python-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo apt-get -y install python-pip || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install flask || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install apscheduler || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install pyserial || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(for the webcam support) -sudo apt-get -y install fswebcam || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(for the image thumbnail support) -sudo apt-get -y install libjpeg-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo pip install Pillow || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(for external IP address, using DNS) -sudo apt-get -y install dnsutils || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(encryption) -sudo pip install pbkdf2 || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -#(web server) -sudo pip install tornado || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -} - -function enable_I2C() -{ - -# --- Enable I2C and Spi : -# /boot/config.txt - -sed -i 's/\(^.*#dtparam=i2c_arm=on.*$\)/dtparam=i2c_arm=on/' /boot/config.txt -sed -i 's/\(^.*#dtparam=spi=on.*$\)/dtparam=spi=on/' /boot/config.txt -sed -i 's/\(^.*#dtparam=i2s=on.*$\)/dtparam=i2s=on/' /boot/config.txt - -# --- Add modules: -# /etc/modules -aconf="/etc/modules" - -sed -i '/i2c-bcm2708/d' $aconf -sed -i -e "\$ai2c-bcm2708" $aconf - -sed -i '/i2c-dev/d' $aconf -sed -i -e "\$ai2c-dev" $aconf - -sed -i '/i2c-bcm2835/d' $aconf -sed -i -e "\$ai2c-bcm2835" $aconf - -sed -i '/rtc-ds1307/d' $aconf -sed -i -e "\$artc-ds1307" $aconf - -sed -i '/bcm2835-v4l2/d' $aconf -sed -i -e "\$abcm2835-v4l2" $aconf - - -# --- install I2C tools -sudo apt-get -y install git build-essential python-dev python-smbus || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} -sudo apt-get -y install -y i2c-tools || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -} - - -# --- enable raspicam - -############# MISSING ############## - -function modify_RClocal() -{ - -# --- Real Time Clock (RTC) -# /etc/rc.local - -autostart="yes" -# copy the below lines between # START and #END to rc.local -tmpfile=$(mktemp) -sudo sed '/#START/,/#END/d' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local -# Remove to growing plank lines. -sudo awk '!NF {if (++n <= 1) print; next}; {n=0;print}' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local -if [ "$autostart" == "yes" ]; then - if ! grep -Fq '#START HYDROSYS4 SECTION' /etc/rc.local; then - sudo sed -i '/exit 0/d' /etc/rc.local - sudo bash -c "cat >> /etc/rc.local" << EOF -#START HYDROSYS4 SECTION -# iptables -sudo iptables-restore < /home/pi/iptables.rules - -# clock -echo "HYDROSYS4-set HW clock ****************************************" -echo ds3231 0x68 > /sys/class/i2c-adapter/i2c-1/new_device || true -hwclock -s || true - -echo "HYDROSYS4-start system ****************************************" -cd /home/pi/env/autonom/ -sudo python /home/pi/env/autonom/bentornado.py & - -#END HYDROSYS4 SECTION - -exit 0 -EOF - else - tmpfile=$(mktemp) - sudo sed '/#START/,/#END/d' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local - # Remove to growing plank lines. - sudo awk '!NF {if (++n <= 1) print; next}; {n=0;print}' /etc/rc.local > "$tmpfile" && sudo mv "$tmpfile" /etc/rc.local - fi - -fi - -sudo chown root:root /etc/rc.local -sudo chmod 755 /etc/rc.local -# end modification to RC.local - -} - - -### -- WIFI setup --- STANDARD - -function valid_ip() -{ - local ip=$1 - local stat=1 - - if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then - OIFS=$IFS - IFS='.' - ip=($ip) - IFS=$OIFS - [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \ - && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]] - stat=$? - fi - return $stat -} - - -input_UI () -{ - -echo "Hello, following initial setting is requested:" - -# IP part input - -IP="0" -while ! valid_ip $IP; do - read -p "Local IP address (range 192.168.0.100-192.168.1.200), to confirm press [ENTER] or modify: " -e -i 192.168.1.172 IP - if valid_ip $IP; then stat='good'; - else stat='bad'; echo "WRONG FORMAT, please enter a valid value for IP address" - fi - -done - echo "Confirmed IP address: "$IP - -PORT="" -while [[ ! $PORT =~ ^[0-9]+$ ]]; do -read -p "Local PORT, to confirm press [ENTER] or modify: " -e -i 5172 PORT - if [[ ! $PORT =~ ^[0-9]+$ ]]; - then echo "WRONG FORMAT, please enter a valid value for PORT"; - fi -done - echo "Confirmed PORT: "$PORT - -# Local WiFi AP name and password setting - -read -p "System WiFi AP name, to confirm press [ENTER] or modify: " -e -i Hydrosys4 WiFiAPname -echo "Confirmed Name: "$WiFiAPname - -read -p "System WiFi AP password, to confirm press [ENTER] or modify: " -e -i hydrosystem WiFiAPpsw -echo "Confirmed Password: "$WiFiAPpsw - -read -p "Do you want to change hostname? (y,n): " -e -i y ChangeHostName -echo "Confirmed Answer: "$ChangeHostName - -if [ "$ChangeHostName" == "y" ]; then - read -p "System Hostname, to confirm press [ENTER] or modify: " -e -i hydrosys4-172 NewHostName - echo "Confirmed Hostname: "$NewHostName -fi - -} - - -apply_newhostname () -{ - -# --- change system hostname -if [ "$ChangeHostName" == "y" ]; then - sudo hostnamectl set-hostname $NewHostName -fi - -} - - -ask_reboot () -{ - - -read -p "Do you want to reboot the system? (y,n): " -e -i y doreboot -echo "Confirmed Answer: "$doreboot - -if [ "$doreboot" == "y" ]; then - sudo reboot -fi - -} - - - - -install_MotorShieldlib () -{ - -# --- installing the python dev-library -sudo apt-get -y install build-essential python-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/MotorHat/master.zip" -if [ -f $aconf ]; then - cd /home/pi/env/autonom/libraries/MotorHat - unzip master.zip - cd Adafruit-Motor-HAT-Python-Library-master - sudo python setup.py install - cd /home/pi -else - cd /home/pi - sudo rm -r MotorHat - mkdir MotorHat - cd MotorHat - wget https://github.com/adafruit/Adafruit-Motor-HAT-Python-Library/archive/master.zip - unzip master.zip - cd Adafruit-Motor-HAT-Python-Library-master - sudo python setup.py install - cd /home/pi -fi -} - - - - -install_DHT22lib () -{ - -# --- installing the DHT22 Sensor libraries -sudo apt-get -y install build-essential python-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/DHT22/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/DHT22 - unzip master.zip - cd Adafruit_Python_DHT-master - # setup1plus is file that try to make the DTH22 work with both RaspberryPi zero,1 and model 2,3 - sudo python setup1plus.py install - cd /home/pi -else - cd /home/pi - sudo rm -r DHT22 - mkdir DHT22 - cd DHT22 - wget https://github.com/adafruit/Adafruit_Python_DHT/archive/master.zip - unzip master.zip - cd Adafruit_Python_DHT-master - sudo python setup.py install - cd /home/pi -fi -} - - -install_SPIlib () -{ - - -# --- INSTALL SPI library: - -sudo apt-get -y install python2.7-dev || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/SPI/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/SPI - unzip master.zip - cd py-spidev-master - sudo python setup.py install - cd /home/pi -else - -cd /home/pi -sudo rm -r SPIDEV -mkdir SPIDEV -cd SPIDEV - -wget https://github.com/Gadgetoid/py-spidev/archive/master.zip - -unzip master.zip - -rm master.zip - -cd py-spidev-master - -sudo python setup.py install - -cd .. -cd .. - -fi -} - - -install_BMPlib () -{ - -# --- INSTALL BMP180 library (pressure sensor) - -sudo apt-get -y install build-essential python-dev python-smbus || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - - -# check if file exist in local folder -aconf="/home/pi/env/autonom/libraries/BMP/master.zip" -if [ -f $aconf ]; then - - cd /home/pi/env/autonom/libraries/BMP - unzip master.zip - cd Adafruit_Python_BMP-master - sudo python setup.py install - cd /home/pi -else - -cd /home/pi -sudo rm -r bmp180 -sudo mkdir bmp180 -cd bmp180 -wget https://github.com/adafruit/Adafruit_Python_BMP/archive/master.zip -cd Adafruit_Python_BMP-master -sudo python setup.py install -cd .. -cd .. - -fi -} - - -install_hydrosys4 () -{ -# --- INSTALL Hydrosys4 software -sudo apt-get -y install git || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - - -# check if file exist in local folder -aconf="/home/pi/env/autonom" -if [ -d $aconf ]; then # if the directory exist - cd /home/pi -else - cd /home/pi - sudo rm -r env - mkdir env - cd env - sudo rm -r autonom - git clone https://github.com/Hydrosys4/Master.git - sudo killall python - mv Master autonom - cd .. - -fi - -} - - - - - - -fn_hostapd () -{ - -sudo apt-get -y install hostapd || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -# unmask the service -sudo systemctl unmask hostapd.service - -# create hostapd.conf file -aconf="/etc/hostapd/hostapd.conf" -if [ -f $aconf ]; then - cp $aconf $aconf.1 - sudo rm $aconf - echo "remove file" -fi - - -sudo bash -c "cat >> $aconf" << EOF -# HERE-> {"name": "IPsetting", "LocalIPaddress": "$IP", "LocalPORT": "$PORT", "LocalAPSSID" : "$WiFiAPname"} -ieee80211n=1 -interface=wlan0 -ssid=$WiFiAPname -hw_mode=g -channel=6 -macaddr_acl=0 -auth_algs=1 -ignore_broadcast_ssid=0 -wpa=2 -wpa_passphrase=$WiFiAPpsw -wpa_key_mgmt=WPA-PSK -wpa_pairwise=TKIP -rsn_pairwise=CCMP -EOF - - -aconf="/etc/init.d/hostapd" -# Update hostapd main config file -sudo sed -i "s/\(^.*DAEMON_CONF=.*$\)/DAEMON_CONF=\/etc\/hostapd\/hostapd.conf/" $aconf - -aconf="/etc/default/hostapd" -# Update hostapd main config file -sudo sed -i "s/\(^.*DAEMON_CONF=.*$\)/DAEMON_CONF=\/etc\/hostapd\/hostapd.conf/" $aconf - -sudo systemctl enable hostapd.service - -} - - -fn_dnsmasq () -{ - -sudo apt-get -y install dnsmasq || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - - -# edit /etc/dnsmasq.conf file -aconf="/etc/dnsmasq.conf" - -# delete rows between #START and #END -sed -i '/^#START HYDROSYS4 SECTION/,/^#END HYDROSYS4 SECTION/{/^#START HYDROSYS4 SECTION/!{/^#END HYDROSYS4 SECTION/!d}}' $aconf -sed -i '/#START HYDROSYS4 SECTION/d' $aconf -sed -i '/#END HYDROSYS4 SECTION/d' $aconf - -# calculation of the range starting from assigned IP address -IFS="." read -a a <<< $IP -IFS="." read -a b <<< 0.0.0.1 -IFS="." read -a c <<< 0.0.0.9 -IPSTART="$[a[0]].$[a[1]].$[a[2]].$[a[3]+b[3]]" -IPEND="$[a[0]].$[a[1]].$[a[2]].$[a[3]+c[3]]" -if [[ a[3] -gt 244 ]]; then -IPSTART="$[a[0]].$[a[1]].$[a[2]].$[a[3]-c[3]]" -IPEND="$[a[0]].$[a[1]].$[a[2]].$[a[3]-b[3]]" -fi - -echo $IPSTART $IPEND - - - -# ----- - - - -sudo bash -c "cat >> $aconf" << EOF -#START HYDROSYS4 SECTION -interface=wlan0 -dhcp-range=$IPSTART,$IPEND,12h -#no-resolv -#END HYDROSYS4 SECTION -EOF - -sudo systemctl enable dnsmasq.service - - -} - - -fn_dhcpcd () -{ - -# edit /etc/dnsmasq.conf file -aconf="/etc/dhcpcd.conf" - -# delete rows between #START and #END -sed -i '/^#START HYDROSYS4 SECTION/,/^#END HYDROSYS4 SECTION/{/^#START HYDROSYS4 SECTION/!{/^#END HYDROSYS4 SECTION/!d}}' $aconf -sed -i '/#START HYDROSYS4 SECTION/d' $aconf -sed -i '/#END HYDROSYS4 SECTION/d' $aconf - - -sudo bash -c "cat >> $aconf" << EOF -#START HYDROSYS4 SECTION -profile static_wlan0 -static ip_address=$IP/24 -#static routers=192.168.1.1 -#static domain_name_servers=192.169.1.1 -# fallback to static profile on wlan0 -interface wlan0 -fallback static_wlan0 -#END HYDROSYS4 SECTION -EOF - - -} - -fn_ifnames () -{ -# this is to preserve the network interfaces names, becasue staring from debian stretch (9) the ifnames have new rules -# edit /etc/dnsmasq.conf file -aconf="/boot/cmdline.txt" - -APPEND=' net.ifnames=0' -echo "$(cat $aconf)$APPEND" > $aconf - -} - - - - - - - - - -install_mjpegstr () -{ -cd /home/pi - -sudo rm -r mjpg-streamer - -sudo apt-get -y install cmake libjpeg8-dev git - -sudo git clone https://github.com/jacksonliam/mjpg-streamer.git - -cd mjpg-streamer/mjpg-streamer-experimental - -sudo make - -sudo make install - -cd .. -cd .. - -} - - - -install_nginx () -{ -# this function is not used anymore -cd /home/pi - -sudo apt-get -y install nginx - -# create default file -aconf="/etc/nginx/sites-enabled/default" -if [ -f $aconf ]; then - cp $aconf /home/pi/$aconf.1 - sudo rm $aconf - echo "remove file" -fi - - -sudo bash -c "cat >> $aconf" << EOF -server { - # for a public HTTP server: - listen $PORT; - server_name localhost; - - access_log off; - error_log off; - - location / { - proxy_pass http://127.0.0.1:5020; - } - - location /stream { - rewrite ^/stream/(.*) /$1 break; - proxy_pass http://127.0.0.1:5022; - proxy_buffering off; - } - - location /favicon.ico { - alias /home/pi/env/autonom/static/favicon.ico; - } -} -EOF - -sudo service nginx start - -cd .. -cd .. - -} - - -install_squid3 () -{ -# this function is used to install the squid3 program used as reverse proxy -cd /home/pi - -sudo apt-get install squid3 -y || { echo "ERROR --------------------------Installation failed ----------------" && exit ;} - -# add configuration to squid.conf, the file should already exist if installation is succesful -adir="/etc/squid3" -if [ -d $adir ]; then - aconf="/etc/squid3/squid.conf" -fi -adir="/etc/squid" -if [ -d $adir ]; then - aconf="/etc/squid/squid.conf" -fi - -if [ -f $aconf ]; then - cp $aconf $aconf.1 - sudo rm $aconf - echo "remove file" -fi - - - -sudo bash -c "cat >> $aconf" << EOF -# hydrosys4 configurations - -http_port $PORT accel defaultsite=hydrosys4 vhost - -acl Safe_ports port $PORT # unregistered ports - -acl videostream urlpath_regex \?action=stream - -cache_peer localhost parent 5020 0 no-query originserver name=server1 -cache_peer_access server1 deny videostream - -cache_peer localhost parent 5022 0 no-query originserver name=server2 -cache_peer_access server2 allow videostream -cache_peer_access server2 deny all - -http_access allow Safe_ports - -# default configurations - -# WELCOME TO SQUID 3.5.12 -acl SSL_ports port 443 -acl Safe_ports port 80 # http -acl Safe_ports port 21 # ftp -acl Safe_ports port 443 # https -acl Safe_ports port 70 # gopher -acl Safe_ports port 210 # wais -acl Safe_ports port 1025-65535 # unregistered ports -acl Safe_ports port 280 # http-mgmt -acl Safe_ports port 488 # gss-http -acl Safe_ports port 591 # filemaker -acl Safe_ports port 777 # multiling http -acl CONNECT method CONNECT -http_access deny !Safe_ports -http_access deny CONNECT !SSL_ports -http_access allow localhost manager -http_access deny manager -http_access allow localhost -http_access deny all -coredump_dir /var/spool/squid -refresh_pattern ^ftp: 1440 20% 10080 -refresh_pattern ^gopher: 1440 0% 1440 -refresh_pattern -i (/cgi-bin/|\?) 0 0% 0 -refresh_pattern (Release|Packages(.gz)*)$ 0 20% 2880 -refresh_pattern . 0 20% 4320 -EOF - -sudo service squid3 start - -cd .. -cd .. - -} - - - -edit_defaultnetworkdb () -{ - - -aconf="/home/pi/env/autonom/database/default/defnetwork.txt " - -# if file already exist then no action, otherwise create it -if [ -f $aconf ]; then - echo "network default file already exist" - else - sudo bash -c "cat >> $aconf" << EOF -{"name": "IPsetting", "LocalIPaddress": "192.168.0.172", "LocalPORT": "5012" , "LocalAPSSID" : "Hydrosys4"} -EOF - -fi - -} - -edit_networkdb () -{ - - -aconf="/home/pi/env/autonom/database/network.txt " - -# if file already exist then delete it -if [ -f $aconf ]; then - sudo rm $aconf - echo "remove file" -fi - -sudo bash -c "cat >> $aconf" << EOF -{"name": "IPsetting", "LocalIPaddress": "$IP", "LocalPORT": "$PORT", "LocalAPSSID" : "$WiFiAPname"} -EOF - - -} - - -iptables_blockports () -{ -sudo iptables -A INPUT -p tcp -s localhost --dport 5020 -j ACCEPT -sudo iptables -A INPUT -p tcp -s localhost --dport 5022 -j ACCEPT -sudo iptables -A INPUT -p tcp --dport 5020 -j DROP -sudo iptables -A INPUT -p tcp --dport 5022 -j DROP - -sudo iptables-save > /home/pi/iptables.rules - -} - - -# --- RUN the functions -killpython -input_UI -system_update_light -#system_update_UI -install_dependencies -enable_I2C -modify_RClocal -fn_hostapd -fn_dnsmasq -fn_dhcpcd -fn_ifnames -install_mjpegstr -#install_squid3 -install_nginx -install_hydrosys4 # this should be called before the DHT22 , SPI and BMP due to local library references -install_DHT22lib -install_SPIlib -install_BMPlib -install_MotorShieldlib -edit_defaultnetworkdb -#edit_networkdb -iptables_blockports -apply_newhostname -echo "installation is finished!!! " -ask_reboot diff --git a/camera_pi (picamera).py b/camera_pi (picamera).py old mode 100644 new mode 100755 index 48696ba..9f6f4c0 --- a/camera_pi (picamera).py +++ b/camera_pi (picamera).py @@ -1,3 +1,4 @@ +from builtins import object import time import io import threading diff --git a/camera_pi.py b/camera_pi.py old mode 100644 new mode 100755 index a2899a0..18bc8d4 --- a/camera_pi.py +++ b/camera_pi.py @@ -1,3 +1,4 @@ +from builtins import object import time import io import threading diff --git a/cameradbmod.py b/cameradbmod.py old mode 100644 new mode 100755 index ebfe852..c237ed7 --- a/cameradbmod.py +++ b/cameradbmod.py @@ -2,7 +2,9 @@ """ camera setting storage utilities """ +from __future__ import print_function +from builtins import str import logging import os import os.path @@ -31,7 +33,7 @@ if not filestoragemod.readfiledata(DATAFILENAME,data): #read watering setting file #read from default file filestoragemod.readfiledata(DEFDATAFILENAME,data) - print "Watering writing default calibration data" + print("Watering writing default calibration data") filestoragemod.savefiledata(DATAFILENAME,data) # end read data ----- diff --git a/changelog/change b/changelog/change old mode 100644 new mode 100755 index 7f8684c..41b0006 --- a/changelog/change +++ b/changelog/change @@ -583,6 +583,49 @@ Verified clock setting behavior, when the Internet connection is present the set - Improve interrupt Counter Algorithm. +2020-04-22 -> release 116b-117 + +- Made SlowWire independent +- introducing Weather forrecast provider interface + +2020-04-24 -> release 117a + +- Weather forecast GUI and Query + +2020-04-28 -> release 117f + +- Autotesting procedure + +2020-05-04 -> release 118 + +- Add weaterAPI file export inport + +2020-05-10 -> release 318e + +- Upgrade whole project to python3 +- New bash installer +- Fixed ugrade issues (IPextrernal, Photo, and a bunch of other). Probably some more bugs will be catch later during testing +- Drop some old lybrary support + +2020-05-11 -> release 319 + +- fix pressuresensor reading when error +- Fixed Upload all confing with name different than default + +2020-05-11 -> release 319 + +- fix pressuresensor reading when error +- Fixed Upload all confing with name different than default + +2020-05-11 -> release 319a + +- fix graph representation when "oneshot" scheduler type +- autowatering change to utcnow() +- fix the graphical view of teh interrupt + +2020-05-13 -> release 319c + +- Minor graphic changes ------- Future releases: ----------- diff --git a/clockdbmod.py b/clockdbmod.py old mode 100644 new mode 100755 index 93b7e1f..155ab79 --- a/clockdbmod.py +++ b/clockdbmod.py @@ -2,6 +2,7 @@ """ fertilizer UI setting storage utilities """ +from __future__ import print_function #import logging import os @@ -45,7 +46,7 @@ def changesavesetting(FTparameter,FTvalue): searchvalue="clock" isok=filestoragemod.savechange(DATAFILENAME,searchfield,searchvalue,FTparameter,FTvalue) if not isok: - print "problem saving paramete" + print("problem saving paramete") return isok def restoredefault(): @@ -76,7 +77,7 @@ def get_path(): changesavesetting("timezone",timezone) - print gettimezone() + print(gettimezone()) diff --git a/clockmod.py b/clockmod.py old mode 100644 new mode 100755 index cd2c5dd..61665bf --- a/clockmod.py +++ b/clockmod.py @@ -1,3 +1,4 @@ +from __future__ import print_function import logging import sys import time @@ -17,7 +18,7 @@ timezone=clockdbmod.gettimezone() os.environ['TZ'] = timezone time.tzset() -print "timezone set to ->", timezone +print("timezone set to ->", timezone) #logger.info('Timezone Set to = %s', timezone) # if this is enabled,for some reason the whole logging become empty @@ -28,7 +29,7 @@ def timediffinsec(timestr1, timestr2): datetime1=datetime.strptime(timestr1, DATEFORMAT) datetime2=datetime.strptime(timestr2, DATEFORMAT) except: - print "Time in wrong format, not able to make diffsec " + print("Time in wrong format, not able to make diffsec ") return 0 delta=datetime2-datetime1 timediff=abs(delta.total_seconds()) @@ -45,19 +46,19 @@ def getNTPTime(host = "pool.ntp.org"): msg = '\x1b' + 47 * '\0' # reference time (in seconds since 1900-01-01 00:00:00) - TIME1970 = 2208988800L # 1970-01-01 00:00:00 + TIME1970 = 2208988800 # 1970-01-01 00:00:00 # connect to server try: client = socket.socket( AF_INET, SOCK_DGRAM) client.settimeout(2) - client.sendto(msg, address) + client.sendto(msg.encode(), address) msg, address = client.recvfrom( buf ) - except socket.timeout, e: - print "server timeout" + except socket.timeout as e: + print("server timeout") return "" - except socket.error, e: - print "connection error" + except socket.error as e: + print("connection error") return "" if msg: @@ -72,24 +73,24 @@ def getNTPTime(host = "pool.ntp.org"): strvalue=convertUTCtoLOC(strvalueUTC) return strvalue else: - print "No valid data in server answer " + print("No valid data in server answer ") return "" def getHWclock(): #need to check how to do it - print "not done" + print("not done") def setHWclock(datetime_format): datetimeUTC=convertLOCtoUTC(datetime_format) - print "Set HWclock datetime UTC ->" ,datetimeUTC + print("Set HWclock datetime UTC ->" ,datetimeUTC) datetimetype=datetime.strptime(datetimeUTC, DATEFORMAT) newformat="%d %b %Y %H:%M:%S" date_str="\"" + datetimetype.strftime(newformat) + "\"" - print "Set HW clock ->" , date_str + print("Set HW clock ->" , date_str) try: os.system('hwclock --set --date %s --localtime' % date_str) @@ -104,7 +105,7 @@ def setHWclock(datetime_format): # return " - ERROR: not able to set Hardware Clock -" return " - HardwareClock Set - " except: - print "Not able to set Hardware Clock " + print("Not able to set Hardware Clock ") #logger.error('Not able to set Hardware Clock') return "ERROR: not able to set Hardware Clock" @@ -113,14 +114,14 @@ def setHWclock(datetime_format): def setsystemclock(datetime_format): datetimeUTC=convertLOCtoUTC(datetime_format) - print "Set System date to datetime UTC ->" ,datetimeUTC + print("Set System date to datetime UTC ->" ,datetimeUTC) datetimetype=datetime.strptime(datetimeUTC, DATEFORMAT) - print "Set system clock ->", datetimetype + print("Set system clock ->", datetimetype) newformat="%d %b %Y %H:%M:%S" date_str="\"" + datetimetype.strftime(newformat) + "\"" - print "Datetime value format for date setting ", date_str + print("Datetime value format for date setting ", date_str) try: @@ -129,14 +130,14 @@ def setsystemclock(datetime_format): newdatetime=datetime.utcnow() delta=newdatetime-datetimetype timediff=abs(delta.total_seconds()) - print "time difference ", timediff , " System date " ,newdatetime , " Set Date" , datetimetype + print("time difference ", timediff , " System date " ,newdatetime , " Set Date" , datetimetype) if timediff<60: return "- System Clock Set -" else: return " - ERROR: not able to set system Clock -" except: - print "Not able to set system Clock " + print("Not able to set system Clock ") #logger.error('Not able to set Hardware Clock') return "- ERROR: not able to set system Clock -" diff --git a/database/default/presetAPIsetting/weatherAPI.txt b/database/default/presetAPIsetting/weatherAPI.txt new file mode 100755 index 0000000..f1a6cff --- /dev/null +++ b/database/default/presetAPIsetting/weatherAPI.txt @@ -0,0 +1,74 @@ +{ +"BasicInfo": {"visible":"yes","name":"weatherAPI", "GUItype":"link", "value":"http://www.weatherapi.com/", "note":"linkback to weather provider"}, +"QueryGroup": [ + { + "QueryItems":[ + { "name":"URL","value":"http://api.weatherapi.com/v1/forecast.json?","format":"string","param":"","usedfor":"url"}, + { "name":"Key","visible":"yes","GUItype":"input","value":"","format":"string","param":"key","usedfor":"queryparam"}, + { "name":"Location","visible":"yes","GUItype":"input","value":"","format":"string","param":"q","usedfor":"queryparam"}, + { "name":"Time","value":"Time Now", "allowedvalues":["Time Now","Time +1 day","Time +2 days","Time -1 day","Time -2 days"],"format":"%Y/%m/%d","param":"dt","usedfor":"queryparam"} + ], + "ParseItems":[ + {"visible":"yes", "GUItype":"output", "name": "RainForecast+0day(mm)", "note":"This data is provided by querying the weather provider API", + "searchpath":[ + {"keyword":"forecast"}, + {"keyword":"forecastday"}, + {"keyword":"date", "match":"Time Now", "format":"%Y-%m-%d"}, + {"keyword":"day"}, + {"keyword":"totalprecip_mm"} + ] + }]}, + { + "QueryItems":[ + { "name":"URL","value":"http://api.weatherapi.com/v1/forecast.json?","format":"string","param":"","usedfor":"url"}, + { "name":"Key","visible":"yes","GUItype":"input","value":"","format":"string","param":"key","usedfor":"queryparam"}, + { "name":"Location","visible":"yes","GUItype":"input","value":"","format":"string","param":"q","usedfor":"queryparam"}, + { "name":"Time","value":"Time +1 day", "allowedvalues":["Time Now","Time +1 day","Time +2 days","Time -1 day","Time -2 days"],"format":"%Y/%m/%d","param":"dt","usedfor":"queryparam"} + ], + "ParseItems":[ + {"visible":"yes", "GUItype":"output", "name": "RainForecast+1day(mm)", "note":"This data is provided by querying the weather provider API", + "searchpath":[ + {"keyword":"forecast"}, + {"keyword":"forecastday"}, + {"keyword":"date", "match":"Time +1 day", "format":"%Y-%m-%d"}, + {"keyword":"day"}, + {"keyword":"totalprecip_mm"} + ] + }]}, + { + "QueryItems":[ + { "name":"URL","value":"http://api.weatherapi.com/v1/forecast.json?","format":"string","param":"","usedfor":"url"}, + { "name":"Key","visible":"yes","GUItype":"input","value":"","format":"string","param":"key","usedfor":"queryparam"}, + { "name":"Location","visible":"yes","GUItype":"input","value":"","format":"string","param":"q","usedfor":"queryparam"}, + { "name":"Time","value":"Time +2 days", "allowedvalues":["Time Now","Time +1 day","Time +2 days","Time -1 day","Time -2 days"],"format":"%Y/%m/%d", "param":"dt","usedfor":"queryparam"} + ], + "ParseItems":[ + {"visible":"yes", "GUItype":"output", "name": "RainForecast+2day(mm)", "note":"This data is provided by querying the weather provider API", + "searchpath":[ + {"keyword":"forecast"}, + {"keyword":"forecastday"}, + {"keyword":"date", "match":"Time +2 days", "format":"%Y-%m-%d"}, + {"keyword":"day"}, + {"keyword":"totalprecip_mm"} + ] + }]} + + ], +"CounterInfo": {"visible":"yes" , "GUItype":"title" , "name": "RainMultiplier", + "weights":[ + {"visible":"yes","name":"Weight1", "GUItype":"input", "value":"-5", "note":"Weight that will be multiplied to the first data parameter"}, + {"visible":"yes","name":"Weight2", "GUItype":"input", "value":"-2.5", "note":"Weight that will be multiplied to the second data parameter"}, + {"visible":"yes","name":"Weight3", "GUItype":"input", "value":"-1", "note":"Weight that will be multiplied to the third data parameter"} + ], + "min": { "GUItype":"output" , "name": "Min", "value": "0"}, + "max": { "GUItype":"output" , "name": "Max", "value": "100"}, + "initialValue": { "GUItype":"output" , "name": "InitialValue", "value": "100"}, + "queryintervalmin": { "GUItype":"output" , "name": "QueryIntervalmin", "value": "240"} + }, +"Wateractuators": [] +} + + + + + diff --git a/database/default/presetHWsetting/defhwdata-Temp+Humid+Press+Light+8Water.txt b/database/default/presetHWsetting/defhwdata-Temp+Humid+Press+Light+8Water.txt old mode 100644 new mode 100755 index c17adf7..128d521 --- a/database/default/presetHWsetting/defhwdata-Temp+Humid+Press+Light+8Water.txt +++ b/database/default/presetHWsetting/defhwdata-Temp+Humid+Press+Light+8Water.txt @@ -8,8 +8,8 @@ {"IOtype": "output" , "controllercmd": "pulse", "logic": "neg", "name": "water4", "pin": "19", "usefor": "watercontrol", "measure": "Time" , "unit" : "sec", "schedulingtype":"oneshot"} {"IOtype": "output" , "controllercmd": "pulse", "logic": "neg", "name": "water5", "pin": "26", "usefor": "watercontrol", "measure": "Time" , "unit" : "sec", "schedulingtype":"oneshot"} {"IOtype": "output" , "controllercmd": "pulse", "logic": "neg", "name": "water6", "pin": "12", "usefor": "watercontrol", "measure": "Time" , "unit" : "sec", "schedulingtype":"oneshot"} -{"IOtype": "output" , "controllercmd": "pulse", "logic": "neg", "name": "doser1", "pin": "20", "usefor": "fertilizercontrol", "measure": "Time" , "unit" : "sec", "schedulingtype":"oneshot"} -{"IOtype": "output" , "controllercmd": "pulse", "logic": "neg", "name": "doser2", "pin": "16", "usefor": "fertilizercontrol", "measure": "Time" , "unit" : "sec", "schedulingtype":"oneshot"} +{"IOtype": "output" , "controllercmd": "pulse", "logic": "neg", "name": "doser1", "pin": "20", "usefor": "watercontrol", "measure": "Time" , "unit" : "sec", "schedulingtype":"oneshot"} +{"IOtype": "output" , "controllercmd": "pulse", "logic": "neg", "name": "doser2", "pin": "16", "usefor": "watercontrol", "measure": "Time" , "unit" : "sec", "schedulingtype":"oneshot"} {"IOtype": "output" ,"usefor": "mailcontrol", "address": "", "controllercmd": "mail+info+link","name": "mail1", "time": "10:00", "title": "Hydrosys today report", "measure" : "Mail" , "unit" : "pcs" , "schedulingtype":"oneshot"} {"IOtype": "output" ,"usefor": "mailcontrol", "address": "", "controllercmd": "mail+info","name": "mail2", "time": "10:00", "title": "Hydrosys today report", "measure" : "Mail" , "unit" : "pcs" , "schedulingtype":"oneshot"} {"IOtype": "output" ,"usefor": "photocontrol", "controllercmd": "photo", "name": "photo", "time": "09:30", "measure" : "Photo" , "unit" : "pcs", "schedulingtype":"oneshot"} diff --git a/databasemod.py b/databasemod.py old mode 100644 new mode 100755 index 28e5bdc..0e4f513 --- a/databasemod.py +++ b/databasemod.py @@ -2,6 +2,9 @@ """ Database utility """ +from __future__ import print_function +from builtins import str +from builtins import range import basicSetting import logging import os @@ -36,15 +39,15 @@ def init_db(filename): """Creates the database tables.""" if not os.path.isfile(dbpath(filename)): #file is there conn = sqlite3.connect(dbpath(filename)) - print "create empty database" - print 'Creating schema from file' + print("create empty database") + print('Creating schema from file') schemafilename = os.path.splitext(filename)[0]+'sc.sql' if os.path.isfile(schemapath(schemafilename)): with open(schemapath(schemafilename), 'rt') as f: schema = f.read() conn.executescript(schema) else: - print filename, "database exists" + print(filename, "database exists") @@ -108,22 +111,22 @@ def columninfo(filename,table): with sqlite3.connect(dbpath(filename)) as conn: cursor = conn.cursor() cursor.execute('select * from "' + table + '"') - print 'table has these columns:' + print('table has these columns:') for colinfo in cursor.description: - print colinfo + print(colinfo) def rowdescription(filename,table,deletefirstN): with sqlite3.connect(dbpath(filename)) as conn: cursor = conn.cursor() cursor.execute('select * from "' + table + '"') - print 'table has these columns:' + print('table has these columns:') rowdata=[] for colinfo in cursor.description: rowdata.append( colinfo [0]) for i in range(deletefirstN): del rowdata[0] - print rowdata + print(rowdata) return rowdata def get_db(filename): @@ -132,11 +135,11 @@ def get_db(filename): conn = sqlite3.connect(dbpath(filename)) return conn, True except: - print "Error Reading database" + print("Error Reading database") return conn, False def getvaluelist(filename,table,field,valuelist): - print "visualizzazione field ", field + print("visualizzazione field ", field) db, connected = get_db(filename) if connected: cur = db.execute('select distinct "' + field + '" from "' + table + '" order by "' + field + '"') @@ -146,7 +149,7 @@ def getvaluelist(filename,table,field,valuelist): valuelist.append(str(na[0])) conn.close() else: - print "not able to connect to database ", filename + print("not able to connect to database ", filename) def getdatafromfields(filename,table,fieldlist,valuelist): @@ -166,7 +169,7 @@ def getdatafromfields(filename,table,fieldlist,valuelist): row.append(str(rowdata[i])) valuelist.append(row) except: - print "problem reading database " , table + print("problem reading database " , table) db.close() @@ -203,7 +206,7 @@ def getdatafromfieldslimit(filename,table,fieldlist,valuelist,limit): def deleterowwithfield(filename,table,field,value): - print "delete field ", field , " with value ", value + print("delete field ", field , " with value ", value) db, connected = get_db(filename) if connected: #remove old items from database in case the same name is already present @@ -212,7 +215,7 @@ def deleterowwithfield(filename,table,field,value): db.close() def deleteallrow(filename,table): - print "delete all row in table ", table + print("delete all row in table ", table) db, connected = get_db(filename) if connected: #remove old items from database in case the same name is already present @@ -242,7 +245,7 @@ def insertrowfields(filename,table,rowfield,rowvalue): db.commit() except: - print "Error reading the sensor database, sql querystring=",query_string + print("Error reading the sensor database, sql querystring=",query_string) db.close() @@ -289,14 +292,14 @@ def gettable(filename,dbtable,searchfield,searchvalue): #get table with column getdatafromfieldslimit(DATABASEDUMMYFILE,TABLE,["two"],valuelist,4) end = datetime.now() timeperiod = end - start - print valuelist - print timeperiod + print(valuelist) + print(timeperiod) start = datetime.now() getdatafromfields(DATABASEDUMMYFILE,TABLE,["two"],valuelist) end = datetime.now() timeperiod = end - start - print valuelist - print timeperiod + print(valuelist) + print(timeperiod) # database reading diff --git a/debuggingmod.py b/debuggingmod.py old mode 100644 new mode 100755 index 3df6792..b6b0dc2 --- a/debuggingmod.py +++ b/debuggingmod.py @@ -1,3 +1,5 @@ +from __future__ import print_function +from builtins import str import logging import subprocess import filestoragemod @@ -15,7 +17,7 @@ def createfiletailsyslog(dstfile): filestoragemod.savefiledata_plaintext(dstfile,data) return True else: - print "data empty" + print("data empty") return False @@ -34,7 +36,7 @@ def searchsyslogkeyword(keyword): return extract def searchLOGkeyword(filename,keyword): - print "debugging check errors in: ", filename + print("debugging check errors in: ", filename) rownumber="300" data=tailLOGcmd(filename,rownumber) numrowafter=10 @@ -63,7 +65,7 @@ def execcommand(cmd): try: scanoutput = subprocess.check_output(cmd).decode('utf-8') except: - print "error to execute the command" , cmd + print("error to execute the command" , cmd) logger.error("error to execute the command %s",cmd) return [] return scanoutput.split('\n') @@ -74,5 +76,5 @@ def execcommand(cmd): if __name__ == '__main__': # comment #a=[] - print "Hello" + print("Hello") diff --git a/emaildbmod.py b/emaildbmod.py old mode 100644 new mode 100755 index 2e35a74..f3e3b70 --- a/emaildbmod.py +++ b/emaildbmod.py @@ -2,6 +2,7 @@ """ fertilizer UI setting storage utilities """ +from __future__ import print_function import logging import os @@ -62,7 +63,7 @@ def changesavesetting(FTparameter,FTvalue): searchvalue="email" isok=filestoragemod.savechange(DATAFILENAME,searchfield,searchvalue,FTparameter,FTvalue) if not isok: - print "problem saving paramete" + print("problem saving paramete") return isok def restoredefault(): @@ -93,8 +94,8 @@ def get_path(): password="haha" changesavesetting("address",address) changesavesetting("password",password) - print getaddress() - print getpassword() + print(getaddress()) + print(getpassword()) diff --git a/emailmod.py b/emailmod.py old mode 100644 new mode 100755 index 74e99d7..49f36d4 --- a/emailmod.py +++ b/emailmod.py @@ -1,3 +1,6 @@ +from __future__ import print_function +from builtins import str +from builtins import range import logging import datetime import hardwaremod @@ -20,7 +23,7 @@ # GET path --------------------------------------------- global MYPATH -print "path ",hardwaremod.get_path() +print("path ",hardwaremod.get_path()) MYPATH=hardwaremod.get_path() global IPEXTERNALSENT @@ -45,9 +48,9 @@ def send_email(user, pwd, recipient, subject, body): server.login(gmail_user, gmail_pwd) server.sendmail(FROM, TO, message) server.quit() - print 'successfully sent the mail' + print('successfully sent the mail') except: - print "failed to send mail" + print("failed to send mail") def create_htmlopen(): @@ -146,7 +149,7 @@ def send_email_html(user, pwd, recipient, subject, html, showpicture): you=[] for address in recipient.split(";"): you.append(address.strip()) - print " Sending mail to : ", recipient + print(" Sending mail to : ", recipient) # Create message container - the correct MIME type is multipart/alternative. msg = MIMEMultipart() @@ -180,7 +183,7 @@ def send_email_html(user, pwd, recipient, subject, html, showpicture): for filename in imgfiles: # Open the files in binary mode. Let the MIMEImage class automatically # guess the specific image type. - print "filename " , filename + print("filename " , filename) fp = open(filename, 'rb') img = MIMEImage(fp.read()) fp.close() @@ -195,12 +198,12 @@ def send_email_html(user, pwd, recipient, subject, html, showpicture): server.login(gmail_user, gmail_pwd) server.sendmail(me, you, msg.as_string()) server.quit() - print 'successfully sent the mail' + print('successfully sent the mail') logger.info('mail sent succesfully ') return True except: logger.error('failed to send mail') - print "failed to send mail" + print("failed to send mail") return False @@ -242,7 +245,7 @@ def send_email_main(address,title,cmd,mailtype,intromessage,bodytextlist=[]): logger.info('Stored external IP address is empty, try to get it from network') ipext=networkmod.get_external_ip() - print "Try to send mail" + print("Try to send mail") # subject of the mail subject=starttitle +" " + title + " " + currentdate htmlbody=create_htmlopen() @@ -250,7 +253,7 @@ def send_email_main(address,title,cmd,mailtype,intromessage,bodytextlist=[]): if showlink: if ipext=="": - print "No external IP address available" + print("No external IP address available") logger.error('Unable to get external IP address') else: port=str(networkmod.PUBLICPORT) @@ -265,7 +268,7 @@ def send_email_main(address,title,cmd,mailtype,intromessage,bodytextlist=[]): if not customURL=="": addresslist.append(customURL) descriptionlist.append("your Link") - print "Mail url list ",addresslist + print("Mail url list ",addresslist) htmlbody=htmlbody+create_htmladdresses(descriptionlist,addresslist, port) @@ -295,15 +298,15 @@ def sendmail(hwname,mailtype,intromessage,bodytextlist=[]): address=hardwaremod.searchdata(hardwaremod.HW_INFO_NAME,hwname,hardwaremod.HW_CTRL_ADDR) if not address=="": - print "mail recipient ", address + print("mail recipient ", address) title=hardwaremod.searchdata(hardwaremod.HW_INFO_NAME,hwname,hardwaremod.HW_CTRL_TITLE) - print "mail title " , title + print("mail title " , title) cmd=hardwaremod.searchdata(hardwaremod.HW_INFO_NAME,hwname,hardwaremod.HW_CTRL_CMD) - print "mail type " , cmd + print("mail type " , cmd) issent=send_email_main(address,title,cmd,mailtype,intromessage,bodytextlist) return issent else: - print "No address specified" + print("No address specified") logger.warning('No address specified') return False diff --git a/fertilizerdbmod.py b/fertilizerdbmod.py old mode 100644 new mode 100755 index b818307..f1a4528 --- a/fertilizerdbmod.py +++ b/fertilizerdbmod.py @@ -2,7 +2,9 @@ """ fertilizer UI setting storage utilities """ +from __future__ import print_function +from builtins import str import logging import os import os.path @@ -30,7 +32,7 @@ if not filestoragemod.readfiledata(FTDATAFILENAME,FTdata): #read setting file #read from default file filestoragemod.readfiledata(DEFFTDATAFILENAME,FTdata) - print "Fertilizer writing default calibration data" + print("Fertilizer writing default calibration data") filestoragemod.savefiledata(FTDATAFILENAME,FTdata) # end read IOdata ----- diff --git a/filemanagementmod.py b/filemanagementmod.py old mode 100644 new mode 100755 index 480f4ce..9deedcf --- a/filemanagementmod.py +++ b/filemanagementmod.py @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- +from __future__ import print_function import shutil import logging import re @@ -29,7 +30,7 @@ def folderfilelist(basefolder, folder , filetype): # control if the folder exist otherwise create it if not os.path.exists(folderpath): os.makedirs(folderpath) - print " folder has been created" + print(" folder has been created") filelist=[] sortedlist=sorted([f for f in os.listdir(folderpath) if os.path.isfile(os.path.join(folderpath, f))]) @@ -52,7 +53,7 @@ def copyfiles(basefolder, filelist, relativedstfolder): dstfilename=filedata["filename"] fulldstfolder=os.path.join(basefolder, relativedstfolder) dst=os.path.join(fulldstfolder, dstfilename) - print "COPY, source = " , src, "destination =" , dst + print("COPY, source = " , src, "destination =" , dst) try: shutil.copyfile(src, dst) answer="ready" @@ -65,7 +66,7 @@ def deletefilesinfolder(basefolder, relativefolder): # control if the folder exist otherwise create it if not os.path.exists(fullfolderpath): os.makedirs(fullfolderpath) - print " folder has been created" + print(" folder has been created") return 0 sortedlist=os.listdir(fullfolderpath) @@ -92,14 +93,13 @@ def zipfolder(basefolder, relativefolder, zipfilename , relativezipfolder): def unzipfolder(basefolder, relativefolder, zipfilename , absolutezipfolder): fullfolderpath=os.path.join(basefolder, relativefolder) zipfullpath=absolutezipfolder - zipfilename=zipfilename+".zip" zipfilenamepath=os.path.join(zipfullpath, zipfilename) # control if the folder exist otherwise create it if not os.path.exists(fullfolderpath): os.makedirs(fullfolderpath) - print " folder has been created" - print "unzip file=" , zipfilenamepath + print(" folder has been created") + print("unzip file=" , zipfilenamepath) if os.path.isfile(zipfilenamepath): # unzipping @@ -132,7 +132,7 @@ def configfilezip(): filelink=ZIPCONFIGDOWNLOADPATH+"/"+zipfilename+".zip" # relative path vithout static else: filelink="" - print filelink + print(filelink) return filelink def configfileunzip(): @@ -142,19 +142,18 @@ def configfileunzip(): #delete files in download folder, or create it if not existing deletefilesinfolder(basefolder, relativedstfolder) # make unzip zip file and get link - zipfilename="allconfigfiles" + zipfilename="allconfigfiles.zip" unzipfolder(basefolder, relativedstfolder, zipfilename , relativezipfolder) filelink=ZIPCONFIGDOWNLOADPATH+"/"+zipfilename # relative path vithout static - print filelink + print(filelink) return filelink -def restoreconfigfilefromzip(absolutezipfolder): +def restoreconfigfilefromzip(absolutezipfolder, zipfilename): #zipfilename is only the filename without path, zipfilename should have .zip extension basefolder=get_path() relativedstfolder=os.path.join("static", CONFIGDOWNLOADPATH) #delete files in download folder, or create it if not existing deletefilesinfolder(basefolder, relativedstfolder) # make unzip zip file and get link - zipfilename="allconfigfiles" unzipfolder(basefolder, relativedstfolder, zipfilename , absolutezipfolder) #get config files list relativeconfigfolder=relativedstfolder @@ -185,7 +184,7 @@ def get_path(): if __name__ == '__main__': # comment - print "test copy and zip" + print("test copy and zip") configfileunzip() #restoreconfigfilefromzip() diff --git a/filestoragemod.py b/filestoragemod.py old mode 100644 new mode 100755 index d568dec..a09ff3a --- a/filestoragemod.py +++ b/filestoragemod.py @@ -2,6 +2,8 @@ """ file storage utility """ +from __future__ import print_function +from builtins import range import basicSetting import logging import os @@ -41,9 +43,37 @@ def readfiledata(filename,filedata): #print IOdata[0]["name"] return True else: - print "----------------------------------------------------------------------> warning no file ", filename + print("----------------------------------------------------------------------> warning no file ", filename) + return False + + +def readfiledata_full(filename): + if os.path.isfile(dbpath(filename)): #file is there + # read the selected table file + #in_file = open(dbpath(filename),"r") + with open(dbpath(filename)) as json_file: + try: + data = json.load(json_file) + except: + print("not able to parse Json file") + return False + json_file.close() + return data + else: + print("----------------------------------------------------------------------> warning no file ", filename) return False + + +def savefiledata_full(filename,filedata): +# questo possibile lista di dizionario: { 'name':'', 'm':0.0, 'q':0.0, 'lastupdate':'' } #variabile tipo dizionario + out_file = open(dbpath(filename),"w") + jsonStr=json.dumps(filedata, sort_keys=True, indent=4) + out_file.write(jsonStr) + out_file.close() + + + # START Plain text file functions ---------------------------------------- Used for generic file manipulation @@ -58,7 +88,7 @@ def readfiledata_plaintext(pathfilename,filedata): #return list with row of the filedata.append(ln.strip("\n")) return True else: - print "-----------------------------------------> warning no file ", pathfilename + print("-----------------------------------------> warning no file ", pathfilename) return False def savefiledata_plaintext(pathfilename,filedata): @@ -85,7 +115,7 @@ def readfiledata_spec(pathfilename,identifier,filedata): # used also in networkd #print IOdata[0]["name"] return False else: - print "------------------------------------------> warning no file ", pathfilename + print("------------------------------------------> warning no file ", pathfilename) return False @@ -96,9 +126,9 @@ def savechangerow_plaintext(pathfilename,searchvalue,newrow): # used to replace for i in range(len(filedata)): line=filedata[i] if searchvalue in line: - print " row found ------------ !!!!!!!!! " , line + print(" row found ------------ !!!!!!!!! " , line) filedata[i]=newrow - print " new row ------------ !!!!!!!!! " , newrow + print(" new row ------------ !!!!!!!!! " , newrow) savefiledata_plaintext(pathfilename,filedata) return True return False @@ -239,7 +269,7 @@ def getfieldinstringvalue(filename,fielditem,stringtofind,valuelist): savechange(FILENAME,"name","ECsensor1","q",2.0) filedata=[] readfiledata(FILENAME,filedata) - print filedata + print(filedata) diff --git a/hardwaremod.py b/hardwaremod.py old mode 100644 new mode 100755 index e20d6e7..591acd1 --- a/hardwaremod.py +++ b/hardwaremod.py @@ -2,6 +2,11 @@ """ selected plan utility """ +from __future__ import print_function +from __future__ import division +from builtins import str +from builtins import range +from past.utils import old_div import shutil import logging import re @@ -34,7 +39,7 @@ DEFHWDATAFILENAME="default/defhwdata.txt" logger = logging.getLogger("hydrosys4."+__name__) -print "logger name ", __name__ +print("logger name ", __name__) # ///////////////// -- Hawrware data structure Setting -- /////////////////////////////// #important this data is used almost everywhere @@ -109,10 +114,10 @@ IOdata=[] # read IOdata ----- if not filestoragemod.readfiledata(HWDATAFILENAME,IOdata): #read calibration file - print "warning hwdata file not found -------------------------------------------------------" + print("warning hwdata file not found -------------------------------------------------------") #read from default file filestoragemod.readfiledata(DEFHWDATAFILENAME,IOdata) - print "writing default calibration data" + print("writing default calibration data") filestoragemod.savefiledata(HWDATAFILENAME,IOdata) # end read IOdata ----- IOdatatemp=copy.deepcopy(IOdata) @@ -174,6 +179,10 @@ def IOdatafromtemp(): global IOdata IOdata=copy.deepcopy(IOdatatemp) filestoragemod.savefiledata(HWDATAFILENAME,IOdata) + +def SaveData(): + filestoragemod.savefiledata(HWDATAFILENAME,IOdata) + def checkdata(fieldtocheck,dictdata,temp=True): # check if basic info in the fields are correct # name is the unique key indicating the row of the list, dictdata contains the datato be verified @@ -284,10 +293,10 @@ def normalizesensordata(reading_str,sensorname): if abs(Minvalue-Maxvalue)>0.01: # in case values are zero or not consistent, stops here if Direction!="inv": den=Maxvalue-Minvalue - readingvalue=(readingvalue-Minvalue)/den + readingvalue=old_div((readingvalue-Minvalue),den) else: den=Maxvalue-Minvalue - readingvalue=1-(readingvalue-Minvalue)/den + readingvalue=1-old_div((readingvalue-Minvalue),den) if Scalevalue>0: readingvalue=readingvalue*Scalevalue readingvalue=readingvalue+Offsetvalue @@ -324,19 +333,19 @@ def getsensordata(sensorname,attemptnumber): #needed Thereading=normalizesensordata(recdata[1],sensorname) # output is a string - print " Sensor " , sensorname , "Normalized reading ",Thereading + print(" Sensor " , sensorname , "Normalized reading ",Thereading) logger.info("Sensor %s reading: %s", sensorname,Thereading) else: - print "Problem with sensor reading ", sensorname + print("Problem with sensor reading ", sensorname) logger.error("Problem with sensor reading: %s", sensorname) else: - print "Problem with response consistency ", sensorname , " cmd " , cmd + print("Problem with response consistency ", sensorname , " cmd " , cmd) logger.error("Problem with response consistency : %s", sensorname) else: - print "no answer from Hardware control module", sensorname + print("no answer from Hardware control module", sensorname) logger.error("no answer from Hardware control module: %s", sensorname) else: - print "sensor name not found in list of sensors ", sensorname + print("sensor name not found in list of sensors ", sensorname) logger.error("sensor name not found in list of sensors : %s", sensorname) return Thereading @@ -349,10 +358,10 @@ def makepulse(target,duration,addtime=True, priority=0): # pulse in seconds , ad return "error" if activated=="on": if not addtime: - print "Already ON, no action" + print("Already ON, no action") return "Already ON" else: - print "Already ON, add time" + print("Already ON, add time") #print "Fire Pulse - ", target @@ -364,7 +373,7 @@ def makepulse(target,duration,addtime=True, priority=0): # pulse in seconds , ad testpulsetimeint=int(duration) testpulsetime=str(testpulsetimeint) # durantion in seconds except ValueError: - print " No valid data or zero ", target + print(" No valid data or zero ", target) return "error" logic=searchdata(HW_INFO_NAME,target,HW_CTRL_LOGIC) @@ -415,7 +424,7 @@ def stoppulse(target): if activated=="error": return "error" if activated=="off": - print "Already OFF" + print("Already OFF") return "Already OFF" #print "Stop Pulse - ", target @@ -458,7 +467,7 @@ def servoangle(target,percentage,delay,priority=0): #percentage go from zeo to 1 #search the data in IOdata isok=False - print "Move Servo - ", target #normally is servo1 + print("Move Servo - ", target) #normally is servo1 # check if servo is belonging to servolist servolist=searchdatalist(HW_CTRL_CMD,"servo",HW_INFO_NAME) @@ -481,31 +490,31 @@ def servoangle(target,percentage,delay,priority=0): #percentage go from zeo to 1 percentagediff=abs(float(100)*difference/(int(MAX)-int(MIN))) if percentagediff<1: # one percent difference - print " No difference with prevoius position ", target , " percentage difference ", percentagediff + print(" No difference with prevoius position ", target , " percentage difference ", percentagediff) return "same" , isok if 0<=int(percentage)<=100: - print "range OK" + print("range OK") else: - print " No valid data for Servo ", target , " out of Range" + print(" No valid data for Servo ", target , " out of Range") return "Out of Range" , isok except ValueError: - print " No valid data for Servo", target + print(" No valid data for Servo", target) return "error" , isok sendstring="servo:"+PIN+":"+FREQ+":"+dutycycle+":"+str(delay)+":"+previousduty+":"+stepsnumber - print " sendstring " , sendstring + print(" sendstring " , sendstring) i=0 while (not(isok))and(i<2): i=i+1 recdata=[] ack= sendcommand("servo",sendstring,recdata,target,priority) - print "returned data " , recdata + print("returned data " , recdata) if ack and recdata[1]!="e": - print target, "correctly activated" + print(target, "correctly activated") # save duty as new status statusdataDBmod.write_status_data(Servo_Status,target,'duty',dutycycle) isok=True @@ -522,16 +531,16 @@ def getservopercentage(target): #print " MIN ", MIN , " MAX ", MAX try: den=(int(MAX)-int(MIN)) - percentage_num=int((100*(float(getservoduty(target))-int(MIN)))/den) + percentage_num=int(old_div((100*(float(getservoduty(target))-int(MIN))),den)) if percentage_num<0: percentage_num=0 if percentage_num>100: percentage_num=100 percentage=str(percentage_num) except: - print " No valid data for Servo", target + print(" No valid data for Servo", target) - print "servo percntage " , percentage + print("servo percntage " , percentage) return percentage def getservoduty(element): @@ -573,16 +582,16 @@ def get_stepper_HWstatus(target): return "error" , isok sendstring="stepperstatus:"+Interface_Number - print " sendstring " , sendstring + print(" sendstring " , sendstring) i=0 while (not(isok))and(i<2): i=i+1 recdata=[] ack= sendcommand("stepperstatus",sendstring,recdata,target,0) - print "returned data " , recdata + print("returned data " , recdata) if ack: - print target, "correctly activated" - print "get stepper status : " , recdata[1] + print(target, "correctly activated") + print("get stepper status : " , recdata[1]) isok=True return recdata[1], isok @@ -594,11 +603,11 @@ def GO_stepper(target,steps,direction,priority=0): global Stepper_Status #search the data in IOdata isok=False - print "Move Stepper - ", target #only supported the I2C default address, the module supports 2 stepper interfaces: 1,2 + print("Move Stepper - ", target) #only supported the I2C default address, the module supports 2 stepper interfaces: 1,2 position_string=getstepperposition(target) - print " position " , position_string + print(" position " , position_string) try: Interface_Number=searchdata(HW_INFO_NAME,target,HW_CTRL_ADCCH) @@ -609,7 +618,7 @@ def GO_stepper(target,steps,direction,priority=0): steps=int(steps) if steps<=0: - print " No valid range for Stepper ", target + print(" No valid range for Stepper ", target) return "Out of Range" , isok # simulate endpoints @@ -621,27 +630,27 @@ def GO_stepper(target,steps,direction,priority=0): position=position-steps if int(MIN)<=(position)<=int(MAX): - print "range OK" + print("range OK") else: - print " No valid range for Stepper ", target + print(" No valid range for Stepper ", target) return "Out of Range" , isok except ValueError: - print " No valid data for Servo", target + print(" No valid data for Servo", target) return "error" , isok sendstring="stepper:"+Interface_Number+":"+direction+":"+FREQ+":"+str(steps) - print " sendstring " , sendstring + print(" sendstring " , sendstring) i=0 while (not(isok))and(i<2): i=i+1 recdata=[] ack= sendcommand("stepper",sendstring,recdata,target,priority) - print "returned data " , recdata + print("returned data " , recdata) if ack and recdata[1]!="e": - print target, "correctly activated" + print(target, "correctly activated") # save position as new status statusdataDBmod.write_status_data(Stepper_Status,target,'position',str(position),True,"Stepper_Status") @@ -689,7 +698,7 @@ def get_hbridge_busystatus(target): PIN2=searchdata(HW_INFO_NAME,target,HW_CTRL_PIN2) logic=searchdata(HW_INFO_NAME,target,HW_CTRL_LOGIC) - print "Check target is already ON ", target + print("Check target is already ON ", target) priority=0 activated1=getpinstate_pin(PIN1,logic, priority) activated2=getpinstate_pin(PIN2,logic, priority) @@ -714,16 +723,16 @@ def get_hbridge_HWstatus(target): return "error" , isok sendstring="hbridgestatus:"+PIN1+PIN2 - print " sendstring " , sendstring + print(" sendstring " , sendstring) i=0 while (not(isok))and(i<2): i=i+1 recdata=[] ack= sendcommand("hbridgestatus",sendstring,recdata,target,0) - print "returned data " , recdata + print("returned data " , recdata) if ack: - print target, "correctly activated" - print "get hbridge status : " , recdata[1] + print(target, "correctly activated") + print("get hbridge status : " , recdata[1]) isok=True return recdata[1], isok @@ -735,11 +744,11 @@ def GO_hbridge(target,steps,zerooffset,direction,priority=0): global Hbridge_Status #search the data in IOdata isok=False - print "Move Hbridge - ", target + print("Move Hbridge - ", target) position_string=gethbridgeposition(target) - print " position " , position_string + print(" position " , position_string) try: PIN1=searchdata(HW_INFO_NAME,target,HW_CTRL_PIN) @@ -751,7 +760,7 @@ def GO_hbridge(target,steps,zerooffset,direction,priority=0): steps=int(steps) if steps<=0: - print " No valid range for pulse ", target + print(" No valid range for pulse ", target) return "Out of Range" , isok # simulate endpoints @@ -763,13 +772,13 @@ def GO_hbridge(target,steps,zerooffset,direction,priority=0): position=position-steps if int(MIN)<=(position)<=int(MAX): - print "range OK" + print("range OK") else: - print " No valid range for hbridge ", target + print(" No valid range for hbridge ", target) return "Out of Range" , isok except ValueError: - print " No valid data for hbridge", target + print(" No valid data for hbridge", target) return "error" , isok # here apply the offset @@ -777,7 +786,7 @@ def GO_hbridge(target,steps,zerooffset,direction,priority=0): sendstring="hbridge:"+PIN1+":"+PIN2+":"+direction+":"+str(steps)+":"+logic - print " sendstring " , sendstring + print(" sendstring " , sendstring) errorcode="error" i=0 @@ -785,9 +794,9 @@ def GO_hbridge(target,steps,zerooffset,direction,priority=0): i=i+1 recdata=[] ack= sendcommand("hbridge",sendstring,recdata,target,priority) - print "returned data " , recdata + print("returned data " , recdata) if ack and recdata[1]!="e": - print target, "correctly activated" + print(target, "correctly activated") # save position as new status statusdataDBmod.write_status_data(Hbridge_Status,target,'position',str(position),True,"Hbridge_Status") # save in persistent mode isok=True @@ -812,7 +821,7 @@ def sethbridgeposition(element, position): def getpinstate(target, priority=0): #search the data in IOdata - print "Check PIN state ", target + print("Check PIN state ", target) PIN=searchdata(HW_INFO_NAME,target,HW_CTRL_PIN) logic=searchdata(HW_INFO_NAME,target,HW_CTRL_LOGIC) return getpinstate_pin(PIN, logic, priority) @@ -829,7 +838,7 @@ def getpinstate_pin(PIN, logic, priority=0): i=i+1 recdata=[] ack= sendcommand("pinstate",sendstring,recdata) - print "returned data " , recdata + print("returned data " , recdata) if ack and recdata[1]!="e": value=recdata[1] isok=True @@ -899,7 +908,7 @@ def readallsensors(): def checkallsensors(): # check if the sensor respond properly according to sensor list in HWdata file - print " check sensor list " + print(" check sensor list ") sensorlist=searchdatalist(HW_INFO_IOTYPE,"input",HW_INFO_NAME) sensorvalues={} for sensorname in sensorlist: @@ -928,26 +937,26 @@ def checkGPIOconsistency(): PIN=ln[HW_CTRL_PIN] if (iotype=="input"): if PIN in inputpinlist: - print "Warning input PIN duplicated", PIN + print("Warning input PIN duplicated", PIN) logger.warning('Warning, input PIN duplicated PIN=%s', PIN) inputpinlist.append(PIN) if (iotype=="output"): if (PIN in outputpinlist)and(PIN in HWcontrol.RPIMODBGPIOPINLIST): - print "Warning output PIN duplicated", PIN + print("Warning output PIN duplicated", PIN) logger.warning('Warning, output PIN duplicated PIN=%s', PIN) else: outputpinlist.append(PIN) if (HW_CTRL_PWRPIN in ln): PWRPIN=ln[HW_CTRL_PWRPIN] if (PWRPIN in outputpinlist)and(PWRPIN in HWcontrol.RPIMODBGPIOPINLIST): - print "Warning output PWRPIN overlapping", PWRPIN + print("Warning output PWRPIN overlapping", PWRPIN) logger.warning('Warning, output PWRPIN overlapping PIN=%s', PWRPIN) else: outputpinlist.append(PWRPIN) if (HW_CTRL_PIN2 in ln): PIN2=ln[HW_CTRL_PIN2] if (PIN2 in outputpinlist)and(PIN2 in HWcontrol.RPIMODBGPIOPINLIST): - print "Warning output PIN2 overlapping", PIN2 + print("Warning output PIN2 overlapping", PIN2) logger.warning('Warning, output PIN2 overlapping PIN=%s', PIN2) else: outputpinlist.append(PIN2) @@ -963,7 +972,7 @@ def checkGPIOconsistency(): for inputpin in inputpinlist: if inputpin in outputpinlist: if inputpin in HWcontrol.RPIMODBGPIOPINLIST: - print "error output PIN and Input PIN are the same", inputpin + print("error output PIN and Input PIN are the same", inputpin) logger.error('Error, output PIN and Input PIN are the same PIN=%s', inputpin) return True @@ -1008,7 +1017,7 @@ def initallGPIOoutput(): #print "power PIN ", ln[HW_CTRL_PWRPIN] , " set to 1 " else: HWcontrol.GPIO_output(PWRPIN, 0) # assume logic is positive - print "power PIN ", ln[HW_CTRL_PWRPIN] , " set to 0, No logic information available " + print("power PIN ", ln[HW_CTRL_PWRPIN] , " set to 0, No logic information available ") # Input: enable one wire if (iotype=="input") : @@ -1044,7 +1053,7 @@ def Set_1wire_Pin(PIN,logic): #ifup_output = subprocess.check_output(cmd).decode('utf-8') return True except: - print "Fail to set the One Wire driver" + print("Fail to set the One Wire driver") logger.error('Fail to set the One Wire driver') return False @@ -1053,7 +1062,7 @@ def get_devices_list(): devtype="One Wire" devicelist=HWcontrol.get_1wire_devices_list() - print devicelist + print(devicelist) for item in devicelist: outlist.append({"address":item , "type":devtype}) @@ -1103,7 +1112,7 @@ def get_device_list_address_property(): item["cmd"]="" item["changeaddressflag"]=0 - print "after=", addresslist + print("after=", addresslist) return addresslist @@ -1130,23 +1139,23 @@ def removeallinterruptevents(): def removeinterruptevents(): - print "load interrupt list " + print("load interrupt list ") interruptlist=searchdatalist2keys(HW_INFO_IOTYPE,"input", HW_CTRL_CMD, "readinputpin" ,HW_INFO_NAME) - print "len interrupt list " , len(interruptlist) + print("len interrupt list " , len(interruptlist)) for item in interruptlist: - print "got into the loop " + print("got into the loop ") # get PIN number recordkey=HW_INFO_NAME recordvalue=item keytosearch=HW_CTRL_PIN PINstr=searchdata(recordkey,recordvalue,keytosearch) - print "set event for the PIN ", PINstr + print("set event for the PIN ", PINstr) try: HWcontrol.GPIO_remove_event_detect(PIN) except: - print "Warning, not able to remove the event detect" + print("Warning, not able to remove the event detect") logger.info('Warning, not able to remove the event detect') return "" @@ -1208,6 +1217,28 @@ def searchrowtempbyname(recordvalue): return searchrowtemp(recordkey,recordvalue) +def AddUpdateRowByName(datarow): + global IOdata + recordkey=HW_INFO_NAME + if recordkey in datarow: + name=datarow[recordkey] + else: + return False + + # search row by name + for ln in IOdata: + if recordkey in ln: + if ln[recordkey]==name: + # found + for key in datarow: #update all fileds present in the row + ln[key]=datarow[key] + SaveData() + return True + #add row to the bottom + IOdata.append(datarow) + SaveData() + + def searchmatch(recordkey,recordvalue,temp): if temp: for ln in IOdatatemp: @@ -1232,14 +1263,21 @@ def separatetimestringint(timestr): # given the string input "hh:mm:ss" output a outlist=[] timelist=timestr.split(":") for i in range(3): + value=0 if i=startdate: isok=True else: isok=True except: - print "file name format not compatible with date" + print("file name format not compatible with date") if isok: templist=[] @@ -1346,7 +1384,7 @@ def loglist(apprunningpath,logfolder,searchstring): folderpath=os.path.join(apprunningpath,logfolder) # control if the folder exist otherwise exit if not os.path.exists(folderpath): - print "log folder does not exist" + print("log folder does not exist") return templist filenamelist=[] sortedlist=sorted(os.listdir(folderpath)) @@ -1402,27 +1440,27 @@ def removephotodataperiod(removebeforedays, maxphototoremove=20): num = pastdays tdelta=timedelta(days=num) startdate=enddate-tdelta - print " stratdate " ,startdate - print " enddate ", enddate + print(" stratdate " ,startdate) + print(" enddate ", enddate) photodata=photolist(get_path()) i=0 for photo in photodata: dateref=photo[2] if isinstance(dateref, datetime): - print dateref + print(dateref) if (dateref>=startdate)and(dateref<=enddate)and(i1: - IOdatarow[th]=fields[th][0] + datarow[th]=fields[th][0] else: - IOdatarow[th]="" - return True + datarow[th]="" + return datarow + def addrow(dictrow, temp=True): dicttemp=copy.deepcopy(dictrow) diff --git a/hx711_AV.py b/hx711_AV.py old mode 100644 new mode 100755 index b339032..e77eb40 --- a/hx711_AV.py +++ b/hx711_AV.py @@ -5,6 +5,8 @@ #!/usr/bin/env python from __future__ import print_function +from builtins import range +from builtins import object import time # this is in python 2.7 which does not have the routine "time.perf_counter" in python 2.7 need a way to operate import sys @@ -29,7 +31,7 @@ import RPi.GPIO as GPIO -class HX711: +class HX711(object): """ HX711 represents chip for reading load cells. """ diff --git a/interruptdbmod.py b/interruptdbmod.py old mode 100644 new mode 100755 index 9d8cfc4..2906b94 --- a/interruptdbmod.py +++ b/interruptdbmod.py @@ -2,6 +2,7 @@ """ Auto watering UI setting storage utilities """ +from __future__ import print_function import logging import os @@ -32,7 +33,7 @@ if not filestoragemod.readfiledata(WTDATAFILENAME,WTdata): #read watering setting file #read from default file filestoragemod.readfiledata(DEFWTDATAFILENAME,WTdata) - print "Watering writing default calibration data" + print("Watering writing default calibration data") filestoragemod.savefiledata(WTDATAFILENAME,WTdata) # end read IOdata ----- @@ -186,7 +187,7 @@ def getrowdata(recordvalue,paramlist,index): #for parameters with array of integ for param in paramlist: try: datalist.append(int(ln[param][index])) - except Exception, e: + except Exception as e: #print 'Failed to load value, set value to zero. Error: '+ str(e) datalist.append(0) diff --git a/interruptmod.py b/interruptmod.py old mode 100644 new mode 100755 index 38baefc..3f46979 --- a/interruptmod.py +++ b/interruptmod.py @@ -1,3 +1,7 @@ +from __future__ import print_function +from __future__ import division +from builtins import str +from past.utils import old_div import logging from datetime import datetime , time ,timedelta import _strptime @@ -19,6 +23,7 @@ ACTIONPRIORITYLEVEL=5 NONBLOCKINGPRIORITY=0 SAVEBLOCKINGBUSY=False +SAVEBLOCKINGDIFFBUSY=False NOWTIMELIST=[] @@ -106,18 +111,18 @@ def setinterruptevents(): hardwaremod.removeallinterruptevents() - print "load interrupt list " + print("load interrupt list ") interruptlist=interruptdbmod.sensorlist() - print "len interrupt list " , len(interruptlist) + print("len interrupt list " , len(interruptlist)) for item in interruptlist: - print "got into the loop " + print("got into the loop ") # get PIN number recordkey=hardwaremod.HW_INFO_NAME recordvalue=item keytosearch=hardwaremod.HW_CTRL_PIN PINstr=hardwaremod.searchdata(recordkey,recordvalue,keytosearch) - print "set event for the PIN ", PINstr + print("set event for the PIN ", PINstr) if not PINstr=="": keytosearch=hardwaremod.HW_CTRL_LOGIC @@ -142,7 +147,7 @@ def setinterruptevents(): bouncetimeINT=200 else: frequencyINT=hardwaremod.toint(frequency,5) - bouncetimeINT=1000/frequencyINT # in ms. this is ok to be trunk of the int. For frequencies higher than 1000 the bouncetime is exactly zero + bouncetimeINT=old_div(1000,frequencyINT) # in ms. this is ok to be trunk of the int. For frequencies higher than 1000 the bouncetime is exactly zero # RPI.GPIO library does not accept bouncetime=0, it gives runtime error if bouncetimeINT<=0: @@ -175,7 +180,7 @@ def setinterruptevents(): if (workmode!="None")and(workmode!=""): sensor=interruptdbmod.searchdata("element",element,"sensor") #saveblockingdiff(sensor) - print " what a sensor ", sensor + print(" what a sensor ", sensor) if sensor!="": startblockingstate(element,10,False) @@ -227,7 +232,7 @@ def cyclereset(element): else: sensorblockingcounter[sensor]=1 - print sensorblockingcounter + print(sensorblockingcounter) global BLOCKING_data for sensor in sensorblockingcounter: statusdataDBmod.write_status_data(BLOCKING_data,sensor,"BlockingNumbers",sensorblockingcounter[sensor]) @@ -264,7 +269,7 @@ def ReadInterruptFrequency(PIN): nowtime=datetime.utcnow() diffseconds=(nowtime-Startcounttime).total_seconds() if diffseconds>0: - Frequency=sensorinterruptcount/diffseconds + Frequency=old_div(sensorinterruptcount,diffseconds) else: Frequency = 0 # azzera timer e counter @@ -281,7 +286,7 @@ def interruptexecute(refsensor,element): if (workmode=="None"): # None case - print "No Action required, workmode set to None, element: " , element + print("No Action required, workmode set to None, element: " , element) logger.info("No Action required, workmode set to None, element: %s " , element) return @@ -492,7 +497,7 @@ def CheckActivateNotify(element,sensor,preemptiontime,actuatoroutput,actionmodea statusdataDBmod.write_status_data(AUTO_data,element,"validinterruptcount",validinterruptcount) - print " validinterruptcount --------------------->", validinterruptcount + #print(" validinterruptcount --------------------->", validinterruptcount) #print "********" ,validinterruptcount , "******" @@ -504,7 +509,7 @@ def CheckActivateNotify(element,sensor,preemptiontime,actuatoroutput,actionmodea if validinterruptcount>=interrupt_triggernumber: - print "Implement Actuator Value ", value + print("Implement Actuator Value ", value) logger.info('Procedure to start actuator %s, for value = %s', element, value) isok=activateactuator(element, value) @@ -523,10 +528,11 @@ def CheckActivateNotify(element,sensor,preemptiontime,actuatoroutput,actionmodea #save data + print("first save in database") saveblockingdiff(sensor) #-- # start the blocking state - print "Start blocking state" + print("Start blocking state") startblockingstate(element,preemptiontime) #save data @@ -547,18 +553,18 @@ def CheckActivateNotify(element,sensor,preemptiontime,actuatoroutput,actionmodea return if actionmodeafterfirst=="Extend blocking state": # extend only the pre-emption blocking period, no action - print "Extend blocking state" + print("Extend blocking state") startblockingstate(element,preemptiontime) if actionmodeafterfirst=="Remove blocking state" or actionmodeafterfirst=="Remove and Follow-up": # remove the pre-emption blocking period, no action - print "Remove blocking state" + print("Remove blocking state") endblocking(element) if actionmodeafterfirst=="Follow-up action" or actionmodeafterfirst=="Remove and Follow-up": # execute the action followup, no variation in the preemption period value=actuatoroutputfollowup # followup action - print "Implement Actuator Value followup", value + print("Implement Actuator Value followup", value) logger.info('Procedure to start actuator followup %s, for value = %s', element, value) isok=activateactuator(element, value) @@ -634,7 +640,7 @@ def endblocking(element, saveend=True): statusdataDBmod.write_status_data(AUTO_data,element,"threadID",None) statusdataDBmod.write_status_data(AUTO_data,element,"blockingstate",False) else: # renew the blocking status - print "Interrupt LEVEL High, Do not stop blocking period, Extend it" + print("Interrupt LEVEL High, Do not stop blocking period, Extend it") # reload the period in case this is chnaged preemptiontimemin=hardwaremod.toint(interruptdbmod.searchdata("element",element,"preemptive_period"),0) period=preemptiontimemin*60 @@ -681,28 +687,39 @@ def checkstopcondition(element): def saveblockingdiff(sensor): # this function minimize the writing over the database, keep them at 1 sec distance and provides a visual pleasant graph :) global BLOCKING_data - threadID=statusdataDBmod.read_status_data(BLOCKING_data,sensor,"BlockingNumbersThreadID") - if (threadID!=None) and (threadID!=""): # thread already present - threadID.cancel() - else: - # no thread present already - x = threading.Thread(target=saveblocking, args=(sensor,)) - x.start() - - #logger.warning("SaveBlockDIFF ---> Sensor %s", sensor) - threadID = threading.Timer(1, saveblocking, [sensor]) - threadID.start() - statusdataDBmod.write_status_data(BLOCKING_data,sensor,"BlockingNumbersThreadID",threadID) + global SAVEBLOCKINGDIFFBUSY + if not SAVEBLOCKINGDIFFBUSY: + SAVEBLOCKINGDIFFBUSY=True + threadID=statusdataDBmod.read_status_data(BLOCKING_data,sensor,"BlockingNumbersThreadID") + print(" threadID ", threadID) + if (threadID!=None) and (threadID!=""): # thread already present + print("thread present already, remove it") + threadID.cancel() + else: + # no thread present already + print("no thread present already ") + x = threading.Thread(target=saveblocking, args=(sensor,False)) + x.start() -def saveblocking(sensor): + #logger.warning("SaveBlockDIFF ---> Sensor %s", sensor) + threadID = threading.Timer(1, saveblocking, [sensor]) + threadID.start() + statusdataDBmod.write_status_data(BLOCKING_data,sensor,"BlockingNumbersThreadID",threadID) + SAVEBLOCKINGDIFFBUSY=False + else: + print(" BUSYYYYY") + +def saveblocking(sensor,cleanThreadID=True): + global SAVEBLOCKINGBUSY + global BLOCKING_data if not SAVEBLOCKINGBUSY: SAVEBLOCKINGBUSY=True - global BLOCKING_data BlockingNumbers=statusdataDBmod.read_status_data(BLOCKING_data,sensor,"BlockingNumbers") - #print "SAVING :::::: sensor ",sensor," BlockingNumbers " ,BlockingNumbers + print("SAVING :::::: sensor ",sensor," BlockingNumbers " ,BlockingNumbers) savedata(sensor,BlockingNumbers) - statusdataDBmod.write_status_data(BLOCKING_data,sensor,"BlockingNumbersThreadID",None) - global SAVEBLOCKINGBUSY + if cleanThreadID: + statusdataDBmod.write_status_data(BLOCKING_data,sensor,"BlockingNumbersThreadID",None) + SAVEBLOCKINGBUSY=False diff --git a/libraries/BMP/__init__.py b/libraries/BMP/__init__.py new file mode 100755 index 0000000..8d1c8b6 --- /dev/null +++ b/libraries/BMP/__init__.py @@ -0,0 +1 @@ + diff --git a/libraries/BMP/bmp180/Adafruit_I2C.py b/libraries/BMP/bmp180/Adafruit_I2C.py new file mode 100755 index 0000000..23b2222 --- /dev/null +++ b/libraries/BMP/bmp180/Adafruit_I2C.py @@ -0,0 +1,161 @@ +#!/usr/bin/python +import re +import smbus + +# =========================================================================== +# Adafruit_I2C Class +# =========================================================================== + +class Adafruit_I2C(object): + + @staticmethod + def getPiRevision(): + "Gets the version number of the Raspberry Pi board" + # Revision list available at: http://elinux.org/RPi_HardwareHistory#Board_Revision_History + try: + with open('/proc/cpuinfo', 'r') as infile: + for line in infile: + # Match a line of the form "Revision : 0002" while ignoring extra + # info in front of the revsion (like 1000 when the Pi was over-volted). + match = re.match('Revision\s+:\s+.*(\w{4})$', line) + if match and match.group(1) in ['0000', '0002', '0003']: + # Return revision 1 if revision ends with 0000, 0002 or 0003. + return 1 + elif match: + # Assume revision 2 if revision ends with any other 4 chars. + return 2 + # Couldn't find the revision, assume revision 0 like older code for compatibility. + return 0 + except: + return 0 + + @staticmethod + def getPiI2CBusNumber(): + # Gets the I2C bus number /dev/i2c# + return 1 if Adafruit_I2C.getPiRevision() > 1 else 0 + + def __init__(self, address, busnum=-1, debug=False): + self.address = address + # By default, the correct I2C bus is auto-detected using /proc/cpuinfo + # Alternatively, you can hard-code the bus version below: + # self.bus = smbus.SMBus(0); # Force I2C0 (early 256MB Pi's) + # self.bus = smbus.SMBus(1); # Force I2C1 (512MB Pi's) + self.bus = smbus.SMBus(busnum if busnum >= 0 else Adafruit_I2C.getPiI2CBusNumber()) + self.debug = debug + + def reverseByteOrder(self, data): + "Reverses the byte order of an int (16-bit) or long (32-bit) value" + # Courtesy Vishal Sapre + byteCount = len(hex(data)[2:].replace('L','')[::2]) + val = 0 + for i in range(byteCount): + val = (val << 8) | (data & 0xff) + data >>= 8 + return val + + def errMsg(self): + print("Error accessing 0x%02X: Check your I2C address" % self.address) + return -1 + + def write8(self, reg, value): + "Writes an 8-bit value to the specified register/address" + try: + self.bus.write_byte_data(self.address, reg, value) + if self.debug: + print("I2C: Wrote 0x%02X to register 0x%02X" % (value, reg)) + except IOError as err: + return self.errMsg() + + def write16(self, reg, value): + "Writes a 16-bit value to the specified register/address pair" + try: + self.bus.write_word_data(self.address, reg, value) + if self.debug: + print ("I2C: Wrote 0x%02X to register pair 0x%02X,0x%02X" % + (value, reg, reg+1)) + except IOError as err: + return self.errMsg() + + def writeRaw8(self, value): + "Writes an 8-bit value on the bus" + try: + self.bus.write_byte(self.address, value) + if self.debug: + print("I2C: Wrote 0x%02X" % value) + except IOError as err: + return self.errMsg() + + def writeList(self, reg, list): + "Writes an array of bytes using I2C format" + try: + if self.debug: + print("I2C: Writing list to register 0x%02X:" % reg) + print(list) + self.bus.write_i2c_block_data(self.address, reg, list) + except IOError as err: + return self.errMsg() + + def readList(self, reg, length): + "Read a list of bytes from the I2C device" + try: + results = self.bus.read_i2c_block_data(self.address, reg, length) + if self.debug: + print ("I2C: Device 0x%02X returned the following from reg 0x%02X" % + (self.address, reg)) + print(results) + return results + except IOError as err: + return self.errMsg() + + def readU8(self, reg): + "Read an unsigned byte from the I2C device" + try: + result = self.bus.read_byte_data(self.address, reg) + if self.debug: + print("I2C: Device 0x%02X returned 0x%02X from reg 0x%02X" % + (self.address, result & 0xFF, reg)) + return result + except IOError as err: + return self.errMsg() + + def readS8(self, reg): + "Reads a signed byte from the I2C device" + try: + result = self.bus.read_byte_data(self.address, reg) + if result > 127: result -= 256 + if self.debug: + print("I2C: Device 0x%02X returned 0x%02X from reg 0x%02X" % + (self.address, result & 0xFF, reg)) + return result + except IOError as err: + return self.errMsg() + + def readU16(self, reg, little_endian=True): + "Reads an unsigned 16-bit value from the I2C device" + try: + result = self.bus.read_word_data(self.address,reg) + # Swap bytes if using big endian because read_word_data assumes little + # endian on ARM (little endian) systems. + if not little_endian: + result = ((result << 8) & 0xFF00) + (result >> 8) + if (self.debug): + print("I2C: Device 0x%02X returned 0x%04X from reg 0x%02X" % (self.address, result & 0xFFFF, reg)) + return result + except IOError as err: + return self.errMsg() + + def readS16(self, reg, little_endian=True): + "Reads a signed 16-bit value from the I2C device" + try: + result = self.readU16(reg,little_endian) + if result > 32767: result -= 65536 + return result + except IOError as err: + return self.errMsg() + +if __name__ == '__main__': + try: + bus = Adafruit_I2C(address=0) + print("Default I2C bus is accessible") + except: + print("Error accessing default I2C bus") diff --git a/libraries/BMP/bmp180/__init__.py b/libraries/BMP/bmp180/__init__.py new file mode 100755 index 0000000..8d1c8b6 --- /dev/null +++ b/libraries/BMP/bmp180/__init__.py @@ -0,0 +1 @@ + diff --git a/libraries/BMP/bmp180/__pycache__/Adafruit_I2C.cpython-37.pyc b/libraries/BMP/bmp180/__pycache__/Adafruit_I2C.cpython-37.pyc new file mode 100644 index 0000000..3f0574a Binary files /dev/null and b/libraries/BMP/bmp180/__pycache__/Adafruit_I2C.cpython-37.pyc differ diff --git a/libraries/BMP/bmp180/__pycache__/__init__.cpython-37.pyc b/libraries/BMP/bmp180/__pycache__/__init__.cpython-37.pyc new file mode 100755 index 0000000..336bbf2 Binary files /dev/null and b/libraries/BMP/bmp180/__pycache__/__init__.cpython-37.pyc differ diff --git a/libraries/BMP/bmp180/__pycache__/grove_i2c_barometic_sensor_BMP180.cpython-37.pyc b/libraries/BMP/bmp180/__pycache__/grove_i2c_barometic_sensor_BMP180.cpython-37.pyc new file mode 100644 index 0000000..d73fc9b Binary files /dev/null and b/libraries/BMP/bmp180/__pycache__/grove_i2c_barometic_sensor_BMP180.cpython-37.pyc differ diff --git a/libraries/BMP/bmp180/grove_i2c_barometic_sensor_BMP180.py b/libraries/BMP/bmp180/grove_i2c_barometic_sensor_BMP180.py new file mode 100755 index 0000000..d9cc657 --- /dev/null +++ b/libraries/BMP/bmp180/grove_i2c_barometic_sensor_BMP180.py @@ -0,0 +1,298 @@ +#!/usr/bin/python +# Copyright 2014 Johan Vandewalle. All rights reserved. +# +# Redistributian and use in source and binary forms, with or without +# modification, are permitted provide that the following conditions are +# met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR +# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE +# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR +# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +import time +from Adafruit_I2C import Adafruit_I2C +import math + +# =========================================================================== +# BMP085 Class +# =========================================================================== + +class BMP085 : + i2c = None + + # Operating Modes + __BMP085_ULTRALOWPOWER = 0 + __BMP085_STANDARD = 1 + __BMP085_HIGHRES = 2 + __BMP085_ULTRAHIGHRES = 3 + + # BMP085 Registers + __BMP085_CAL_AC1 = 0xAA # R Calibration data (16 bits) + __BMP085_CAL_AC2 = 0xAC # R Calibration data (16 bits) + __BMP085_CAL_AC3 = 0xAE # R Calibration data (16 bits) + __BMP085_CAL_AC4 = 0xB0 # R Calibration data (16 bits) + __BMP085_CAL_AC5 = 0xB2 # R Calibration data (16 bits) + __BMP085_CAL_AC6 = 0xB4 # R Calibration data (16 bits) + __BMP085_CAL_B1 = 0xB6 # R Calibration data (16 bits) + __BMP085_CAL_B2 = 0xB8 # R Calibration data (16 bits) + __BMP085_CAL_MB = 0xBA # R Calibration data (16 bits) + __BMP085_CAL_MC = 0xBC # R Calibration data (16 bits) + __BMP085_CAL_MD = 0xBE # R Calibration data (16 bits) + __BMP085_CONTROL = 0xF4 + __BMP085_TEMPDATA = 0xF6 + __BMP085_PRESSUREDATA = 0xF6 + __BMP085_READTEMPCMD = 0x2E + __BMP085_READPRESSURECMD = 0x34 + + # Private Fields + _cal_AC1 = 0 + _cal_AC2 = 0 + _cal_AC3 = 0 + _cal_AC4 = 0 + _cal_AC5 = 0 + _cal_AC6 = 0 + _cal_B1 = 0 + _cal_B2 = 0 + _cal_MB = 0 + _cal_MC = 0 + _cal_MD = 0 + + # Constructor + def __init__(self, address=0x77, mode=1, debug=False): + self.i2c = Adafruit_I2C(address) + + self.address = address + self.debug = debug + # Make sure the specified mode is in the appropriate range + if ((mode < 0) | (mode > 3)): + if (self.debug): + print("Invalid Mode: Using STANDARD by default") + self.mode = self.__BMP085_STANDARD + else: + self.mode = mode + # Read the calibration data + self.readCalibrationData() + + def readS16(self, register): + "Reads a signed 16-bit value" + hi = self.i2c.readS8(register) + lo = self.i2c.readU8(register+1) + return (hi << 8) + lo + + def readU16(self, register): + "Reads an unsigned 16-bit value" + hi = self.i2c.readU8(register) + lo = self.i2c.readU8(register+1) + return (hi << 8) + lo + + def readCalibrationData(self): + "Reads the calibration data from the IC" + self._cal_AC1 = self.readS16(self.__BMP085_CAL_AC1) # INT16 + self._cal_AC2 = self.readS16(self.__BMP085_CAL_AC2) # INT16 + self._cal_AC3 = self.readS16(self.__BMP085_CAL_AC3) # INT16 + self._cal_AC4 = self.readU16(self.__BMP085_CAL_AC4) # UINT16 + self._cal_AC5 = self.readU16(self.__BMP085_CAL_AC5) # UINT16 + self._cal_AC6 = self.readU16(self.__BMP085_CAL_AC6) # UINT16 + self._cal_B1 = self.readS16(self.__BMP085_CAL_B1) # INT16 + self._cal_B2 = self.readS16(self.__BMP085_CAL_B2) # INT16 + self._cal_MB = self.readS16(self.__BMP085_CAL_MB) # INT16 + self._cal_MC = self.readS16(self.__BMP085_CAL_MC) # INT16 + self._cal_MD = self.readS16(self.__BMP085_CAL_MD) # INT16 + if (self.debug): + self.showCalibrationData() + + def showCalibrationData(self): + "Displays the calibration values for debugging purposes" + print("DBG: AC1 = %6d" % (self._cal_AC1)) + print("DBG: AC2 = %6d" % (self._cal_AC2)) + print("DBG: AC3 = %6d" % (self._cal_AC3)) + print("DBG: AC4 = %6d" % (self._cal_AC4)) + print("DBG: AC5 = %6d" % (self._cal_AC5)) + print("DBG: AC6 = %6d" % (self._cal_AC6)) + print("DBG: B1 = %6d" % (self._cal_B1)) + print("DBG: B2 = %6d" % (self._cal_B2)) + print("DBG: MB = %6d" % (self._cal_MB)) + print("DBG: MC = %6d" % (self._cal_MC)) + print("DBG: MD = %6d" % (self._cal_MD)) + + def readRawTemp(self): + "Reads the raw (uncompensated) temperature from the sensor" + self.i2c.write8(self.__BMP085_CONTROL, self.__BMP085_READTEMPCMD) + time.sleep(0.005) # Wait 5ms + raw = self.readU16(self.__BMP085_TEMPDATA) + if (raw == -1): + print ("RawTemperature: Error reading the data ") + return False ,0 + if (self.debug): + print("DBG: Raw Temp: 0x%04X (%d)" % (raw & 0xFFFF, raw)) + return True , raw + + def readRawPressure(self): + "Reads the raw (uncompensated) pressure level from the sensor" + self.i2c.write8(self.__BMP085_CONTROL, self.__BMP085_READPRESSURECMD + (self.mode << 6)) + if (self.mode == self.__BMP085_ULTRALOWPOWER): + time.sleep(0.005) + elif (self.mode == self.__BMP085_HIGHRES): + time.sleep(0.014) + elif (self.mode == self.__BMP085_ULTRAHIGHRES): + time.sleep(0.026) + else: + time.sleep(0.008) + msb = self.i2c.readU8(self.__BMP085_PRESSUREDATA) + lsb = self.i2c.readU8(self.__BMP085_PRESSUREDATA+1) + #print (" msb ", msb , " lsb ", lsb) + if (msb == -1)and(lsb == -1): + print ("RawPressure: Error reading the data ") + return False ,0 + xlsb = self.i2c.readU8(self.__BMP085_PRESSUREDATA+2) + raw = ((msb << 16) + (lsb << 8) + xlsb) >> (8 - self.mode) + if (self.debug): + print("DBG: Raw Pressure: 0x%04X (%d)" % (raw & 0xFFFF, raw)) + return True , raw + + def readTemperature(self): + "Gets the compensated temperature in degrees celcius" + UT = 0 + X1 = 0 + X2 = 0 + B5 = 0 + temp = 0.0 + + # Read raw temp before aligning it with the calibration values + UT = self.readRawTemp() + X1 = ((UT - self._cal_AC6) * self._cal_AC5) >> 15 + X2 = (self._cal_MC << 11) / (X1 + self._cal_MD) + B5 = X1 + X2 + temp = (int(B5 + 8) >> 4) / 10.0 + if (self.debug): + print("DBG: Calibrated temperature = %f C" % temp) + return temp + + def readPressure(self): + "Gets the compensated pressure in pascal" + UT = 0 + UP = 0 + B3 = 0 + B5 = 0 + B6 = 0 + X1 = 0 + X2 = 0 + X3 = 0 + p = 0 + B4 = 0 + B7 = 0 + + Tisok, UT = self.readRawTemp() + Pisok, UP = self.readRawPressure() + + if (not Tisok) or (not Pisok): + return False, 0 + + # You can use the datasheet values to test the conversion results + # dsValues = True + dsValues = False + + if (dsValues): + UT = 27898 + UP = 23843 + self._cal_AC6 = 23153 + self._cal_AC5 = 32757 + self._cal_MB = -32768; + self._cal_MC = -8711 + self._cal_MD = 2868 + self._cal_B1 = 6190 + self._cal_B2 = 4 + self._cal_AC3 = -14383 + self._cal_AC2 = -72 + self._cal_AC1 = 408 + self._cal_AC4 = 32741 + self.mode = self.__BMP085_ULTRALOWPOWER + if (self.debug): + self.showCalibrationData() + + # True Temperature Calculations + X1 = ((UT - self._cal_AC6) * self._cal_AC5) >> 15 + X2 = (self._cal_MC << 11) / (X1 + self._cal_MD) + B5 = X1 + X2 + if (self.debug): + print("DBG: X1 = %d" % (X1)) + print("DBG: X2 = %d" % (X2)) + print("DBG: B5 = %d" % (B5)) + print("DBG: True Temperature = %.2f C" % (((B5 + 8) >> 4) / 10.0)) + + # Pressure Calculations + B6 = B5 - 4000 + X1 = (int(self._cal_B2) * int(B6 * B6) >> 12) >> 11 + X2 = int(self._cal_AC2 * B6) >> 11 + X3 = X1 + X2 + B3 = (((self._cal_AC1 * 4 + X3) << self.mode) + 2) / 4 + if (self.debug): + print("DBG: B6 = %d" % (B6)) + print("DBG: X1 = %d" % (X1)) + print("DBG: X2 = %d" % (X2)) + print("DBG: X3 = %d" % (X3)) + print("DBG: B3 = %d" % (B3)) + + X1 = int(self._cal_AC3 * B6) >> 13 + X2 = (int(self._cal_B1) * (int(B6 * B6) >> 12)) >> 16 + X3 = ((X1 + X2) + 2) >> 2 + B4 = (self._cal_AC4 * (X3 + 32768)) >> 15 + B7 = (UP - B3) * (50000 >> self.mode) + if (self.debug): + print("DBG: X1 = %d" % (X1)) + print("DBG: X2 = %d" % (X2)) + print("DBG: X3 = %d" % (X3)) + print("DBG: B4 = %d" % (B4)) + print("DBG: B7 = %d" % (B7)) + + if (B7 < 0x80000000): + p = (B7 * 2) / B4 + else: + p = (B7 / B4) * 2 + + if (self.debug): + print("DBG: X1 = %d" % (X1)) + + X1 = (int(p) >> 8) * (int(p) >> 8) + X1 = (X1 * 3038) >> 16 + X2 = (-7357 * int(p)) >> 16 + if (self.debug): + print("DBG: p = %d" % (p)) + print("DBG: X1 = %d" % (X1)) + print("DBG: X2 = %d" % (X2)) + + p = p + ((X1 + X2 + 3791) >> 4) + if (self.debug): + print("DBG: Pressure = %d Pa" % (p)) + + return True, p + + def readAltitude(self, seaLevelPressure=101325): + "Calculates the altitude in meters" + altitude = 0.0 + pressure = float(self.readPressure()) + temperature = float(self.readTemperature()) +# altitude = 44330.0 * (1.0 - pow(pressure / seaLevelPressure, 0.1903)) + altitude = round( -math.log( pressure / seaLevelPressure ) * 8314 * ( temperature + 273.15 ) / ( 25 * 9.81 ) , 2 ) + # this isn't completely correct. The formula uses the temperature of the sensor while it should be using the temperature + # at sea level. At lower altitudes and close (less then 200 km) from the shore, the difference is neglectable. If you want + # to use the script at higher locations or deeper inland, comment this line and uncomment the line above. + if (self.debug): + print("DBG: Altitude = %.2f m" % (altitude)) + return altitude + + return 0 diff --git a/libraries/BMP/bmp180/grove_i2c_barometic_sensor_example.py b/libraries/BMP/bmp180/grove_i2c_barometic_sensor_example.py new file mode 100755 index 0000000..9fdc99b --- /dev/null +++ b/libraries/BMP/bmp180/grove_i2c_barometic_sensor_example.py @@ -0,0 +1,43 @@ +#!/usr/bin/python + +import smbus +import RPi.GPIO as GPIO +from grove_i2c_barometic_sensor_BMP180 import BMP085 + +# =========================================================================== +# Example Code +# =========================================================================== + +# Initialise the BMP085 and use STANDARD mode (default value) +# bmp = BMP085(0x77, debug=True) +bmp = BMP085(0x77, 1) + +# To specify a different operating mode, uncomment one of the following: +# bmp = BMP085(0x77, 0) # ULTRALOWPOWER Mode +# bmp = BMP085(0x77, 1) # STANDARD Mode +# bmp = BMP085(0x77, 2) # HIRES Mode +# bmp = BMP085(0x77, 3) # ULTRAHIRES Mode + +rev = GPIO.RPI_REVISION +if rev == 2 or rev == 3: + bus = smbus.SMBus(1) +else: + bus = smbus.SMBus(0) + +temp = bmp.readTemperature() + +# Read the current barometric pressure level +pressure = bmp.readPressure() + +# To calculate altitude based on an estimated mean sea level pressure +# (1013.25 hPa) call the function as follows, but this won't be very accurate +# altitude = bmp.readAltitude() + +# To specify a more accurate altitude, enter the correct mean sea level +# pressure level. For example, if the current pressure level is 1023.50 hPa +# enter 102350 since we include two decimal places in the integer value +altitude = bmp.readAltitude(101560) + +print("Temperature: %.2f C" % temp) +print("Pressure: %.2f hPa" % (pressure / 100.0)) +print("Altitude: %.2f m" % altitude) diff --git a/libraries/BMP/master.zip b/libraries/BMP/master.zip deleted file mode 100644 index 92269ec..0000000 Binary files a/libraries/BMP/master.zip and /dev/null differ diff --git a/libraries/MotorHat/Adafruit_I2C_2.py b/libraries/MotorHat/Adafruit_I2C_2.py new file mode 100644 index 0000000..5510d6f --- /dev/null +++ b/libraries/MotorHat/Adafruit_I2C_2.py @@ -0,0 +1,161 @@ +#!/usr/bin/python +import re +import smbus + +# =========================================================================== +# I2C Class +# =========================================================================== + +class I2C(object): + + @staticmethod + def getPiRevision(): + "Gets the version number of the Raspberry Pi board" + # Revision list available at: http://elinux.org/RPi_HardwareHistory#Board_Revision_History + try: + with open('/proc/cpuinfo', 'r') as infile: + for line in infile: + # Match a line of the form "Revision : 0002" while ignoring extra + # info in front of the revsion (like 1000 when the Pi was over-volted). + match = re.match('Revision\s+:\s+.*(\w{4})$', line) + if match and match.group(1) in ['0000', '0002', '0003']: + # Return revision 1 if revision ends with 0000, 0002 or 0003. + return 1 + elif match: + # Assume revision 2 if revision ends with any other 4 chars. + return 2 + # Couldn't find the revision, assume revision 0 like older code for compatibility. + return 0 + except: + return 0 + + @staticmethod + def getPiI2CBusNumber(): + # Gets the I2C bus number /dev/i2c# + return 1 if I2C.getPiRevision() > 1 else 0 + + def __init__(self, address, busnum=-1, debug=False): + self.address = address + # By default, the correct I2C bus is auto-detected using /proc/cpuinfo + # Alternatively, you can hard-code the bus version below: + # self.bus = smbus.SMBus(0); # Force I2C0 (early 256MB Pi's) + # self.bus = smbus.SMBus(1); # Force I2C1 (512MB Pi's) + self.bus = smbus.SMBus(busnum if busnum >= 0 else I2C.getPiI2CBusNumber()) + self.debug = debug + + def reverseByteOrder(self, data): + "Reverses the byte order of an int (16-bit) or long (32-bit) value" + # Courtesy Vishal Sapre + byteCount = len(hex(data)[2:].replace('L','')[::2]) + val = 0 + for i in range(byteCount): + val = (val << 8) | (data & 0xff) + data >>= 8 + return val + + def errMsg(self): + print("Error accessing 0x%02X: Check your I2C address" % self.address) + return -1 + + def write8(self, reg, value): + "Writes an 8-bit value to the specified register/address" + try: + self.bus.write_byte_data(self.address, reg, value) + if self.debug: + print("I2C: Wrote 0x%02X to register 0x%02X" % (value, reg)) + except IOError as err: + return self.errMsg() + + def write16(self, reg, value): + "Writes a 16-bit value to the specified register/address pair" + try: + self.bus.write_word_data(self.address, reg, value) + if self.debug: + print ("I2C: Wrote 0x%02X to register pair 0x%02X,0x%02X" % + (value, reg, reg+1)) + except IOError as err: + return self.errMsg() + + def writeRaw8(self, value): + "Writes an 8-bit value on the bus" + try: + self.bus.write_byte(self.address, value) + if self.debug: + print("I2C: Wrote 0x%02X" % value) + except IOError as err: + return self.errMsg() + + def writeList(self, reg, list): + "Writes an array of bytes using I2C format" + try: + if self.debug: + print("I2C: Writing list to register 0x%02X:" % reg) + print(list) + self.bus.write_i2c_block_data(self.address, reg, list) + except IOError as err: + return self.errMsg() + + def readList(self, reg, length): + "Read a list of bytes from the I2C device" + try: + results = self.bus.read_i2c_block_data(self.address, reg, length) + if self.debug: + print ("I2C: Device 0x%02X returned the following from reg 0x%02X" % + (self.address, reg)) + print(results) + return results + except IOError as err: + return self.errMsg() + + def readU8(self, reg): + "Read an unsigned byte from the I2C device" + try: + result = self.bus.read_byte_data(self.address, reg) + if self.debug: + print("I2C: Device 0x%02X returned 0x%02X from reg 0x%02X" % + (self.address, result & 0xFF, reg)) + return result + except IOError as err: + return self.errMsg() + + def readS8(self, reg): + "Reads a signed byte from the I2C device" + try: + result = self.bus.read_byte_data(self.address, reg) + if result > 127: result -= 256 + if self.debug: + print("I2C: Device 0x%02X returned 0x%02X from reg 0x%02X" % + (self.address, result & 0xFF, reg)) + return result + except IOError as err: + return self.errMsg() + + def readU16(self, reg, little_endian=True): + "Reads an unsigned 16-bit value from the I2C device" + try: + result = self.bus.read_word_data(self.address,reg) + # Swap bytes if using big endian because read_word_data assumes little + # endian on ARM (little endian) systems. + if not little_endian: + result = ((result << 8) & 0xFF00) + (result >> 8) + if (self.debug): + print("I2C: Device 0x%02X returned 0x%04X from reg 0x%02X" % (self.address, result & 0xFFFF, reg)) + return result + except IOError as err: + return self.errMsg() + + def readS16(self, reg, little_endian=True): + "Reads a signed 16-bit value from the I2C device" + try: + result = self.readU16(reg,little_endian) + if result > 32767: result -= 65536 + return result + except IOError as err: + return self.errMsg() + +if __name__ == '__main__': + try: + bus = I2C(address=0) + print("Default I2C bus is accessible") + except: + print("Error accessing default I2C bus") diff --git a/libraries/MotorHat/__init__.py b/libraries/MotorHat/__init__.py new file mode 100755 index 0000000..8d1c8b6 --- /dev/null +++ b/libraries/MotorHat/__init__.py @@ -0,0 +1 @@ + diff --git a/libraries/MotorHat/master.zip b/libraries/MotorHat/master.zip deleted file mode 100644 index c345229..0000000 Binary files a/libraries/MotorHat/master.zip and /dev/null differ diff --git a/stepperDOUBLEmod.py b/libraries/MotorHat/stepperDOUBLEmod.py old mode 100644 new mode 100755 similarity index 85% rename from stepperDOUBLEmod.py rename to libraries/MotorHat/stepperDOUBLEmod.py index 13a2ec0..7369b95 --- a/stepperDOUBLEmod.py +++ b/libraries/MotorHat/stepperDOUBLEmod.py @@ -1,26 +1,19 @@ +from __future__ import print_function +from __future__ import division # ============================================================================ # Adafruit PCA9685 16-Channel PWM Servo Driver # ============================================================================ +from builtins import range +from past.utils import old_div +from builtins import object import logging import math import time - +from Adafruit_I2C_2 import I2C logger = logging.getLogger(__name__) -def get_i2c_device(address, i2c, i2c_bus): - # Helper method to get a device at the specified address from the I2C bus. - # If no i2c bus is specified (i2c param is None) then the default I2C bus - # for the platform will be used. - if i2c is not None: - return i2c.get_i2c_device(address) - else: - import Adafruit_GPIO.I2C as I2C - if i2c_bus is None: - return I2C.get_i2c_device(address) - else: - return I2C.get_i2c_device(address, busnum=i2c_bus) class PWM(object): @@ -50,21 +43,19 @@ class PWM(object): regvals = {} # new code from me @classmethod - def softwareReset(cls, i2c=None, i2c_bus=None): - "Sends a software reset (SWRST) command to all the servo drivers on the bus" - general_call_i2c = get_i2c_device(0x00, i2c, i2c_bus) - general_call_i2c.writeRaw8(0x06) # SWRST + def __init__(self, address=0x40, debug=False, i2c=None, i2c_bus=None): - self.i2c = get_i2c_device(address, i2c, i2c_bus) + self.i2c = I2C(address) + #self.i2c = get_i2c_device(address, i2c, i2c_bus) logger.debug("Reseting PCA9685 MODE1 (without SLEEP) and MODE2") - self.setAllPWM(0, 0) - self.write8my(self.__MODE2, self.__OUTDRV) - self.write8my(self.__MODE1, self.__ALLCALL) + self.setAllPWM(self, 0, 0) + self.write8my(self, self.__MODE2, self.__OUTDRV) + self.write8my(self, self.__MODE1, self.__ALLCALL) time.sleep(0.005) # wait for oscillator mode1 = self.i2c.readU8(self.__MODE1) mode1 = mode1 & ~self.__SLEEP # wake up (reset sleep) - self.write8my(self.__MODE1, mode1) + self.write8my(self, self.__MODE1, mode1) time.sleep(0.005) # wait for oscillator @@ -96,25 +87,25 @@ def setPWM(self, channel, on, off): # got here finally ------------------------ def setAllPWM(self, on, off): "Sets a all PWM channels" - self.write8my(self.__ALL_LED_ON_L, on & 0xFF) - self.write8my(self.__ALL_LED_ON_H, on >> 8) - self.write8my(self.__ALL_LED_OFF_L, off & 0xFF) - self.write8my(self.__ALL_LED_OFF_H, off >> 8) + self.write8my(self, self.__ALL_LED_ON_L, on & 0xFF) + self.write8my(self, self.__ALL_LED_ON_H, on >> 8) + self.write8my(self, self.__ALL_LED_OFF_L, off & 0xFF) + self.write8my(self, self.__ALL_LED_OFF_H, off >> 8) def write8my(self, reg, value): # new function created by me to optimize the I2C traffic speed up about 5 times the stepper speed! - if reg not in self.regvals: - self.i2c.write8(reg, value) - self.regvals[reg] = value - else: - if self.regvals[reg] != value: - self.i2c.write8(reg, value) - self.regvals[reg] = value - #else: - # print "no need to transfer on I2C" + if reg not in self.regvals: + self.i2c.write8(reg, value) + self.regvals[reg] = value + else: + if self.regvals[reg] != value: + self.i2c.write8(reg, value) + self.regvals[reg] = value + #else: + # print "no need to transfer on I2C" -class Adafruit_StepperMotor: +class Adafruit_StepperMotor(object): MICROSTEPS = 8 MICROSTEP_CURVE = [0, 50, 98, 142, 180, 212, 236, 250, 255] @@ -150,7 +141,7 @@ def __init__(self, controller, num, steps=200): raise NameError('MotorHAT Stepper must be between 1 and 2 inclusive') def setSpeed(self, rpm): - self.sec_per_step = 60.0 / (self.revsteps * rpm) + self.sec_per_step = old_div(60.0, (self.revsteps * rpm)) self.steppingcounter = 0 def oneStep(self, dir, style): @@ -258,7 +249,7 @@ def step(self, steps, direction, stepstyle): lateststep = 0 if (stepstyle == Adafruit_MotorHAT.INTERLEAVE): - s_per_s = s_per_s / 2.0 + s_per_s = old_div(s_per_s, 2.0) if (stepstyle == Adafruit_MotorHAT.MICROSTEP): s_per_s /= self.MICROSTEPS steps *= self.MICROSTEPS @@ -276,7 +267,7 @@ def step(self, steps, direction, stepstyle): lateststep = self.oneStep(direction, stepstyle) time.sleep(s_per_s) -class Adafruit_DCMotor: +class Adafruit_DCMotor(object): def __init__(self, controller, num): self.MC = controller self.motornum = num @@ -324,7 +315,7 @@ def setSpeed(self, speed): self.MC._pwm.setPWM(self.PWMpin, 0, speed*16) -class Adafruit_MotorHAT: +class Adafruit_MotorHAT(object): FORWARD = 1 BACKWARD = 2 BRAKE = 3 @@ -364,3 +355,32 @@ def getMotor(self, num): def reset(self): self._pwm.softwareReset() + + + + + +if __name__ == '__main__': + + direction="BACKWARD" + # comment + # create a default object, no changes to I2C address or frequency + mh = Adafruit_MotorHAT() + + # set motor parameters + myStepper = mh.getStepper(200, 1) # 200 steps/rev, motor port #1 or #2 + myStepper.setSpeed(30) # 30 RPM + + #print "Double coil steps" + if direction=="FORWARD": + myStepper.step(100, Adafruit_MotorHAT.FORWARD, Adafruit_MotorHAT.DOUBLE) + elif direction=="BACKWARD": + myStepper.step(100, Adafruit_MotorHAT.BACKWARD, Adafruit_MotorHAT.DOUBLE) + + # turn off motors + mh.getMotor(1).run(Adafruit_MotorHAT.RELEASE) + mh.getMotor(2).run(Adafruit_MotorHAT.RELEASE) + mh.getMotor(3).run(Adafruit_MotorHAT.RELEASE) + mh.getMotor(4).run(Adafruit_MotorHAT.RELEASE) + + del mh diff --git a/libraries/__init__.py b/libraries/__init__.py new file mode 100755 index 0000000..8d1c8b6 --- /dev/null +++ b/libraries/__init__.py @@ -0,0 +1 @@ + diff --git a/logindbmod.py b/logindbmod.py old mode 100644 new mode 100755 index ccafe6e..6626dea --- a/logindbmod.py +++ b/logindbmod.py @@ -2,6 +2,7 @@ """ fertilizer UI setting storage utilities """ +from __future__ import print_function import logging import os @@ -61,7 +62,7 @@ def changesavesetting(FTparameter,FTvalue): searchvalue="login" isok=filestoragemod.savechange(DATAFILENAME,searchfield,searchvalue,FTparameter,FTvalue) if not isok: - print "problem saving parameter" + print("problem saving parameter") return isok @@ -85,4 +86,4 @@ def get_path(): if __name__ == '__main__': # comment - print "Hello there " + print("Hello there ") diff --git a/networkdbmod.py b/networkdbmod.py old mode 100644 new mode 100755 index d0e2ab0..042b567 --- a/networkdbmod.py +++ b/networkdbmod.py @@ -2,6 +2,7 @@ """ fertilizer UI setting storage utilities """ +from __future__ import print_function import logging import os @@ -34,11 +35,11 @@ #read data from BASICDATAFILENAME file done=filestoragemod.readfiledata_spec(BASICDATAFILENAME,"# HERE->",data) if done: - print "writing default network data" + print("writing default network data") filestoragemod.savefiledata(DATAFILENAME,data) logger.info('Basic network data acquired') else: - print "ERROR ----------------------------- not able to get network data" + print("ERROR ----------------------------- not able to get network data") logger.error('Not able to get basic network data ---------------------') # end read IOdata ----- @@ -114,7 +115,7 @@ def changesavesetting(FTparameter,FTvalue): searchvalue="IPsetting" isok=filestoragemod.savechange(DATAFILENAME,searchfield,searchvalue,FTparameter,FTvalue) if not isok: - print "problem saving parameters" + print("problem saving parameters") return isok diff --git a/networkmod.py b/networkmod.py old mode 100644 new mode 100755 index 3f8a0a2..9e36c38 --- a/networkmod.py +++ b/networkmod.py @@ -1,3 +1,7 @@ +from __future__ import print_function +from future import standard_library +standard_library.install_aliases() +from builtins import str import logging import subprocess import threading @@ -7,7 +11,7 @@ # stuff for the IP detection import shlex import re -import urllib2 +import urllib.request, urllib.error, urllib.parse import socket import time import wpa_cli_mod @@ -17,7 +21,7 @@ localwifisystem=networkdbmod.getAPSSID() if localwifisystem=="": localwifisystem="hydrosys4" - print "error the name of AP not found, double check the hostapd configuration" + print("error the name of AP not found, double check the hostapd configuration") logger.error("error the name of AP not found, double check the hostapd configuration") LOCALPORT=5020 PUBLICPORT=networkdbmod.getPORT() @@ -36,14 +40,14 @@ def stopNTP(): #sudo systemctl disable systemd-timesyncd.service #sudo service systemd-timesyncd stop logger.info("Stop NTP") - print "Stop NTP (Network Time Protocol)" + print("Stop NTP (Network Time Protocol)") # hostnamectl set-hostname $NewHostName cmd = [ 'service' , 'systemd-timesyncd' , 'stop'] try: output_string = subprocess.check_output(cmd).decode('utf-8').strip() return output_string except subprocess.CalledProcessError as e: - print "error to execute the command" , cmd + print("error to execute the command" , cmd) logger.error("error to execute the command %s",cmd) return "error" time.sleep(2) @@ -52,14 +56,14 @@ def disableNTP(): #sudo systemctl disable systemd-timesyncd.service #sudo service systemd-timesyncd stop logger.info("Disable NTP") - print "Disable NTP (Network Time Protocol)" + print("Disable NTP (Network Time Protocol)") # hostnamectl set-hostname $NewHostName cmd = [ 'systemctl' , 'disable' , 'systemd-timesyncd.service'] try: output_string = subprocess.check_output(cmd).decode('utf-8').strip() return output_string except subprocess.CalledProcessError as e: - print "error to execute the command" , cmd + print("error to execute the command" , cmd) logger.error("error to execute the command %s",cmd) return "error" time.sleep(2) @@ -91,7 +95,7 @@ def savewificonnect(ssid, password): selectedplanmod.CheckNTPandAdjustClockandResetSched() # instead of waiting the next Heartbeat, it reset master scheduler if clock changes def waitandsavewifiandconnect(pulsesecond,ssid,password): - print "try to save wifi after " , pulsesecond , " seconds" + print("try to save wifi after " , pulsesecond , " seconds") argvect=[] argvect.append(ssid) argvect.append(password) @@ -105,7 +109,7 @@ def savedefaultAP(): #defaultstr=["iface wlan0-"+ssid+" inet static", "address 10.0.0.1", "netmask 255.255.255.0", "broadcast 255.0.0.0"] scheme = Scheme('wlan0', ssid, "static", APINTERFACEMODE) scheme.save() # modify the interfaces file adding the wlano-xx network data on the basis of the network encription type - print "default AP schema has been saved" + print("default AP schema has been saved") def removewifi(ssid): @@ -121,7 +125,7 @@ def restoredefault(): def connect_savedwifi(thessid): # get all cells from the air - print "connecting to saved wifi network" + print("connecting to saved wifi network") flushIP("wlan0") isok=False #ifdown("wlan0") @@ -131,28 +135,28 @@ def connect_savedwifi(thessid): def connect_preconditions(): - print "checking preconditions for WiFi connection" + print("checking preconditions for WiFi connection") # get list of saved networks savedssids = wpa_cli_mod.listsavednetwork("wlan0") - print "Saved ssID =", savedssids + print("Saved ssID =", savedssids) if savedssids: # get all cells from the air ssids=[] ssids=wifilist_ssid(3) - print "ssID on air =", ssids + print("ssID on air =", ssids) logger.info("Final Number of scan SSID: %d",len(ssids)) for ssid in savedssids: #print " Scheme ", scheme if ssid in ssids: - print "At least one of WIFI network detected have saved credentials, ssid=" , ssid + print("At least one of WIFI network detected have saved credentials, ssid=" , ssid) logger.info("At least one of WIFI network can be connected, ssid=%s" , ssid) return ssid else: - print "No Saved wifi network to connect to" + print("No Saved wifi network to connect to") logger.info("No Saved wifi network to connect to") - print "No conditions to connect to wifi network" + print("No conditions to connect to wifi network") logger.info("No conditions to connect to wifi network") return "" @@ -165,7 +169,7 @@ def connectedssid(): cmd = ['iw', 'dev', 'wlan0', 'link'] wordtofind="SSID" ssids=iwcommand(cmd,wordtofind) - print "Connected to ", ssids + print("Connected to ", ssids) return ssids def iwcommand(cmd,wordtofind): @@ -173,7 +177,7 @@ def iwcommand(cmd,wordtofind): try: scanoutput = subprocess.check_output(cmd).decode('utf-8') except: - print "error to execute the command" , cmd + print("error to execute the command" , cmd) logger.error("error to execute the command %s",cmd) return ssids @@ -200,13 +204,13 @@ def CheckandUnlockWlan(): time.sleep(0.1) if isblocked: - print "Warning WiFi locked, try to unlock" + print("Warning WiFi locked, try to unlock") logger.warning("wlan status locked, try to unlock, please double check the wifi locale setting") cmd = ['rfkill', 'unblock', 'wifi'] try: scanoutput = subprocess.check_output(cmd).decode('utf-8') except: - print "error to execute the command" , cmd + print("error to execute the command" , cmd) logger.error("error to execute the command %s",cmd) return False time.sleep(0.1) @@ -216,10 +220,10 @@ def CheckandUnlockWlan(): if isblocked: # check if the command worked logger.error("Not able to unlock WiFi") - print "Error WiFi still locked after attempt to unlock" + print("Error WiFi still locked after attempt to unlock") else: logger.info("wifi status unlocked :)") - print "Wifi Unlocked ***************+" + print("Wifi Unlocked ***************+") return not isblocked @@ -229,7 +233,7 @@ def ExecCLIandFindOutput(cmd,wordtofind,wordtofindinrow): try: scanoutput = subprocess.check_output(cmd).decode('utf-8') except: - print "error to execute the command" , cmd + print("error to execute the command" , cmd) logger.error("error to execute the command %s",cmd) return wordfound @@ -242,48 +246,48 @@ def ExecCLIandFindOutput(cmd,wordtofind,wordtofindinrow): return wordfound def gethostname(): - print "Get hostname" + print("Get hostname") cmd = ['hostname'] try: output_string = subprocess.check_output(cmd).decode('utf-8').strip() time.sleep(0.5) - print output_string + print(output_string) return output_string except subprocess.CalledProcessError as e: - print "error to execute the command" , cmd + print("error to execute the command" , cmd) logger.error("error to execute the command %s",cmd) return "error" def setnewhostname(HOSTNAME): - print "Set hostname" + print("Set hostname") # hostnamectl set-hostname $NewHostName cmd = [ "hostnamectl" , 'set-hostname' , HOSTNAME] try: output_string = subprocess.check_output(cmd).decode('utf-8').strip() return output_string except subprocess.CalledProcessError as e: - print "error to execute the command" , cmd + print("error to execute the command" , cmd) logger.error("error to execute the command %s",cmd) return "error" def start_hostapd(): done=False - print "try to start hostapd" + print("try to start hostapd") # systemctl restart dnsmasq.service cmd = ['systemctl' , 'restart' , 'hostapd.service'] try: output = subprocess.check_output(cmd).decode('utf-8') time.sleep(2) except: - print "error to execute the command" , cmd + print("error to execute the command" , cmd) logger.error("error to execute the command %s",cmd) - print "Hostapd error failed to start the service " + print("Hostapd error failed to start the service ") return False else: strstart=output.find("failed") if strstart>-1: - print "failed to start hostapd" + print("failed to start hostapd") done=False else: done=True @@ -291,21 +295,21 @@ def start_hostapd(): def stop_hostapd(): done=False - print "try to stop hostapd" + print("try to stop hostapd") # systemctl restart dnsmasq.service cmd = ['systemctl' , 'stop' , 'hostapd.service'] try: output = subprocess.check_output(cmd).decode('utf-8') time.sleep(1) except: - print "error to execute the command" , cmd + print("error to execute the command" , cmd) logger.error("error to execute the command %s",cmd) - print "Hostapd error, failed to stop the service " + print("Hostapd error, failed to stop the service ") return False else: strstart=output.find("failed") if strstart>-1: - print "failed to stop hostapd" + print("failed to stop hostapd") done=False else: done=True @@ -313,21 +317,21 @@ def stop_hostapd(): def start_dnsmasq(): done=False - print "try to start DNSmasq" + print("try to start DNSmasq") # systemctl restart dnsmasq.service cmd = ['systemctl' , 'restart' , 'dnsmasq.service'] try: output = subprocess.check_output(cmd).decode('utf-8') time.sleep(1) except: - print "error to execute the command" , cmd + print("error to execute the command" , cmd) logger.error("error to execute the command %s",cmd) - print "DNSmasq error, failed to start " + print("DNSmasq error, failed to start ") return False else: strstart=output.find("failed") if strstart>-1: - print "DNSmasq error, failed to start " + print("DNSmasq error, failed to start ") done=False else: done=True @@ -336,21 +340,21 @@ def start_dnsmasq(): def stop_dnsmasq(): done=False - print "try to stop dnsmasq" + print("try to stop dnsmasq") # systemctl restart dnsmasq.service cmd = ['systemctl' , 'stop' , 'dnsmasq.service'] try: output = subprocess.check_output(cmd).decode('utf-8') time.sleep(1) except: - print "error to execute the command" , cmd + print("error to execute the command" , cmd) logger.error("error to execute the command %s",cmd) - print "DNSmasq error, failed to stop " + print("DNSmasq error, failed to stop ") return False else: strstart=output.find("failed") if strstart>-1: - print "DNSmasq error, failed to stop " + print("DNSmasq error, failed to stop ") done=False else: done=True @@ -360,22 +364,22 @@ def stop_dnsmasq(): # ip link set wlan0 down def ifdown(interface): - print "try ifdown" + print("try ifdown") cmd = ['ip' , 'link' , 'set', interface, 'down'] try: ifup_output = subprocess.check_output(cmd).decode('utf-8') time.sleep(1) - print "ifdown OK " + print("ifdown OK ") #sudo ifdown --force wlan0 #seems to work return True except subprocess.CalledProcessError as e: - print "ifdown failed: ", e - print "error to execute the command" , cmd + print("ifdown failed: ", e) + print("error to execute the command" , cmd) logger.error("error to execute the command %s",cmd) return False def ifup(interface): - print "try ifup" + print("try ifup") cmd = ['ip' , 'link' , 'set', interface, 'up'] try: ifup_output = subprocess.check_output(cmd).decode('utf-8') @@ -383,9 +387,9 @@ def ifup(interface): time.sleep(2) return True except subprocess.CalledProcessError as e: - print "error to execute the command" , cmd + print("error to execute the command" , cmd) logger.error("error to execute the command %s",cmd) - print "ifup failed: ", e + print("ifup failed: ", e) return False def waituntilIFUP(interface,timeout): # not working properly, to be re-evaluated @@ -396,56 +400,56 @@ def waituntilIFUP(interface,timeout): # not working properly, to be re-evaluated try: ifup_output = subprocess.check_output(cmd).decode('utf-8') except: - print "error to execute the command" , cmd + print("error to execute the command" , cmd) logger.error("error to execute the command %s",cmd) ifup_output="" if not ifup_output: - print "interface ", interface , " still down, check again in one second" + print("interface ", interface , " still down, check again in one second") time.sleep(1) i=i+1 else: done=True - print "interface ", interface , " UP after seconds: ", i - print "output ", ifup_output + print("interface ", interface , " UP after seconds: ", i) + print("output ", ifup_output) return done def flushIP(interface): #------------------- - print "try flush IP" + print("try flush IP") cmd = ['ip', 'addr' , 'flush' , 'dev', interface] try: # sudo ip addr flush dev wlan0 ifup_output = subprocess.check_output(cmd).decode('utf-8') - print "FlushIP: ", interface , " OK ", ifup_output + print("FlushIP: ", interface , " OK ", ifup_output) time.sleep(0.5) return True except subprocess.CalledProcessError as e: - print "error to execute the command" , cmd + print("error to execute the command" , cmd) logger.error("error to execute the command %s",cmd) - print "IP flush failed: ", e + print("IP flush failed: ", e) return False def resetDHCP(): - print "try to reset DHCP" + print("try to reset DHCP") cmd = ['dhclient', '-v' ] try: ifup_output = subprocess.check_output(cmd).decode('utf-8') - print "Reset DHCP " + print("Reset DHCP ") time.sleep(0.5) return True except subprocess.CalledProcessError as e: - print "error to execute the command" , cmd + print("error to execute the command" , cmd) logger.error("error to execute the command %s",cmd) - print "Reset DHCP Failed: ", e + print("Reset DHCP Failed: ", e) return False def checkGWsubnet(interface): #------------------- - print "Check if the Gateway IP address has same subnet of statip ip" + print("Check if the Gateway IP address has same subnet of statip ip") logger.info("Check if the Gateway IP address has same subnet of statip ip") # the command -ip route- will provide the -default- gateway address, when in AP mode or this will not be present # when connected to the WIFi router the "wlan0" will be present @@ -460,7 +464,7 @@ def checkGWsubnet(interface): #------------------- ifup_output = subprocess.check_output(cmd).decode('utf-8') time.sleep(0.5) except: - print "error to execute the command" , cmd + print("error to execute the command" , cmd) logger.error("error to execute the command %s",cmd) return True, ipaddr @@ -475,7 +479,7 @@ def checkGWsubnet(interface): #------------------- break if isaddress: - print "got default Gateway for ",interface + print("got default Gateway for ",interface) logger.info("got default Gateway for wlan0 = %s", ipaddr) #check if same subnet staticIPlist=IPADDRESS.split(".") @@ -484,7 +488,7 @@ def checkGWsubnet(interface): #------------------- i=0 minlen=min(len(staticIPlist), len(gwIPlist)) while (staticIPlist[i]==gwIPlist[i]) and (i0: @@ -827,9 +831,9 @@ def connect_network(internetcheck=False, backtoAP=False): if not ssid==thessid: - print "try to connect to wifi network" + print("try to connect to wifi network") logger.info('try to connect to wifi network %s ' ,thessid) - print "try to stop AP services, hostapd, dnsmasq" + print("try to stop AP services, hostapd, dnsmasq") logger.info('try to stop AP services, hostapd, dnsmasq ') i=0 done=False @@ -851,11 +855,11 @@ def connect_network(internetcheck=False, backtoAP=False): i=i+1 if done: time.sleep(1+i*5) - print "wifi connection attempt ",i - print "check connected SSID" + print("wifi connection attempt ",i) + print("check connected SSID") logger.info('Connection command executed attempt %d, check connected SSID ',i) else: - print "Connection command NOT executed properly , attempt ",i + print("Connection command NOT executed properly , attempt ",i) logger.info('Connection command NOT executed properly , attempt %d ',i) ssids=connectedssid() @@ -865,23 +869,23 @@ def connect_network(internetcheck=False, backtoAP=False): else: ssid="" logger.info('NO connected SSID') - print "Connected to the SSID ", ssid + print("Connected to the SSID ", ssid) logger.info('Connected SSID: %s -- ', ssid) addIP("wlan0") else: - print "already connected to the SSID ", ssid + print("already connected to the SSID ", ssid) if len(ssids)==0: - print "No SSID established, fallback to AP mode" + print("No SSID established, fallback to AP mode") # go back and connect in Access point Mode logger.info('No Wifi Network connected, no AP connected, going back to Access Point mode') connect_AP() connected=False else: logger.info('Connected to Wifi Network %s' , ssid ) - print 'Connected to Wifi Network ' , ssid + print('Connected to Wifi Network ' , ssid) @@ -889,15 +893,15 @@ def connect_network(internetcheck=False, backtoAP=False): if internetcheck: connected=check_internet_connection(3) if connected: - print "Google is reacheable !" + print("Google is reacheable !") logger.info('Google is reacheable ! ') #send first mail - print "Send first mail !" + print("Send first mail !") logger.info('Send first mail ! ') emailmod.sendallmail("alert", "System has been reconnected to wifi network") else: if backtoAP: # in case connection to Internet not working - print "Connectivity problem with WiFi network " ,ssid[0] , "going back to wifi access point mode" + print("Connectivity problem with WiFi network " ,ssid[0] , "going back to wifi access point mode") logger.info('Connectivity problem with WiFi network, %s, gong back to wifi access point mode' ,ssid ) connect_AP() else: @@ -906,9 +910,9 @@ def connect_network(internetcheck=False, backtoAP=False): # ALL below not needed anymore since I disabled the NTP network time protocal daemon ***** else: - print "No Saved Wifi Network available" + print("No Saved Wifi Network available") logger.info('No Saved Wifi Network available') - print "try to fallback to AP mode" + print("try to fallback to AP mode") # go back and connect in Access point Mode logger.info('Going back to Access Point mode') connect_AP() @@ -919,7 +923,7 @@ def connect_network(internetcheck=False, backtoAP=False): def internet_on_old(): try: - response=urllib2.urlopen('http://www.google.com',timeout=1) + response=urllib.request.urlopen('http://www.google.com',timeout=1) logger.info('Internet status ON') return True except: @@ -932,10 +936,10 @@ def internet_on(): for site in websites: for timeout in timeouts: try: - response=urllib2.urlopen(site,timeout=timeout) + response=urllib.request.urlopen(site,timeout=timeout) return True except: - print "internet_on: Error to connect" + print("internet_on: Error to connect") return False def check_internet_connection(ntimes=3): @@ -960,22 +964,23 @@ def get_external_ip(): try: proc=subprocess.Popen(shlex.split(cmd),stdout=subprocess.PIPE) out,err=proc.communicate() + out=out.decode() logger.info('Got reply from openDNS') except: - print "error to execute the command" , cmd + print("error to execute the command" , cmd) logger.error("error to execute the command %s",cmd) - print "External IP Error " + print("External IP Error ") logger.error('Error to get External IP') return "" logger.info('Reply from openDNS: %s', out) isaddress , ipaddr = IPv4fromString(out) if not isaddress: - print "External IP Error " + print("External IP Error ") logger.error('Error to get external IP , wrong syntax') return "" - print "External IP address " , ipaddr + print("External IP address " , ipaddr) logger.info("External IP address %s" , ipaddr) #myip = urllib2.urlopen("http://myip.dnsdynamic.org/").read() #print myip @@ -992,16 +997,16 @@ def get_local_ip(): cmd = ["hostname -I"] try: ipaddrlist = subprocess.check_output(cmd, shell=True).decode('utf-8') - print "IP addresses " , ipaddrlist + print("IP addresses " , ipaddrlist) #hostname -I #s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) #s.connect(("gmail.com",80)) #ipaddr=s.getsockname()[0] #s.close() except: - print "error to execute the command" , cmd + print("error to execute the command" , cmd) logger.error("error to execute the command %s",cmd) - print "Local IP Error " + print("Local IP Error ") logger.error('Error to get local IP') return "" global IPADDRESS @@ -1009,10 +1014,10 @@ def get_local_ip(): return IPADDRESS isaddress , ipaddr = IPv4fromString(ipaddrlist) if not isaddress: - print "Local IP Error with Sintax" + print("Local IP Error with Sintax") logger.error('Error to get local IP, wrong suntax') return "" - print ipaddr + print(ipaddr) return ipaddr @@ -1021,9 +1026,9 @@ def get_local_ip_list(): try: cmd_output = subprocess.check_output(cmd, shell=True).decode('utf-8') except: - print "error to execute the command" , cmd + print("error to execute the command" , cmd) logger.error("error to execute the command %s",cmd) - print "Local IP Error " + print("Local IP Error ") logger.error('Error to get local IP') return "" ipaddrlist=[] @@ -1032,21 +1037,21 @@ def get_local_ip_list(): isaddress , ipaddr = IPv4fromString(ipstrings) if isaddress: ipaddrlist.append(ipaddr) - print ipaddr + print(ipaddr) return ipaddrlist def get_local_ip_raw(): cmd = ["hostname -I"] try: ipaddrlist = subprocess.check_output(cmd, shell=True).decode('utf-8') - print "IP addresses " , ipaddrlist + print("IP addresses " , ipaddrlist) except: - print "error to execute the command" , cmd + print("error to execute the command" , cmd) logger.error("error to execute the command %s",cmd) - print "Local IP Error " + print("Local IP Error ") logger.error('Error to get local IP') return "" - print ipaddrlist + print(ipaddrlist) return ipaddrlist @@ -1062,11 +1067,11 @@ def multiIPv4fromString(ipaddrlist): return addresslist def IPv4fromString(ip_string): #extract the first valid IPv4 address in the string - print " Start -- " + print(" Start -- ") iprows=ip_string.split('\n') ip_address="" for ip in iprows: - print "String IP address ", ip + print("String IP address ", ip) countdigit=0 countdot=0 start=-1 @@ -1086,7 +1091,7 @@ def IPv4fromString(ip_string): #extract the first valid IPv4 address in the stri thestring=ip[start:inde] if checkstringIPv4(thestring): ip_address=thestring - print "IP extracted succesfully " , ip_address + print("IP extracted succesfully " , ip_address) return True , ip_address start=-1 @@ -1103,14 +1108,14 @@ def IPv4fromString(ip_string): #extract the first valid IPv4 address in the stri thestring=ip[start:inde] if checkstringIPv4(thestring): ip_address=thestring - print "IP extracted succesfully " , ip_address + print("IP extracted succesfully " , ip_address) return True, ip_address return False , "" def checkstringIPv4(thestring): - print thestring + print(thestring) numbers=thestring.split(".") if len(numbers)==4: try: @@ -1139,8 +1144,8 @@ def checkstringIPv4(thestring): ip_string="sad 23.3.2.1 ceh ca2cchio 12.2.0.12ma chi siete" ip_address="" isok, string = IPv4fromString(ip_string) - print isok - print "the extracted string ", string + print(isok) + print("the extracted string ", string) - print "NEXT TEST" - print checkGWsubnet("wlan0") + print("NEXT TEST") + print(checkGWsubnet("wlan0")) diff --git a/photomod-fswebcam.py b/photomod-fswebcam.py old mode 100644 new mode 100755 index 54ca3b6..81790ce --- a/photomod-fswebcam.py +++ b/photomod-fswebcam.py @@ -1,3 +1,4 @@ +from __future__ import print_function import time from time import sleep import datetime @@ -10,7 +11,7 @@ def saveshot(filepath,realshot=True): shottaken=False currentdate=datetime.datetime.now().strftime("%y-%m-%d,%H:%M") - print "Current date and time: " , currentdate + print("Current date and time: " , currentdate) cam_list = "/dev/video0" if cam_list: gonext=True @@ -19,10 +20,10 @@ def saveshot(filepath,realshot=True): filepath=os.path.join(filepath, currentdate+".jpg") else: filepath=os.path.join(filepath, "testimage.jpg") - print filepath + print(filepath) filexist=os.path.isfile(filepath) - print "file already exist = ", filexist + print("file already exist = ", filexist) if filexist: os.rename(filepath, filepath + ".bak") @@ -32,23 +33,23 @@ def saveshot(filepath,realshot=True): myproc = Popen("fswebcam -d "+ cam_list +" -r 1280x1024 -S 35 --jpeg 95 " + filepath, shell=True, stdout=PIPE, stderr=PIPE) #sleep(10) - print myproc.stdout.readline() - print 'Return code was ', myproc.returncode + print(myproc.stdout.readline()) + print('Return code was ', myproc.returncode) sleep(2) newfilexist=os.path.isfile(filepath) - print "file was created = ", newfilexist + print("file was created = ", newfilexist) shottaken=True if not newfilexist: shottaken=False if filexist: os.rename(filepath + ".bak", filepath) - print "Picture take = " ,shottaken + print("Picture take = " ,shottaken) else: - print "camera not connected" + print("camera not connected") return shottaken @@ -68,9 +69,9 @@ def saveshot(filepath,realshot=True): # If run from command line dir_path = sys.path[0] - print dir_path + print(dir_path) filepath=os.path.join(dir_path, "static") filepath=os.path.join(filepath, "cameratest") - print filepath + print(filepath) saveshot(filepath,False) #saveshot() diff --git a/photomod-raspicam.py b/photomod-raspicam.py old mode 100644 new mode 100755 index 0407444..242eaa2 --- a/photomod-raspicam.py +++ b/photomod-raspicam.py @@ -1,3 +1,4 @@ +from __future__ import print_function import time from time import sleep import datetime @@ -16,7 +17,7 @@ def saveshot(filepath,realshot=True): shottaken=False currentdate=datetime.datetime.now().strftime("%y-%m-%d,%H:%M") - print "Current date and time: " , currentdate + print("Current date and time: " , currentdate) cam_list = "/dev/video0" if ISRPI: gonext=True @@ -25,10 +26,10 @@ def saveshot(filepath,realshot=True): filepath=os.path.join(filepath, currentdate+".jpg") else: filepath=os.path.join(filepath, "testimage.jpg") - print filepath + print(filepath) filexist=os.path.isfile(filepath) - print "file already exist = ", filexist + print("file already exist = ", filexist) if filexist: os.rename(filepath, filepath + ".bak") @@ -48,18 +49,18 @@ def saveshot(filepath,realshot=True): # shot taken newfilexist=os.path.isfile(filepath) - print "file was created = ", newfilexist + print("file was created = ", newfilexist) shottaken=True if not newfilexist: shottaken=False if filexist: os.rename(filepath + ".bak", filepath) - print "Picture take = " ,shottaken + print("Picture take = " ,shottaken) else: - print "camera not connected" + print("camera not connected") return shottaken @@ -79,9 +80,9 @@ def saveshot(filepath,realshot=True): # If run from command line dir_path = sys.path[0] - print dir_path + print(dir_path) filepath=os.path.join(dir_path, "static") filepath=os.path.join(filepath, "cameratest") - print filepath + print(filepath) saveshot(filepath,False) #saveshot() diff --git a/photomod.py b/photomod.py old mode 100644 new mode 100755 index 3ebc66d..462fbf6 --- a/photomod.py +++ b/photomod.py @@ -1,3 +1,4 @@ +from __future__ import print_function import time from time import sleep import datetime @@ -24,13 +25,13 @@ def videodevlist(): videonumber=int(videonumberstr) except: videonumber=-1 - print "not able to convert the video number" + print("not able to convert the video number") if videonumber>-1: if (videonumber<10): - print "check video " , filename + print("check video " , filename) # following code was necessary starting from raspbian buster, linux kernel v4l2 was updated, now one single webcam can show more than one videoXX dev if checkvideoformatexist(videonumberstr): - print "OK video " , filename + print("OK video " , filename) videolist.append(filename) return videolist # item1 (path) item2 (name) item3 (datetime) @@ -47,18 +48,18 @@ def checkvideoformatexist(videonumberstr): try: scanoutput = subprocess.check_output(cmd).decode('utf-8') except: - print "error to execute the command" , cmd + print("error to execute the command" , cmd) logger.error("error to execute the command %s",cmd) return False if not DeviceType in scanoutput: - print "not a video capture device =" , videonumberstr + print("not a video capture device =" , videonumberstr) return False # check if one of the format is inside the output string for formatitem in formats: if formatitem in scanoutput: - print "At least a format = ", formatitem ," for video capture device =" , videonumberstr + print("At least a format = ", formatitem ," for video capture device =" , videonumberstr) return True return False @@ -83,7 +84,7 @@ def executeandsearch(cmd,wordtofind): try: scanoutput = subprocess.check_output(cmd).decode('utf-8') except: - print "error to execute the command" , cmd + print("error to execute the command" , cmd) logger.error("error to execute the command %s",cmd) return False @@ -103,7 +104,7 @@ def executeandsearch(cmd,wordtofind): def saveshot(filepath, video, realshot, resolution, positionvalue, vdirection): shottaken=False - print "take photo" + print("take photo") if vdirection=="neg": rotdeg="180" @@ -111,7 +112,7 @@ def saveshot(filepath, video, realshot, resolution, positionvalue, vdirection): rotdeg="0" currentdate=datetime.datetime.now().strftime("%y-%m-%d,%H:%M") - print "Current date and time: " , currentdate + print("Current date and time: " , currentdate) if realshot: filenamenopath=currentdate+"@"+video+"@"+positionvalue+".jpg" filenamenopath2=currentdate+"@"+video+"@"+positionvalue+"F.jpg" @@ -122,8 +123,8 @@ def saveshot(filepath, video, realshot, resolution, positionvalue, vdirection): filenamenopath3=filenamenopath filename=os.path.join(filepath, filenamenopath) - print "Start Photo procedure: ", video , " ************************************************" - print "FILE : ", filename + print("Start Photo procedure: ", video , " ************************************************") + print("FILE : ", filename) cam_list = "/dev/" + video @@ -131,7 +132,7 @@ def saveshot(filepath, video, realshot, resolution, positionvalue, vdirection): filexist=os.path.isfile(filename) - print "file already exist = ", filexist + print("file already exist = ", filexist) if (filexist)and(not realshot): os.rename(filename, filename + ".bak") @@ -166,12 +167,12 @@ def saveshot(filepath, video, realshot, resolution, positionvalue, vdirection): if checkPIcam(video): - print "The video device should be PI camera" + print("The video device should be PI camera") shottaken=takeshotandsave_raspistill(filepath,filenamenopath3, video, resolution,rotdeg) if not shottaken: # gives it a second chance :) shottaken=takeshotandsave_fswebcam(filepath,filenamenopath2, video, resolution,rotdeg) else: - print " The video device should be USB camera" + print(" The video device should be USB camera") shottaken=takeshotandsave_fswebcam(filepath,filenamenopath2, video, resolution,rotdeg) #shottaken=takeshotandsave_mjpg_streamer(filepath,filenamenopath, video, resolution) @@ -180,12 +181,12 @@ def saveshot(filepath, video, realshot, resolution, positionvalue, vdirection): if filexist: os.rename(filename + ".bak", filename) - print "Picture acknowledge return = " ,shottaken + print("Picture acknowledge return = " ,shottaken) else: - print "camera not connected" + print("camera not connected") return shottaken @@ -196,7 +197,7 @@ def takeshotandsave_raspistill(filepath,filenamenopath, video, resolution, rotde vflip="-vf -hf" else: vflip="" - print "flip ", vflip + print("flip ", vflip) cam_list = "/dev/" + video @@ -205,41 +206,43 @@ def takeshotandsave_raspistill(filepath,filenamenopath, video, resolution, rotde while (not shottaken)and(i<3): i=i+1 filename=os.path.join(filepath, filenamenopath) - print "FILE : ", filename + print("FILE : ", filename) shottaken=False w=resolution.split("x")[0] h=resolution.split("x")[1] - print "try raspistill" + print("try raspistill") filenamebase=filenamenopath.split(".")[0] extension=filename.split(".")[1] # create the picture files + isok=False try: myproc = subprocess.check_output("raspistill "+vflip+" -w "+w+" -h "+h+" -q 95 -a 12 -a \"%Y-%m-%d %X (UTC)\" -o " + filename, shell=True, stderr=subprocess.STDOUT) + isok=True except: - print "problem to execute command" - myproc = "error" + print("problem to execute command") + newfilexist=os.path.isfile(filename) - print "file was created = ", newfilexist + print("file was created = ", newfilexist) - if (myproc=="")and(newfilexist): - print "raspistill got picture" + if (isok)and(newfilexist): + print("raspistill got picture") shottaken=True # make thumbnail ExistandThumb(filepath,filenamenopath,shottaken) else: - print "raspistill not able to get picture" + print("raspistill not able to get picture") shottaken=False - print "RASPISTILL Picture take = " ,shottaken, " Attempt ", i + print("RASPISTILL Picture take = " ,shottaken, " Attempt ", i) return shottaken @@ -259,7 +262,7 @@ def takeshotandsave_fswebcam(filepath,filenamenopath, video, resolution, rotdeg) while (not shottaken)and(i<3): i=i+1 filename=os.path.join(filepath, filenamenopath) - print "FILE : ", filename + print("FILE : ", filename) @@ -267,7 +270,7 @@ def takeshotandsave_fswebcam(filepath,filenamenopath, video, resolution, rotdeg) w=resolution.split("x")[0] h=resolution.split("x")[1] - print "try fswebcam" + print("try fswebcam") filenamebase=filenamenopath.split(".")[0] @@ -281,11 +284,13 @@ def takeshotandsave_fswebcam(filepath,filenamenopath, video, resolution, rotdeg) # create the picture files #fswebcam option + isok=False try: myproc = subprocess.check_output("fswebcam -q -d "+ cam_list +" -r "+resolution+" -S "+S+" --rotate "+rotdeg+" -s brightness=50% -s Contrast=50% --jpeg 95 " + filename, shell=True, stderr=subprocess.STDOUT) + isok=True except: - print "problem to execute command" - myproc = "error" + print("problem to execute command") + # -R use read() method -- NOT WORKING --- # -D delay before taking frames # -S skip the first frames @@ -294,27 +299,27 @@ def takeshotandsave_fswebcam(filepath,filenamenopath, video, resolution, rotdeg) # -r resoltion # -F takes frames - print "output from subprocess: " , myproc + print("output from subprocess: " , myproc) newfilexist=os.path.isfile(filename) - print "file was created = ", newfilexist + print("file was created = ", newfilexist) - if (myproc=="")and(newfilexist): - print "fswebcam got picture" + if (isok)and(newfilexist): + print("fswebcam got picture") shottaken=True # make thumbnail ExistandThumb(filepath,filenamenopath,shottaken) else: - print "fswebcam not able to get picture" + print("fswebcam not able to get picture") shottaken=False - print "FSWEBCAM Picture take = " ,shottaken, " Attempt ", i + print("FSWEBCAM Picture take = " ,shottaken, " Attempt ", i) else: - print "camera not connected" + print("camera not connected") return shottaken def takeshotandsave_mjpg_streamer(filepath,filenamenopath, video, resolution , rotdeg): @@ -322,7 +327,7 @@ def takeshotandsave_mjpg_streamer(filepath,filenamenopath, video, resolution , r filename=os.path.join(filepath, filenamenopath) - print "FILE : ", filename + print("FILE : ", filename) @@ -333,7 +338,7 @@ def takeshotandsave_mjpg_streamer(filepath,filenamenopath, video, resolution , r w=resolution.split("x")[0] h=resolution.split("x")[1] - print "try mjpg_streamer" + print("try mjpg_streamer") filenamebase=filenamenopath.split(".")[0] @@ -357,7 +362,7 @@ def takeshotandsave_mjpg_streamer(filepath,filenamenopath, video, resolution , r fps="20" if (video=="video0")and(int(w)>1024): - print "mjpg_streamer using the raspicam" + print("mjpg_streamer using the raspicam") stream="mjpg_streamer -i '/usr/local/lib/mjpg-streamer/input_raspicam.so -d /dev/"+video+" -x "+w+" -y "+h+" -fps "+fps+" -rot "+rotdeg+"' -o '/usr/local/lib/mjpg-streamer/output_file.so -f "+pathmjpg+" -d 100' &" else: stream="mjpg_streamer -i '/usr/local/lib/mjpg-streamer/input_uvc.so -d /dev/"+video+" -r "+w+"x"+h+" -f "+fps+" -rot "+rotdeg+"' -o '/usr/local/lib/mjpg-streamer/output_file.so -f "+pathmjpg+" -d 100' &" @@ -388,17 +393,17 @@ def takeshotandsave_mjpg_streamer(filepath,filenamenopath, video, resolution , r # make thumbnail ExistandThumb(filepath,filenamenopath,shottaken) else: - print "mjpg_streame not able to get picture" + print("mjpg_streame not able to get picture") shottaken=False - print "MJPG_STREAMER Picture take = " ,shottaken + print("MJPG_STREAMER Picture take = " ,shottaken) else: - print "camera not connected" + print("camera not connected") return shottaken @@ -418,7 +423,7 @@ def ExistandThumb(filepath,filenamenopath,shottaken): thumbname=os.path.join(paththumb,filenamenopath) image.save(thumbname) except: - print "not able to make thumbnail" + print("not able to make thumbnail") return newfilexist @@ -430,11 +435,11 @@ def thumbconsistency(apprunningpath): # control if the folder hydropicture exist otherwise create it if not os.path.exists(filepath): os.makedirs(filepath) - print "Hydropicture folder has been created" + print("Hydropicture folder has been created") paththumb=os.path.join(filepath,"thumb") if not os.path.exists(paththumb): os.makedirs(paththumb) - print "Hydropicture thumbnail folder has been created" + print("Hydropicture thumbnail folder has been created") filenamelist=os.listdir(filepath) @@ -442,7 +447,7 @@ def thumbconsistency(apprunningpath): for thumbnail in thumbnamelist: if thumbnail not in filenamelist: - print "thumbnail has no corresponding image, delete" + print("thumbnail has no corresponding image, delete") os.remove(os.path.join(paththumb, thumbnail)) # create thumbnail in case picture has no coresponding thumbnail @@ -451,7 +456,7 @@ def thumbconsistency(apprunningpath): for fileimage in filenamelist: if os.path.isfile(os.path.join(filepath, fileimage)): if fileimage not in thumbnamelist: - print "image has no corresponding thumbnail, create" + print("image has no corresponding thumbnail, create") #create thumbnail try: image = Image.open(os.path.join(filepath,fileimage)) @@ -474,5 +479,5 @@ def thumbconsistency(apprunningpath): """ prova funzioni di camera """ - print "PI cam device :" , findPIcam() + print("PI cam device :" , findPIcam()) #saveshot() diff --git a/selectedplanmod.py b/selectedplanmod.py old mode 100644 new mode 100755 index 32d457e..ac2134c --- a/selectedplanmod.py +++ b/selectedplanmod.py @@ -2,7 +2,12 @@ """ selected plan utility """ +from __future__ import print_function +from __future__ import division +from builtins import str +from builtins import range +from past.utils import old_div import logging import os import os.path @@ -26,6 +31,7 @@ import automationmod import debuggingmod import basicSetting +import weatherAPImod DEBUGMODE=basicSetting.data["DEBUGMODE"] MASTERSCHEDULERTIME="00:05:00" @@ -52,7 +58,7 @@ def activateandregister(target,activationseconds): # function to activate the actuators duration=hardwaremod.toint(activationseconds,0) - print target, " ",duration, " " , datetime.now() + print(target, " ",duration, " " , datetime.now()) logger.info('Pulse time for sec = %s', duration) # start pulse pulseok=hardwaremod.makepulse(target,duration) @@ -95,18 +101,18 @@ def startpump(target,activationseconds,MinAveragetemp,MaxAverageHumid): return False duration=hardwaremod.toint(activationseconds,0) - print target, " ",duration, " " , datetime.now() + print(target, " ",duration, " " , datetime.now()) # evaluate parameters #MinAverageLight=500 not used now MinutesOfAverage=120 #minutes in which the average data is calculated from sensor sampling - print "waterpump check" + print("waterpump check") logger.info('execute water pump check %s', datetime.now().strftime("%Y-%m-%d %H:%M:%S")) # then check the temperature and Humidity - print "Check Humidity and Temperature" + print("Check Humidity and Temperature") MinAveragetempnum=hardwaremod.tonumber(MinAveragetemp,"NA") MaxAverageHumidnum=hardwaremod.tonumber(MaxAverageHumid,"NA") @@ -124,14 +130,14 @@ def startpump(target,activationseconds,MinAveragetemp,MaxAverageHumid): humquantity=quantitylist["average"] logger.info('Waterpump Check parameter if humquantity=%s < MaxAverageHumid=%s ', str(humquantity), str(MaxAverageHumid)) - print 'Waterpump Check parameter if humquantity=',humquantity,' < MaxAverageHumid=' ,MaxAverageHumid + print('Waterpump Check parameter if humquantity=',humquantity,' < MaxAverageHumid=' ,MaxAverageHumid) if (MaxAverageHumidnum!="NA"): if (humquantity MinAveragetemp=%s ', str(tempquantity), str(MinAveragetemp)) - print 'Waterpump Check parameter if tempquantity=',tempquantity,' > MinAveragetemp=' ,MinAveragetemp + print('Waterpump Check parameter if tempquantity=',tempquantity,' > MinAveragetemp=' ,MinAveragetemp) if (MinAveragetempnum!="NA"): if (tempquantity>MinAveragetempnum): logger.info('Temperature check PASSED, tempquantity=%s > MinAveragetemp=%s ', str(tempquantity), str(MinAveragetemp)) else: logger.info('Temperature check FAILED') - print 'Temperature check FAILED' + print('Temperature check FAILED') pumpit=False + + # weather Forecast + sensorname=weatherAPImod.DefaultCounterName() + sensorlist=sensordbmod.gettablelist() + if sensorname in sensorlist: + ActiveActuatorList=weatherAPImod.ActiveActuatorList() + if target in ActiveActuatorList: + sensordata=[] + samplesnumber=1 + sensordbmod.getsensordbdatasamplesN(sensorname,sensordata,samplesnumber) + MaxPastMinutes=1200 + starttimecalc=datetime.now()-timedelta(minutes=MaxPastMinutes) + isok , quantitylist=sensordbmod.EvaluateDataPeriod(sensordata,starttimecalc,datetime.now()) + if isok: + RainMultipier=quantitylist["average"] + logger.info('Waterpump weather multiplier =%s ', str(RainMultipier)) + else: + logger.warning('Waterpump weather multiplier NOT found within 20 Hours apply 100 ') + RainMultipier=100 + duration=int(duration*RainMultipier/100) + else: + logger.warning('Weather Sensor not found, no multpilier applied ') + - if pumpit: + if pumpit: # activation of the doser before the pump doseron=autofertilizermod.checkactivate(target,duration) # watering @@ -170,7 +199,7 @@ def startpump(target,activationseconds,MinAveragetemp,MaxAverageHumid): def periodicdatarequest(sensorname): - print "Read sensors request: ", sensorname , " " , datetime.now() + print("Read sensors request: ", sensorname , " " , datetime.now()) logger.info('Read sensor data: %s - %s', sensorname, datetime.now().strftime("%Y-%m-%d %H:%M:%S")) sensorvalue=hardwaremod.getsensordata(sensorname,3) if sensorvalue!="": @@ -184,7 +213,7 @@ def periodicdatarequest(sensorname): def CheckNTPandAdjustClockandResetSched(timediffsec=60): # try to get the clock from network - print "check system clock" + print("check system clock") logger.info('Check system clock vs NTP (Network Time Protocol)') networktime=clockmod.getNTPTime() logger.info('Network time NTP: %s ', networktime) @@ -194,9 +223,9 @@ def CheckNTPandAdjustClockandResetSched(timediffsec=60): diffsec=clockmod.timediffinsec(networktime, systemtime) logger.info('Difference between system time and network time, diffsec = %d ', diffsec) if diffsec>timediffsec: - print "Warning difference between system time and network time >",timediffsec ," sec, diffsec = " , diffsec + print("Warning difference between system time and network time >",timediffsec ," sec, diffsec = " , diffsec) logger.warning('Warning difference between system time and network time >%d sec, diffsec = %d ', timediffsec , diffsec) - print "Apply network datetime to system" + print("Apply network datetime to system") logger.warning('Apply network datetime to system ') clockmod.setHWclock(networktime) clockmod.setsystemclock(networktime) @@ -205,24 +234,24 @@ def CheckNTPandAdjustClockandResetSched(timediffsec=60): resetmastercallback() return True else: - print "Clock OK" + print("Clock OK") logger.info('Clock OK') else: - print "not able to get network time" + print("not able to get network time") logger.warning('Not able to get network time') return False def heartbeat(): - print "start heartbeat check", " " , datetime.now() + print("start heartbeat check", " " , datetime.now()) logger.info('Start heartbeat routine %s', datetime.now().strftime("%Y-%m-%d %H:%M:%S")) # check wifi connection connectedssid=networkmod.connectedssid() connected=False if len(connectedssid)==0: logger.warning('Heartbeat check , no network connected -------------- try to connect') - print 'Heartbeat check , no network connected -------------- try to connect' + print('Heartbeat check , no network connected -------------- try to connect') connected=networkmod.connect_network() else: logger.info('Heartbeat check , Connected Wifi Network: %s ', connectedssid[0]) @@ -235,7 +264,7 @@ def heartbeat(): if not reachgoogle: logger.warning('Heartbeat check wifi SSID ok, but test ping not able to reach Google') - print 'Heartbeat check , no IP connection' + print('Heartbeat check , no IP connection') #connected=networkmod.connect_network() # use this in case you require the system to try connect wifi again in case no internet is reached #logger.warning('Heartbeat check , DHCP reset counter %s' , str(networkmod.DHCP_COUNTER)) # DHCP reset @@ -260,7 +289,7 @@ def heartbeat(): connected=False else: logger.info('Heartbeat check , wifi connection OK') - print 'Heartbeat check , wifi connection OK' + print('Heartbeat check , wifi connection OK') #networkmod.DHCP_COUNTER=0 connected=True @@ -271,19 +300,19 @@ def heartbeat(): if (ipext!=""): if (emailmod.IPEXTERNALSENT!=""): if ipext!=emailmod.IPEXTERNALSENT: - print "Heartbeat check, IP address change detected. Send email with updated IP address" + print("Heartbeat check, IP address change detected. Send email with updated IP address") logger.info('Heartbeat check, IP address change detected. Send email with updated IP address') emailmod.sendallmail("alert","System detected IP address change, below the updated links") else: logger.info('Heartbeat check, IP address unchanged') else: # first mail has not been sent succesfully of IPEXTERNALSENT was not available by the time - print "System has been reconnected" + print("System has been reconnected") logger.info("System has been reconnected, IPEXTERNALSENT was empty") emailmod.sendallmail("alert","System has been reconnected") else: - print "not able to establish an internet connection" + print("not able to establish an internet connection") logger.warning("not able to establish an internet connection") # check clock with NTP and reset master scheduler in case of clock change @@ -307,15 +336,15 @@ def heartbeat(): if isok: datenow=datetime.utcnow() datenextrun = datenextrun.replace(tzinfo=None) - print "Master Scheduler Next run " , datenextrun , " Now (UTC) ", datenow + print("Master Scheduler Next run " , datenextrun , " Now (UTC) ", datenow) if datenextrun>datenow: - print "Masterschedule next RUN confirmed" + print("Masterschedule next RUN confirmed") logger.info('Heartbeat check , Master Scheduler OK') else: isok=False if not isok: - print "No next run for master scheduler" + print("No next run for master scheduler") logger.warning('Heartbeat check , Master Scheduler Interrupted') #emailmod.sendallmail("alert","Master Scheduler has been interrupted, try to restart scheduler") resetmastercallback() @@ -326,14 +355,14 @@ def heartbeat(): logger.info('Heartbeat check , check errors in Syslog file') Errortextlist=debuggingmod.searchsyslogkeyword("error") if Errortextlist: - print "found error in syslog" + print("found error in syslog") logger.warning("ERROR: found error in syslog -------------------------") #send notification mail if debuggingmod.SENTERRORTEXT!=Errortextlist[0]: emailmod.sendallmail("alert","Error found in Syslog",Errortextlist) debuggingmod.SENTERRORTEXT=Errortextlist[0] else: - print "No error found in syslog" + print("No error found in syslog") logger.info('Heartbeat check , SYSLOG ok') # check if there have been errors in Schedulerlog @@ -344,14 +373,14 @@ def heartbeat(): filenameandpath=os.path.join(MYPATH, filename) Errortextlist=debuggingmod.searchLOGkeyword(filenameandpath,"error") if Errortextlist: - print "found error in LOG ",filename + print("found error in LOG ",filename) logger.warning("ERROR: found error in LOG , %s -------------------------",filename) #send notification mail if debuggingmod.SENTERRORTEXT!=Errortextlist[0]: emailmod.sendallmail("alert","Error found in LOG",Errortextlist) debuggingmod.SENTERRORTEXT=Errortextlist[0] else: - print "No error found in LOG", filename + print("No error found in LOG", filename) logger.info('Heartbeat check , LOG ok') return True @@ -362,7 +391,7 @@ def sendmail(target): issent=emailmod.sendmail(target,"report","Periodic system report generated automatically") if issent: actuatordbmod.insertdataintable(target,1) - print "Action", target , " " , datetime.now() + print("Action", target , " " , datetime.now()) return True @@ -372,7 +401,7 @@ def takephoto(target): # save action in database if isok: actuatordbmod.insertdataintable(target,1) - print "Action", target ," " , datetime.now() + print("Action", target ," " , datetime.now()) return True def setlight(MinimumLightinde,MaximumLightONinde): @@ -397,16 +426,16 @@ def setmastercallback(): thedateloc=datetime.now()+timedelta(days=1) timelist=hardwaremod.separatetimestringint(MASTERSCHEDULERTIME) starttimeloc=thedateloc.replace(hour=timelist[0], minute=timelist[1], second=timelist[2]) - print timelist + print(timelist) #convert to UTC time starttime=clockmod.convertLOCtoUTC_datetime(starttimeloc) - print "setup master job" + print("setup master job") argument=[True] try: SchedulerMod.sched.add_job(mastercallback, 'interval', days=1, start_date=starttime, args=argument, misfire_grace_time=120, name="master") logger.info('Master Scheduler - Started without errors') except ValueError: - print 'Date value for job scheduler not valid' + print('Date value for job scheduler not valid') logger.warning('Heartbeat check , Master Scheduler not Started properly') mastercallback() @@ -420,7 +449,7 @@ def waitandsetmastercallback(pulsesecond, offset): secondint=int(f)+offset except: secondint=200 - print "try to setmastercallback after " , secondint , " seconds" + print("try to setmastercallback after " , secondint , " seconds") t = threading.Timer(secondint, resetmastercallback ).start() def resetmastercallback(): @@ -432,13 +461,13 @@ def resetmastercallback(): SETMASTERBUSY=True logger.info('Reset Master Scheduler') # remove all the current jobs - print "Reset scheduler, List existing jobs to be removed:" + print("Reset scheduler, List existing jobs to be removed:") SchedulerMod.sched.print_jobs() SchedulerMod.removealljobs() - print "list of jobs after removal:" + print("list of jobs after removal:") SchedulerMod.sched.print_jobs() setmastercallback() - print "new jobs to be set in scheduler" + print("new jobs to be set in scheduler") SchedulerMod.sched.print_jobs() SETMASTERBUSY=False return True @@ -451,22 +480,22 @@ def checkheartbeat(): if isok: datenow=datetime.utcnow() datenextrun = datenextrun.replace(tzinfo=None) - print "Master heartbeat Next run " , datenextrun , " Now (UTC) ", datenow + print("Master heartbeat Next run " , datenextrun , " Now (UTC) ", datenow) datenowplusone = datenow + timedelta(days=2) if (datenextrun>datenow)and(datenextrun0) and (fertilizerpulsesecond>0): themonthdays=30 #approximate number of days in a month - dayinterval=themonthdays/fertilizerpulsenumber - halfinterval=(dayinterval+1)/2 - print "day=" , day , " dayinterval=", dayinterval, " half=", halfinterval + dayinterval=old_div(themonthdays,fertilizerpulsenumber) + halfinterval=old_div((dayinterval+1),2) + print("day=" , day , " dayinterval=", dayinterval, " half=", halfinterval) if ((day+int(halfinterval)) % int(dayinterval)) == 0: #timelist=hardwaremod.gettimedata("06:00:00") timelist=autofertilizermod.timelist(dosername) @@ -692,14 +721,15 @@ def setschedulercallback(calltype,timelist,argument,callbackname,jobname): iserror=False callback=schedulercallback[callbackname] if calltype=="periodic": - theinterval=timelist[1] + theintervalminutes=timelist[1] + theintervalhours=timelist[0] startdelaysec=timelist[2] - if theinterval<1: # the time interval is too short, no action + if (theintervalminutes+theintervalhours==0): # the time interval is too short, no action iserror=True - logger.warning('The scheduler for the input %s is not less than 1 minute, no log record of this input will be taken',jobname) + logger.warning('The scheduler interval for the input %s is Zero, no log record of this input will be taken',jobname) return iserror try: - print "add job ", jobname + print("add job ", jobname) thedateloc=datetime.now()+timedelta(seconds=startdelaysec) @@ -715,15 +745,15 @@ def setschedulercallback(calltype,timelist,argument,callbackname,jobname): try: if not FASTSCHEDULER: - SchedulerMod.sched.add_job(callback, 'interval', minutes=theinterval, start_date=thedate, end_date=enddate ,args=argument, misfire_grace_time=5, name=jobname) + SchedulerMod.sched.add_job(callback, 'interval', hours=theintervalhours, minutes=theintervalminutes, start_date=thedate, end_date=enddate ,args=argument, misfire_grace_time=5, name=jobname) else: - SchedulerMod.sched.add_job(callback, 'interval', seconds=theinterval, start_date=thedate, end_date=enddate ,args=argument, misfire_grace_time=5, name=jobname) + SchedulerMod.sched.add_job(callback, 'interval', seconds=theintervalminutes, start_date=thedate, end_date=enddate ,args=argument, misfire_grace_time=5, name=jobname) except ValueError: iserror=True - print 'Date value for job scheduler not valid' + print('Date value for job scheduler not valid') except ValueError as e: iserror=True - print 'Error: ', e + print('Error: ', e) else: # one shot type tday = date.today() todaydate = datetime(tday.year, tday.month, tday.day, 0, 0, 0) @@ -732,15 +762,15 @@ def setschedulercallback(calltype,timelist,argument,callbackname,jobname): thedate=clockmod.convertLOCtoUTC_datetime(thedateloc) if len(argument)>0: - print "date ", thedate , " callbackname " , callbackname , " Pump line ", argument[0] + print("date ", thedate , " callbackname " , callbackname , " Pump line ", argument[0]) else: - print "date ", thedate , " callbackname " , callbackname + print("date ", thedate , " callbackname " , callbackname) try: #print argument job = SchedulerMod.sched.add_job(callback, 'date', run_date=thedate, args=argument, misfire_grace_time=120, name=jobname) except ValueError as e: iserror=True - print 'Error: ', e + print('Error: ', e) return iserror @@ -777,7 +807,7 @@ def removeallscheduledjobs(): setmastercallback() SchedulerMod.print_job() time.sleep(9999) - print "close" + print("close") SchedulerMod.stop_scheduler() diff --git a/sensordbmod.py b/sensordbmod.py old mode 100644 new mode 100755 index f80631e..89d5f5b --- a/sensordbmod.py +++ b/sensordbmod.py @@ -2,7 +2,12 @@ """ utility for the planning database """ +from __future__ import print_function +from __future__ import division +from builtins import str +from builtins import range +from past.utils import old_div import logging import string from datetime import datetime,date,timedelta @@ -28,7 +33,7 @@ # ///////////////// -- MODULE INIZIALIZATION --- ////////////////////////////////////////// -print "SensordDBmod inizialization" +print("SensordDBmod inizialization") databasemod.init_db(DBFILENAME) tablelist=hardwaremod.searchdatalist(hardwaremod.HW_INFO_IOTYPE,"input",hardwaremod.HW_INFO_NAME) databasemod.aligndbtable(DBFILENAME, tablelist) @@ -115,10 +120,11 @@ def getsensordbdatadays(selsensor,sensordata,days): fieldlist.append(TIMEFIELD) fieldlist.append(DATAFIELD) sampletime=hardwaremod.searchdata(hardwaremod.HW_INFO_NAME,selsensor,hardwaremod.HW_FUNC_TIME) - if sampletime!="": + schedtype=hardwaremod.searchdata(hardwaremod.HW_INFO_NAME,selsensor,hardwaremod.HW_FUNC_SCHEDTYPE) # ["oneshot", "periodic"] #scheduling type + if (sampletime!="")and(schedtype=="periodic"): samplingintervalminutes=int(sampletime.split(":")[1]) if samplingintervalminutes>=1: - samplesnumber=(days*24*60)/samplingintervalminutes + samplesnumber=old_div((days*24*60),samplingintervalminutes) databasemod.getdatafromfieldslimit(DBFILENAME,selsensor,fieldlist,sensordata,samplesnumber) else: databasemod.getdatafromfields(DBFILENAME,selsensor,fieldlist,sensordata) @@ -164,7 +170,7 @@ def getSensorDataPeriod(selsensor,sensordata,enddate,pastdays): templist=[rowdata[0], value] sensordata.append(templist) except ValueError: - print "Error in database reading ",rowdata + print("Error in database reading ",rowdata) # sensor data -------------------------------------------- def getSensorDataPeriodXminutes(selsensor,datax,datay,startdate,enddate): # return sensordata in form of a matrix Nx2 @@ -184,13 +190,13 @@ def getSensorDataPeriodXminutes(selsensor,datax,datay,startdate,enddate): # retu datay.append(valuey) lenght=lenght+1 except ValueError: - print "Error in database reading ",rowdata + print("Error in database reading ",rowdata) return lenght def timediffinminutes(data2, data1): diff = data1 - data2 - return abs(diff.days*1440 + diff.seconds/60) + return abs(diff.days*1440 + old_div(diff.seconds,60)) def timediffdays(data2, data1): @@ -231,7 +237,7 @@ def getAllSensorsDataPeriodv2(enddate,pastdays): if maxtime0: outputallsensordata.append(sensordata) usedsensorlist.append(selsensor) @@ -284,11 +290,11 @@ def EvaluateDataPeriod(sensordata,startdate,enddate): summa=summa+number inde=inde+1 except ValueError: - print "Evaluation : Error in database reading ",dateref , " " ,data[1] + print("Evaluation : Error in database reading ",dateref , " " ,data[1]) if inde>0: - average=summa/inde + average=old_div(summa,inde) isok=True else: average=0 @@ -310,7 +316,7 @@ def SumProductDataPeriod(sensordata,startdate,enddate,timeinterval): try: sum=sum+float(data[1])*timeinterval except ValueError: - print data[1] + print(data[1]) return sum @@ -379,8 +385,8 @@ def consistencycheck(): sensordata=[] getsensordbdata("temp1",sensordata) getSensorDataPeriod("temp1",sensordata,datetime.now(),1) - print "data: " - print sensordata + print("data: ") + print(sensordata) rowvalue=[] teperatura=10 PHreading=10 diff --git a/serialcmdmod.py b/serialcmdmod.py old mode 100644 new mode 100755 index 1482d10..79060f8 --- a/serialcmdmod.py +++ b/serialcmdmod.py @@ -2,6 +2,10 @@ #to kill python processes use -- pkill python +from __future__ import print_function +from builtins import str +from builtins import range +from builtins import object import time import datetime import sys,os @@ -46,19 +50,19 @@ def initserial(self): portconnect=False for device in locations: try: - print "Trying...",device + print("Trying...",device) self.sp = serial.Serial(device, 9600) #for some reason this make the port reset starting with different baud rate self.sp = serial.Serial(device, self.baudrate) portconnect=True break except: portconnect=False - print "Failed to connect on",device + print("Failed to connect on",device) if not portconnect: - print 'could not open port' + print('could not open port') break else: - print "RESET ARDUINO" + print("RESET ARDUINO") self.sp.setDTR(False) # Drop DTR time.sleep(0.030) # Read somewhere that 22ms is what the UI does. self.sp.setDTR(True) # UP the DTR back @@ -68,11 +72,11 @@ def initserial(self): while (not self.bytes_available())and(cou<5): time.sleep(1) # delays for n seconds cou=cou+1 - print "received transmission" , self.bytes_available() + print("received transmission" , self.bytes_available()) rdata=[] while self.bytes_available(): answer=self.iterate(rdata) - print "Received data -",rdata + print("Received data -",rdata) recdata=["no"] @@ -86,12 +90,12 @@ def initserial(self): time.sleep(1) # delays for n seconds if (ack): self.finishinit=True - print "initialization of serial port finished succesfully" - print "start time " ,self.laststart + print("initialization of serial port finished succesfully") + print("start time " ,self.laststart) else: if hasattr(self, 'sp'): self.sp.close() - print "closed" + print("closed") @@ -153,7 +157,7 @@ def iterate(self, dataanswer): try: byte = self.sp.read() except IOError: - print "something wrong with serial connection no data to read initiate restart" + print("something wrong with serial connection no data to read initiate restart") self.restartserial() return False @@ -196,11 +200,11 @@ def exit(self): """ Call this to exit cleanly. """ if hasattr(self, 'sp'): self.sp.close() - print "Serial connection closed" + print("Serial connection closed") def restartserial(self): currenttime= datetime.datetime.now() - print "try to recover serial connection in ", (datetime.timedelta(minutes=1)-(currenttime-self.laststart)) + print("try to recover serial connection in ", (datetime.timedelta(minutes=1)-(currenttime-self.laststart))) if (currenttime-self.laststart)> datetime.timedelta(minutes=1): self.exit() self.initserial() @@ -221,7 +225,7 @@ def sendcommand_task(self,cmd, message, recdata): return False if not self.finishinit: - print "Serial not initiated properly" + print("Serial not initiated properly") self.restartserial() sendcanstart=True return False @@ -233,11 +237,11 @@ def sendcommand_task(self,cmd, message, recdata): try: self.sp.write(str(writestring)) except IOError: - print "something wrong with serial connection" + print("something wrong with serial connection") self.restartserial() #SerialException: write failed: [Errno 5] Input/output error - print "Sent -",writestring, " -------------------->>>>> " + print("Sent -",writestring, " -------------------->>>>> ") # Iterate over the messages to get arduino answer answer=False rcmd="" @@ -247,7 +251,7 @@ def sendcommand_task(self,cmd, message, recdata): while ((not self.bytes_available()) and cou<50): self.pass_time(0.01) cou=cou+1 - print "data received after seconds: ", cou*0.01 + print("data received after seconds: ", cou*0.01) self.pass_time(0.05) @@ -280,7 +284,7 @@ def sendcommand_task(self,cmd, message, recdata): recdata[i]="" - print "received: cmd ",rdata[0], " Data: ",recdata , " Answer integrity: ", (answer)and(ack) , " <<<< " + print("received: cmd ",rdata[0], " Data: ",recdata , " Answer integrity: ", (answer)and(ack) , " <<<< ") sendcanstart=True return (answer)and(ack) # return true if there was no receiver problem and the answer is acknowledge @@ -295,7 +299,7 @@ def sendcommand(self,cmd, message, recdata): self.sendcommand_task(cmd, message, recdata) return True else: - print "time expired" + print("time expired") return False @@ -348,7 +352,7 @@ def _handle_report_firmware(self, *data): #print ack, " ", recdata; ack=board1.sendcommand("5","PH",recdata) - print "verify wrong propocol:" + print("verify wrong propocol:") ack=board1.sendcommand("6","",recdata) diff --git a/start.py b/start.py old mode 100644 new mode 100755 index bb02f61..8d166f8 --- a/start.py +++ b/start.py @@ -1,5 +1,8 @@ # -*- coding: utf-8 -*- -Release="1.16a" +from __future__ import print_function +from builtins import str +from builtins import range +Release="3.19c" #--------------------- from loggerconfig import LOG_SETTINGS @@ -26,7 +29,7 @@ from flask import Flask, request, session, g, redirect, url_for, abort, \ - render_template, flash, _app_ctx_stack, jsonify , Response + render_template, flash, _app_ctx_stack, jsonify , Response from datetime import datetime,date,timedelta import systemtimeMod @@ -69,6 +72,7 @@ import sysconfigfilemod import debuggingmod import filemanagementmod +import weatherAPImod @@ -78,7 +82,7 @@ # ///////////////// -- GLOBAL VARIABLES AND INIZIALIZATION --- ////////////////////////////////////////// application = Flask(__name__) application.config.from_object('flasksettings') #read the configuration variables from a separate module (.py) file, this file is mandatory for Flask operations -print "-----------------" , basicSetting.data["INTRO"], "--------------------" +print("-----------------" , basicSetting.data["INTRO"], "--------------------") MYPATH="" @@ -96,8 +100,8 @@ #setup log file --------------------------------------- -print "starting new log session", datetime.now().strftime("%Y-%m-%d %H:%M:%S") -logger.info('Start logging -------------------------------------------- %s' , datetime.now().strftime("%Y-%m-%d %H:%M:%S")) +print("starting new log session", datetime.now().strftime("%Y-%m-%d %H:%M:%S")) +logger.info('Start logging -------------------------------------------- %s Version Release: %s' , datetime.now().strftime("%Y-%m-%d %H:%M:%S"),Release) logger.debug('This is a sample DEBUG message') logger.info('This is a sample INFO message') logger.warning('This is a sample WARNING message') @@ -143,11 +147,11 @@ def initallGPIOpins(): #initiate the GPIO OUT pins initallGPIOpins() -print "Finish interrupt initialization" +print("Finish interrupt initialization") # GET path --------------------------------------------- -print "path ",hardwaremod.get_path() +print("path ",hardwaremod.get_path()) MYPATH=hardwaremod.get_path() # RUN ALL consistency chacks ------------------------ @@ -163,10 +167,10 @@ def initallGPIOpins(): networkmod.disableNTP() networkmod.CheckandUnlockWlan() try: - print "start networking" + print("start networking") isconnecting=networkmod.init_network() # this includes also the clock check and scheduler setup except: - print "No WiFi available" + print("No WiFi available") #scheduler setup--------------------- if not isconnecting: @@ -195,17 +199,17 @@ def initallGPIOpins(): @application.teardown_appcontext def close_db_connection(exception): - """Closes the database again at the end of the request.""" - top = _app_ctx_stack.top - if hasattr(top, 'sqlite_db'): - top.sqlite_db.close() + """Closes the database again at the end of the request.""" + top = _app_ctx_stack.top + if hasattr(top, 'sqlite_db'): + top.sqlite_db.close() @application.route('/') def show_entries(): if not session.get('logged_in'): return render_template('login.html',error=None, change=False) - print "preparing home page" + print("preparing home page") currentday=date.today() #Picture panel------------------------------------ @@ -555,7 +559,7 @@ def network(): savedssid=[] filenamelist="wifi networks" - print "visualizzazione menu network:" + print("visualizzazione menu network:") iplocal=networkmod.get_local_ip() @@ -583,10 +587,10 @@ def network(): def wificonfig(): if not session.get('logged_in'): return render_template('login.html',error=None, change=False) - print "method " , request.method + print("method " , request.method) if request.method == 'GET': ssid = request.args.get('ssid') - print " argument = ", ssid + print(" argument = ", ssid) if request.method == 'POST': ssid = request.form['ssid'] @@ -599,16 +603,16 @@ def wificonfig(): return redirect(url_for('login', message="Please wait until the WiFi disconnect and reconnect")) elif request.form['buttonsub'] == "Forget": - print "forget" + print("forget") networkmod.waitandremovewifi(7,ssid) - print "remove network ", ssid - print "Try to connect AP" + print("remove network ", ssid) + print("Try to connect AP") networkmod.waitandconnect_AP(9) session.pop('logged_in', None) return redirect(url_for('login', message="Please wait until the WiFi disconnect and reconnect")) else: - print "cancel" + print("cancel") return redirect(url_for('network')) return render_template('wificonfig.html', ssid=ssid) @@ -632,7 +636,7 @@ def imageshow(): if actiontype=="DeleteAll": # delete all files in the folder deletedfilenumber=hardwaremod.deleteallpictures(MYPATH) - print " picture files deleted " , deletedfilenumber + print(" picture files deleted " , deletedfilenumber) logger.info(' all image files deleted ') else: @@ -820,7 +824,7 @@ def doit(): if not session.get('logged_in'): ret_data = {"answer":"Login Needed"} return jsonify(ret_data) - # send command to the actuator for test + # send command to the actuator for test cmd="" sendstring="" recdata=[] @@ -839,7 +843,7 @@ def doit(): testpulsetime="20" element=request.args['element'] - print "starting pulse test " , testpulsetime + print("starting pulse test " , testpulsetime) answer=selectedplanmod.activateandregister(element,testpulsetime) ret_data = {"answer": answer} @@ -847,13 +851,13 @@ def doit(): idx=1 element=request.args['element'] - print "stop pulse " , element + print("stop pulse " , element) answer=hardwaremod.stoppulse(element) ret_data = {"answer": answer} elif name=="servo2": - print "want to test servo" + print("want to test servo") idx=1 if idx < len(argumentlist): steps=int(argumentlist[idx]) @@ -877,7 +881,7 @@ def doit(): elif name=="stepper": - print "want to test stepper" + print("want to test stepper") idx=1 if idx < len(argumentlist): steps=argumentlist[idx] @@ -892,7 +896,7 @@ def doit(): elif name=="setstepper": - print "want to set stepper position" + print("want to set stepper position") idx=1 if idx < len(argumentlist): newposition=argumentlist[idx] @@ -903,7 +907,7 @@ def doit(): ret_data = {"answer": newposition} elif name=="hbridge": - print "want to test hbridge" + print("want to test hbridge") idx=1 if idx < len(argumentlist): steps=argumentlist[idx] @@ -919,7 +923,7 @@ def doit(): elif name=="sethbridge": - print "want to set hbridge position" + print("want to set hbridge position") idx=1 if idx < len(argumentlist): newposition=argumentlist[idx] @@ -933,7 +937,7 @@ def doit(): elif name=="photo": - print "want to test photo" + print("want to test photo") idx=1 if idx < len(argumentlist): @@ -961,7 +965,7 @@ def doit(): mailaddress=request.args['address'] mailtitle=request.args['title'] cmd=hardwaremod.searchdata(hardwaremod.HW_INFO_NAME,mailaname,hardwaremod.HW_CTRL_CMD) - print "want to test mail, address=" , mailaddress , " Title=" , mailtitle + print("want to test mail, address=" , mailaddress , " Title=" , mailtitle) issent=emailmod.send_email_main(mailaddress,mailtitle,cmd,"report","Periodic system report generated automatically") if issent: ret_data = {"answer": "Mail sent"} @@ -982,7 +986,7 @@ def doit(): else: answer="ready" elif element=="setHWClock": - print "datetime Local ->" ,datetime + print("datetime Local ->" ,datetime) logger.info('Clock has been manually changed') answer1=clockmod.setsystemclock(datetime) answer2=clockmod.setHWclock(datetime) @@ -991,11 +995,32 @@ def doit(): ret_data = {"answer":answer, "value":datetime} + elif name=="APItesting": + answer="nothing to declare" + testtype=request.args['element'] + if testtype=="createURL": + #print " creating URL" + URLlist=weatherAPImod.CreateQueryUrlall() + #print " The URL" , URLlist + answer='\n'.join(URLlist) + + elif testtype=="parse": + print(" creating URL") + isok , result=weatherAPImod.CalculateRainMultiplier() + print(" result" , result) + answer = str(result) + + + ret_data = {"answer": answer} + + + + elif name=="timezone": element=request.args['element'] timezone=request.args['timezone'] if element=="settimezone": - print "Set timezone ->" ,timezone + print("Set timezone ->" ,timezone) logger.info('Time Zone has been manually changed') answer=clockmod.settimezone(timezone) clockdbmod.changesavesetting("timezone",timezone) @@ -1010,13 +1035,13 @@ def saveit(): if not session.get('logged_in'): ret_data = {"answer":"Login needed"} return jsonify(ret_data) - # send command to the actuator for test + # send command to the actuator for test cmd="" sendstring="" recdata=[] ret_data={} name=request.args['name'] - print "Saving .." , name + print("Saving .." , name) if name=="mail": mailaname=request.args['element'] mailaddress=request.args['address'] @@ -1038,7 +1063,7 @@ def saveit(): elif name=="setsensor": - print "want to save sensor calibration" + print("want to save sensor calibration") element=request.args['element'] paramnamelist=request.args.getlist('paramname') @@ -1058,7 +1083,7 @@ def saveit(): phototime="" phototime=request.args['time'] - print "save photo setting, time=" , phototime + print("save photo setting, time=" , phototime) hwname=hardwaremod.searchdata(hardwaremod.HW_FUNC_USEDFOR,"photocontrol",hardwaremod.HW_INFO_NAME) hardwaremod.changesavecalibartion(hwname,hardwaremod.HW_FUNC_TIME,phototime) #hardwaremod.changesavecalibartion(hwname,hardwaremod.HW_CTRL_LOGIC,vdirection) @@ -1083,12 +1108,12 @@ def saveit(): elif name=="light1": lighttime="" lighttime=request.args['time'] - print "save light setting, time=" , lighttime + print("save light setting, time=" , lighttime) hardwaremod.changesavecalibartion(name,hardwaremod.HW_FUNC_TIME,lighttime) ret_data = {"answer": "saved"} - print "The actuator ", ret_data + print("The actuator ", ret_data) return jsonify(ret_data) @@ -1098,12 +1123,12 @@ def downloadit(): if not session.get('logged_in'): ret_data = {"answer":"Login Needed"} return jsonify(ret_data) - # check the download destination folder exist otherwise create it + # check the download destination folder exist otherwise create it folderpath=os.path.join(MYPATH, "static") folderpath=os.path.join(folderpath, "download") if not os.path.exists(folderpath): os.makedirs(folderpath) - + recdata=[] ret_data={} @@ -1114,7 +1139,7 @@ def downloadit(): folderpath=os.path.join(MYPATH, "static") folderpath=os.path.join(folderpath, "download") dst=os.path.join(folderpath, dstfilename+".txt") - print "prepare file for download, address=" , filename, "destination " , dst + print("prepare file for download, address=" , filename, "destination " , dst) try: shutil.copyfile(filename, dst) answer="ready" @@ -1137,7 +1162,7 @@ def downloadit(): for dstfilename in sortedlist: dst=os.path.join(folderpath, dstfilename+".txt") source=os.path.join(logfolder, dstfilename) - print "prepare file for download, address=" , source, "destination " , dst + print("prepare file for download, address=" , source, "destination " , dst) try: shutil.copyfile(source, dst) answer="ready" @@ -1151,7 +1176,7 @@ def downloadit(): folderpath=os.path.join(MYPATH, "static") folderpath=os.path.join(folderpath, "download") dst=os.path.join(folderpath, dstfilename+".txt") - print "prepare file for download, address=" , filename, "destination " , dst + print("prepare file for download, address=" , filename, "destination " , dst) try: shutil.copyfile(filename, dst) answer="ready" @@ -1167,7 +1192,7 @@ def downloadit(): folderpath=os.path.join(MYPATH, "static") folderpath=os.path.join(folderpath, "download") dst=os.path.join(folderpath, hardwaremod.HWDATAFILENAME) - print "prepare file for download, address=" , filename, "destination " , dst + print("prepare file for download, address=" , filename, "destination " , dst) try: shutil.copyfile(filename, dst) answer="ready" @@ -1181,7 +1206,7 @@ def downloadit(): folderpath=os.path.join(MYPATH, "static") folderpath=os.path.join(folderpath, "download") dst=os.path.join(folderpath, dstfilename) - print "prepare file for download, destination " , dst + print("prepare file for download, destination " , dst) # create the file using the tail command isok=debuggingmod.createfiletailsyslog(dst) if not isok: @@ -1201,11 +1226,25 @@ def downloadit(): dstfilenamelist=[] dstfilenamelist.append(dstfilename) - + elif name=="weatherAPIdata": # configuration of the weatherAPI page + dstfilename=weatherAPImod.weatherAPIdbmod.DATAFILENAME + filename=os.path.join(hardwaremod.DATABASEPATH, dstfilename) + folderpath=os.path.join(MYPATH, "static") + folderpath=os.path.join(folderpath, "download") + dst=os.path.join(folderpath, dstfilename) + print("prepare file for download, address=" , filename, "destination " , dst) + try: + shutil.copyfile(filename, dst) + answer="ready" + except: + answer="problem copying file" + dstfilenamelist=[] + dstfilenamelist.append("download/"+dstfilename) + ret_data = {"answer": answer, "filename": dstfilenamelist} - print "The actuator ", ret_data + print("The actuator ", ret_data) return jsonify(ret_data) @application.route('/testit/', methods=['GET']) @@ -1220,11 +1259,11 @@ def testit(): name=request.args['name'] if name=="testing": answer="done" - print "testing" - answer=functiontest() + print("testing") + answer=Autotesting() ret_data = {"answer": answer} - print "The actuator ", ret_data + print("The actuator ", ret_data) return jsonify(ret_data) @@ -1256,7 +1295,7 @@ def systemmailsetting(): #print " here we are" reqtype = request.form['button'] if reqtype=="save": - print "saving email credentials" + print("saving email credentials") address=request.form['address'] password=request.form['password'] isok1=emaildbmod.changesavesetting('address',address) @@ -1280,10 +1319,10 @@ def networksetting(): Fake_password="AP-password" if request.method == 'POST': - print " here we are at network setting" + print(" here we are at network setting") reqtype = request.form['button'] if reqtype=="save": - print "saving network advanced setting" + print("saving network advanced setting") gotADDRESS=request.form['IPADDRESS'] AP_SSID=request.form['AP_SSID'] AP_PASSWORD=request.form['AP_PASSWORD'] @@ -1315,7 +1354,7 @@ def networksetting(): - print "save in network file in database" + print("save in network file in database") networkdbmod.changesavesetting('LocalIPaddress',IPADDRESS) networkdbmod.changesavesetting('LocalAPSSID',AP_SSID) networkdbmod.changesavesetting('APtime',AP_TIME) @@ -1326,7 +1365,7 @@ def networksetting(): if AP_PASSWORD!=Fake_password: # change password in the HOSTAPD config file sysconfigfilemod.hostapdsavechangerow("wpa_passphrase",AP_PASSWORD) - print "password changed" + print("password changed") else: AP_PASSWORD="" @@ -1393,12 +1432,12 @@ def show_about(): def show_Calibration(): #on the contrary of the name, this show the setting menu if not session.get('logged_in'): return render_template('login.html',error=None, change=False) - print "visualizzazione menu Setting:" + print("visualizzazione menu Setting:") if request.method == 'POST': requesttype=request.form['buttonsub'] if requesttype=="delete": #remove the calibration file and read the default - print "restore hardware default file" + print("restore hardware default file") #hardwaremod.restoredefault() wateringdbmod.restoredefault() fertilizerdbmod.restoredefault() @@ -1420,7 +1459,7 @@ def show_Calibration(): #on the contrary of the name, this show the setting men return hardwaresettingeditfield() if requesttype=="uploadfile": - print "upload" + print("upload") if 'file' not in request.files: @@ -1431,18 +1470,19 @@ def show_Calibration(): #on the contrary of the name, this show the setting men flash('No file selected') else: if ".zip" in f.filename: + print( " ZIP filename ", f.filename) # control if the folder exist otherwise create it uploadfolder=application.config['UPLOAD_FOLDER'] fullfolderpath=os.path.join(MYPATH, uploadfolder) if not os.path.exists(fullfolderpath): os.makedirs(fullfolderpath) - print " folder has been created" + print(" folder has been created") - f = request.files['file'] + #f.save(f.filename) f.save(os.path.join(uploadfolder, f.filename)) - filemanagementmod.restoreconfigfilefromzip(fullfolderpath) - print "Align the data to the new files config" + filemanagementmod.restoreconfigfilefromzip(fullfolderpath,f.filename) + print("Align the data to the new files config") #align the files and memory runallreadfile() # align the data @@ -1520,7 +1560,7 @@ def show_Calibration(): #on the contrary of the name, this show the setting men #timezone countries=countryinfo.countries timezone=clockdbmod.gettimezone() - print "Current timezone ->", timezone + print("Current timezone ->", timezone) return render_template('ShowCalibration.html',servolist=servolist,servostatuslist=servostatuslist,stepperlist=stepperlist,stepperstatuslist=stepperstatuslist,hbridgelist=hbridgelist,hbridgestatuslist=hbridgestatuslist,videolist=videolist,actuatorlist=actuatorlist, sensorlist=sensorlist,deviceaddresseslist=deviceaddresseslist,lightsetting=lightsetting,photosetting=photosetting, camerasettinglist=camerasettinglist ,mailsettinglist=mailsettinglist, unitdict=unitdict, initdatetime=initdatetime, countries=countries, timezone=timezone) @@ -1530,7 +1570,7 @@ def show_Calibration(): #on the contrary of the name, this show the setting men def setinputcalibration(): # set the hbridge zero point if not session.get('logged_in'): return render_template('login.html',error=None, change=False) - print "visualizzazione menu sensor calibration:" + print("visualizzazione menu sensor calibration:") if request.method == 'POST': requesttype=request.form['buttonsub'] if requesttype=="cancel": @@ -1556,7 +1596,7 @@ def setinputcalibration(): # set the hbridge zero point def showdeviceaddresseslist(): # set the hbridge zero point if not session.get('logged_in'): return render_template('login.html',error=None, change=False) - print "visualizzazione menu :" + print("visualizzazione menu :") if request.method == 'POST': requesttype=request.form['buttonsub'] if requesttype=="cancel": @@ -1572,7 +1612,7 @@ def showdeviceaddresseslist(): # set the hbridge zero point def setstepper(): # set the stepper zero point if not session.get('logged_in'): return render_template('login.html',error=None, change=False) - print "visualizzazione menu set stepper:" + print("visualizzazione menu set stepper:") if request.method == 'POST': requesttype=request.form['buttonsub'] if requesttype=="cancel": @@ -1596,7 +1636,7 @@ def setstepper(): # set the stepper zero point def sethbridge(): # set the hbridge zero point if not session.get('logged_in'): return render_template('login.html',error=None, change=False) - print "visualizzazione menu set hbridge:" + print("visualizzazione menu set hbridge:") if request.method == 'POST': requesttype=request.form['buttonsub'] if requesttype=="cancel": @@ -1654,7 +1694,7 @@ def show_sensordata(): hygrosensornumlistwithoutactive=[] if actiontype=="delete": - print "delete all records" + print("delete all records") sensordbmod.deleteallrow() actuatordbmod.deleteallrow() actiontype="show" @@ -1781,15 +1821,15 @@ def wateringplan(): if elementlist: selectedelement=elementlist[0] - print " watering plan - selectedelement ", selectedelement + print(" watering plan - selectedelement ", selectedelement) if request.method == 'POST': actiontype=request.form['actionbtn'] - print actiontype + print(actiontype) if actiontype == "save": element=request.form['element'] - print "save il water form...:" , element + print("save il water form...:" , element) selectedelement=element @@ -1815,7 +1855,7 @@ def wateringplan(): selectedplanmod.resetmastercallback() if actiontype == "advconfig": - print "open advanced setting" + print("open advanced setting") return redirect('/Advanced/') @@ -1845,11 +1885,11 @@ def autowatering(): if request.method == 'POST': actiontype=request.form['actionbtn'] - print actiontype + print(actiontype) if actiontype == "save": element=request.form['element'] - print "save il water form...:" , element + print("save il water form...:" , element) selectedelement=element @@ -1872,14 +1912,14 @@ def autowatering(): autowateringdbmod.replacerow(element,dicttemp) flash('Table has been saved') - print "Reset the Cycle:" , element + print("Reset the Cycle:" , element) autowateringmod.cyclereset(element) #selectedplanmod.resetmastercallback() if actiontype == "reset": element=request.form['element'] - print "Reset the Cycle:" , element + print("Reset the Cycle:" , element) selectedelement=element autowateringmod.cyclereset(element) @@ -1943,11 +1983,11 @@ def automation(): if request.method == 'POST': actiontype=request.form['actionbtn'] - print actiontype + print(actiontype) if actiontype == "save": element=request.form['element'] - print "save il form...:" , element + print("save il form...:" , element) selectedelement=element @@ -1970,14 +2010,14 @@ def automation(): automationdbmod.replacerow(element,dicttemp) flash('Table has been saved') - print "Reset the Cycle:" , element + print("Reset the Cycle:" , element) automationmod.cyclereset(element) #selectedplanmod.resetmastercallback() if actiontype == "reset": element=request.form['element'] - print "Reset the Cycle:" , element + print("Reset the Cycle:" , element) selectedelement=element automationmod.cyclereset(element) @@ -2041,11 +2081,11 @@ def interrupt(): if request.method == 'POST': actiontype=request.form['actionbtn'] - print actiontype + print(actiontype) if actiontype == "save": element=request.form['element'] - print "save il form...:" , element + print("save il form...:" , element) selectedelement=element #add proper formatting @@ -2073,7 +2113,7 @@ def interrupt(): if actiontype == "reset": element=request.form['element'] - print "Reset the Cycle:" , element + print("Reset the Cycle:" , element) selectedelement=element interruptmod.cyclereset(element) @@ -2107,7 +2147,7 @@ def interrupt(): #{"cyclestartdate":datetime.utcnow(),"lastwateringtime":datetime.utcnow(),"cyclestatus":"done", "checkcounter":0, "alertcounter":0, "watercounter":0} cyclestatuslist.append(cyclestatus) - print "ready to go to html" + print("ready to go to html") return render_template("interrupt.html", title=title,selectedelement=selectedelement,modelist=modelist,sensormodelist=sensormodelist,followupactionlist=followupactionlist,sensorlist=sensorlist,watersettinglist=watersettinglist, cyclestatuslist=cyclestatuslist, alertlist=alertlist, timetriggerlist=timetriggerlist, triggermode=triggermode) @@ -2152,11 +2192,11 @@ def fertilizerplan(): if request.method == 'POST': actiontype=request.form['actionbtn'] - print actiontype + print(actiontype) if actiontype == "save": element=request.form['element'] - print "save il fertilizer form...:" , element + print("save il fertilizer form...:" , element) selectedelement=element #add proper formatting dicttemp={} @@ -2188,7 +2228,7 @@ def fertilizerplan(): flash('Table has been saved') if actiontype == "advconfig": - print "open advanced setting" + print("open advanced setting") return redirect('/Advanced/') @@ -2221,16 +2261,16 @@ def advanced(): selectedelement=elementlist[0] #print "table " ,table - + if request.method == 'POST': actiontype=request.form['actionbtn'] - print actiontype + print(actiontype) if actiontype == "save": element=request.form['element'] - print "save advanced form...:" , element + print("save advanced form...:" , element) selectedelement=element @@ -2269,7 +2309,7 @@ def advanced(): advancedmod.replacerow(element,dicttemp) # reset the scheduler selectedplanmod.resetmastercallback() - print "Table saved" + print("Table saved") flash('Table has been saved') table=advancedmod.gettable() @@ -2279,16 +2319,16 @@ def advanced(): if actiontype == "setdefault": advancedmod.restoredefault() - print "default restored" + print("default restored") flash('Default values have been set') if actiontype == "goback": - print "open watering plan setting" + print("open watering plan setting") return redirect('/wateringplan/') - - - - + + + + return render_template("advanced.html", title=title,paramlist=paramlist,elementlist=elementlist,table=table,tablehead=tablehead,selectedelement=selectedelement) @@ -2302,7 +2342,7 @@ def login(): password=logindbmod.getpassword() if request.method == 'POST': - print " LOGIN " , username + print(" LOGIN " , username) reqtype = request.form['button'] if reqtype=="login": usernameform=request.form['username'].lower() @@ -2315,11 +2355,11 @@ def login(): return redirect(url_for('show_entries')) elif reqtype=="change": - print "Display change password interface" + print("Display change password interface") change=True elif reqtype=="save": - print "saving new login password" + print("saving new login password") usernameform=request.form['username'].lower() passwordform=request.form['password'] newpassword=request.form['newpassword'] @@ -2347,23 +2387,23 @@ def login(): @application.route('/logout') def logout(): - session.pop('logged_in', None) - #flash('You were logged out') - return redirect(url_for('show_entries')) + session.pop('logged_in', None) + #flash('You were logged out') + return redirect(url_for('show_entries')) @application.route('/HardwareSetting/', methods=['GET', 'POST']) def hardwaresetting(): if not session.get('logged_in'): return render_template('login.html',error=None, change=False) - print "visualizzazione menu hardwareSetting:" + print("visualizzazione menu hardwareSetting:") fields=hardwaremod.HWdataKEYWORDS hwdata=hardwaremod.IOdata debugmode=DEBUGMODE tablehead=[] - for key, value in fields.iteritems(): + for key, value in fields.items(): tablehead.append(key) #print "tablehead ", tablehead @@ -2384,12 +2424,12 @@ def hardwaresetting(): if request.method == 'POST': requestinfo=request.form['buttonsub'] requesttype=requestinfo.split("_")[0] - print "requesttype " , requestinfo , " " , requesttype + print("requesttype " , requestinfo , " " , requesttype) if requesttype=="applyHWpreset": - print "Apply HW setting" + print("Apply HW setting") selectedpath="" selectedfilename=request.form['HWfilelist'] for items in HWfilelist: @@ -2414,7 +2454,7 @@ def hardwaresetting(): answer="problem copying file" else: - print "No file was selected" + print("No file was selected") answer="No file selected" @@ -2440,25 +2480,25 @@ def hardwaresetting(): def hardwaresettingedit(): if not session.get('logged_in'): return render_template('login.html',error=None, change=False) - print "visualizzazione menu hardwareSettingedit:" + print("visualizzazione menu hardwareSettingedit:") fields=hardwaremod.HWdataKEYWORDS tablehead=[] - for key, value in fields.iteritems(): + for key, value in fields.items(): tablehead.append(key) #print "tablehead ", tablehead if request.method == 'POST': requestinfo=request.form['buttonsub'] requesttype=requestinfo.split("_")[0] - print "requesttype POST " , requestinfo , " " , requesttype + print("requesttype POST " , requestinfo , " " , requesttype) if requestinfo=="edit": #request coming from previous page, need init table from zero - print "the temporary Tables have been reset" + print("the temporary Tables have been reset") #initialize IOdatarow hardwaremod.additionalRowInit() @@ -2467,7 +2507,7 @@ def hardwaresettingedit(): if requesttype=="confirm": - print "Confirm table" + print("Confirm table") # Copy the hardwaremod IOdatatemp to IOdata and save it hardwaremod.IOdatafromtemp() @@ -2490,10 +2530,10 @@ def hardwaresettingedit(): strposition=len(requesttype) name=requestinfo[strposition+1:] #remove the row in IOdatatemp - print " Delete ", name + print(" Delete ", name) if hardwaremod.deleterow(name): flash('Row has been correctly deleted') - print " deleted" + print(" deleted") else: flash('Errors to delete the row','danger') @@ -2507,7 +2547,7 @@ def hardwaresettingedit(): ret_data = {"answer":"Added"} hardwaremod.IOdatarow[hardwaremod.HW_INFO_NAME]="" else: - print "problem ", message + print("problem ", message) flash(message,'danger') ret_data = {"answer":"Error"} @@ -2523,7 +2563,7 @@ def hardwaresettingedit(): def hardwaresettingeditfield(): if not session.get('logged_in'): return render_template('login.html',error=None, change=False) - print "visualizzazione menu hardwareSettingedit:" + print("visualizzazione menu hardwareSettingedit:") fields=hardwaremod.HWdataKEYWORDS @@ -2539,7 +2579,7 @@ def hardwaresettingeditfield(): if request.method == 'POST': requestinfo=request.form['buttonsub'] requesttype=requestinfo.split("_")[0] - print "hardwaresettingeditfield requesttype POST " , requestinfo , " " , requesttype + print("hardwaresettingeditfield requesttype POST " , requestinfo , " " , requesttype) #if requestinfo=="editnames": #request coming from previous page, need init table from zero @@ -2551,7 +2591,7 @@ def hardwaresettingeditfield(): if requesttype=="confirm": - print "Confirm table" + print("Confirm table") # get the diferences in name field newnames=[] hardwaremod.getfieldvaluelisttemp("name",newnames) @@ -2606,11 +2646,11 @@ def HWsettingEditAjax(): return jsonify(ret_data) - + recdata=[] ret_data={} if request.method == 'POST': - print "we are in the HWsettingEdit" + print("we are in the HWsettingEdit") pk = request.form['pk'] value = request.form['value'] name = request.form['name'] @@ -2632,7 +2672,7 @@ def HWsettingEditAjax(): notok=False if isok: - print "data is OK" + print("data is OK") #modify the IOdatatemp matrix if IOname=="addrow": hardwaremod.IOdatarow[name]=value @@ -2648,19 +2688,279 @@ def HWsettingEditAjax(): ret_data = {"answer": message} return jsonify(ret_data) else: - print "data NOK ", message + print("data NOK ", message) ret_data = message return ret_data,400 +@application.route('/weatherAPI/', methods=['GET', 'POST']) +def weatherAPI(): + if not session.get('logged_in'): + return render_template('login.html',error=None, change=False) + print("visualizzazione menu weatherAPI:") + + + APIfilelist=weatherAPImod.APIpresetlist() #list of fiels (path , Name) + presetfilenamelist=[] + listitem={} + listitem["title"]="-No Selection-" + listitem["filename"]="-No Selection-" + presetfilenamelist.append(listitem) + for item in APIfilelist: + itemstr=item[1] + listitem={} + listitem["title"]=itemstr + listitem["filename"]=itemstr + presetfilenamelist.append(listitem) + + #print "HW file list ---> ", presetfilenamelist + + GUIitems=weatherAPImod.GetVisibleParam() + for i in range(len(GUIitems)): + GUIitems[i]["nameID"]=GUIitems[i]["name"]+"_"+str(i) + + #print " GUIitems ******************************** ", GUIitems + + wateringtems= wateringdbmod.getelementlist() + activewateringlist=weatherAPImod.getactivewatering() + wateringtemsGUI=[] + for item in wateringtems: + dicttemp={} + dicttemp["name"]=item + if item in activewateringlist: + dicttemp["active"]="True" + else: + dicttemp["active"]="False" + wateringtemsGUI.append(dicttemp) + + + #print " wateringtemsGUI ******************************+++++ ", wateringtemsGUI + + if request.method == 'POST': + requestinfo=request.form['buttonsub'] + requesttype=requestinfo.split("_")[0] + #print "requesttype " , requestinfo , " " , requesttype + + + + if requesttype=="applypreset": + #print "Apply API setting" + selectedpath="" + selectedfilename=request.form['APIfilelist'] + for items in APIfilelist: + if items[1]==selectedfilename: + selectedpath=items[0] + + isdone=False + isdone=weatherAPImod.CopytoDatabase(selectedpath) + + + # apply changes to the system + if isdone: + GUIitems=weatherAPImod.GetVisibleParam() + for i in range(len(GUIitems)): + GUIitems[i]["nameID"]=GUIitems[i]["name"]+"_"+str(i) + + #print " GUIitems ******************************** ", GUIitems + + wateringtems= wateringdbmod.getelementlist() + activewateringlist=weatherAPImod.getactivewatering() + wateringtemsGUI=[] + for item in wateringtems: + dicttemp={} + dicttemp["name"]=item + if item in activewateringlist: + dicttemp["active"]="True" + else: + dicttemp["active"]="False" + wateringtemsGUI.append(dicttemp) + + flash('New API configuration has been Applied ') + else: + flash('Problem reading the configuration ','danger') + + + if requesttype=="save": + print("save") + #print "GUIitems --------------------------->",GUIitems + for formdata in GUIitems: + if formdata["GUItype"]=="input": + #print " reuest from web " , formdata["nameID"] + formdata["value"]=request.form[formdata["nameID"]] + + #print " ................... FINISH GETTING DATA .............................::::" + weatherAPImod.SetVisibleParam(GUIitems) + wateringtemsactivelist=[] + wateringtems= wateringdbmod.getelementlist() + for item in wateringtems: + #print "selsettingactive_" + item + isactive=request.form["selsettingactive_" + item] + #print isactive + if isactive=="True": + wateringtemsactivelist.append(item) + weatherAPImod.SetWateractuators(wateringtemsactivelist) + + weatherAPImod.SaveSetting() + + activewateringlist=weatherAPImod.getactivewatering() + wateringtemsGUI=[] + for item in wateringtems: + dicttemp={} + dicttemp["name"]=item + if item in activewateringlist: + dicttemp["active"]="True" + else: + dicttemp["active"]="False" + wateringtemsGUI.append(dicttemp) + + + if requesttype=="TestQuery": + + weatherAPImod.QueryParse(GUIitems) + + if requesttype=="apply": + # create counter + newHWsettingRow=hardwaremod.InitRowHWsetting() + weatherAPImod.ProvideHWsettingFields(newHWsettingRow) # change relevant fields in dataromw + + #print "Row data" , newHWsettingRow + # Copy the hardwaremod IOdatatemp to IOdata and save it + + hardwaremod.AddUpdateRowByName(newHWsettingRow) + + # apply changes to the system + runallconsistencycheck() + #scheduler setup--------------------- + selectedplanmod.resetmastercallback() + #initiate the GPIO OUT pins + #initallGPIOpins() + flash('New Hardware configuration has been Applied ') + + # activate multiplier for the watering + + if requesttype=="uploadfile": + print("import configuration file") + + + if 'file' not in request.files: + flash('No file','danger') + else: + f = request.files['file'] + if f.filename == '': + flash('No file selected','danger') + else: + if ".txt" in f.filename: + # control if the folder exist otherwise create it + uploadfolder=application.config['UPLOAD_FOLDER'] # load the folder from config file, this is a fix folder, the file will be then moved + fullfolderpath=os.path.join(MYPATH, uploadfolder) + if not os.path.exists(fullfolderpath): + os.makedirs(fullfolderpath) + print(" folder has been created") + + f = request.files['file'] + #f.save(f.filename) + selectedpath=os.path.join(uploadfolder, f.filename) + f.save(selectedpath) + # copy file to database folder + isdone=False + isdone=weatherAPImod.CopytoDatabase(selectedpath) + + print("Align the data to the new files config") + + # apply changes to the system + if isdone: + GUIitems=weatherAPImod.GetVisibleParam() + for i in range(len(GUIitems)): + GUIitems[i]["nameID"]=GUIitems[i]["name"]+"_"+str(i) + + #print " GUIitems ******************************** ", GUIitems + + wateringtems= wateringdbmod.getelementlist() + activewateringlist=weatherAPImod.getactivewatering() + wateringtemsGUI=[] + for item in wateringtems: + dicttemp={} + dicttemp["name"]=item + if item in activewateringlist: + dicttemp["active"]="True" + else: + dicttemp["active"]="False" + wateringtemsGUI.append(dicttemp) + + flash('New API configuration has been Applied ') + else: + flash('Problem reading the configuration ','danger') + + else: + flash('Allowed file types is .txt ','danger') + + + return render_template('weatherAPI.html', presetfilenamelist=presetfilenamelist,GUIitems=GUIitems, wateringtemsGUI=wateringtemsGUI) + + + + + + + + def currentpath(filename): return os.path.join(MYPATH, filename) +def Autotesting(): + print("Auto testing Automation HAT") + print("Ensure that the right HWsetting is loaded") + + ActuatorList=["Relay1_2","Relay1_3","Relay1_4","Relay1_5","Relay1_6","Relay1_7","Relay1_8","Relay2_1","Relay2_2","Relay2_3","Relay2_4","Relay2_5","Relay2_6","Relay2_7","Relay2_8"] + + for target in ActuatorList: + hardwaremod.makepulse(target,"1",True, 0) + print(" Actuator ", target) + time.sleep(1.5) + + Sensorlist=[ + {"name":"pressuresensor1","min":800, "max":1200}, + {"name":"tempsensor1", "min":10, "max":40}, + {"name":"Analog0","min":2.4, "max":2.6}, + {"name":"Analog1","min":2.4, "max":2.6}, + {"name":"Analog2","min":2.4, "max":2.6}, + {"name":"Analog3","min":2.4, "max":2.6}, + {"name":"Analog4","min":2.4, "max":2.6}, + {"name":"Analog5_15v","min":4.5, "max":5.5} + ] + Errorcounter=0 + for sensor in Sensorlist: + sensorname=sensor["name"] + rangemin=sensor["min"] + rangemax=sensor["max"] + readingstr=hardwaremod.getsensordata(sensorname,1) + try: + reading=float(readingstr) + print(" sensorname " , sensorname , " data " , reading) + + if (reading>rangemin)and(reading0: + returnstr="Probelms :(" + else: + returnstr="Well DONE ! :)" + + return returnstr + + def functiontest(): - print " testing " + print(" testing ") selectedplanmod.periodicdatarequest("Temp_DS18B20") @@ -2739,7 +3039,7 @@ def videocontrol(): ret_data = {"answer":"login"} videocontrolmod.stop_stream() return jsonify(ret_data) - # this is used for debugging purposes, activate the functiontest from web button + # this is used for debugging purposes, activate the functiontest from web button ret_data={} cmd="" sendstring="" @@ -2748,7 +3048,7 @@ def videocontrol(): if name=="testing": - print "testing video stop" + print("testing video stop") answer="done" answer=videocontrolmod.stream_video() @@ -2770,18 +3070,18 @@ def videocontrol(): if name=="close": - print "Closing mjpg-streamer server" + print("Closing mjpg-streamer server") videocontrolmod.stop_stream("non blocking") answer="closed" if name=="stop": - print "Stop mjpg-streamer server" + print("Stop mjpg-streamer server") videocontrolmod.stop_stream() answer="stopped" ret_data = {"answer": answer} - print "response data ", ret_data + print("response data ", ret_data) return jsonify(ret_data) @@ -2801,7 +3101,7 @@ def videocontrol(): # start web server--------------- ------------------------- - print "start web server" + print("start web server") global PUBLICPORT if PUBLICMODE: application.run(debug=DEBUGMODE,use_reloader=False,host= '0.0.0.0',port=networkmod.LOCALPORT) @@ -2809,5 +3109,5 @@ def videocontrol(): else: application.run(debug=DEBUGMODE,use_reloader=False,port=80) - print "close" + print("close") diff --git a/statusdataDBmod.py b/statusdataDBmod.py old mode 100644 new mode 100755 index cc2cbb8..3cabbaa --- a/statusdataDBmod.py +++ b/statusdataDBmod.py @@ -1,3 +1,5 @@ +from __future__ import print_function +from builtins import str import logging import filestoragemod @@ -18,7 +20,7 @@ def read_status_data(data,element,variable,permanent=False, storeid=""): output=elementdata[variable] else: - print " element NOT present" + print(" element NOT present") # element not present in the data use the default data[element]=data["default"].copy() elementdata=data[element] @@ -34,7 +36,7 @@ def read_status_data(data,element,variable,permanent=False, storeid=""): if isok: if not (persistenooutput==output): - print "status variable output mismatch between current value and stored value" + print("status variable output mismatch between current value and stored value") logger.error('status variable output mismatch between current value =%s and stored value =%s', str(output) , str(persistenooutput)) output=persistenooutput @@ -151,7 +153,7 @@ def readstoredvariable(storeid,element,variable): permanent=True storeid="PROVA_data2" write_status_data(PROVA_data,element,variable,value,permanent, storeid) - print read_status_data(PROVA_data,element,variable,permanent, storeid) + print(read_status_data(PROVA_data,element,variable,permanent, storeid)) value="nonadesso" write_status_data(PROVA_data,element,variable,value) - print read_status_data(PROVA_data,element,variable,permanent, storeid) + print(read_status_data(PROVA_data,element,variable,permanent, storeid)) diff --git a/sysconfigfilemod.py b/sysconfigfilemod.py old mode 100644 new mode 100755 index a9a5ed5..11538da --- a/sysconfigfilemod.py +++ b/sysconfigfilemod.py @@ -2,6 +2,9 @@ """ file storage utility """ +from __future__ import print_function +from builtins import str +from builtins import range import logging import os import os.path @@ -62,7 +65,7 @@ def calculaterange(IPaddress): IPEND[3]=str(int(IPlist[3])+c) IPSTARTstring=".".join(IPSTART) IPENDstring=".".join(IPEND) - print " result ", IPSTARTstring+","+IPENDstring + print(" result ", IPSTARTstring+","+IPENDstring) return IPSTARTstring+","+IPENDstring else: return "" @@ -84,18 +87,18 @@ def modifyfilestring(filename, oldstring, newstring, afterkeyword, beforekeyword if (beforekeyword!="") and (beforekeyword in line): can_modify=False if (keyword in line) and (can_modify): - print " row found ------------ !!!!!!!!! " , line + print(" row found ------------ !!!!!!!!! " , line) if oldstring in line: # isolate and change the string #print " oldstring ", oldstring, " new ", newstring filedata[i]=line.replace(oldstring,newstring) - print " new row ------------ !!!!!!!!! " , filedata[i] + print(" new row ------------ !!!!!!!!! " , filedata[i]) filestoragemod.savefiledata_plaintext(filename,filedata) return True else: - print "String value not found ", oldstring + print("String value not found ", oldstring) return False diff --git a/templates/layout.html b/templates/layout.html old mode 100644 new mode 100755 index cec337e..d83b547 --- a/templates/layout.html +++ b/templates/layout.html @@ -65,6 +65,7 @@ ('/Imageshow/', 'imageshow', 'Images'), ('/wateringplan/', 'wateringplan', 'WateringPlan'), ('/autowatering/', 'autowatering', 'AutoWatering'), + ('/weatherAPI/', 'weatherAPI', 'WeatherAPI'), ('/fertilizerplan/', 'fertilizerplan', 'FertilizerPlan'), ('/automation/', 'automation', 'Automation'), ('/interrupt/', 'interrupt', 'Interrupt'), diff --git a/templates/weatherAPI.html b/templates/weatherAPI.html new file mode 100755 index 0000000..ca97a46 --- /dev/null +++ b/templates/weatherAPI.html @@ -0,0 +1,469 @@ +{% extends "layout.html" %} +{% set active_page = "weatherAPI" %} +{% block body %} + {% if session.logged_in %} + + +
+ + +
+
+ +
+
+ + +
+ + + + + +
+ + + +
+ + +
All the customization will be lost
+ + + + + + +
+
+
+ Parameters Setting +
+
+
+ + + {% if GUIitems|length > 0 %} + +
+ + {% for items in GUIitems %} + + +
+
+ + + + {% if items.GUItype=="title" %} +
+ {{items.name}} +
+ {% else %} +
+ +
+
+ {% if items.GUItype=="input" %} + + {% elif items.GUItype=="output" %} + + {% elif items.GUItype=="link" %} + {{items.value}} + + {% endif %} + + + {% if items.note!="" %} +
{{items.note}}
+ {% endif %} +
+ + + {% endif %} + +
+
+ + + + + {% endfor %} + +
+ + +
Note: If the query is successful the parameters in the above table will be populated
+ + + + +
+
+ +
+ + +
+
+ + +
+ +
+ +
+ +
+ + + +
+
+ +
+ +
+ +
+ + + + + +
+ +
+
+
+ Enable Rain multiplier in Irrigation Lines +
+
+
+ + + + + + + + + {% for item in wateringtemsGUI %} + + + + + + {% endfor %} + + + +
+ + {% if item.active=="True" %} + + + {% else %} + + + {% endif %} + + + + + + +
+ +
+ + + + +
+ + +
+ +
+ + +
+
+ +
+ +
+
+ {% else %} + +
+ +
+
+
No data
+
+
+
+ + {% endif %} + + +
+ + + + +
+ + + + +
+ + + + + + + + + +
+ + + + + +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + {% else %} + +

Please log in

+ + + {% endif %} +
    + +
+{% endblock %} diff --git a/videocontrolmod.py b/videocontrolmod.py old mode 100644 new mode 100755 index 2505705..962ece1 --- a/videocontrolmod.py +++ b/videocontrolmod.py @@ -1,3 +1,4 @@ +from __future__ import print_function from subprocess import call , Popen import sys import time @@ -53,7 +54,7 @@ def streamedit(dictdata): global videostreamport if (video=="video0")and(int(width)>1024): - print "try using the raspicam" + print("try using the raspicam") stream="mjpg_streamer -i '/usr/local/lib/mjpg-streamer/input_raspicam.so -d /dev/"+video+" -x "+width+" -y "+height+" -fps "+fps+"' -o '/usr/local/lib/mjpg-streamer/output_http.so -w /usr/local/share/mjpg-streamer/www -p "+videostreamport+"' &" #stream="mjpg_streamer -i '/usr/local/lib/mjpg-streamer/input_raspicam.so -d /dev/"+video+" -x "+width+" -y "+height+" -fps "+fps+"' -o '/usr/local/lib/mjpg-streamer/output_http.so -w /usr/local/share/mjpg-streamer/www -p "+videostreamport+" -c "+username+":"+password+"' &" @@ -84,20 +85,20 @@ def stream_video(videodev="",resolution={}): done=False try: - print "starting streaming\n%s" % stream + print("starting streaming\n%s" % stream) call ([stream], shell=True) - except: - print "Exception error failed to start VLC streaming " + except: + print("Exception error failed to start VLC streaming ") return "Exception" else: - print "Streaming" + print("Streaming") done="Streaming" return done def stop_stream_VLC(): - print "stopping streaming" + print("stopping streaming") #call (["pkill raspivid"], shell=True) call (["sudo pkill vlc"], shell=True) @@ -105,7 +106,7 @@ def stop_stream_VLC(): def stop_stream(blockingtype="blocking"): # non blocking subprocess.Popen # blocking subprocess.call - print "stopping streaming" + print("stopping streaming") #call (["pkill mjpg_streamer"], shell=True) if blockingtype=="blocking": call (["sudo pkill mjpg_streamer"], shell=True) diff --git a/videomod.py b/videomod.py old mode 100644 new mode 100755 index 758895b..d735321 --- a/videomod.py +++ b/videomod.py @@ -1,3 +1,4 @@ +from __future__ import print_function import time from time import sleep import datetime @@ -10,13 +11,13 @@ def StartServerTimer(lasttime): shottaken=False currentdate=datetime.datetime.now().strftime("%y-%m-%d-%H:%M") - print "Current date and time: " , currentdate + print("Current date and time: " , currentdate) myproc = Popen('mjpg_streamer -i "/usr/lib/input_uvc.so -d /dev/video0 -r 320x240 -f 15" -o "/usr/lib/output_http.so -p 8090 -w /usr/www"', shell=True, stdout=PIPE, stderr=PIPE) #sleep(10) - print myproc.stdout.readline() - print 'Return code was ', myproc.returncode + print(myproc.stdout.readline()) + print('Return code was ', myproc.returncode) sleep(2) @@ -25,13 +26,13 @@ def StartServerTimer(lasttime): def StopServerTimer(lasttime): shottaken=False currentdate=datetime.datetime.now().strftime("%y-%m-%d-%H:%M") - print "Current date and time: " , currentdate + print("Current date and time: " , currentdate) myproc = Popen('killall mjpg_streamer', shell=True, stdout=PIPE, stderr=PIPE) #sleep(10) - print myproc.stdout.readline() - print 'Return code was ', myproc.returncode + print(myproc.stdout.readline()) + print('Return code was ', myproc.returncode) sleep(2) diff --git a/wateringdbmod.py b/wateringdbmod.py old mode 100644 new mode 100755 index 6b125ad..a72a658 --- a/wateringdbmod.py +++ b/wateringdbmod.py @@ -2,7 +2,9 @@ """ watering UI setting storage utilities """ +from __future__ import print_function +from builtins import str import logging import os import os.path @@ -30,7 +32,7 @@ if not filestoragemod.readfiledata(WTDATAFILENAME,WTdata): #read watering setting file #read from default file filestoragemod.readfiledata(DEFWTDATAFILENAME,WTdata) - print "Watering writing default calibration data" + print("Watering writing default calibration data") filestoragemod.savefiledata(WTDATAFILENAME,WTdata) # end read IOdata ----- @@ -164,7 +166,7 @@ def getrowdata(recordvalue,paramlist,index): for param in paramlist: try: datalist.append(int(ln[param][index])) - except Exception, e: + except Exception as e: #print 'Failed to load value, set value to zero. Error: '+ str(e) datalist.append(0) diff --git a/weatherAPIdbmod.py b/weatherAPIdbmod.py new file mode 100755 index 0000000..5bd2b90 --- /dev/null +++ b/weatherAPIdbmod.py @@ -0,0 +1,274 @@ +# -*- coding: utf-8 -*- +""" +Auto watering UI setting storage utilities +""" +from __future__ import print_function + +import logging +import os +import os.path +import sys +import shutil +import string +from datetime import datetime,date,timedelta +import time +import filestoragemod +import hardwaremod + + + +# ///////////////// -- GLOBAL VARIABLES AND INIZIALIZATION --- ////////////////////////////////////////// + + +global DATAFILENAME +DATAFILENAME="APIdata.txt" + + +global WTdata +WTdata={} + + + +# read WTdata ----- +WTdata=filestoragemod.readfiledata_full(DATAFILENAME) +#if not WTdata: #read watering setting file + #read from default file, the below groups should always be present + #WTdata={"BasicInfo": {},"QueryGroup": [{"QueryItems":[],"ParseItems":[]}],"CounterInfo": {}, "Wateractuators": {} } + + #print "Watering writing default calibration data" + #filestoragemod.savefiledata_full(DATAFILENAME,WTdata) + + +# ///////////////// --- END GLOBAL VARIABLES ------ + + +def APIpresetlist(): + apprunningpath=get_path() + folderpath=os.path.join(apprunningpath, "database") + folderpath=os.path.join(folderpath, "default") + folderpath=os.path.join(folderpath, "presetAPIsetting") + filenamelist=[] + sortedlist=sorted(os.listdir(folderpath)) + sortedlist.reverse() + for files in sortedlist: + templist=[] + templist.append("database/default/presetAPIsetting/"+files) + templist.append(files) + filenamelist.append(templist) + return filenamelist # item1 (path) item2 (name) + +def CopytoDatabase(selectedpath): + global WTdata + isdone=False + if selectedpath!="": + MYPATH=get_path() + # copy file to the default HWdata + filename=os.path.join(MYPATH, selectedpath) + folderpath=os.path.join(MYPATH, hardwaremod.DATABASEPATH) + dstdef=os.path.join(folderpath, DATAFILENAME) + #print "Source selected path ", filename , " Destination ", dstdef + + + try: + shutil.copyfile(filename, dstdef) #this is the default HW file + readdata=filestoragemod.readfiledata_full(DATAFILENAME) + if readdata: + WTdata=readdata + isdone=True + else: + print("*************************** problem Parsing the file *******************************") + isdone=False + except: + isdone=False + return isdone + + + + + + + + +def readfromfile(): + global WTdata + WTdata=filestoragemod.readfiledata_full(DATAFILENAME) + + + + + + + + + +def saveWTsetting(): + filestoragemod.savefiledata_full(DATAFILENAME,WTdata) + + +def getelementlist(): + recordkey=hardwaremod.HW_INFO_IOTYPE + recordvalue="output" + keytosearch=hardwaremod.HW_INFO_NAME + datalist=hardwaremod.searchdatalist(recordkey,recordvalue,keytosearch) + excludewatercontrol=True + if not excludewatercontrol: + recordkey=hardwaremod.HW_FUNC_USEDFOR + recordvalue="watercontrol" + keytosearch=hardwaremod.HW_INFO_NAME + removelist=hardwaremod.searchdatalist(recordkey,recordvalue,keytosearch) + for element in removelist: + datalist.remove(element) + + #print "elementlist= ",datalist + return datalist + +def sensorlist(): + tablelist=hardwaremod.searchdatalist2keys(hardwaremod.HW_INFO_IOTYPE,"input", hardwaremod.HW_CTRL_CMD, "readinputpin" ,hardwaremod.HW_INFO_NAME) + return tablelist + +def sensorlisttriggertime(): + tablelist=hardwaremod.searchdatalist(hardwaremod.HW_INFO_IOTYPE,"input",hardwaremod.HW_INFO_NAME) + timetriggerlist=[] + for item in tablelist: + timelist=hardwaremod.gettimedata(item) + theinterval=timelist[1] # minutes + timetriggerlist.append(theinterval) + return timetriggerlist + + +def gethygrosensorfromactuator(actuatorname): + recordkey="element" + recordvalue=actuatorname + keytosearch="sensor" + if searchdata(recordkey,recordvalue,"workmode")!="None": + return searchdata(recordkey,recordvalue,keytosearch) + else: + return "" + + + + +def getrowdata(recordvalue,paramlist,index): #for parameters with array of integers + recordkey="element" + datalist=[] + for ln in WTdata: + if recordkey in ln: + if ln[recordkey]==recordvalue: + for param in paramlist: + try: + datalist.append(int(ln[param][index])) + except Exception as e: + #print 'Failed to load value, set value to zero. Error: '+ str(e) + datalist.append(0) + + return datalist + +def gettable(index): + paramlist=getparamlist() + #print "paramlist" , paramlist + elementlist=getelementlist() + datalist=[] + for row in elementlist: + rowdatalist=getrowdata(row,paramlist,index) + datalist.append(rowdatalist) + #print datalist + return datalist + + +def replacerow(element,dicttemp): + searchfield="element" + searchvalue=element + for line in WTdata: + if searchfield in line: + if line[searchfield]==searchvalue: + for row in dicttemp: # modified, in this way it adds the new items is present + line[row]=dicttemp[row] + filestoragemod.savefiledata(DATAFILENAME,WTdata) + return True + return False + + +def changesaveWTsetting(WTname,WTparameter,WTvalue): +# questo il possibile dizionario: { 'name':'', 'm':0.0, 'q':0.0, 'lastupdate':'' } #variabile tipo dizionario + for line in WTdata: + if line["name"]==WTname: + line[WTparameter]=WTvalue + saveWTsetting() + return True + return False + +def searchdata(recordkey,recordvalue,keytosearch): + for ln in WTdata: + if recordkey in ln: + if ln[recordkey]==recordvalue: + if keytosearch in ln: + return ln[keytosearch] + return "" + + + +def gettimedata(name): + # return list with three integer values: hour , minute, second + timestr=searchdata("name",name,"time") + returntime=[] + if not timestr=="": + timelist=timestr.split(":") + for timeitem in timelist: + returntime.append(timeitem) + if len(timelist)<3: + returntime.append("00") + return returntime + else: + return ["00","00","00"] + + + +def searchdatalist(recordkey,recordvalue,keytosearch): + datalist=[] + for ln in WTdata: + if recordkey in ln: + if ln[recordkey]==recordvalue: + if keytosearch in ln: + datalist.append(ln[keytosearch]) + return datalist + +def getfieldvaluelist(fielditem,valuelist): + del valuelist[:] + for line in WTdata: + valuelist.append(line[fielditem]) + +def getfieldinstringvalue(fielditem,stringtofind,valuelist): + del valuelist[:] + for line in WTdata: + name=line[fielditem] + if name.find(stringtofind)>-1: + valuelist.append(name) + + + + +def get_path(): + '''Get the path to this script no matter how it's run.''' + #Determine if the application is a py/pyw or a frozen exe. + if hasattr(sys, 'frozen'): + # If run from exe + dir_path = os.path.dirname(sys.executable) + elif '__file__' in locals(): + # If run from py + dir_path = os.path.dirname(__file__) + else: + # If run from command line + dir_path = sys.path[0] + return dir_path + +#--end --------//////////////////////////////////////////////////////////////////////////////////// + + +if __name__ == '__main__': + # comment + a=10 + + + + + diff --git a/weatherAPImod.py b/weatherAPImod.py new file mode 100755 index 0000000..6659453 --- /dev/null +++ b/weatherAPImod.py @@ -0,0 +1,518 @@ +from __future__ import print_function +from future import standard_library +standard_library.install_aliases() +from builtins import str +import logging +from datetime import datetime , time ,timedelta +import _strptime +import hardwaremod +import os +import subprocess +import weatherAPIdbmod +import autofertilizermod +import statusdataDBmod +import threading +import urllib.request, urllib.error, json +from urllib.parse import urlencode + + + + +counterdefaultdata={"IOtype": "input" , "controllercmd": "WeatherAPI", "measure": "Percentage", "name": "RainMultiplier", "schedulingtype": "periodic", "time": "00:120:00", "unit": "%", "usefor": "watercontrol"} +index0=0 + +NOWTIMELIST=[] + +#In hardware, an internal 10K resistor between the input channel and 3.3V (pull-up) or 0V (pull-down) is commonly used. +#https://sourceforge.net/p/raspberry-gpio-python/wiki/Inputs/ + +logger = logging.getLogger("hydrosys4."+__name__) + + +waitingtime=1200 + +# ///////////////// -- STATUS VARIABLES -- /////////////////////////////// + +AUTO_data={} # dictionary of dictionary +AUTO_data["default"]={"lasteventtime":datetime.utcnow()- timedelta(minutes=waitingtime),"lastinterrupttime":datetime.utcnow(),"validinterruptcount":0,"eventactivated":False,"lastactiontime":datetime.utcnow()- timedelta(minutes=waitingtime),"actionvalue":0, "alertcounter":0, "infocounter":0, "status":"ok" , "threadID":None , "blockingstate":False} + +SENSOR_data={} # used for the associated sensor in a separate hardwareSetting Row +SENSOR_data["default"]={"Startcounttime":datetime.utcnow(),"InterruptCount":0} + +PIN_attributes={} # to speed up the operation during interurpt +PIN_attributes["default"]={"logic":"pos","refsensor":"","bouncetimeSec":0.001} + +BLOCKING_data={} # to speed up the operation during interurpt +BLOCKING_data["default"]={"BlockingNumbers":0,"BlockingNumbersThreadID":None} + + + +def APIpresetlist(): + return weatherAPIdbmod.APIpresetlist() + +def CopytoDatabase(selectedpath): + return weatherAPIdbmod.CopytoDatabase(selectedpath) + +def SaveSetting(): + return weatherAPIdbmod.saveWTsetting() + +def MakeDictforGUI(params): + dicttemp={} + if params: + if ("name" in params): + dicttemp["name"]=params["name"] + if ("value" in params): + dicttemp["value"]=params["value"] + else: + dicttemp["value"]="" + if ("GUItype" in params): + dicttemp["GUItype"]=params["GUItype"] + else: + dicttemp["GUItype"]="output" + if ("note" in params): + dicttemp["note"]=params["note"] + else: + dicttemp["note"]="" + + return dicttemp + +def RecursiveSearch(subStruct,visiblelist): + keyword="visible" + + if isinstance(subStruct, dict): + if keyword in subStruct: + visiblelist.append(MakeDictforGUI(subStruct)) + #print "found ----------------------------------" + for key in subStruct: + RecursiveSearch(subStruct[key],visiblelist) + + elif isinstance(subStruct, list): + for items in subStruct: + RecursiveSearch(items,visiblelist) + + +def GetVisibleParam_no(): # not usable because the dict items are not shown in order, this is a problem of Python + var=weatherAPIdbmod.WTdata + visiblelist=[] + RecursiveSearch(var,visiblelist) + return visiblelist + + +def GetVisibleParam(): + var=weatherAPIdbmod.WTdata + visiblelist=[] + if var: + key="visible" + + # BasicInfo + params=var["BasicInfo"] + RecursiveSearch(params,visiblelist) + + # QueryGroup + Itemslist=var["QueryGroup"] + for items in Itemslist: + + # query param + QueryParam=items["QueryItems"] + RecursiveSearch(QueryParam,visiblelist) + + #parse param + ParseParam=items["ParseItems"] + RecursiveSearch(ParseParam,visiblelist) + + + # CounterInfo + params=var["CounterInfo"] + RecursiveSearch(params,visiblelist) + + #print " visiblelist " , visiblelist + return visiblelist + + +def RecursiveSearchSet(subStruct,GUIdata): + global index0 + keyword="visible" + + if isinstance(subStruct, dict): + if keyword in subStruct: + #found + if "name" in subStruct: + if "value" in subStruct: + subStruct["value"]=GUIdata[index0]["value"] + print(subStruct["name"]) + index0=index0+1 + print("found ----------------------------------", index0) + for key in subStruct: + RecursiveSearchSet(subStruct[key],GUIdata) + + elif isinstance(subStruct, list): + for items in subStruct: + RecursiveSearchSet(items,GUIdata) + + +def SetVisibleParam(GUIdata): # uses positional system + global index0 + print("len GUI data ", len(GUIdata)) + var=weatherAPIdbmod.WTdata + if var: + index0=0 + key="visible" + + # BasicInfo + params=var["BasicInfo"] + RecursiveSearchSet(params,GUIdata) + + + # querygroup + Itemslist=var["QueryGroup"] + for items in Itemslist: + + # query param + QueryParam=items["QueryItems"] + RecursiveSearchSet(QueryParam,GUIdata) + + #parse param + ParseParam=items["ParseItems"] + RecursiveSearchSet(ParseParam,GUIdata) + + # CounterInfo + params=var["CounterInfo"] + RecursiveSearchSet(params,GUIdata) + + +def SetWateractuators(wateringtemsactivelist): + var=weatherAPIdbmod.WTdata + if var: + var["Wateractuators"]=wateringtemsactivelist + +def CreateQueryUlr(QueryParam): # evaluate one item of QueryItems + dicttemp={} + URL="" + for params in QueryParam: + if "usedfor" in params: + if params["usedfor"]=="url": + URL=params["value"] + if params["usedfor"]=="queryparam": + param=params["param"] + paramvalue=params["value"] + # check the format + if "format" in params: + formatstring=params["format"] + else: + formatstring="%Y/%m/%d" + paramvalue = evaluateParam(paramvalue,formatstring) + dicttemp[param]=paramvalue + + URLstring=URL+urlencode(dicttemp) + return URLstring + +def CreateQueryUrlall(): + + var=weatherAPIdbmod.WTdata + if var: + Querystringlist=[] + + # QueryGroup + Itemslist=var["QueryGroup"] + for items in Itemslist: + # query param + QueryParam=items["QueryItems"] + Querystringlist.append(CreateQueryUlr(QueryParam)) + + return Querystringlist + + +def createquerystring(dicttemp): + if "url" in dicttemp: + thestring=dicttemp["url"] + for item in dicttemp: + paramstring="" + if item!="url": + paramstring=item+"="+dicttemp[item]+"&" + thestring=thestring+paramstring + thestring=thestring.rstrip("&") + print("url string ", thestring) + return thestring + else: + return "" + +def evaluateParam(paramvalue,formatstring): + specialparam=["Time Now","Time +1 day","Time +2 days","Time -1 day","Time -2days"] + if paramvalue in specialparam: + thetime=datetime.now() + if paramvalue=="Time +1 day": + thetime=thetime + timedelta(days=1) + if paramvalue=="Time +2 days": + thetime=thetime + timedelta(days=2) + if paramvalue=="Time -1 day": + thetime=thetime - timedelta(days=1) + if paramvalue=="Time -2 days": + thetime=thetime- timedelta(days=2) + + # check the format + paramvalue=thetime.strftime(formatstring) + + return paramvalue + + +def parseJsondataItem(ParseParam,jsondata): # parse for sinlge param item + isok=False + dicttemp={} + print("jsondata " ,jsondata ) + for params in ParseParam: + # for each of this set of params there is a value to be extracted + itemname=params["name"] + searchpathlist=params["searchpath"] + subStruct=jsondata + for searchitems in searchpathlist: + gonext=False + keyword=searchitems["keyword"] + datamatch="" + if "match" in searchitems: + datamatch=searchitems["match"] + formatstring="" + if "format" in searchitems: + formatstring=searchitems["format"] + datamatch=evaluateParam(datamatch,formatstring) + print("Searchitems " ,keyword , " " , datamatch) + # enter the json data structure to search + if isinstance(subStruct, dict): + if keyword in subStruct: + subStruct=subStruct[keyword] + gonext=True + elif isinstance(subStruct, list): + for items in subStruct: + print("list items " , items[keyword]) + if items[keyword]==datamatch: + subStruct=items + gonext=True + break + if gonext==False: + print(" Search Path finished before finding the Object ........") + break + if gonext: + print(" ========> item found ", subStruct) + dicttemp["name"]=itemname + dicttemp["value"]=subStruct + isok=True + + return isok, dicttemp + + + +def parseJsondata(): + jsondataold={"location":{"name":"Rome","region":"Lazio","country":"Italy","lat":41.9,"lon":12.48,"tz_id":"Europe/Rome","localtime_epoch":1587903198,"localtime":"2020-04-26 14:13"},"current":{"last_updated_epoch":1587902415,"last_updated":"2020-04-26 14:00","temp_c":21.0,"temp_f":69.8,"is_day":1,"condition":{"text":"Partly cloudy","icon":"//cdn.weatherapi.com/weather/64x64/day/116.png","code":1003},"wind_mph":0.0,"wind_kph":0.0,"wind_degree":256,"wind_dir":"WSW","pressure_mb":1011.0,"pressure_in":30.3,"precip_mm":0.0,"precip_in":0.0,"humidity":43,"cloud":25,"feelslike_c":21.0,"feelslike_f":69.8,"vis_km":10.0,"vis_miles":6.0,"uv":7.0,"gust_mph":3.6,"gust_kph":5.8},"forecast":{"forecastday":[{"date":"2020-04-28","date_epoch":1588032000,"day":{"maxtemp_c":20.7,"maxtemp_f":69.3,"mintemp_c":12.8,"mintemp_f":55.0,"avgtemp_c":16.4,"avgtemp_f":61.5,"maxwind_mph":11.6,"maxwind_kph":18.7,"totalprecip_mm":1.8,"totalprecip_in":0.07,"avgvis_km":9.0,"avgvis_miles":5.0,"avghumidity":74.0,"condition":{"text":"Light rain shower","icon":"//cdn.weatherapi.com/weather/64x64/day/353.png","code":1240},"uv":7.3},"astro":{"sunrise":"06:10 AM","sunset":"08:06 PM","moonrise":"09:43 AM","moonset":"12:27 AM"}}]},"alert":{}} + + jsondata={"location":{"name":"Rome","region":"Lazio","country":"Italy","lat":41.9,"lon":12.48,"tz_id":"Europe/Rome","localtime_epoch":1588338436,"localtime":"2020-05-01 15:07"},"current":{"last_updated_epoch":1588338016,"last_updated":"2020-05-01 15:00","temp_c":21.0,"temp_f":69.8,"is_day":1,"condition":{"text":"Partly cloudy","icon":"//cdn.weatherapi.com/weather/64x64/day/116.png","code":1003},"wind_mph":8.1,"wind_kph":13.0,"wind_degree":210,"wind_dir":"SSW","pressure_mb":1012.0,"pressure_in":30.4,"precip_mm":0.0,"precip_in":0.0,"humidity":56,"cloud":25,"feelslike_c":21.0,"feelslike_f":69.8,"vis_km":10.0,"vis_miles":6.0,"uv":7.0,"gust_mph":9.2,"gust_kph":14.8},"forecast":{"forecastday":[{"date":"2020-05-03","date_epoch":1588464000,"day":{"maxtemp_c":24.8,"maxtemp_f":76.6,"mintemp_c":13.5,"mintemp_f":56.3,"avgtemp_c":18.7,"avgtemp_f":65.7,"maxwind_mph":8.7,"maxwind_kph":14.0,"totalprecip_mm":0.0,"totalprecip_in":0.0,"avgvis_km":10.0,"avgvis_miles":6.0,"avghumidity":70.0,"condition":{"text":"Partly cloudy","icon":"//cdn.weatherapi.com/weather/64x64/day/116.png","code":1003},"uv":11.0},"astro":{"sunrise":"06:03 AM","sunset":"08:11 PM","moonrise":"03:19 PM","moonset":"04:08 AM"}}]},"alert":{}} + var=weatherAPIdbmod.WTdata + if var: + + # QueryGroup + Itemslist=var["QueryGroup"] + for items in Itemslist: + + + # parse param + ParseParam=items["ParseItems"] + isok, datadict = parseJsondataItem(ParseParam,jsondata) + if isok: + print("DATA : " ,datadict["name"], " " , datadict["value"]) + else: + print("data not found") + +def getJsonfromWeb(url): + data={} + #print("url=", url) + try: + response = urllib.request.urlopen(url) + data = json.loads(response.read()) + except: + logger.warning("WeatherAPI : Site returned error code") + #print data + return data + +def QueryParse(GUIdata): + var=weatherAPIdbmod.WTdata + resultdict={} + if var: + + + # QueryGroup + Itemslist=var["QueryGroup"] + for items in Itemslist: + + # query param + QueryParam=items["QueryItems"] + QueryURL = CreateQueryUlr(QueryParam) + + # ask server + jsondata=getJsonfromWeb(QueryURL) + + # parse param + ParseParam=items["ParseItems"] + isok, datadict = parseJsondataItem(ParseParam,jsondata) + + if isok: + resultdict[datadict["name"]]=datadict["value"] + + + for item in GUIdata: + if item["name"] in resultdict: + item["value"] = resultdict[item["name"]] + + print("GUIdata " , GUIdata) + +def CalculateRainMultiplier(): + isok=True + var=weatherAPIdbmod.WTdata + if var: + + WeaterData=[] + # QueryGroup + Itemslist=var["QueryGroup"] + for items in Itemslist: + + # query param + QueryParam=items["QueryItems"] + QueryURL=CreateQueryUlr(QueryParam) + + # ask server + jsondata=getJsonfromWeb(QueryURL) + + # parse param + ParseParam=items["ParseItems"] + isok, datadict = parseJsondataItem(ParseParam,jsondata) + + if isok: + WeaterData.append(datadict["value"]) + else: + WeaterData.append("0") + + CalculationResult=0 + WeightParam=var["CounterInfo"] + minvalue=0 + maxvalue=100 + initialValue=0 + queryintervalmin=180 + if ("min" in WeightParam): + minvalue=tonumber(WeightParam["min"]["value"],0) + if ("max" in WeightParam): + maxvalue=tonumber(WeightParam["max"]["value"],100) + if ("initialValue" in WeightParam): + initialValue=tonumber( WeightParam["initialValue"]["value"],0) + if ("queryintervalmin" in WeightParam): + queryintervalmin=tonumber( WeightParam["queryintervalmin"]["value"] ,180) + + Itemslist=WeightParam["weights"] + i=0 + for item in Itemslist: + if i < len(WeaterData): + weight=tonumber(item["value"],0) + dataint=tonumber(WeaterData[i], 0) + CalculationResult=CalculationResult+weight*dataint + i=i+1 + else: + print("Mismatch between number of weights and parameters") + + CalculationResult=initialValue+CalculationResult + + if CalculationResultmaxvalue: + CalculationResult=maxvalue + + print("CalculationResult " , CalculationResult) + return isok , CalculationResult + +def getactivewatering(): + # "Wateractuators" + WaterDatalist=[] + var=weatherAPIdbmod.WTdata + if var: + WaterDatalist=var["Wateractuators"] + return WaterDatalist + + +def ProvideHWsettingFields(datarow): + global counterdefaultdata + + # update some data field + for key in counterdefaultdata: + if key in datarow: + datarow[key]=counterdefaultdata[key] + + var=weatherAPIdbmod.WTdata + if var: + WeightParam=var["CounterInfo"] + if ("queryintervalmin" in WeightParam): + queryintervalmin=WeightParam["queryintervalmin"]["value"] + + timestr="00:"+queryintervalmin+":00" + datalist= hardwaremod.separatetimestringint(timestr) + timestr=str(datalist[0])+":"+str(datalist[1])+":"+str(datalist[2]) + + print(timestr) + if "time" in datarow: + datarow["time"]=timestr + + + return True + +def DefaultCounterName(): + return counterdefaultdata["name"] + +def ActiveActuatorList(): + var=weatherAPIdbmod.WTdata + if var: + return var["Wateractuators"] + +def tonumber(thestring, outwhenfail): + try: + n=float(thestring) + return n + except: + return outwhenfail + +def gen_dict_extract(key, var): # not used but very interesting search function + if hasattr(var,'items'): # should be "items" in python 3 + for k, v in var.items(): + if k == key: + yield var + if isinstance(v, dict): + for result in gen_dict_extract(key, v): + yield result + elif isinstance(v, list): + for d in v: + for result in gen_dict_extract(key, d): + yield result + + +def readstatus(element,item): + return statusdataDBmod.read_status_data(AUTO_data,element,item) + +def savedata(sensorname,sensorvalue): + sensorvalue_str=str(sensorvalue) + sensorvalue_norm=hardwaremod.normalizesensordata(sensorvalue_str,sensorname) + sensordbmod.insertdataintable(sensorname,sensorvalue_norm) + return + + +def isNowInTimePeriod(startTime, endTime, nowTime): + #print "iNSIDE pERIOD" ,startTime," ", endTime," " , nowTime + if startTime < endTime: + return nowTime >= startTime and nowTime <= endTime + else: #Over midnight + return nowTime >= startTime or nowTime <= endTime + + + + + +if __name__ == '__main__': + + """ + prova functions + """ + + + diff --git a/wifischeme_old.py b/wifischeme_old.py old mode 100644 new mode 100755 index 55a2ddb..17276c1 --- a/wifischeme_old.py +++ b/wifischeme_old.py @@ -1,3 +1,7 @@ +from __future__ import print_function +from builtins import str +from builtins import filter +from builtins import object import re import itertools import os @@ -105,7 +109,7 @@ def __str__(self): in the /etc/network/interfaces file. """ iface = "iface {interface}-{name} inet {mode}".format(**vars(self)) - options = ''.join("\n {k} {v}".format(k=k, v=v) for k, v in self.options.items()) + options = ''.join("\n {k} {v}".format(k=k, v=v) for k, v in list(self.options.items())) return iface + options + '\n' def __repr__(self): @@ -189,7 +193,7 @@ def iface(self): def as_args(self): args = list(itertools.chain.from_iterable( - ('-o', '{k}={v}'.format(k=k, v=v)) for k, v in self.options.items())) + ('-o', '{k}={v}'.format(k=k, v=v)) for k, v in list(self.options.items()))) return [self.interface + '=' + self.iface] + args @@ -201,7 +205,7 @@ def activate(self): subprocess.check_output(['/sbin/ifdown', self.interface], stderr=subprocess.STDOUT) ifup_output = subprocess.check_output(['/sbin/ifup'] + self.as_args(), stderr=subprocess.STDOUT) ifup_output = ifup_output.decode('utf-8') - print ifup_output + print(ifup_output) return self.parse_ifup_output(ifup_output) @@ -210,7 +214,7 @@ def parse_ifup_output(self, output): if matches: return Connection(scheme=self, ip_address=matches.group('ip_address')) else: - print "Failed to connect to " , self + print("Failed to connect to " , self) return False diff --git a/wpa_cli_mod.py b/wpa_cli_mod.py old mode 100644 new mode 100755 index 06a376b..877076c --- a/wpa_cli_mod.py +++ b/wpa_cli_mod.py @@ -1,3 +1,6 @@ +from __future__ import print_function +from __future__ import division +from past.utils import old_div import logging import time import subprocess @@ -5,12 +8,12 @@ logger = logging.getLogger("hydrosys4."+__name__) def db2dbm(quality): - """ - Converts the Radio (Received) Signal Strength Indicator (in db) to a dBm - value. Please see http://stackoverflow.com/a/15798024/1013960 - """ - dbm = int((quality / 2) - 100) - return min(max(dbm, -100), -50) + """ + Converts the Radio (Received) Signal Strength Indicator (in db) to a dBm + value. Please see http://stackoverflow.com/a/15798024/1013960 + """ + dbm = int((old_div(quality, 2)) - 100) + return min(max(dbm, -100), -50) """ target is to implement the following: @@ -39,7 +42,7 @@ def run_program(cmd): time.sleep(0.5) return ifup_output except subprocess.CalledProcessError as e: - print "Something wrong: ", e + print("Something wrong: ", e) return "FAIL" @@ -86,15 +89,15 @@ def get_networks(iface, retry=1): def remove_all(iface): - """ - Disconnect all wireless networks. - """ - cmd=['wpa_cli', '-i' + iface , 'list_networks'] - lines = run_program(cmd).split("\n") - if lines: - for line in lines[1:-1]: - net_id=line.split()[0] - remove_network(iface,net_id) + """ + Disconnect all wireless networks. + """ + cmd=['wpa_cli', '-i' + iface , 'list_networks'] + lines = run_program(cmd).split("\n") + if lines: + for line in lines[1:-1]: + net_id=line.split()[0] + remove_network(iface,net_id) def remove_network(iface,net_id): cmd=['wpa_cli', '-i' + iface , 'remove_network' , net_id] @@ -118,7 +121,7 @@ def get_net_id(iface,ssid): for item in networks: if item["ssid"]==ssid: net_id=item["net_id"] - print "Network ID of the SSID = ",ssid, " ID= ", net_id + print("Network ID of the SSID = ",ssid, " ID= ", net_id) return net_id return "" @@ -128,9 +131,9 @@ def remove_network_ssid(iface,ssid): # find net_id net_id=get_net_id(iface,ssid) if net_id: - print "net id to remove ", net_id + print("net id to remove ", net_id) remove_network(iface,net_id) - print "saved ", saveconfig(iface) + print("saved ", saveconfig(iface)) updateconfig(iface) return True return False @@ -138,17 +141,17 @@ def remove_network_ssid(iface,ssid): def disable_all(iface): - """ - Disable all wireless networks. - """ - cmd=['wpa_cli', '-i' + iface , 'list_networks'] - lines = run_program(cmd).split("\n") - if lines: - for line in lines[1:-1]: - net_id=line.split()[0] - disable_network(iface,net_id) - return True - return False + """ + Disable all wireless networks. + """ + cmd=['wpa_cli', '-i' + iface , 'list_networks'] + lines = run_program(cmd).split("\n") + if lines: + for line in lines[1:-1]: + net_id=line.split()[0] + disable_network(iface,net_id) + return True + return False def disable_network_ssid(iface,ssid): if ssid=="": @@ -157,7 +160,7 @@ def disable_network_ssid(iface,ssid): # find net_id net_id=get_net_id(iface,ssid) if net_id: - print "net id to disable ", net_id + print("net id to disable ", net_id) return disable_network(iface,net_id) return False @@ -189,15 +192,15 @@ def save_network(iface,ssid,password): remove_network_ssid(iface,ssid) cmd=['wpa_cli', '-i' + iface , 'add_network'] net_id=run_program(cmd) - print "Net ID to add " , net_id + print("Net ID to add " , net_id) cmd=['wpa_cli', '-i' + iface , 'set_network', net_id , 'ssid' , '"'+ssid+'"' ] strout=run_program(cmd) - print "ssid set " , strout + print("ssid set " , strout) if not "OK" in strout: return False cmd=['wpa_cli', '-i' + iface , 'set_network', net_id , 'psk' , '"'+password+'"' ] strout=run_program(cmd) - print "ssid psk " , strout + print("ssid psk " , strout) if not "OK" in strout: return False @@ -215,10 +218,10 @@ def save_network(iface,ssid,password): def enable_ssid(iface, ssid): - cmd=['wpa_cli', '-i' + iface , 'list_networks'] - lines = run_program(cmd).split("\n") - if lines: - for line in lines[1:-1]: + cmd=['wpa_cli', '-i' + iface , 'list_networks'] + lines = run_program(cmd).split("\n") + if lines: + for line in lines[1:-1]: strlist = line.split("\t") # do not use space as separator, the SSID can have spaces inside if strlist: net_id=strlist[0] @@ -229,12 +232,12 @@ def enable_ssid(iface, ssid): return False def listsavednetwork(iface): - #updateconfig(iface) - cmd=['wpa_cli', '-i' + iface , 'list_networks'] - lines = run_program(cmd).split("\n") - data=[] - if lines: - for line in lines[1:-1]: + #updateconfig(iface) + cmd=['wpa_cli', '-i' + iface , 'list_networks'] + lines = run_program(cmd).split("\n") + data=[] + if lines: + for line in lines[1:-1]: strlist = line.split("\t") # do not use space as separator, the SSID can have spaces inside if len(strlist)>1: net_id=strlist[0] @@ -261,30 +264,30 @@ def status(iface): return data def has_ip(_iface): - """ - Check if we have an IP address assigned - """ - status = run_program("wpa_cli -i %s status" % _iface) - r = re.search("ip_address=(.*)", status) - if r: - return r.group(1) - return False + """ + Check if we have an IP address assigned + """ + status = run_program("wpa_cli -i %s status" % _iface) + r = re.search("ip_address=(.*)", status) + if r: + return r.group(1) + return False def do_dhcp(_iface): - """ - Request a DHCP lease. - """ - run_program("dhclient %s" % _iface) + """ + Request a DHCP lease. + """ + run_program("dhclient %s" % _iface) if __name__ == "__main__": network = get_networks("wlan0") for item in network: - print " ssid : " , item["ssid"] , " flags : " , item["flag"] + print(" ssid : " , item["ssid"] , " flags : " , item["flag"]) #print status("wlan0") - print "saved SSids" - print listsavednetwork("wlan0") + print("saved SSids") + print(listsavednetwork("wlan0")) save_connect_network("wlan0","beccolo2","daicazzo") remove_network_ssid("wlan0","eccolo2")