Farm alarm #29

Merged
senaduka merged 10 commits from farm_alarm into master 2016-11-19 11:06:52 +01:00
42 changed files with 567 additions and 59 deletions

View File

@@ -30,4 +30,5 @@ dependencies {
compile 'com.android.support:support-v4:24.2.1'
compile 'com.android.support:support-vector-drawable:24.2.1'
testCompile 'junit:junit:4.12'
compile 'com.android.volley:volley:1.0.0'
}

View File

@@ -4,6 +4,8 @@
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
@@ -14,23 +16,31 @@
<activity
android:name=".MainScreen"
android:label="@string/app_name"
android:screenOrientation="portrait"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="http" />
<data android:scheme="https" />
<data android:host="agrar.zoblak.com" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="http" />
<data android:scheme="https" />
<data android:host="agrar.zoblak.com" />
</intent-filter>
</activity>
<service
android:name=".AlarmPollingService"
android:exported="false" />
<service
android:name=".SoundPlayingService"
android:exported="false" />
<receiver
android:name=".PeriodicalPingReceiver"
@@ -40,11 +50,21 @@
<activity
android:name=".SettingsActivity"
android:label="@string/title_activity_settings"
android:parentActivityName=".MainScreen">
android:parentActivityName=".MainScreen"
android:screenOrientation="portrait">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.zoblak.farmalarm.MainScreen" />
</activity>
<receiver
android:name=".BootBroadcastReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>

View File

@@ -42,19 +42,18 @@ public class AlarmNotification {
* @see #cancel(Context)
*/
public static void notify(final Context context,
final String exampleString, final int number) {
final String message, final int number) {
final Resources res = context.getResources();
// This image is used as the notification's large icon (thumbnail).
// TODO: Remove this if your notification has no relevant thumbnail.
final Bitmap picture = BitmapFactory.decodeResource(res, R.drawable.example_picture);
final Bitmap picture = BitmapFactory.decodeResource(res, R.drawable.ic_stat_zoblak);
final String ticker = exampleString;
final String ticker = message;
final String title = res.getString(
R.string.alarm_notification_title_template, exampleString);
final String text = res.getString(
R.string.alarm_notification_placeholder_text_template, exampleString);
R.string.alarm_notification_title_template, message);
final String text = message;
final NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
@@ -64,7 +63,7 @@ public class AlarmNotification {
// Set required fields, including the small icon, the
// notification title, and text.
.setSmallIcon(R.drawable.ic_stat_alarm)
.setSmallIcon(R.drawable.ic_stat_zoblak)
.setContentTitle(title)
.setContentText(text)
@@ -100,7 +99,7 @@ public class AlarmNotification {
PendingIntent.getActivity(
context,
0,
new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com")),
new Intent(context, MainScreen.class),
PendingIntent.FLAG_UPDATE_CURRENT))
// Automatically dismiss the notification when it is touched.
.setAutoCancel(true);

View File

@@ -0,0 +1,100 @@
package com.zoblak.farmalarm;
/**
* Created by senadu on 11/15/16.
*/
public class AlarmPingResponse {
private String controller;
public AlarmPingResponse(String controller) {
this.controller = controller;
}
private Boolean alarmTriggered = false;
private Boolean tooHot = false;
private Boolean tooCold = false;
private Boolean boxSilent = false;
private Boolean phoneSilent = false;
private Boolean serverError = false;
public Boolean getAlarmTriggered() {
return alarmTriggered;
}
public void setAlarmTriggered(Boolean alarmTriggered) {
this.alarmTriggered = alarmTriggered;
}
public Boolean getTooHot() {
return tooHot;
}
public void setTooHot(Boolean tooHot) {
this.tooHot = tooHot;
}
public Boolean getTooCold() {
return tooCold;
}
public void setTooCold(Boolean tooCold) {
this.tooCold = tooCold;
}
public Boolean getBoxSilent() {
return boxSilent;
}
public void setBoxSilent(Boolean boxSilent) {
this.boxSilent = boxSilent;
}
public Boolean getPhoneSilent() {
return phoneSilent;
}
public void setPhoneSilent(Boolean phoneSilent) {
this.phoneSilent = phoneSilent;
}
public Boolean getServerError() {
return serverError;
}
public void setServerError(Boolean serverError) {
this.serverError = serverError;
}
public String toNotificationMessage() {
String message = "Sve je OK!";
if(getAlarmTriggered()) {
if (getAlarmTriggered()) {
message = "Alarm pokrenut! ";
}
if (getTooHot()) {
message += "Temperatura previsoka!";
}
if (getTooCold()) {
message += "Temperatura preniska!";
}
if (getBoxSilent()) {
message += "Zoblak kutija se nije javila na vrijeme!";
}
if (getPhoneSilent()) {
message += "Ni jedan telefon se nije javio na vrijeme! ";
}
if (getServerError()) {
message += "Ne radi internet na telefonu! ";
}
}
return message;
}
}

View File

@@ -3,6 +3,12 @@ package com.zoblak.farmalarm;
import android.app.IntentService;
import android.content.Intent;
import android.content.Context;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.PowerManager;
import android.util.Log;
import android.widget.Toast;
/**
* An {@link IntentService} subclass for handling asynchronous task requests in
@@ -15,10 +21,13 @@ public class AlarmPollingService extends IntentService {
// TODO: Rename actions, choose action names that describe tasks that this
// IntentService can perform, e.g. ACTION_FETCH_NEW_ITEMS
private static final String ACTION_PING = "com.zoblak.farmalarm.action.PING";
private static final String ACTION_STOP_ALARM = "com.zoblak.farmalarm.action.STOP_ALARM";
// TODO: Rename parameters
private static final String CONTROLLERS = "com.zoblak.farmalarm.extra.CONTROLLLERS";
private AlarmResponseHandler handler;
public AlarmPollingService() {
super("AlarmPollingService");
@@ -30,7 +39,6 @@ public class AlarmPollingService extends IntentService {
*
* @see IntentService
*/
// TODO: Customize helper method
public static void startActionPing(Context context, String controllers) {
Intent intent = new Intent(context, AlarmPollingService.class);
intent.setAction(ACTION_PING);
@@ -55,7 +63,16 @@ public class AlarmPollingService extends IntentService {
* parameters.
*/
private void handleActionPing(String controllers) {
// do something
PowerManager powerManager = (PowerManager) this.getSystemService(POWER_SERVICE);
PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"AlarmPingerWakeLock");
wakeLock.acquire();
ZoblakClient zc = new ZoblakClient(controllers);
handler = new AlarmResponseHandler(this,zc.PingServer());
handler.handle();
wakeLock.release();
}

View File

@@ -0,0 +1,39 @@
package com.zoblak.farmalarm;
import android.annotation.TargetApi;
import android.content.Context;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
/**
* Created by senadu on 11/15/16.
*/
public class AlarmResponseHandler {
AlarmPingResponse response;
Context context;
public AlarmResponseHandler(Context context, AlarmPingResponse response) {
this.response = response;
this.context = context;
}
public void handle() {
if (response.getAlarmTriggered()) {
AlarmNotification.notify(context, response.toNotificationMessage(), 1);
SoundPlayingService.startPlayingAlarm(context);
}
}
}

View File

@@ -0,0 +1,15 @@
package com.zoblak.farmalarm;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class BootBroadcastReceiver extends BroadcastReceiver {
public BootBroadcastReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
MainScreen.setupAlarmManager(context);
}
}

View File

@@ -1,5 +1,12 @@
package com.zoblak.farmalarm;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
@@ -9,23 +16,49 @@ import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import java.lang.System;
public class MainScreen extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setupAlarmManager(this);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
public static void setupAlarmManager(Context context) {
AlarmManager alarmMgr;
PendingIntent alarmIntent;
Intent intent = new Intent(context, PeriodicalPingReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
int PERIOD_IN_MS = 2 * 60 * 1000; // 2 minutes
alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
// Hopefully your alarm will have a lower frequency than this!
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis(),
PERIOD_IN_MS, alarmIntent);
}
@Override
protected void onResume() {
super.onResume();
SoundPlayingService.stopPlayingAlarm(this);
}
@Override
@@ -44,9 +77,13 @@ public class MainScreen extends AppCompatActivity {
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
}

View File

@@ -1,5 +1,7 @@
package com.zoblak.farmalarm;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
@@ -27,7 +29,10 @@ public class MainScreenFragment extends Fragment {
WebView webView = (WebView)view.findViewById(R.id.main_web_view);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.loadUrl("http://agrar.zoblak.com/alarm");
webSettings.setDomStorageEnabled(true);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.getContext());
String controllers = prefs.getString("controllers", "");
webView.loadUrl("http://agrar.zoblak.com/alarm?controller_id=" + controllers);
return view;
}

View File

@@ -4,14 +4,19 @@ import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;
import static android.content.Context.POWER_SERVICE;
public class PeriodicalPingReceiver extends BroadcastReceiver {
public PeriodicalPingReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
public void onReceive(Context context, Intent intent) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String controllers = prefs.getString("controllers", null);

View File

@@ -188,7 +188,6 @@ public class SettingsActivity extends AppCompatPreferenceActivity {
// to their values. When their values change, their summaries are
// updated to reflect the new value, per the Android Design
// guidelines.
bindPreferenceSummaryToValue(findPreference("alarm_set"));
bindPreferenceSummaryToValue(findPreference("controllers"));
bindPreferenceSummaryToValue(findPreference("period_minutes"));
}

View File

@@ -0,0 +1,73 @@
package com.zoblak.farmalarm;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.IBinder;
/**
* Created by senadu on 11/18/16.
*/
public class SoundPlayingService extends Service
{
private Ringtone ringtone;
@Override
public IBinder onBind(Intent intent)
{
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
startTheAlarm();
return START_NOT_STICKY;
}
@Override
public void onDestroy()
{
stopTheAlarm();
}
public static void startPlayingAlarm(Context context) {
Intent startIntent = new Intent(context, SoundPlayingService.class);
context.startService(startIntent);
}
public static void stopPlayingAlarm(Context context) {
Intent startIntent = new Intent(context, SoundPlayingService.class);
context.stopService(startIntent);
}
@SuppressWarnings("deprecation")
private void startTheAlarm() {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
ringtone = RingtoneManager.getRingtone(this, notification);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
AudioAttributes attributes = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_GAME)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build();
ringtone.setAudioAttributes(attributes);
} else {
ringtone.setStreamType(AudioManager.STREAM_ALARM);
}
ringtone.play();
}
public void stopTheAlarm() {
if(ringtone != null && ringtone.isPlaying()) {
ringtone.stop();
}
}
}

View File

@@ -0,0 +1,131 @@
package com.zoblak.farmalarm;
import android.util.JsonReader;
import android.util.JsonToken;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by senadu on 11/14/16.
*/
public class ZoblakClient {
private String controllers;
public ZoblakClient(String controllers) {
this.controllers = controllers;
}
public AlarmPingResponse PingServer() {
HttpURLConnection urlConnection = null;
AlarmPingResponse result = new AlarmPingResponse(controllers);
URL url = null;
try {
url = new URL("http://agrar.zoblak.com/api/v1.0/alarm/" + controllers + "/phonePing");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write("{}");
writer.flush();
writer.close();
os.close();
urlConnection.connect();
InputStream in = urlConnection.getInputStream();
String jsonString = convertStreamToString(in);
Log.e("JsonString", jsonString);
JsonReader jr = new JsonReader(new StringReader(jsonString));
result = readResponse(jr);
} catch (MalformedURLException e) {
Log.e("zoblakClient", "malformed: " + e.getLocalizedMessage());
} catch (IOException e) {
Log.e("zoblakClient", "ioexception: " + e.getLocalizedMessage());
result.setAlarmTriggered(true);
result.setServerError(true);
}
if (urlConnection != null) urlConnection.disconnect();
return result; // if no response then
}
private AlarmPingResponse readResponse(JsonReader reader) {
AlarmPingResponse result = new AlarmPingResponse(controllers);
try {
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("alarmTriggered") && reader.peek() != JsonToken.NULL) {
result.setAlarmTriggered(reader.nextBoolean());
} else if (name.equals("tooHot") && reader.peek() != JsonToken.NULL) {
result.setTooHot(reader.nextBoolean());
} else if (name.equals("tooCold") && reader.peek() != JsonToken.NULL) {
result.setTooCold(reader.nextBoolean());
} else if (name.equals("boxSilent") && reader.peek() != JsonToken.NULL) {
result.setBoxSilent(reader.nextBoolean());
} else {
reader.skipValue();
}
}
} catch (IOException e) {
Log.e("zoblakClient", "reading result: " + e.getLocalizedMessage());
}
return result;
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 644 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 644 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 417 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 425 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 913 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 911 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

View File

@@ -23,12 +23,4 @@
<include layout="@layout/content_main_screen" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
app:srcCompat="@android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>

View File

@@ -15,7 +15,6 @@
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/main_web_view"
android:partition="persist:browser"
></WebView>
</RelativeLayout>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.3 KiB

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.2 KiB

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.7 KiB

After

Width:  |  Height:  |  Size: 5.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.5 KiB

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

After

Width:  |  Height:  |  Size: 14 KiB

View File

@@ -1,6 +1,6 @@
<resources>
<string name="app_name">Farm Alarm</string>
<string name="action_settings">Settings</string>
<string name="action_settings">Podešavanje</string>
<string name="title_activity_settings">Podešavanje</string>
<!-- Strings related to Settings -->

View File

@@ -6,6 +6,7 @@
android:defaultValue="false"
android:title="Uključiti alram"
android:key="alarm_set" />
<EditTextPreference
android:selectAllOnFocus="true"
android:singleLine="true"

View File

@@ -18,6 +18,12 @@ allprojects {
}
}
allprojects {
repositories {
maven { url "https://jitpack.io" }
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}

View File

@@ -1,10 +1,10 @@
<template name="alarm">
<div class="hello">
<h1> Temperatura </h1>
<div class="jumbotron text-center center-block" >
{{#with state}}
{{#if alarmTriggered}}
<strong class="bg-danger">{{ pretty_reasons alarmReasons }}</strong>
<img src="/images/alarm.gif" class="img-responsive center-block" id="alarm_image" />
<button id="stop_alarm" class="btn btn-danger"> <i class="fa fa-ban"></i> Prekini </button>
{{/if}}

View File

@@ -39,6 +39,22 @@ Template.alarm.helpers({
result += '' + parseFloat(temperatures[i]).toFixed(1) + ' °C ';
}
return result;
},
pretty_reasons: function(reasons) {
var results = "";
if(reasons.tooHot) {
results += "Temperatura previsoka!";
}
if(reasons.tooCold) {
results += "Temperatura preniska!";
}
if(reasons.phoneSilent) {
results += "Mobitel nedostupan! Provjerite internet!";
}
if(reasons.boxSilent) {
results += "Zoblak kutija se ne javlja! Provjerite internet!";
}
return results;
}
});

View File

@@ -6,8 +6,12 @@
padding-top: 10px;
}
.hidden {
display: none;
}
.huge_text {
font-size: 3em;
font-size: 2.5em;
}
@media all and (orientation: portrait) {
@@ -28,18 +32,18 @@
@media all and (orientation: portrait) {
#alarm_image {
width: 90%;
width: 70%;
cursor: pointer;
}
}
@media all and (orientation: landscape) {
#alarm_image {
width: 40%;
width: 30%;
cursor: pointer;
}
}
.clickable {
cursor:pointer;
cursor:pointer;
}

View File

@@ -9,6 +9,14 @@ Tracker.autorun(function() {
function safeRoute(route) {
return function () {
var controllerId = this.params.query.controller_id;
if(controllerId) {
Session.setPersistent('controller_id', controllerId);
Session.setPersistent('hide_controller_selection', true);
} else {
Session.setPersistent('hide_controller_selection', false);
}
console.log('go ', route);
if (Meteor.zoblak.client.accessible(route)) {
Session.set('templateName', route);

View File

@@ -21,7 +21,7 @@
<li role="presentation" class="{{ class_for 'alarm' }}"><a class="clickable">Alarm</a></li>
{{/if}}
<li role="presentation" class="controller_selection"> <input type="number" id="controller" name="controller" value="{{ selected_controller }}" min="1" max="99999"> <button id="switch" name="switch">Prebaci</button>
<li role="presentation" class="{{ class_for_changer }}"> <input type="number" id="controller" name="controller" value="{{ selected_controller }}" min="1" max="99999"> <button id="switch" name="switch">Prebaci</button>
</li>
</ul>
</template>

View File

@@ -11,31 +11,43 @@ Template.tabs.helpers({
}
},
class_for_changer: function() {
var hide = Session.get('hide_controller_selection');
return (hide) ? "controller_selection hidden" : "controller_selection";
},
selected_controller: function() {
return Session.get('controller_id');
return
},
accessible: Meteor.zoblak.client.accessible
});
function saveParamsAndGo(where) {
var hideControllerSelection = Session.get('hide_controller_selection');
if (hideControllerSelection) {
Router.go(where + "?controller_id=" + Session.get('controller_id'));
} else {
Router.go(where);
}
}
Template.tabs.events({
'click .start': function() {
Router.go('/');
saveParamsAndGo('/');
},
'click .weather': function() {
Router.go('/weather');
saveParamsAndGo('/weather');
},
'click .log': function() {
Router.go('/log');
saveParamsAndGo('/log');
},
'click .surveillance': function() {
Router.go('/surveillance');
saveParamsAndGo('/surveillance');
},
'click .alarm': function() {
Router.go('/alarm');
saveParamsAndGo('/alarm');
},
'click .settings': function() {
Session.set('templateName', 'settings');

View File

@@ -28,6 +28,7 @@ Api.addRoute('sensorData', {
created_at: new Date()
};
SensorData.insert(sensorObject);
reactToAlarmData(this.bodyParams.controllerId);
return [];
}
});
@@ -36,13 +37,27 @@ Api.addRoute('alarm/:id/phonePing', {
authRequired: false
}, {
post: function() {
return ControllerState.update({
ControllerState.update({
controller_id: this.urlParams.id
}, {
'$set': {
'lastPhoneContact': new Date(),
}
});
var state = stateOrDefault(this.urlParams.id).state;
if(state.alarmTriggered) {
return {
'alarmTriggered': state.alarmTriggered,
'tooHot': state.alarmReasons.tooHot,
'tooCold': state.alarmReasons.tooCold,
'phoneSilent': state.alarmReasons.phoneSilent,
'boxSilent': state.alarmReasons.boxSilent
};
} else {
return {};
}
}
});
@@ -170,7 +185,14 @@ function stateOrDefault(id) {
controller_id: id,
state: {
out_valve: 'closed',
in_valve: 'closed'
in_valve: 'closed',
alarmTriggered: false,
alarmReasons: {
tooHot: false,
tooCold: false,
boxSilent: false,
phoneSilent: false
}
},
time: new Date(),
config: {

View File

@@ -149,8 +149,8 @@ function saveAlarmSettings(controller_id, minTemperature, maxTemperature, timeou
'$set': {
'config.minTemperature': parseFloat(minTemperature),
'config.maxTemperature': parseFloat(maxTemperature),
'config.timeoutBox': parseInt(timeoutBox),
'config.timeoutPhone': parseInt(timeoutPhone),
'config.timeoutBox': timeoutBox ? parseInt(timeoutBox) : null,
'config.timeoutPhone': timeoutPhone ? parseInt(timeoutPhone) : null,
'config.smsNumbers': smsNumbers,
'config.sms1': smsNumbers[0],
'config.sms2': smsNumbers[1],
@@ -164,12 +164,14 @@ function saveAlarmSettings(controller_id, minTemperature, maxTemperature, timeou
SyncedCron.add({
name: jobName,
schedule: function(parser) {
return parser.text('every 30 seconds');
return parser.text('every 10 seconds');
},
job: function() {
reactToAlarmData(controller_id);
}
});
reactToAlarmData(controller_id);
}
@@ -178,13 +180,13 @@ function saveAlarmSettings(controller_id, minTemperature, maxTemperature, timeou
// 2. triggered ( state.alarmTriggered: true, state.alarmStopped: null )
// 3. silenced ( state.alarmTriggered: false, state.alarmStopped: (sometime) )
function reactToAlarmData(controller_id) {
reactToAlarmData = function(controller_id) {
var reading = last_sensor_reading(controller_id);
var state = Meteor.zoblak.server.controller_state(controller_id);
var config = state.config;
var minTemperature = function(temperatures) {
// if it gets a lot colder than absolute zero we will
// if it gets a lot colder than absolute zero
// we will have more problems than the bug in this code
if (temperatures.length <= 0) return -1000;
var minimal = parseFloat(temperatures[0]);
@@ -218,6 +220,7 @@ function reactToAlarmData(controller_id) {
var minutesSinceLastPhoneContact = state.lastPhoneContact ? moment(new Date()).diff(moment(state.lastPhoneContact), 'minutes') : -1;
var phoneSilent = config.timeoutPhone && minutesSinceLastPhoneContact > config.timeoutPhone;
console.log("too ", tooCold, tooHot, boxSilent, phoneSilent);
console.log("lpc", state.lastPhoneContact);
console.log("mslpc", minutesSinceLastPhoneContact);
console.log("phoneSilent", phoneSilent);
@@ -249,7 +252,7 @@ function soundTheAlarm(controller_id, tooCold, tooHot, boxSilent, phoneSilent) {
};
var smsSent = !!state.state.alarmSmsSent;
var needsToSendSms = !smsSent; // && (boxSilent || phoneSilent);
var needsToSendSms = !smsSent && phoneSilent;
var sendSmsPart = needsToSendSms ? { 'state.alarmSmsSent': true } : {};

View File

@@ -17,6 +17,10 @@ Meteor.publish("controller_state", function(controllerId) {
});
});
Meteor.publish("all_controller_states", function() {
return ControllerState.find({});
});
// This code only runs on the server
Meteor.publish("pictures", function(controllerId) {