def test_when_request_times_out(self): with unittest.mock.patch('http.client.HTTPSConnection') as MockHTTPSConnection: mock_connection = MockHTTPSConnection.return_value mock_connection.request = unittest.mock.MagicMock(side_effect=socket.timeout()) system_id = 'b90e1fc0-53d3-42ba-8bf6-83453e6af744' flic_last_seen_secs = 5 success = heartbeat.send_heartbeat(flic_last_seen_secs, system_id) assert success == False assert mock_connection.request.called
def test_when_heartbeat_server_is_not_working(self): with unittest.mock.patch('http.client.HTTPSConnection') as MockHTTPSConnection: mock_connection = MockHTTPSConnection.return_value mock_response = unittest.mock.MagicMock() mock_response.status = 500 mock_connection.getresponse.return_value = mock_response mock_connection.request = unittest.mock.MagicMock() system_id = 'b90e1fc0-53d3-42ba-8bf6-83453e6af744' flic_last_seen_secs = 5 success = heartbeat.send_heartbeat(flic_last_seen_secs, system_id) assert success == False assert mock_connection.request.called
def tof_readings(): # for heartbeat start_time = datetime.now() heartbeat_delta = timedelta(minutes=15) #MQTT Client setup client = mqtt.Client(client_id="T1_TOF") client.username_pw_set(username="******", password="******") client.connect("18.141.11.6") # client.publish("test", "randylovesyellow") global readings lowerThreshold = 300 upperThreshold = 1500 outside = 0 inside = 0 status = 0 # toggle ROI: 0 - inside, 1 - outside i = 1 zero_count = 0 prev_reading = [0, 0] while True: now = datetime.now() # Heartbeat logic if (now - start_time) >= heartbeat_delta: heartbeat.send_heartbeat(client, "E_TOF") start_time = now curr_reading = [0, 0] #inside, outside if status: outside = outsideDistance(lowerThreshold, upperThreshold) if outside: curr_reading[1] = 1 #print("outside") #print("Left: " + str(showLeft) + " |") status = 0 if not status: inside = insideDistance(lowerThreshold, upperThreshold) if inside: curr_reading[0] = 1 #print("inside") #print(" | Right: " + str(showRight) ) status = 1 if i == 1 and sum(curr_reading) == 1: readings.append(curr_reading) prev_reading = curr_reading[:] i = 0 zero_count = 0 #print(readings) pass if curr_reading != prev_reading: if sum(curr_reading) == 1: readings.append(curr_reading) prev_reading = curr_reading[:] zero_count = 0 #print(readings) pass if sum(curr_reading) == 0: zero_count += 1 if zero_count > 7 and i == 0: readings.append(curr_reading) i = 1 prev_reading = [0, 0] #process_thread = threading.Thread(target=counting, args=[readings]) #process_thread.start() counting(readings) readings = []
def main(): # Instantiate Capacitive Sensor object mpr121 = MPR121.MPR121() # Admin attributes SEAT_NUMBER = 4 start_time = datetime.now() heartbeat_delta = timedelta(minutes=5) # Capacitive Sensor Setup CHANNEL_NUM = 11 SD_THRESHOLD = 5 EMPTY_THRESHOLD = 120 HOGGING_THRESHOLD = 100 mpr121.sensor_init() mpr121.set_threshold(0x60) mpr121.wait_for_ready() readings = np.array([]) minimum_readings = 50 window = 50 status = "Unoccupied" change = False # PIR Motion Sensor Setup pir_sensor = 8 led_port = 4 motion = 0 grovepi.pinMode(pir_sensor, "INPUT") grovepi.pinMode(led_port, "OUTPUT") last_motion = datetime.now() max_delta = timedelta(seconds=3) #max_delta = timedelta(hours=2) time.sleep(5) #MQTT Client setup client = mqtt.Client(client_id="T5-2") client.username_pw_set(username="******", password="******") client.connect("18.141.11.6") heartbeat.send_heartbeat(client, SEAT_NUMBER) print("Starting monitoring") while True: try: original_status = status now = datetime.now() # Heartbeat logic if (now - start_time) >= heartbeat_delta: heartbeat.send_heartbeat(client, SEAT_NUMBER) start_time = now client.reconnect() #print("Client reconnect") # Capacitive logic readings_arr = mpr121.listen_sensor_status() r = readings_arr[CHANNEL_NUM] # Add newest reading to array readings = np.append(readings, [r]) # If less than required window of readings, continue taking if len(readings) < window: continue # This else-if calibrates the baseline to either 2 SDs below or a fixed amount slightly lower # If an item is on the table when this is run, the empty baseline will be calibrated too low elif len(readings) == window: # Reset the desk status back to unoccupied client.reconnect() msg = "['" + str(SEAT_NUMBER) + "','" + str(now) + "','" + str( 0) + "']" client.publish("hd/status", msg) # EMPTY_THRESHOLD = np.mean(readings) - np.std(readings) * 2 EMPTY_THRESHOLD = np.mean(readings) - 3 continue # Remove oldest reading readings = np.delete(readings, 0) print(readings) # Get mean and standard deviation average = np.mean(readings) sd = np.std(readings) print(average) # print(sd) # If std. deviation > threshold, means change in state # if sd >= SD_THRESHOLD: # change = True # Motion Sensor logic motion = grovepi.digitalRead(pir_sensor) if motion == 0 or motion == 1: # check if reads were 0 or 1 it can be 255 also because of IO Errors so remove those values if motion == 1: # print ('Motion Detected') last_motion = datetime.now() if average > EMPTY_THRESHOLD: status = "Unoccupied" elif average > HOGGING_THRESHOLD: # status = "Items on desk" status = "Occupied" else: # status = "Laptop on desk" status = "Occupied" time_difference = now - last_motion # if the time difference if greater than 2 hours and the status is not unoccupied , means hogging if time_difference >= max_delta and status != "Unoccupied": status = "Hogged" print(status) # print(original_status) if status != original_status: change = True # change in statuses must be sent to server via MQTT if change: # msg = {'id': SEAT_NUMBER, 'timestamp': str(now), 'occStatus': OccupancyStatus.OccupancyStatus[status].value} # msg = json.dumps(msg) msg = "['" + str(SEAT_NUMBER) + "','" + str(now) + "','" + str( OccupancyStatus.OccupancyStatus[status].value) + "']" #print(msg) with open("actuations.txt", "a") as log: log.write(msg + "\n") client.reconnect() client.publish("hd/status", msg) print("Data sent") msg = "" change = False if status == "Hogged" or status == "Unoccupied": grovepi.digitalWrite(led_port, 255) else: grovepi.digitalWrite(led_port, 0) time.sleep(0.25) except IOError: print("IO Error") except Exception as e: print(e)
motion = 0 grovepi.pinMode(pir_sensor, "INPUT") client = create_client("grp5_motion") motion_counter = 0 time_in_sec = 0 start_time = datetime.now() heartbeat_delta = timedelta(minutes=1) curr_reading = 0 prev_reading = 0 no_motion_count = 0 while True: print("Start detecting") heartbeat_check = datetime.now() if (heartbeat_check - start_time) >= heartbeat_delta: heartbeat.send_heartbeat(client, "E_Motion") start_time = heartbeat_check try: # Sense motion, usually human, within the target range print("Motion Counter", str(motion_counter)) print("Time in seconds", str(time_in_sec)) motion = grovepi.digitalRead(pir_sensor) if motion == 1: time_in_sec += 1 motion_counter += 1 elif motion == 0: print("No motion detected") time_in_sec += 1 else: write_error()