def __init__(self,io):						#Initialisation
      
	Sensors.__init__(self, io )
        self.X_difference = 0.0						#Reading difference of light sensors in X-axis
	self.Y_difference = 0.0						#Reading difference of light sensors in X-axis
	self.current_reading_of_light_sensors = [0.0, 0.0, 0.0, 0.0]	#Variable for collecting current readings of Light sensors
        self.X_diff_normalised = 0.0
	self.Y_diff_normalised = 0.0
示例#2
0
 def __init__(self):
     """Constructor for the internal state of the robot, e.g. in which direction he is
     currently looking"""
     self.direction = Directions.up
     self.gy = GyroSensor()
     self.steer_pair = MoveSteering(OUTPUT_A, OUTPUT_D, motor_class= LargeMotor)
     self.zero_point = ColorSensor().reflected_light_intensity
     self.s = Sensors()
示例#3
0
 def read(self):
     if (self.curr_val_char is None):
         print ("ERROR: Devices are not connected.")
         sys.exit(1)            
     rawdata = self.curr_val_char.read()
     rawdata = struct.unpack('BBBBHHHHHHHH', rawdata)
     sensors = Sensors()
     sensors.set(rawdata)
     return sensors
    def __init__(self,io):
      
	Sensors.__init__(self, io )
        #self.IO = io
        self.BR = (0,0)
        self.BL = (0,0)
        self.button_1_pressed = False
        self.button_2_pressed = False
        self.button_3_pressed = False
class SensorsModule(threading.Thread):
    """Obtain data from the Sensors installed in the device."""
    def __init__(self, lock):
        threading.Thread.__init__(self)

        self.shutdown_flag = threading.Event()
        self.lock = lock

        #Set GPIO interface
        GPIO.setwarnings(False)
        GPIO.cleanup()  # Clean up previous configuration
        GPIO.setmode(GPIO.BCM)  # Specify the pin numbering system

        # Set PWM cycle to generate 1.4 volts for MQ-7 sensors
        GPIO.setwarnings(False)
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(16, GPIO.OUT)
        self.pwm = GPIO.PWM(16, 100)
        self.pwm.start(
            14)  # Generate a duty cycle capable of providing 1.4 volts

        self.sensors = Sensors(MQ7_Ro, MQ2_Ro)

    def run(self):
        global sensor_data

        print('* Sensors module has started')
        sys.stdout.flush()
        sensor_data_aux = {}

        # First measurement
        self.lock.acquire()
        sensor_data = self.sensors.getSensorData().copy()
        self.lock.release()

        while not self.shutdown_flag.is_set():
            # Obtain data from sensors
            self.pwm.start(
                14
            )  # Generate a duty cycle capable of providing 1.4 volts to MQ-7
            time.sleep(60)  # Wait 60 seconds to obtain results
            sensor_data_aux = self.sensors.getSensorData().copy()

            # Apply smoothed average and copy the data into the global variable
            self.lock.acquire()
            for k, v in sensor_data_aux.items():
                sensor_data[k] = ALPHA * v + (1 - ALPHA) * sensor_data[k]
            self.lock.release()

            self.pwm.start(
                100
            )  # Generate a duty cycle capable of providing 1.4 volts to MQ-7
            time.sleep(90)

        print('* Sensors module has stopped')
        sys.stdout.flush()
示例#6
0
    def __init__(self):
        self.ser = self._initialize_serial_communication()  # establish serial communication
        self._initialize_car()  # initialize the car
        self.sensor = Sensors()  # initialize sensors

        # first few frames of camera feed are low quality
        for i in range(0, 10):
            self.update_sensors()

        self.action = CarActions(self)  # allows us to perform hard-coded actions in the car
        self.rf = NewFollower()
示例#7
0
class SensorsTest(unittest.TestCase):
    def setUp(self):
        self.sensors = Sensors()

    def tearDown(self):
        pass

    def test_update(self):
        self.sensors.discover()
        self.assertEqual(len(self.sensors), 1)
        before = self.sensors[0].getReadings()
        self.sensors.update_environmental_data()
        self.sensors.update_environmental_data()
        after = self.sensors[0].getReadings()
        self.assertEqual(after['counter']['value'], before['counter']['value']+1)
示例#8
0
def slave(timeout=6):
    nrf.listen = True  # put radio into RX mode and power up
    start_timer = time.monotonic()  # used as a timeout
    while (time.monotonic() - start_timer) < timeout:
        humidity, temp = Sensors.readTempHumid()
        if nrf.available():
            length = nrf.any()  # grab payload length info
            pipe = nrf.pipe  # grab pipe number info
            received = nrf.read(length)  # clears info from any() and nrf.pipe
            question = received.decode('utf-8')
            nrf.listen = False  # put the radio in TX mode
            result = False
            ack_timeout = time.monotonic_ns() + 200000000
            while not result and time.monotonic_ns() < ack_timeout:
                # try to send reply for 200 milliseconds (at most)
                answer = bytes(str(humidity), 'utf-8')
                result = nrf.send(answer)
            nrf.listen = True  # put the radio back in RX mode
            print(
                "Received {} Sent: {}".format(
                    bytes(received).decode("utf-8"),
                    answer.decode('utf-8'),
                ),
                end=" ", flush=True
            )
            print("", flush=True)
            if not result:
                print("Response failed or timed out", flush=True)
            start_timer = time.monotonic()  # reset timeout

    # recommended behavior is to keep in TX mode when in idle
    nrf.listen = False  # put the nRF24L01 in TX mode + Standby-I power state
示例#9
0
 def __init__(self):
     self._state = {}
     GPIO.setmode(GPIO.BCM)
     self._gpio = GPIO
     self._driver = Driver.Driver(self._gpio)
     self._sensors = Sensors.Sensors(self._gpio)
     self._vision = Vision.Vision((640, 480))
     self._laser = Laser.Laser(self._gpio, 25)
    def __init__(self, io):

        Sensors.__init__(self, io)

        # Collision to the left IR
        self.LeftIRcollision = (0, 0)

        # Collision to the right IR
        self.RightIRcollision = (0, 0)

        # Collision to the Sonar
        self.SonarCollison = (0, 0)

        # Thresholds of its sensor
        self.left_IR_limit = 414  # 15 #480
        self.right_IR_limit = 414
        self.sonar_limit = 22  # 22
        self.turn = 1
    def __init__(self, lock):
        threading.Thread.__init__(self)

        self.shutdown_flag = threading.Event()
        self.lock = lock

        #Set GPIO interface
        GPIO.setwarnings(False)
        GPIO.cleanup()  # Clean up previous configuration
        GPIO.setmode(GPIO.BCM)  # Specify the pin numbering system

        # Set PWM cycle to generate 1.4 volts for MQ-7 sensors
        GPIO.setwarnings(False)
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(16, GPIO.OUT)
        self.pwm = GPIO.PWM(16, 100)
        self.pwm.start(
            14)  # Generate a duty cycle capable of providing 1.4 volts

        self.sensors = Sensors(MQ7_Ro, MQ2_Ro)
示例#12
0
    def __init__(self, buddy_configuration, logger):
        """
        Initialize the object.
        """

        self.__configuration__ = buddy_configuration
        self.__logger__ = logger
        self.__lcd__ = None
        self.__lcd_status_id__ = 0
        self.__initialize_lcd__()
        self.__is_gas_detected__ = False
        self.__system_start_time__ = datetime.datetime.now()
        self.__sensors__ = Sensors(buddy_configuration)

        serial_connection = self.__initialize_modem__()
        if serial_connection is None and not local_debug.is_debug():
            self.__logger__.log_warning_message(
                "Unable to initialize serial connection, quiting.")
            sys.exit()

        self.__fona_manager__ = FonaManager(
            self.__logger__, serial_connection,
            self.__configuration__.cell_power_status_pin,
            self.__configuration__.cell_ring_indicator_pin,
            self.__configuration__.utc_offset)

        # create heater relay instance
        self.__relay_controller__ = RelayManager(
            buddy_configuration, logger, self.__heater_turned_on_callback__,
            self.__heater_turned_off_callback__,
            self.__heater_max_time_off_callback__)
        self.__gas_sensor_queue__ = MPQueue()

        self.__logger__.log_info_message(
            "Starting SMS monitoring and heater service")
        self.__clear_existing_messages__()

        self.__logger__.log_info_message("Begin monitoring for SMS messages")
        self.__queue_message_to_all_numbers__(
            "HangarBuddy monitoring started." + "\n" +
            self.__get_help_status__())
        self.__queue_message_to_all_numbers__(self.__get_full_status__())
        self.__lcd__.clear()
        self.__lcd__.write(0, 0, "Ready")
示例#13
0
def listen(timeout=3):
    nrf.listen = True  # put radio into RX mode and power up
    start_timer = time.monotonic()  # used as a timeout
    while (time.monotonic() - start_timer) < timeout:
        if nrf.available():
            length = nrf.any()  # grab payload length info
            question = nrf.read(length)  # clears info from any() and nrf.pipe

            nrf.listen = False  # put the radio in TX mode
            result = False
            ack_timeout = time.monotonic_ns() + 200000000
            while not result and time.monotonic_ns() < ack_timeout:
                # try to send reply for 200 milliseconds (at most)
                answer = bytes(Sensors.getAnswer(question),
                               'utf-8')  #convert answer to bytes
                result = nrf.send(answer)
            nrf.listen = True  # put the radio back in RX mode

            if not result:
                print("Response failed or timed out")
            start_timer = time.monotonic()  # reset timeout

        nrf.listen = False  # put the nRF24L01 in TX mode + Standby-I power state
示例#14
0
    udp_sender.join()
    sensors.stop()
    sensors.join()
    Log("Application stopped")
    sys.exit(0)


###############################################################################
## main #######################################################################
if __name__ == "__main__":
    shutdown_application = Shutdown(shutdown_func=shutdown_application)
    data = Sensordata()

    display = Display(data)

    udp_sender = UDP_Sender(data)
    udp_sender.start()

    sensors = Sensors(data, update_display=display.print)
    sensors.start()

    scheduler = Scheduler(data)
    scheduler.start()

    control = Control(data, scheduler)
    control.start()

    app.run(host="0.0.0.0")

# eof #
示例#15
0
from DHT import DHT
from Sensors import Sensors
from File import File
from MySQL import *
from MongoDB import *
import sys

newSQL = MySQL()
newMongo = MongoDB()
newSQL.Conexion()
newMongo.mongoConexion()

sensors = Sensors()
sensorList = sensors.getAllInstance()
print(sensorList)
sensorList.returnData()
示例#16
0
 def setUp(self):
     self.sensors = Sensors()
示例#17
0
class Robot():
#"""Class for roboter movements."""

    def __init__(self):
        """Constructor for the internal state of the robot, e.g. in which direction he is
        currently looking"""
        self.direction = Directions.up
        self.gy = GyroSensor()
        self.steer_pair = MoveSteering(OUTPUT_A, OUTPUT_D, motor_class= LargeMotor)
        self.zero_point = ColorSensor().reflected_light_intensity
        self.s = Sensors()

    def gyro_reset(self):
        """Method to reset the GyroSensor to 0"""
        self.gy.mode = 'GYRO-RATE'
        self.gy.mode = 'GYRO-ANG'

    def steer_pair_l(self):
        """Method to initalise the steering to the right side with speed set to 100"""
        self.steer_pair.on(steering=-100, speed=30)

    def steer_pair_r(self):
        """Method to initalise the steering to the left side with speed set to 100"""
        self.steer_pair.on(steering=100, speed=30)

    def steer_pair_stop(self):
        self.steer_pair.off(True)

    def turn(self, direction, count):
        """Method to calculate the right degree to turn. LEGOlas can move in the directions Up, Down, LEft, Right. Count tells LEGOlas how many squares he schould move forward in the same direction"""
        self.gyro_reset()
        degrees_to_turn = self.direction - direction
        #print('degrees_to_turn:', degrees_to_turn)
        if degrees_to_turn == 0:
            self.forward(self.cm_to_sec(count, 40), -1, count)
            return 
        switcher = {
                -3: self.turn_left,  #reference to method turn_x (in this "switch" only references are allowed)
                -2: self.turn_back,
                -1: self.turn_right,
                1: self.turn_left,
                2: self.turn_back,
                3: self.turn_right,
        }
        func = switcher.get(degrees_to_turn, "Invalid direction")
        func(count)
        self.direction = direction
        #print(self.direction)

    def turn_right(self, count):
        """Method to turn LEGOlas 90° to the right"""
        lines_passed = 0
        self.gyro_reset()
        self.steer_pair_r()
        while self.gy.value() < 90:
            print("gy.value: " ,self.gy.value())
            if self.zero_point < 20:
                print("new")
                sleep(0.1)
                self.zero_point = ColorSensor().reflected_light_intensity
            if self.s.offset == self.zero_point: #Überlegen wie man reichweite von +/- 2 machen kann
                print(self.s.offset, self.zero_point)
                sleep(0.25) 
                if lines_passed == 3:
                    sleep(0.05)
                    print("Ende vong 1 Drehen her")
                    self.steer_pair_stop()
                    break
                lines_passed += 1
        self.forward(self.cm_to_sec(count, 40), -1, count)
    
    def turn_left(self, count):
        """Method to turn LEGOlas 90° to the left"""
        lines_passed = 0
        self.gyro_reset()
        self.steer_pair_l()
        while self.gy.value() > -100:
            print("gy.value: " ,self.gy.value())
            if self.zero_point < 20:
                print("new")
                sleep(0.1)
                self.zero_point = ColorSensor().reflected_light_intensity
            if self.s.offset == self.zero_point: #Überlegen wie man reichweite von +/- 2 machen kann
                print(self.s.offset, self.zero_point)
                sleep(0.25) 
                if lines_passed == 3:
                    sleep(0.05)
                    print("Ende vong 1 Drehen her")
                    self.steer_pair_stop()
                    break
                lines_passed += 1
        self.forward(self.cm_to_sec(count, 40), 1, count)
    
    def turn_back(self, count):
        """Method to turn LEGOlas 180° around"""
        lines_passed = 0
        self.gyro_reset()
        self.steer_pair_r()
        while self.gy.value() < 200:
            if self.zero_point < 20:
                print("new")
                sleep(0.1)
                self.zero_point = ColorSensor().reflected_light_intensity
            if self.s.offset == self.zero_point: #Überlegen wie man reichweite von +/- 2 machen kann
                sleep(0.25) 
                if lines_passed == 3:
                    print("Ende vong 1 Drehen her")
                    sleep(0.05)
                    self.steer_pair_stop()
                    break
                lines_passed += 1
        self.forward(self.cm_to_sec(count, 40), 1, count)

    def forward(self, x, y, count):
        """Method for driving the robot x seconds forward until LEGOlas reached a crossing"""
        self.s.pid(x, y, count)
        sleep(1)
            
    def cm_to_sec(self, cm, speed):
        """Function to calculate how many seconds the roboter have to move with speed x to drive n cm"""
        sec = 0.0   
        ref_sec = 2.925
        ref_cm = 1
        ref_speed = 1
        sec = ref_sec * cm / speed
        print('sec: ', sec)
        return sec
示例#18
0
#Author: Jack Clarke
from flask import Flask
from Sensors import Sensors
app = Flask(__name__)
sensor = Sensors()


@app.route("/temp")
def getTemp():
    item = {"temp": sensor.getTemp()}
    return item


@app.route("/door")
def doorOpen():
    item = {"doorIsOpen": sensor.doorIsOpen()}
    return item


@app.route("/brightness")
def getBrightness():
    item = {"brightness": sensor.getBrightness()}
    return item


@app.route("/humidity")
def getHumidity():
    item = {"humidity": sensor.getHumidity()}
    return item

示例#19
0
 def setUpClass():
     sensor = Sensors()
     time.sleep(2)
示例#20
0
  t.run = False
  sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)


mp = ALProxy('ALMotion', Config.nao_ip_port[0], Config.nao_ip_port[1])
#mp = ALProxy('ALMotion', '127.0.0.1', 9559)

# Set stiffness
pNames = "Body"
pStiffnessLists = 0.8
pTimeLists = 1.0
mp.stiffnessInterpolation(pNames, pStiffnessLists, pTimeLists)


t = Sensors()
t.start()

sleep(1)

RSRollOmejitve = (-1.6494, -0.0087)
RSPitchOmejitve = (-2.0857, 2.0857)
RERollOmejitve = (0.0087, 1.5621)
REYawOmejitve = (-2.0857, 2.0857)
RWYawOmejitve = (-1.8238, 1.8238)

i = 0
startTime = clock()
naoControll = False

dataI = t.forearm.i
 def test_isRaspPi(self):
     sensor = Sensors()
     self.assertEqual(sensor.isRaspberryPi, False)
     sensor.stop()
     self.assertEqual(sensor.isRunning(), False)
 def test_door(self):
     sensor = Sensors()
     self.assertEqual(isinstance(sensor.doorIsOpen(), bool), True)
     sensor.stop()
     self.assertEqual(sensor.isRunning(), False)
 def test_Brightness(self):
     sensor = Sensors()
     self.assertEqual(isinstance(sensor.getBrightness(), int), True)
     self.assertEqual(sensor.getBrightness() > 0, True)
     sensor.stop()
     self.assertEqual(sensor.isRunning(), False)
 def test_Humidity(self):
     sensor = Sensors()
     self.assertEqual(isinstance(sensor.getHumidity(), int), True)
     self.assertEqual(sensor.getHumidity() > 0, True)
     sensor.stop()
     self.assertEqual(sensor.isRunning(), False)
示例#25
0
            question = nrf.read(length)  # clears info from any() and nrf.pipe

            nrf.listen = False  # put the radio in TX mode
            result = False
            ack_timeout = time.monotonic_ns() + 200000000
            while not result and time.monotonic_ns() < ack_timeout:
                # try to send reply for 200 milliseconds (at most)
                answer = bytes(Sensors.getAnswer(question),
                               'utf-8')  #convert answer to bytes
                result = nrf.send(answer)
            nrf.listen = True  # put the radio back in RX mode

            if not result:
                print("Response failed or timed out")
            start_timer = time.monotonic()  # reset timeout

        nrf.listen = False  # put the nRF24L01 in TX mode + Standby-I power state


Sensors = Sensors()
if __name__ == "__main__":

    try:
        while True:
            Sensors.populateAnswers()
            listen()

    except KeyboardInterrupt:
        print(" Keyboard Interrupt detected. Powering down radio...")
        nrf.power = False
 def test_start(self):
     sensor = Sensors()
     sensor.stop()
     self.assertEqual(sensor.isRunning(), False)
     sensor.start()
     self.assertEqual(sensor.isRunning(), True)
     sensor.stop()
     self.assertEqual(sensor.isRunning(), False)
import time
from datetime import datetime

import paho.mqtt.client as client
import paho.mqtt.publish as publish
from Sensors import Sensors
from getmac import get_mac_address
from pytz import timezone

# Author: Gary A. Stafford
# Date: 10/11/2020
# Usage: python3 sensor_data_to_mosquitto.py \
#           --host "192.168.1.12" --port 1883 \
#           --topic "sensor/output" --frequency 10

sensors = Sensors()

logger = logging.getLogger(__name__)
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)


def main():
    args = parse_args()
    publish_message_to_db(args)


def get_readings():
    sensors.led_state(0)

    # Retrieve sensor readings
    payload_dht = sensors.get_sensor_data_dht()
 def test_init(self):
     sensor = Sensors()
     sensor.stop()
示例#29
0
    def do_GET(self):

        sensors = Sensors()
        # content_length = int (self.headers['Content-Length'])  # <--- Gets the size of data
        # post_data = self.rfile.read (content_length)  # <--- Gets the data itself

        response = BytesIO()

        if (self.path == '/soil_humidity'):

            s_h = sensors.get_soil_humidity()
            print(s_h)
            self._set_headers()
            jsonString = JSONEncoder().encode({
                "soil_humidity": s_h,
                "time": time.asctime()
            })
            print(jsonString)
            self.wfile.write(bytes(jsonString, "utf-8"))

        elif (self.path == '/temperature'):

            te = sensors.get_temperature()
            print(te)
            self._set_headers()
            jsonString = JSONEncoder().encode({
                "temperature": te,
                "time": time.asctime()
            })
            print(jsonString)
            self.wfile.write(bytes(jsonString, "utf-8"))

        elif (self.path == '/rain'):

            rain = sensors.get_rain()
            print(rain)
            self._set_headers()
            jsonString = JSONEncoder().encode({
                "rain": rain[0],
                "rain_verbose": rain[1],
                "time": time.asctime()
            })
            print(jsonString)
            self.wfile.write(bytes(jsonString, "utf-8"))

        elif (self.path == '/light'):

            li = sensors.get_light()
            print(li)
            self._set_headers()
            jsonString = JSONEncoder().encode({
                "light": li[0],
                "condition": li[1],
                "time": time.asctime()
            })
            print(jsonString)
            self.wfile.write(bytes(jsonString, "utf-8"))

        else:
            self.send_response(422)
            self.send_header('Content-type', 'application/json')
            self.end_headers()
 def test_Temperature(self):
     sensor = Sensors()
     self.assertEqual(isinstance(sensor.getTemp(), int), True)
     self.assertEqual(sensor.getTemp() > 0, True)
     sensor.stop()
     self.assertEqual(sensor.isRunning(), False)
示例#31
0
class CarControl:
    """
    This class will be used to control the car.
    """
    def __init__(self):
        self.ser = self._initialize_serial_communication(
        )  # establish serial communication
        self._initialize_car()  # initialize the car
        self.sensor = Sensors()  # initialize sensors

        # first few frames of camera feed are low quality
        for i in range(0, 10):
            self.update_sensors()

        self.action = CarActions(
            self)  # allows us to perform hard-coded actions in the car
        self.rf = ReddFollower()

    def update_sensors(self):
        """
        updates the sensors values
        :return:
        """
        self.sensor.update_sensors()

    def drive(self, speed):
        """
        Commands the car to drive.
        :param speed: -2.0 to 2.0
        :return: nothing
        """
        self._send_command("!speed" + str(speed) + "\n")

    def steer(self, degree):
        """
        Commands the car to turn.
        :param degree: -30.0 to 30.0
        :return: nothing
        """
        self._send_command("!steering" + str(degree) + "\n")

    def _initialize_serial_communication(self):
        """
        Initializes the serial communication.

        :return: Object required for communication.
        """
        print("Initializing Serial Communications")
        ser = serial.Serial("/dev/ttyUSB0", 115200)
        time.sleep(2)  # must sleep for a bit while initializing
        print("Flushing Input")
        ser.flushInput()
        time.sleep(1)  # must sleep for a bit while initializing
        return ser

    def _send_command(self, command, addnewline=False):
        """
        Sends a command to the car. Remember that every command must end with a new line.

        Author: redd
        """
        if addnewline:
            command = command + "\n"
        self.ser.write(command.encode())

    def _initialize_car(self, pid_flag=True):
        """
        Initializes the car. This must be run before we can control the car.

        Author: redd
        """

        print("Initializing Car")
        self._send_command("!straight1430\n")
        self._send_command("!kp0.01\n")
        self._send_command("!kd0.01\n")
        if pid_flag:
            self._send_command("!pid1\n")
        else:
            self._send_command("!pid0\n")
        self._send_command("!start1590\n")
        self.drive(0.0)
        print("Initialization Completed")