Exemplo n.º 1
0
        public static bool Delete(string file)
        {
            // Init SD card
            if (!MountCheck())
            {
                return(false);
            }

            // Check if file exist
            if (!FileExists(file))
            {
                return(true);
            }

            try
            {
                // Write data
                sdCard.StorageDevice.Delete(file);
                VolumeInfo.GetVolumes()[0].FlushAll();
            }
            catch (Exception e)
            {
                DebugOnly.Print("ERROR: Exception while deleting \"" + file + "\": " + e);
                return(false);
            }

            DebugOnly.Print("File \"" + file + "\" successfully deleted");

            return(true);
        }
Exemplo n.º 2
0
        // Loads userlist from server
        private static bool requestUsers()
        {
            // Create URL
            string url = buildUrlFromSettings(DataRequest);

            // Send request
            DebugOnly.Print("Requesting user list to server...");
            Remote.Result result = Remote.Get(url);

            // Parse response
            if (result.Success)
            {
                ArrayList tempUserList = new ArrayList();

                if (Json.ParseNamedArray(UserHeader, result.Content, tempUserList, typeof(User)))
                {
                    // Copy content to main list
                    // NOTE: CopyFrom clears list automatically
                    userList.CopyFrom(tempUserList);

                    // Store cache copy
                    CacheManager.Store(userList, CacheManager.UsersCacheFile);

                    DebugOnly.Print(userList.Count + " users received from server");
                }
                else
                {
                    DebugOnly.Print("ERROR: User list request failed!");
                }
            }

            // Return result of the operation
            return(result.Success);
        }
Exemplo n.º 3
0
        public static Result Post(string url, string body)
        {
            var request          = WebRequest.Create(url) as HttpWebRequest;
            var requestByteArray = Encoding.UTF8.GetBytes(body);

            DebugOnly.Print("Performing POST...");
            DebugOnly.Print("\t\tURL: " + url);
            DebugOnly.Print("\t\tBody: " + body);

            try
            {
                // Send the request
                if (request != null)
                {
                    request.Method        = "POST";
                    request.ContentType   = "application/json; charset=utf-8";
                    request.ContentLength = requestByteArray.Length;

                    var postStream = request.GetRequestStream();

                    postStream.Write(requestByteArray, 0, requestByteArray.Length);
                    postStream.Close();

                    // Grab the response
                    using (var response = request.GetResponse() as HttpWebResponse)
                    {
                        var responseString = string.Empty;

                        // Error
                        if (response == null || response.StatusCode != HttpStatusCode.OK)
                        {
                            DebugOnly.Print("ERROR: request failed. Received HTTP " + response.StatusCode);
                            return(new Result(false, null));
                        }

                        // Grab the response
                        using (var responseStream = response.GetResponseStream())
                        {
                            if (responseStream != null)
                            {
                                using (var reader = new StreamReader(responseStream))
                                {
                                    responseString = reader.ReadToEnd();
                                }

                                DebugOnly.Print("\t\tResponse: " + responseString);
                                return(new Result(true, responseString));
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                DebugOnly.Print("ERROR: Exception while performing POST: " + e);
                return(new Result(false, null));
            }

            return(new Result(false, null));
        }
Exemplo n.º 4
0
        // Network is online event
        private static void NetworkUp(GTM.Module.NetworkModule sender, GTM.Module.NetworkModule.NetworkState state)
        {
            DebugOnly.Print("Network is up!");

            // Start ServerRoutine
            startRoutine();
        }
Exemplo n.º 5
0
        /*
         * NFC ERROR EVENT:
         * This event occurs when the nfc module is not responding to commands.
         */
        private void NfcError()
        {
            DebugOnly.Print("NFC Module is not responding!");
            Log log = new Log(Log.TypeError, "NFC Module is not responding!");

            DataHelper.AddLog(log);
        }
Exemplo n.º 6
0
        // Sends log to server
        private static bool sendLogs()
        {
            // Create JSON String
            var jsonString = Json.BuildNamedArray(LogHeader, logList);

            // Create URL
            string url = buildUrlFromSettings(DataRequest);

            // Send request
            DebugOnly.Print("Sending logs to server...");
            Remote.Result result = Remote.Post(url, jsonString);

            if (result.Success)
            {
                DebugOnly.Print("Logs sent to server");

                // Log list sent to server successfully: delete loglist
                logList.Clear();
                CacheManager.Store(logList, CacheManager.LogsCacheFile);
            }
            else
            {
                DebugOnly.Print("ERROR: Log sending failed!");
            }

            // Return result of the operation
            return(result.Success);
        }
Exemplo n.º 7
0
        private static bool FileExists(string file)
        {
            // Check if file exists
            String root;

            String[] foundFiles;
            try
            {
                root       = sdCard.StorageDevice.RootDirectory;
                foundFiles = sdCard.StorageDevice.ListFiles(root);
            }
            catch (Exception)
            {
                return(false);
            }

            var exist = false;

            foreach (var aFile in foundFiles)
            {
                if (string.Compare(file, aFile) == 0)
                {
                    exist = true;
                    break;
                }
            }

            if (!exist)
            {
                DebugOnly.Print("File \"" + file + "\" not found!");
            }

            return(exist);
        }
Exemplo n.º 8
0
        /*
         * TAG FOUND EVENT:
         * This event occurs when the user passes a NFC card near the reader.
         * It checks if the UID is valid and unlock the door if so.
         */
        private void TagFound(string uid)
        {
            if (!scanWindow.IsShowing())
            {
                // Check authorization
                var authorized = DataHelper.CheckCardId(uid);

                // Show access window
                accessWindow.Show(authorized);

                // Log the event
                string logText;
                Log    log;

                if (authorized)
                {
                    // Access granted
                    UnlockDoor();
                    logText = "Card \"" + uid + "\" inserted. Authorized access.";
                    log     = new Log(Log.TypeAccess, null, uid, logText);
                }
                else
                {
                    // Access denied
                    logText = "Card \"" + uid + "\" inserted. Access denied!";
                    log     = new Log(Log.TypeInfo, logText);
                }

                DebugOnly.Print(logText);

                // Add log to loglist
                DataHelper.AddLog(log);
            }
            else
            {
                // Log new cardID
                var newCardIdLog = new Log(
                    Log.TypeAccess,
                    pendingPin,
                    uid,
                    "Card \"" + uid + "\" has been added for pin \"" + pendingPin + "\".");

                // Update CardID in userList
                DataHelper.AddCardId(pendingPin, uid);

                // Send urgent log
                DataHelper.AddLog(newCardIdLog, true);

                var cardAddedAlert = new AlertWindow(WindowAlertPeriod);
                cardAddedAlert.SetText("NFC card added!");
                cardAddedAlert.SetPositiveButton("Ok", delegate { cardAddedAlert.Dismiss(); });
                cardAddedAlert.Show();

                DebugOnly.Print("Card added to user with pin \"" + pendingPin + "\"");
            }
        }
Exemplo n.º 9
0
 public static string Get(int id)
 {
     if (id < settingArray.Count)
     {
         return(settingArray[id] as string);
     }
     else
     {
         DebugOnly.Print("ERROR: Setting id out of bounds!");
         return(string.Empty);
     }
 }
Exemplo n.º 10
0
        public static bool Load(ArrayList list, string file)
        {
            // Init SD card
            if (!MountCheck())
            {
                return(false);
            }

            // Check if file exist
            if (!FileExists(file))
            {
                return(false);
            }

            byte[] data;

            try
            {
                var f = sdCard.StorageDevice.OpenRead(file);

                // If the file is empty do not parse
                if (f.Length == 0)
                {
                    DebugOnly.Print("ERROR: File \"" + file + "\" is empty!");
                    return(false);
                }

                data = new byte[f.Length];
                f.Read(data, 0, data.Length);
                f.Close();
                VolumeInfo.GetVolumes()[0].FlushAll();
            }
            catch (Exception e)
            {
                DebugOnly.Print("ERROR: Exception while reading \"" + file + "\": " + e);
                return(false);
            }

            try
            {
                var temp = (ArrayList)Reflection.Deserialize(data, typeof(ArrayList));
                list.CopyFrom(temp);
            }
            catch (Exception e)
            {
                DebugOnly.Print("ERROR: Exception while deserializing \"" + file + "\": " + e);
                return(false);
            }

            DebugOnly.Print("File \"" + file + "\" successfully loaded into object");

            return(true);
        }
Exemplo n.º 11
0
        private static bool MountCheck()
        {
            if (!sdCard.IsCardInserted)
            {
                DebugOnly.Print("ERROR: SD slot is empty!");

                if (!slotErrorFlag)
                {
                    // First slot error, send it
                    if (DataHelper.IsInitialized())
                    {
                        slotErrorFlag = true; // Leave it here, otherwise it's recursive!!!
                        DataHelper.AddLog(new Log(Log.TypeError, "SD Card slot is empty!"));
                    }
                }
                return(false);
            }

            if (!sdCard.IsCardMounted)
            {
                DebugOnly.Print("SD Card appears to be unmounted! Mounting...");

                for (int i = 0; i < mountAttempts; i++)
                {
                    if (sdCard.IsCardMounted)
                    {
                        return(true);
                    }
                    if (sdCard.Mount())
                    {
                        return(true);
                    }
                    System.Threading.Thread.Sleep(mountAttemptPeriod);
                }

                // Mounting error
                DebugOnly.Print("ERROR: Mounting failed!");
                if (!mountErrorFlag)
                {
                    // First mount error, send it
                    if (DataHelper.IsInitialized())
                    {
                        DataHelper.AddLog(new Log(Log.TypeError, "Unable to mount SDcard!"));
                        mountErrorFlag = true;
                    }
                }
                return(false);
            }

            slotErrorFlag  = false;
            mountErrorFlag = false;
            return(true);
        }
Exemplo n.º 12
0
 public static bool Set(int id, string content)
 {
     if (id < settingArray.Count)
     {
         settingArray[id] = content;
         return(CacheManager.Store(settingArray, CacheManager.SettingsFile));
     }
     else
     {
         DebugOnly.Print("ERROR: Setting id out of bounds!");
         return(false);
     }
 }
Exemplo n.º 13
0
        public void ProgramStarted()
        {
            DebugOnly.Print("Program started!");

            // Initialize screen
            WindowManager.Init();

            // Set scan window
            scanWindow.SetText("Please scan your NFC card now...");
            scanWindow.SetNegativeButton("Cancel", delegate { scanWindow.Dismiss(); });

            // Windows and window manager
            pinWindow.Id  = WindowPinId;
            scanWindow.Id = WindowScanId;

            // Button
            button.ButtonPressed  += DoorOpen;
            button.ButtonReleased += DoorClosed;

            doorOpen = button.Pressed;
            if (doorOpen)
            {
                pinWindow.SetText("Door open");
            }
            else
            {
                pinWindow.SetText("Door closed");
            }

            unlockedTimer       = new GT.Timer(unlockPeriod);
            unlockedTimer.Tick += UnlockTimeout;

            pinWindow.Show();

            // Event Setup
            adafruit_PN532.TagFound      += TagFound;
            adafruit_PN532.Error         += NfcError;
            pinWindow.PinFound           += PinFound;
            DataHelper.DataSourceChanged += DataSourceChanged;
            WindowManager.WindowChanged  += WindowChanged;

            // Start NFC
            adafruit_PN532.StartScan(NfcScanPeriod, NfcScanTimeout);

            //Init
            CacheManager.Init(sdCard);
            SettingsManager.Init();
            DataHelper.Init(ethernetJ11D);

            adafruit_PN532.Init();
        }
Exemplo n.º 14
0
        public static bool Store(ArrayList list, string file)
        {
            // Init SD card
            if (!MountCheck())
            {
                return(false);
            }

            FileExists(file);

            byte[] data;

            try
            {
                // Serialize data
                data = Reflection.Serialize(list, typeof(ArrayList));

                // This shouldn't happen, just in case...
                if (data.Length == 0)
                {
                    DebugOnly.Print("ERROR: Serialized data \"" + file + "\" is null!");
                    return(false);
                }
            }
            catch (Exception e)
            {
                DebugOnly.Print("ERROR: Exception while serializing \"" + file + "\": " + e);
                return(false);
            }

            try
            {
                // Write data
                var f = sdCard.StorageDevice.OpenWrite(file);
                f.Write(data, 0, data.Length);
                f.Close();
                VolumeInfo.GetVolumes()[0].FlushAll();
            }
            catch (Exception e)
            {
                DebugOnly.Print("ERROR: Exception while writing \"" + file + "\": " + e);
                return(false);
            }

            DebugOnly.Print("Object successfully stored into \"" + file + "\" file");

            return(true);
        }
Exemplo n.º 15
0
        public static void Init(EthernetJ11D _ethernetJ11D)
        {
            // Load ip from settings
            String gadgeteerIp = SettingsManager.Get(SettingsManager.LockIp);

            ethernetJ11D = _ethernetJ11D;
            ethernetJ11D.UseThisNetworkInterface();
            ethernetJ11D.UseStaticIP(gadgeteerIp, "255.255.255.0", "192.168.100.1");
            ethernetJ11D.NetworkUp   += NetworkUp;
            ethernetJ11D.NetworkDown += NetworkDown;

            // Data is not yet loaded, data source is unknown
            ChangeDataSource(DataSourceUnknown);

            // Load users from cache
            if (CacheManager.Load(userList, CacheManager.UsersCacheFile))
            {
                DebugOnly.Print(userList.Count + " users loaded from cache!");

                // Data source is now cache
                ChangeDataSource(DataSourceCache);
            }
            else
            {
                // Empty data cache is assumed as an error!
                if (DataSourceChanged != null)
                {
                    DataSourceChanged(DataSourceError);
                }

                // Clear user list
                userList.Clear();
            }

            // Load logs from cache if any
            if (CacheManager.Load(logList, CacheManager.LogsCacheFile))
            {
                DebugOnly.Print(logList.Count + " logs loaded from cache!");
            }
            else
            {
                // Clear log list
                logList.Clear();
            }

            initialized = true;
        }
Exemplo n.º 16
0
        // Network is offline event
        private static void NetworkDown(GTM.Module.NetworkModule sender, GTM.Module.NetworkModule.NetworkState state)
        {
            DebugOnly.Print("Network is down!");

            // Data source is now cache
            if (userList.Count > 0)
            {
                ChangeDataSource(DataSourceCache);
            }
            else
            {
                ChangeDataSource(DataSourceError);
            }

            // Stop ServerRoutine
            stopRoutine();
        }
Exemplo n.º 17
0
        private void UnlockTimeout(GT.Timer timerAccessWindow)
        {
            if (unlockTimerRunning)
            {
                authorizedAccess = false;

                // Stop timer
                unlockTimerRunning = false;
                unlockedTimer.Stop();

                // New pending unlock error
                pendingUnlockError = true;

                // Send log
                DebugOnly.Print("Unlock timeout! Door is not closed!!!");
                DataHelper.AddLog(new Log(Log.TypeError, "Unlock timeout! Door is not closed!!!"));
            }
        }
Exemplo n.º 18
0
        private void DoorOpen(Button sender, Button.ButtonState state)
        {
            doorOpen = true;

            pinWindow.SetText("Door open");
            DebugOnly.Print("Door open!");

            if (!authorizedAccess)
            {
                // Security breach
                DebugOnly.Print("Security breach! Unauthorized access!");
                DataHelper.AddLog(new Log(Log.TypeError, "Security breach! Unauthorized access!"));

                var breachWindow = new AlertWindow(20000);
                breachWindow.SetText("BREACH ALERT!!! \n UNAUTHORIZED ACCESS!!! \n\n\n\n Please contact the administrator immediately.");
                breachWindow.Show();
            }
        }
Exemplo n.º 19
0
        private void DoorClosed(Button sender, Button.ButtonState state)
        {
            authorizedAccess = false;
            doorOpen         = false;

            pinWindow.SetText("Door closed");
            DebugOnly.Print("Door closed!");

            // Stop timer
            unlockTimerRunning = false;
            unlockedTimer.Stop();

            // Log if there is a pending error
            if (pendingUnlockError)
            {
                pendingUnlockError = false;
                DebugOnly.Print("Door finally closed");
                DataHelper.AddLog(new Log(Log.TypeError, "Door finally closed"));
            }
        }
Exemplo n.º 20
0
        // Request current timestamp
        public static Result Get(string url)
        {
            DebugOnly.Print("Performing GET...");
            DebugOnly.Print("\t\tURL: " + url);

            string responseString = null;
            var    request        = WebRequest.Create(url) as HttpWebRequest;

            try
            {
                if (request != null)
                {
                    using (var response = request.GetResponse() as HttpWebResponse)
                    {
                        // Error
                        if (response == null || response.StatusCode != HttpStatusCode.OK)
                        {
                            DebugOnly.Print("ERROR: request failed. Received HTTP " + response.StatusCode);
                            return(new Result(false, null));
                        }

                        var responseStream = response.GetResponseStream();
                        var responseReader = new StreamReader(responseStream);
                        responseString = responseReader.ReadToEnd();
                        responseStream.Close();
                        responseReader.Close();

                        DebugOnly.Print("\t\tResponse: " + responseString);
                        return(new Result(true, responseString));
                    }
                }
            }
            catch (Exception e)
            {
                DebugOnly.Print("ERROR: Exception while performing GET: " + e);
            }

            return(new Result(false, null));
        }
Exemplo n.º 21
0
        // Get current time from server
        private static bool requestTime()
        {
            string url = buildUrlFromSettings(TimeRequest);

            Remote.Result result = Remote.Get(url);

            if (result.Success)
            {
                // Request current time
                DebugOnly.Print("Requesting current time to server...");
                DateTime serverDt = result.Content.ToDateTime();

                DateTime rtcDt = Utils.SafeRtc();

                if (!serverDt.WeakCompare(rtcDt))
                {
                    // Found time mismatch
                    DebugOnly.Print("ERROR: RTC/Server time mismatch! Server: " + serverDt.ToMyString() + ", RTC: " + rtcDt.ToMyString());
                    DebugOnly.Print("Setting RTC...");
                    Log log = new Log(Log.TypeInfo, "RTC/Server time mismatch! Server: " + serverDt.ToMyString() + ", RTC: " + rtcDt.ToMyString());
                    AddLog(log);

                    RealTimeClock.SetDateTime(serverDt);
                }
                else
                {
                    DebugOnly.Print("RTC already synced with server time!");
                }

                // RTC time is now valid
                timeChecked = true;

                return(true);
            }

            return(false);
        }
Exemplo n.º 22
0
        public static bool ParseNamedArray(string arrayName, string jsonStr, ArrayList list, Type objType)
        {
            var initHash = JsonSerializer.DeserializeString(jsonStr) as Hashtable;

            if (initHash == null)
            {
                DebugOnly.Print("ERROR: Not JSON!");
                return(false);
            }

            var hashList = (ArrayList)initHash[arrayName];

            if (hashList == null)
            {
                DebugOnly.Print("ERROR: JSON doesn't contain array \"" + arrayName + "\"!");
                return(false);
            }

            try
            {
                foreach (Hashtable hash in hashList)
                {
                    var methods = objType.GetMethods();

                    // Construct new object of type objType
                    var constructorInfo = objType.GetConstructor(new Type[0]);
                    if (constructorInfo != null)
                    {
                        var obj = constructorInfo.Invoke(new object[0]);

                        foreach (var method in methods)
                        {
                            var methodName = method.Name;
                            if (methodName.Length > 5)
                            {
                                var prefix = methodName.Substring(0, 4);
                                if (string.Compare(prefix, "set_") == 0)
                                {
                                    // Is a setter
                                    var fieldName   = methodName.Substring(4);
                                    var objFromHash = hash[fieldName];
                                    if (objFromHash != null)
                                    {
                                        method.Invoke(obj, new[] { objFromHash });
                                    }
                                }
                            }
                        }

                        list.Add(obj);
                    }
                }
            }
            catch (Exception e)
            {
                DebugOnly.Print("ERROR: exception while parsing JSON list: " + e);
                return(false);
            }

            return(true);
        }
Exemplo n.º 23
0
        /*
         * PIN FOUND EVENT:
         * This event occurs when the user inserts a pin code. It checks if the pin is valid and unlock the door if so.
         * If the pin has no related CardId it prompts the user to add it.
         */
        private void PinFound(string pin)
        {
            string masterPin = SettingsManager.Get(SettingsManager.MasterPin);

            // Check master pin
            if (String.Compare(masterPin, pin) == 0)
            {
                maintenanceWindow.Show();
                return;
            }

            // Check authorization
            var authorized = DataHelper.CheckPin(pin);
            var nullCardId = DataHelper.PinHasNullCardId(pin);

            // Log the event
            string logText;
            Log    log;

            if (authorized)
            {
                // Access granted
                UnlockDoor();
                logText = "Pin \"" + pin + "\" inserted. Authorized access.";
                log     = new Log(Log.TypeAccess, pin, logText);
            }
            else
            {
                // Access denied
                logText = "Pin \"" + pin + "\" inserted. Access denied!";
                log     = new Log(Log.TypeInfo, logText);
            }

            DebugOnly.Print(logText);

            // Add log to loglist
            DataHelper.AddLog(log);

            if (nullCardId && authorized)
            {
                // Null CardID detected, prompt the user to set one
                var nullCardIdAlert = new AlertWindow(WindowAlertPeriod);
                nullCardIdAlert.SetText(
                    "It happears that this user has no related NFC card.\nDo you want to scan it now?");
                nullCardIdAlert.SetPositiveButton("Yes", delegate
                {
                    // User wants to add a new NFC card
                    pendingPin = pin;
                    scanWindow.Show();
                });
                nullCardIdAlert.SetNegativeButton("No", delegate
                {
                    // User doesn't want to add a new NFC card
                    nullCardIdAlert.Dismiss();
                });
                nullCardIdAlert.Show();
            }
            else
            {
                // Everything is fine
                accessWindow.Show(authorized);
            }
        }
Exemplo n.º 24
0
        /*
         * SERVER ROUTINE:
         * ServerRoutine is the only thread of this class. It periodically updates the current user data, and
         * if logs are stored into logList, it sends the logs to the server.
         */

        private static void ServerRoutine()
        {
            while (threadRunning)
            {
                bool success = true;

                if (ethernetJ11D.IsNetworkUp)
                {
                    ChangeDataSource(DataSourceRefresh);

                    DebugOnly.Print("Beginning server routine...");

                    // Check if ip is valid
                    if (String.Compare(ethernetJ11D.NetworkSettings.IPAddress, "0.0.0.0") != 0)
                    {
                        DebugOnly.Print("My IP is: " + ethernetJ11D.NetworkSettings.IPAddress);
                    }
                    else
                    {
                        DebugOnly.Print("ERROR: Current IP appears to be null!");
                        success = false;
                    }

                    // Request current time
                    if (success && !timeChecked)
                    {
                        success = requestTime();
                    }

                    // Send logs
                    if (success && logList.Count > 0)
                    {
                        DebugOnly.Print(logList.Count + " stored logs must be sent to server!");
                        success = sendLogs();
                    }

                    // Request users
                    if (success)
                    {
                        success = requestUsers();
                    }
                }
                else
                {
                    success = false;
                    DebugOnly.Print("ERROR: No connection, skipping scheduled server polling routine.");
                }

                // Plan next routine
                string periodString;
                int    period;
                if (success)
                {
                    periodString = SettingsManager.Get(SettingsManager.RoutinePeriod);
                    period       = Int32.Parse(periodString);
                    DebugOnly.Print("Server routine completed! Next event in " + periodString);

                    ChangeDataSource(DataSourceRemote);
                }
                else
                {
                    periodString = SettingsManager.Get(SettingsManager.RetryPeriod);
                    period       = Int32.Parse(periodString);
                    DebugOnly.Print("Server routine failed! Next event in " + periodString);

                    // Data source is now cache
                    if (userList.Count > 0)
                    {
                        ChangeDataSource(DataSourceCache);
                    }
                    else
                    {
                        ChangeDataSource(DataSourceError);
                    }
                }

                threadWaitForStop.WaitOne(period, true);
                threadWaitForStop.Reset();
            }
        }