Change enable/disable building logic

parent b4adcc85
FROM python:3.5
RUN apt-get update &&\
apt-get install --no-install-recommends --no-install-suggests -y \
\
# Extra deps
cron \
python3-pip
# Base deps
RUN pip3 install \
requests[security] \
django==1.9.8 \
psycopg2==2.6.2 \
gunicorn \
redis==2.10.3 \
django-redis==4.8.0 \
invoke \
numpy \
pandas \
Sphinx \
django-polymorphic \
manuel \
mpld3 \
six \
unipath \
django_cron \
matplotlib \
djangorestframework
RUN mkdir -p /app
WORKDIR /app
COPY [ \
"setup.py", \
"requirements.txt", \
"boilerplate.ini", \
"manage.py", \
"tasks.py", \
"temp_cron", \
"/app/" \
]
COPY src/ /app/src/
ENV PYTHONPATH=src \
SMI_UNB_PRODUCTION=true
# Setting crontab
RUN crontab temp_cron && rm temp_cron
RUN crontab -l
RUN crontab -r
\ No newline at end of file
......@@ -4,62 +4,45 @@ from smi_unb.buildings.models import Building
from smi_unb.transductor.models import EnergyTransductor, EnergyMeasurements
class EnergyTransductorSerializer(serializers.HyperlinkedModelSerializer):
class EnergyTransductorSerializer(serializers.ModelSerializer):
def __init__(self, *args, **kwargs):
many = kwargs.pop('many', True)
super(EnergyTransductorSerializer, self).__init__(
many=many, *args, **kwargs)
id = serializers.IntegerField()
building = serializers.SerializerMethodField()
model = serializers.SerializerMethodField()
class Meta:
model = EnergyTransductor
fields = (
'url', 'id', 'building', 'model', 'active', 'ip_address',
'id', 'building', 'model', 'active', 'ip_address',
'name', 'serie_number', 'local_description',
'comments', 'creation_date', 'calibration_date',
'broken', 'last_measurement_sent')
def get_building(self, obj):
return obj.building.id
def get_model(self, obj):
return obj.model.id
class BuildingSerializer(serializers.HyperlinkedModelSerializer):
class BuildingSerializer(serializers.ModelSerializer):
id = serializers.IntegerField()
campus = serializers.SerializerMethodField()
class Meta:
model = Building
fields = (
'url', 'id', 'campus', 'name', 'acronym', 'description', 'phone',
'id', 'campus', 'name', 'acronym', 'description', 'phone',
'website_address', 'server_ip_address', 'active')
def get_campus(self, obj):
return obj.campus.id
class EnergyMeasurementsSerializer(serializers.HyperlinkedModelSerializer):
class EnergyMeasurementsSerializer(serializers.ModelSerializer):
def __init__(self, *args, **kwargs):
many = kwargs.pop('many', True)
super(EnergyMeasurementsSerializer, self).__init__(
many=many, *args, **kwargs)
transductor = serializers.SerializerMethodField()
class Meta:
model = EnergyMeasurements
fields = (
'url', 'collection_date', 'transductor',
'collection_date', 'transductor',
'voltage_a', 'voltage_b', 'voltage_c',
'current_a', 'current_b', 'current_c',
'active_power_a', 'active_power_b', 'active_power_c',
'reactive_power_a', 'reactive_power_b', 'reactive_power_c',
'apparent_power_a', 'apparent_power_b', 'apparent_power_c')
def get_transductor(self, obj):
return obj.transductor.id
......@@ -62,8 +62,8 @@ class InstanceSynchronizer(object):
return instance_synchronized
def create_json_data(self, serializer_class, instance, many=False):
object_serialized = serializer_class(instance=instance, many=many)
def create_json_data(self, serializer_class, instance):
object_serialized = serializer_class(instance=instance)
return json.dumps(object_serialized.data)
......@@ -110,8 +110,8 @@ class SyncUtils(object):
return data
@classmethod
def create_json_data(cls, serializer_class, instance, many=False):
object_serialized = serializer_class(instance=instance, many=many)
def create_json_data(cls, serializer_class, instance):
object_serialized = serializer_class(instance=instance)
return json.dumps(object_serialized.data)
......
......@@ -10,7 +10,7 @@ from .serializers import BuildingSerializer, EnergyTransductorSerializer, \
class BuildingViewSet(viewsets.ModelViewSet):
queryset = Building.objects.filter(active=True)
queryset = Building.objects.all()
serializer_class = BuildingSerializer
......
......@@ -117,8 +117,16 @@ class BuildingForm(forms.ModelForm):
url = 'http://' + self.instance.server_ip_address
try:
requests.get(url)
except requests.ConnectionError:
request = requests.get(url, timeout=3)
except:
self.add_error(
None,
_('Não foi possível comunicar com o servidor do Edifício. ' +
'Verifique o endereço de IP informado.')
)
return False
if request.status_code != 200:
self.add_error(
None,
_('Não foi possível comunicar com o servidor do Edifício. ' +
......@@ -145,8 +153,16 @@ class EnableBuildingForm(forms.ModelForm):
url = 'http://' + self.instance.server_ip_address
try:
requests.get(url)
except requests.ConnectionError:
request = requests.get(url, timeout=3)
except:
self.add_error(
None,
_('Não foi possível comunicar com o servidor do Edifício. ' +
'Verifique o endereço de IP informado.')
)
return False
if request.status_code != 200:
self.add_error(
None,
_('Não foi possível comunicar com o servidor do Edifício. ' +
......
......@@ -50,11 +50,9 @@ class Building(models.Model):
return self.transductor_set.filter(active=False)
def set_building_active(self):
self.transductor_set.update(active=True)
self.active = True
def set_building_inactive(self):
self.transductor_set.update(active=False)
self.active = False
def update_transductors_sent(self, id_transductors_to_update):
......
......@@ -9,6 +9,18 @@ from smi_unb.buildings.forms import BuildingForm, EnableBuildingForm, \
from smi_unb.buildings.models import Building
def mocked_requests_get(*args, **kwargs):
class MockResponse:
def __init__(self, json_data, status_code):
self.json_data = json_data
self.status_code = status_code
def json(self):
return self.json_data
return MockResponse(None, 200)
class BuildingsFormsTest(TestCase):
def setUp(self):
self.building = self.create_building()
......@@ -33,7 +45,7 @@ class BuildingsFormsTest(TestCase):
return building
@mock.patch('requests.get', return_value=True)
@mock.patch('requests.get', side_effect=mocked_requests_get)
def test_building_form_valid(self, mock):
data = {
'campus': self.building.campus.id,
......@@ -80,7 +92,7 @@ class BuildingsFormsTest(TestCase):
self.assertFalse(form.is_valid())
@mock.patch('requests.get', return_value=True)
@mock.patch('requests.get', side_effect=mocked_requests_get)
def test_enable_building_form_valid(self, mock):
self.building.active = False
......
......@@ -83,19 +83,11 @@ class BuildingsModelsTests(TestCase):
self.building_active.set_building_active()
self.assertEqual(True, self.building_active.active)
self.assertEqual(
4,
self.building_active.transductor_set.filter(active=True).count()
)
def test_set_building_inactive(self):
self.building_active.set_building_inactive()
self.assertEqual(False, self.building_active.active)
self.assertEqual(
4,
self.building_active.transductor_set.filter(active=False).count()
)
def test_get_all_active_buildings(self):
active_buildings = list(Building.objects.get_all_active_buildings())
......
......@@ -14,6 +14,18 @@ from smi_unb.buildings.forms import EnableBuildingForm, DisableBuildingForm
from smi_unb.buildings.models import Building
def mocked_requests_get(*args, **kwargs):
class MockResponse:
def __init__(self, json_data, status_code):
self.json_data = json_data
self.status_code = status_code
def json(self):
return self.json_data
return MockResponse(None, 200)
class BuildingsViewsTests(TestCase):
def setUp(self):
self.client = Client()
......@@ -186,7 +198,7 @@ class BuildingsViewsTests(TestCase):
Tests Create Building
'''
@mock.patch.object(SyncManager, 'sync_building', return_value=True)
@mock.patch('requests.get', return_value=True)
@mock.patch('requests.get', side_effect=mocked_requests_get)
def test_crete_new_building(self, mock_get, mock_sync):
UserPermissions.add_user_permissions(
self.user, ['manager_buildings'])
......@@ -220,7 +232,7 @@ class BuildingsViewsTests(TestCase):
)
@mock.patch.object(SyncManager, 'sync_building', return_value=True)
@mock.patch('requests.get', return_value=True)
@mock.patch('requests.get', side_effect=mocked_requests_get)
def test_not_create_new_building_invalid_params(self, mock_1, mock_2):
UserPermissions.add_user_permissions(
self.user, ['manager_buildings'])
......@@ -274,7 +286,7 @@ class BuildingsViewsTests(TestCase):
Tests Edit Building
'''
@mock.patch.object(SyncManager, 'sync_building', return_value=True)
@mock.patch('requests.get', return_value=True)
@mock.patch('requests.get', side_effect=mocked_requests_get)
def test_edit_building(self, mock_get, mock_sync):
UserPermissions.add_user_permissions(
self.user, ['manager_buildings'])
......@@ -307,7 +319,7 @@ class BuildingsViewsTests(TestCase):
self.assertEqual(True, edited_building.synchronized)
@mock.patch.object(SyncManager, 'sync_building', return_value=True)
@mock.patch('requests.get', return_value=True)
@mock.patch('requests.get', side_effect=mocked_requests_get)
def test_not_edit_building_wrong_params(self, mock_get, mock_sync):
UserPermissions.add_user_permissions(
self.user, ['manager_buildings'])
......@@ -364,7 +376,7 @@ class BuildingsViewsTests(TestCase):
self.assertFormError(response, 'form', None, error_msg)
@mock.patch('requests.get', return_value=True)
@mock.patch('requests.get', side_effect=mocked_requests_get)
def test_not_edit_building_without_changes(self, mock):
UserPermissions.add_user_permissions(self.user, ['manager_buildings'])
......@@ -560,14 +572,11 @@ class BuildingsViewsTests(TestCase):
# '''
# Tests Disable Building
# '''
@mock.patch.object(
Building, 'set_building_inactive', return_value=True)
@mock.patch.object(SyncManager, 'sync_building', return_value=True)
@mock.patch.object(
DisableBuildingForm, 'is_valid',
autospec=True, return_value=True)
def test_disable_building(
self, mock_is_valid, mock_set_building_inactive
):
def test_disable_building(self, mock_is_valid, mock_sync):
UserPermissions.add_user_permissions(
self.user, ['manager_buildings'])
......@@ -584,7 +593,7 @@ class BuildingsViewsTests(TestCase):
response = self.client.post(url, params)
mock_set_building_inactive.assert_called()
mock_sync.assert_called()
self.assertRedirects(
response,
reverse(
......
......@@ -126,9 +126,9 @@ def enable_building(request, building_id):
if form.is_valid():
building = form.save(commit=False)
building.set_building_active()
building.synchronized = SyncManager.sync_building(
building)
building.set_building_active()
building.save()
next_page = request.POST.get('next')
......@@ -157,8 +157,9 @@ def disable_building(request, building_id):
if form.is_valid():
building = form.save(commit=False)
building.synchronized = False
building.set_building_inactive()
building.synchronized = SyncManager.sync_building(
building)
building.save()
return HttpResponseRedirect(
......
......@@ -6,7 +6,7 @@ import sys
from abc import ABCMeta, abstractmethod
from threading import Thread
from smi_unb.transductor.models import Transductor
from smi_unb.buildings.models import Building
from .exceptions import NumberOfAttempsReachedException, \
RegisterAddressException, \
CRCInvalidException
......@@ -374,7 +374,9 @@ class DataCollector(object):
transductor models.
"""
def __init__(self):
self.transductors = Transductor.objects.filter(active=True)
self.building = Building.objects.first()
self.transductors = self.building.transductor_set.filter(active=True)
# self.transductors = Transductor.objects.filter(active=True)
self.transductor_module = importlib.import_module(
"smi_unb.transductor.models"
)
......@@ -436,13 +438,14 @@ class DataCollector(object):
"""
threads = []
for transductor in self.transductors:
collection_thread = Thread(
target=self.single_data_collection, args=(transductor,)
)
collection_thread.start()
if self.building.active:
for transductor in self.transductors:
collection_thread = Thread(
target=self.single_data_collection, args=(transductor,)
)
collection_thread.start()
threads.append(collection_thread)
threads.append(collection_thread)
for thread in threads:
thread.join()
for thread in threads:
thread.join()
......@@ -52,7 +52,7 @@ else:
print('Running server with DEBUG=False')
if not DEBUG:
ALLOWED_HOSTS = ['localhost']
ALLOWED_HOSTS = ['localhost', '127.0.0.1']
# Application definition
......
......@@ -146,8 +146,15 @@ class EnergyForm(forms.ModelForm):
url = 'http://' + self.instance.building.server_ip_address
try:
requests.get(url)
except requests.ConnectionError:
request = requests.get(url, timeout=3)
except:
self.add_error(
None,
_('Não foi possível comunicar com o servidor do Edifício.')
)
return False
if request.status_code != 200:
self.add_error(
None,
_('Não foi possível comunicar com o servidor do Edifício.')
......@@ -185,8 +192,15 @@ class EnableTransductorForm(forms.ModelForm):
url = 'http://' + self.instance.building.server_ip_address
try:
requests.get(url)
except requests.ConnectionError:
request = requests.get(url, timeout=3)
except:
self.add_error(
None,
_('Não foi possível comunicar com o servidor do Edifício.')
)
return False
if request.status_code != 200:
self.add_error(
None,
_('Não foi possível comunicar com o servidor do Edifício.')
......@@ -224,8 +238,15 @@ class DisableTransductorForm(forms.ModelForm):
url = 'http://' + self.instance.building.server_ip_address
try:
requests.get(url)
except requests.ConnectionError:
request = requests.get(url, timeout=3)
except:
self.add_error(
None,
_('Não foi possível comunicar com o servidor do Edifício.')
)
return False
if request.status_code != 200:
self.add_error(
None,
_('Não foi possível comunicar com o servidor do Edifício.')
......
......@@ -10,6 +10,18 @@ from smi_unb.transductor.forms import EnergyForm
from smi_unb.transductor.models import TransductorModel
def mocked_requests_get(*args, **kwargs):
class MockResponse:
def __init__(self, json_data, status_code):
self.json_data = json_data
self.status_code = status_code
def json(self):
return self.json_data
return MockResponse(None, 200)
class EnergyTransductorForm(TestCase):
def setUp(self):
self.building = self.create_building()
......@@ -41,7 +53,7 @@ class EnergyTransductorForm(TestCase):
return building
@mock.patch('requests.get', return_value=True)
@mock.patch('requests.get', side_effect=mocked_requests_get)
def test_valid_form(self, mock):
data = {
'building': self.building.id,
......@@ -54,7 +66,7 @@ class EnergyTransductorForm(TestCase):
self.assertTrue(form.is_valid())
@mock.patch('requests.get', return_value=True)
@mock.patch('requests.get', side_effect=mocked_requests_get)
def test_invalid_form(self, mock):
data = {
'serie_number': '',
......@@ -66,7 +78,7 @@ class EnergyTransductorForm(TestCase):
self.assertFalse(form.is_valid())
@mock.patch('requests.get', return_value=False)
@mock.patch('requests.get', side_effect=mocked_requests_get)
def test_invalid_form_server_connection(self, mock):
data = {
'serie_number': '',
......@@ -78,7 +90,7 @@ class EnergyTransductorForm(TestCase):
self.assertFalse(form.is_valid())
@mock.patch('requests.get', return_value=True)
@mock.patch('requests.get', side_effect=mocked_requests_get)
def test_energyform_valid_calibration_date(self, mock):
now = timezone.now()
......@@ -93,7 +105,7 @@ class EnergyTransductorForm(TestCase):
form = EnergyForm(data=data, building=self.building)
self.assertTrue(form.is_valid())
@mock.patch('requests.get', return_value=True)
@mock.patch('requests.get', side_effect=mocked_requests_get)
def test_energyform_invalid_calibration_date(self, mock):
later = timezone.now() + timezone.timedelta(days=1)
......
......@@ -15,6 +15,18 @@ from smi_unb.transductor.forms import EnergyForm
from smi_unb.transductor.models import EnergyTransductor, TransductorModel
def mocked_requests_get(*args, **kwargs):
class MockResponse:
def __init__(self, json_data, status_code):
self.json_data = json_data
self.status_code = status_code
def json(self):
return self.json_data
return MockResponse(None, 200)
class TransductorViewsTests(TestCase):
def setUp(self):
self.client = Client()
......@@ -219,7 +231,7 @@ class TransductorViewsTests(TestCase):
response, 'form', 'ip_address', 'Incorrect IP address format')
@mock.patch.object(SyncManager, 'sync_transductor', return_value=True)
@mock.patch('requests.get', return_value=True)
@mock.patch('requests.get', side_effect=mocked_requests_get)
def test_change_transductor_model(self, mock_get, mock_sync):
self.client.login(username='test@test.com', password='password')
......@@ -339,7 +351,7 @@ class TransductorViewsTests(TestCase):
self.building.name, response.content.decode('utf-8'))
@mock.patch.object(SyncManager, 'sync_transductor', return_value=False)
@mock.patch('requests.get', return_value=True)
@mock.patch('requests.get', side_effect=mocked_requests_get)
def test_enable_energy_transductor(self, mock_get, mock_sync):
UserPermissions.add_user_permissions(
self.normaluser, ['manager_transductors'])
......@@ -379,7 +391,7 @@ class TransductorViewsTests(TestCase):
self.assertRedirects(response, next_page)
@mock.patch.object(SyncManager, 'sync_transductor', return_value=True)
@mock.patch('requests.get', return_value=True)
@mock.patch('requests.get', side_effect=mocked_requests_get)
def test_enable_energy_transductor_with_next_param(self, mock_1, mock_2):
UserPermissions.add_user_permissions(
self.normaluser, ['manager_transductors'])
......@@ -484,7 +496,7 @@ class TransductorViewsTests(TestCase):
self.assertRedirects(response, next_page)
@mock.patch.object(SyncManager, 'sync_transductor', return_value=True)
@mock.patch('requests.get', return_value=True)
@mock.patch('requests.get', side_effect=mocked_requests_get)
def test_disable_energy_transductor(self, mock_get, mock_sync):
UserPermissions.add_user_permissions(
self.normaluser, ['manager_transductors'])
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment