Integration with your other Apps and programs

Bhadre system has web interfaces that can be used by any of your applications programs or any other Apps to open or close the garage door. From your applications, you can make an HTTPS POST call to url https://wifisecureaccess.com/devicePortsJson/ giving your credentials and the name of your device and the action to be taken in a JSON format.

1  Activating a port with an HTTPS POST call

To activate a port on a device or to open or close a door/gate, make an HTTPS POST call with the following details:

POST HTTP/1.1
Host: wifisecureaccess.com/devicePortsJson/
Content-Type: application/json

Provide the credentials and data in the following JSON format:
data = { "email": email, "password": password, "device_name": device_name, "port_name": port_name, "action": action, }

--where email and password are the email address and password of the owner of the device connected to your door/gate. device_name is the name of this device. port_name is the name (or label) of the port on that device that you want to activate. If this device is an asccess device such as gate, garage door or door, this will be ignore. action should be either "ON" or "OFF". If you want to open the door/gate, action must be "ON", and if you want to close it, action must be "OFF".

If a POST call is made as per that above format, the door/gate will be activated as per the action specified. Refer to the following sample python program. This sample call will open the door/gate. Edit this code and replace the device_name, email and passwords with those of yours before running this program. Also make sure that requests module is installed in python using 'pip install requests' before running this program.


#!/usr/bin/env python
import requests
import json

# This uses requests module.  So, if not already installed on your computer, install it before running this program
# pip install requests
#

def main_loop():
   url = "https://wifisecureaccess.com/access/devicePortsJson/"
   #the following are just an example.  replace these with your's.
   device_name = 'My Door'  # Replace this with the name of your devicea
   port_name = "GARAGE"   # If the cdevice is a door, gate or Garage, the device has only one port and, therefore, this will be ignored and you csn give anything here
   email = "tester@gmail.com"  # replace this with your email
   password = "12345678"      # replace this with your password
   action = "ON"  # or, action = "OFF", if you want to put OFF the port
   data = {'email': email, 'password': password, 'device_name': device_name, 'port_name': port_name, 'action': action,}
   headers = {'Content-Type': 'application/json', 'Accept': 'application/json',}
   r = requests.post(url, data=json.dumps(data), headers=headers)

   if r.status_code == requests.codes['ok']:
      res = r.json()
      if res['result'] and res['result'] == 'SUCCESS':
         print("SUCCESS")
      elif res['msg']:
         print(res['msg'])
      else:
         print("FAIL")

   else:
      print(r)
      print("Server error or communication error")

if __name__ == '__main__':
  main_loop()

2  HTTPS call to add or remove allowed Users

Repeating what we said in section 4-4 above ...
You can populate the allowed users of any group from any of your applications such as a booking platform using an HTTPS call. This feature helps integrate the Bhadre door controller with your applications such as a booking platform. If these devices are installed, for example, on the door of a hotel room or an AirBnB room, the application platform that makes the booking can enter the customer's email and their start date and expiry date directly into the allowed user's list of the group associated with the controller device. If done, the customer will be allowed to open the door during the period between start-date and expiry-date. The customers can open the door either by a voice prompt, or by scanning the QRCode or NFC tag fixed on the door. Thus, this is an ideal system for hotels and AirBnB users. This eliminates the need to pass on the keys or access cards to the customer.

To add the user to the device's group, make an HTTPS POST call with the following details:

POST HTTP/1.1
Host: wifisecureaccess.com/loadAllowedUsersJson/
Content-Type: application/json
data = { "email": your_email, "password": your_password, "device_group_name": device_group_name, "customers": customers }

-where customers is a double list of customer details.
customers = [customer1, customer2, customer3, ....]
-where each customer is a list as below:
[email_address, start_date, expiry_date]

For example, if you want to add two customers to the allowed group of a device, the customers should be as follows:
customer1 = [customer1_email, customer1_start_date, customer1_expiry_date]
customer2 = [customer2_email, customer2_start_date, customer2_expiry_date]
customers = [customer1, customer2]

Note: Leave start date and expiry date as "", if there is no start date or end date for that customer. If there is no start date, that means that the customer can access immediately. If there is no expiry date, the customer is authorized forever.

Here is a sample program to add two customers as alloowed members in a device group named test_group:


#!/usr/bin/env python
import requests
import json

def main_loop():
   email = 'tester@gmail.com'  # Replace this with your email address
   password = 'password'   # Replace with your password of your account with wifisecureaccess.com
   url = "https://wifisecureaccess.com/access/loadAllowedUsersJson/"
   #customer = [[customer_email, dt_start_str, dt_exp_str[, [.....], [.....],]
   customers = [['customer1@gmail.com', '2021-09-24 10:30', '2021-09-25 10:30'], ['customer2@gmail.com', '', ''],]
   data = {'email': email, 'password': password, 'device_group_name': 'test_group', 'customers': customers,}
   headers = {'Content-Type': 'application/json', 'Accept': 'application/json',}
   r = requests.post(url, data=json.dumps(data), headers=headers)
   if r.status_code == requests.codes['ok']:
      res = r.json()
      #print(res)
      if res['result'] and res['result'] == 'SUCCESS':
         print(res['msg'])
      else:
         print('Error_code = ', res['Error_code'], res['msg'])


if __name__ == '__main__':
    main_loop()


You can also remove any customer from the device's group with another HTTPS call as follows:

POST HTTP/1.1
Host: wifisecureaccess.com/removellowedUsersJson/
Content-Type: application/json
data = { "email": your_email, "password": your_password, "device_group_name": device_group_name, "customers": customers }

-where customers is a list of email address of the customers that you want to remove from the allowed list.
customers = [customer1_email, customer2_email, ......].

And, here is a sample program showing how to make an HHTPS call to remove a customer from the allowed list of a group.

#!/usr/bin/env python
import requests
import json

def main_loop():
   email = 'tester@gmail.com'  # replace with your email address
   password = 'password'  # Replace this with your password of your account with wifisecureaccess.com
   url = "https://wifisecureaccess.com/access/removeAllowedUsersJson/"
   customers = ['customer1@gmail.com', 'customer2@gmail.com',]
   data = {'email': email, 'password': password, 'device_group_name': 'test_group', 'customers': customers,}
   headers = {'Content-Type': 'application/json', 'Accept': 'application/json',}
   r = requests.post(url, data=json.dumps(data), headers=headers)
   if r.status_code == requests.codes['ok']:
      res = r.json()
      #print(res)
      if res['result'] and res['result'] == 'SUCCESS':
         print(res['msg'])
      else:
         print('Error_code = ', res['Error_code'], res['msg'])


if __name__ == '__main__':
    main_loop()

3  HTTPS call to add or remove customers to Special category of a Public Place or Parking Lot

Repeating what we said in section 8-5 above ...
Similar to what we have explained in section 4.4 of this documentation, you can integrate wifisecureaccess with any of your applications (such as online booking) and update the special category through an HTTPS call from that application to wifisecureaccess.com. If Bhadre controllers are installed at the gate of parking lots to control the boom gate (or whatever door they have), the application platform that makes the booking can enter the customer's email and their start date and expiry date directly into the allowed user's list of the group associated with the controller device. If done, the customer will be allowed to enter the parking lot or public place during the period between start-date and expiry-date. The customers can open the gate by scanning the QRCode or NFC tag fixed at the gate. Thus, this is an ideal system for public places (such as cinema halls and other public event places) and parking lots. This eliminates the need to carry tickets and other documents to enter the place..

To add a customer to a special category, of a public place/parking lot, make an HTTPS POST call with the following details:

POST HTTP/1.1
Host: wifisecureaccess.com/addMembersSpCatJson/
Content-Type: application/json
data = { "email": your_email, "password": your_password, "parking_lot_name": parking_lot_name, "customers": customers }

-where customers is a double list of customer details.
customers = [customer1, customer2, customer3, ....]
-where each customer is a list as below:
[email_address, start_date, expiry_date, fee_discount, fine_discount,]

Note: Whenever we use the word 'parking lot', it also means any public access place in addition to parking lot

For example, if you want to add two customers to the allowed group of a device (controller), the customers should be as follows:
customer1 = [customer1_email, customer1_start_date, customer1_expiry_date, customer1_fee_discount, customer1_fine_discount,]
customer2 = [customer2_email, customer2_start_date, customer2_expiry_date, customer2_fee_discount, customer2_fine_discount,]
customers = [customer1, customer2]

Note: Leave start date and expiry date as "", if there is no start date or end date for that customer. If there is no start date, that means that the customer can access immediately. If there is no expiry date, the customer is authorized forever.

As mentioned before, fee_discount and fine_discount are in percentages (0.00 to 100.00)

Here is a sample python program that will populate the allowed users in Special category of a public place or parking lot: This program adds two customers (customer1@gmail.com and customer2@gmail.com to the Special category 10 of the public place/parking lot named 'MY PUBLIC PLACE',


#!/usr/bin/env python
import requests
import json

#This inserts members to special parking category

def main_loop():
   email = 'tester@gmail.com'   # Replace this with your email
   password = 'password'   # Replace this with the password of your account with wifisecureacces.com
   url = "https://wifisecureaccess.com/access/addMembersSpCatJson/"
   #customers = [[customer_email, dt_start, dt_exp_str, %fee_discount, %fine_discount], [.....], [......],]
   customers = [['customer1@gmail.com', '2021-09-25 10:30', '2021-09-27 10:30', 70.0, 50.0,], ['customer2@gmail.com', '', '', 0.0, 0.0,],]
   data = {'email': email, 'password': password, 'parking_lot_name': 'MY PUBLIC PLACE', 'parking_category': 10, 'customers': customers,}
   headers = {'Content-Type': 'application/json', 'Accept': 'application/json',}
   r = requests.post(url, data=json.dumps(data), headers=headers)
   if r.status_code == requests.codes['ok']:
      res = r.json()
      #print(res)
      if res['result'] and res['result'] == 'SUCCESS':
         print(res['msg'])
      else:
         print('Error_code = ', res['Error_code'], res['msg'])


if __name__ == '__main__':
    main_loop()


You can also remove any customer from the special category with another HTTPS call as follows:
POST HTTP/1.1
Host: wifisecureaccess.com/removeMembersSpCatJson/
Content-Type: application/json
data = { "email": your_email, "password": your_password, "parking_lot_name": parking_lot_name, "customers": customers }

-where customers is a list of email address of the customers that you want to remove from the allowed list.
customers = [customer1_email, customer2_email, ......].

And, here is a sample program showing how to make an HHTPS call to remove two customers from the special category(id = 10) of the public place named "My PUBLIC PLSCE".


#!/usr/bin/env python
import requests
import json

#This removes members to special parking category

def main_loop():
   email = 'tester@gmail.com'  # Replace this with your email
   password = 'password'  # Replace this with the password of your account with wifisecureaccess.com
   url = "https://wifisecureaccess.com/access/removeMembersSpCatJson/"
   customers = ['customer1@gmail.com', 'customer2@gmail.com',]
   data = {'email': email, 'password': password, 'parking_lot_name': 'MY PUBLIC PLACE', 'parking_category': 10, 'customers': customers,}
   headers = {'Content-Type': 'application/json', 'Accept': 'application/json',}
   r = requests.post(url, data=json.dumps(data), headers=headers)
   if r.status_code == requests.codes['ok']:
      res = r.json()
      #print(res)
      if res['result'] and res['result'] == 'SUCCESS':
         print(res['msg'])
      else:
         print('Error_code = ', res['Error_code'], res['msg'])


if __name__ == '__main__':
    main_loop()


4  HTTPS call to add a booking in a Public Place or Parking Lot

Here is an example python code to make a booking using an HTTPS POST call:


#!/usr/bin/env python
import requests
import json

def main_loop():
   lot_owner_email = 'tester@gmail.com'   # replace this with the email of the owner of the public place/parking lot
   password = 'password'   # owner's password
   url = "https://wifisecureaccess.com/access/lotAddBookingJson/"
   facility_name = 'abcd'  # replace this with the registered name of the public place/parking lot
   customer_email = 'raman.v.nath@gmail.com'   # replace this with the email address of the customer who is making this booking
   parking_category = 'GENERAL'  #  replace this with the name of the access category that the customer is booking
   booking_start = '2022-01-12 10:30'  # replace this the start date and time
   booking_end = '2022-01-13 10:00'   # replace this with the end date and time of booking
   seat_bay_no = 'A2'  # This is optional.  If you are entering seat/bat number, replace A2 with what the customer is booking
   vehicle_reg_no = 'WAU 971'   #  This must be provided if this is a parking lot, and not a public access place. Replace WAU971 with the customer's vehic;le reg number
   data = {'lot_owner_email': lot_owner_email, 'password': password, 'facility_name': facility_name, 'customer_email': customer_email, 'parking_category': parking_category, 'booking_start': booking_start, 'booking_end': booking_end, 'vehicle_reg_no': vehicle_reg_no, 'seat_bay_no': seat_bay_no,}
   headers = {'Content-Type': 'application/json', 'Accept': 'application/json',}
   r = requests.post(url, data=json.dumps(data), headers=headers)
   if r.status_code == requests.codes['ok']:
      res = r.json()
      print(res)
      if res['result'] and res['result'] == 'SUCCESS':
         print(res['msg'])
      else:
         print('Error_code = ', res['Error_code'], res['msg'])


if __name__ == '__main__':
    main_loop()


5  HTTPS call to delete a booking in a Public Place or Parking Lot

Here is an example python code to delete a booking using an HTTPS POST call:


#!/usr/bin/env python
import requests
import json

def main_loop():
   lot_owner_email = 'tester@gmail.com'   # replace this with the email of the owner of the public place/parking lot
   password = 'password'   # owner's password
   url = "https://wifisecureaccess.com/access/lotDeleteBookingJson/"
   facility_name = 'abcd'  # replace this with the registered name of the public place/parking lot
   customer_email = 'raman.v.nath@gmail.com'   # replace this with the email address of the customer who is making this booking
   booking_start = '2022-01-12 10:30'  # replace this the start date and time
   booking_end = '2022-01-13 10:00'   # replace this with the end date and time of booking
   vehicle_reg_no = 'WAU 971'   #  This must be provided if this is a parking lot, and not a public access place. Replace WAU971 with the customer's vehic;le reg number
   data = {'lot_owner_email': lot_owner_email, 'password': password, 'facility_name': facility_name, 'customer_email': customer_email, 'parking_category': parking_category, 'booking_start': booking_start, 'booking_end': booking_end, 'vehicle_reg_no': vehicle_reg_no, 'seat_bay_no': seat_bay_no,}
   headers = {'Content-Type': 'application/json', 'Accept': 'application/json',}
   r = requests.post(url, data=json.dumps(data), headers=headers)
   if r.status_code == requests.codes['ok']:
      res = r.json()
      print(res)
      if res['result'] and res['result'] == 'SUCCESS':
         print(res['msg'])
      else:
         print('Error_code = ', res['Error_code'], res['msg'])


if __name__ == '__main__':
    main_loop()


6  Copying Device Use Records

'Device Use Records' have the information of anybody's using this device. The owner of a device can see the use records in Dashboard by clicking 'Device Use Records' under 'Device Admin'. These records can also be copied at frequent intervals to your local computer. Given below is an example of a program to copy these records.


#!/usr/bin/env python
import requests
import json
import getpass
import os

def main_loop():
   while True:
      email = input("Enter email : ")
      if email and email != "":
         break
   email = email.upper()
   while True:
      password = getpass.getpass()
      if password and password != "":
         break
   while True:
      device_name = input("Device Name: ")
      if device_name and device_name != '':
         break
   if device_name.isspace():
      print("device name cannot be empty spaces")
      exit(1)
   start_date = input("Start Date (yyyy-mm-dd hh:mm): ")
   if start_date.isspace():
      start_date = ''
   end_date = input("End Date (yyyy-mm-dd hh:mm): ")
   if end_date.isspace():
      end_date = ''
   while True:
      file_name = input("File Name: ")
      if file_name and file_name != '':
         break
   if file_name.isspace():
      print("Error.  File name cannot be blank spaces")
      exit(1)

   s = requests.session()
   n_next = 0
   url = "https://wifisecureaccess.com/access/get_useRecordsJson/"
   headers = {'Content-Type': 'application/json', 'Accept': 'application/json',}
   try:
      f = open(file_name, "a+")
   except:
      print("Unable to open the file %s" % (file_name))
      exit(1)

   while True:
            data = {'email': email, 'password': password, 'records_type': 'device', 'device_name': device_name, 'start_date': start_date, 'end_date': end_date, 'n_next': n_next,}
            r = s.post(url, data=json.dumps(data), headers=headers)
            if r.status_code == requests.codes['ok']:
               res = r.json()
               if res['result'] and res['result'] == 'SUCCESS':
                  if n_next == 0:
                     print("Field Names: ", res['field_names'])
                     if os.stat(file_name).st_size == 0:
                        field_names = res['field_names']
                        for field_name in field_names:
                           f.write(field_name)
                           f.write(", ")
                        f.write("\r\n\r\n")
                  records = res['records']
                  for record in records:
                     for value in record:
                        if not value:
                           value = ''
                        print(value, end=", ")
                        f.write(value)
                        f.write(", ")
                     print()
                     f.write("\r\n")
                  n_next = res['n_next']
                  records_remaining = res['records_remaining']
                  if records_remaining == 0:
                     break
               else:
                  if 'msg' in res:
                     msg = res['msg']
                  else:
                     msg = ""
                  print("FAIL: ", msg)
                  break
            else:
               print(r)
               print("FAIL:  Communication error")
               break
   f.close()

if __name__ == '__main__':
  main_loop()
And, here is a screenshot of the terminal running this program:

$ python test_getDeviceUseRecords.py
Enter email : test53680@gmail.com
Password:
Device Name: New_Device
Start Date (yyyy-mm-dd hh:mm): 2020-03-28 10:30
End Date (yyyy-mm-dd hh:mm): 2020-04-09 23:10
File Name: my_file.txt
{'result': 'SUCCESS', 'msg': 'Login Success'}
Field Names:  ['customer_email', 'use_date', 'use_time']
RAMAN.V.NATH@GMAIL.COM, 2020-04-08, 00:41,
RAMAN.V.NATH@GMAIL.COM, 2020-04-08, 00:44,
RAMAN.V.NATH@GMAIL.COM, 2020-04-08, 00:45,
TEST53680@GMAIL.COM, 2020-04-08, 10:50,
TEST53680@GMAIL.COM, 2020-04-08, 10:52,
TEST53680@GMAIL.COM, 2020-04-08, 10:52,
TEST53680@GMAIL.COM, 2020-04-08, 10:52,
TEST53680@GMAIL.COM, 2020-04-08, 10:52,
TEST53680@GMAIL.COM, 2020-04-08, 10:52,
The above program makes a call to the server. And, it prints out the records on the terminal window of the user's computer. It also appends the same data to the specified local file. Note that it appends the data to the file instead of creating a new file so that records read earlier will not be lost. You can use the data in the file for doing any analysis of the data. The System keeps the use records for 30 days only. So, the owner of the device may read this record, say, every 15 days giving the start data and end date appropriately so that you copy the data from the last end_date. As the program appends the new data to the file, all the previously read records are also in the same file. In doing so, you will have the complete record of as many days as you want. Note: the first line of the file will have the field names. Subsequent lines in the file are the records.

7  Copying Group Use Records

Group records is the use records of a group, showing who used the devices in this group and when. These records can be seen on the dashboard by clicking 'Group Records' under Device Groups in Dashboard. To copy the same records into your computer, you need a program to make calls to the IOT server. Given below is a program to do that.


#!/usr/bin/env python
import requests
import json
import getpass
import os

def main_loop():
   while True:
      email = input("Enter email : ")
      if email and email != "":
         break
   email = email.upper()
   while True:
      password = getpass.getpass()
      if password and password != "":
         break
   while True:
      group_name = input("Group Name: ")
      if group_name and group_name != '':
         break
   if group_name.isspace():
      print("group name cannot be blank spaces")
      exit(1)
   start_date = input("Start Date (yyyy-mm-dd hh:mm): ")
   if start_date.isspace():
      start_date = ''
   end_date = input("End Date (yyyy-mm-dd hh:mm): ")
   if end_date.isspace():
      end_date = ''
   while True:
      file_name = input("File Name: ")
      if file_name and file_name != '':
         break
   if file_name.isspace():
      print("Error.  File name cannot be blank spaces")
      exit(1)

   s = requests.session()
   n_next = 0
   url = "https://wifisecureaccess.com/access/get_useRecordsJson/"
   headers = {'Content-Type': 'application/json', 'Accept': 'application/json',}
   try:
      f = open(file_name, "a+")
   except:
      print("Unable to open the file %s" % (file_name))
      exit(1)

   while True:
            data = {'email': email, 'password': password, 'records_type': 'group', 'group_name': group_name, 'start_date': start_date, 'end_date': end_date, 'n_next': n_next,}
            r = s.post(url, data=json.dumps(data), headers=headers)
            if r.status_code == requests.codes['ok']:
               res = r.json()
               if res['result'] and res['result'] == 'SUCCESS':
                  if n_next == 0:
                     print("Field Names: ", res['field_names'])
                     if os.stat(file_name).st_size == 0:
                        field_names = res['field_names']
                        for field_name in field_names:
                           f.write(field_name)
                           f.write(", ")
                        f.write("\r\n\r\n")
                  records = res['records']
                  for record in records:
                     for value in record:
                        if not value:
                           value = ''
                        print(value, end=', ')
                        f.write(value)
                        f.write(", ")
                     print()
                     f.write("\r\n")
                  n_next = res['n_next']
                  records_remaining = res['records_remaining']
                  if records_remaining == 0:
                     break
               else:
                  if 'msg' in res:
                     msg = res['msg']
                  else:
                     msg = ""
                  print("FAIL: ", msg)
                  break
            else:
               print(r)
               print("FAIL:  Communication error")
               break
   f.close()

if __name__ == '__main__':
  main_loop()
And, here is a sample snapshot of a terminal running this program:

$ python test_get_groupUseRecords.py
Enter email : test53680@gmail.com
Password:
Group Name: My House
Start Date (yyyy-mm-dd hh:mm): 2020-03-10 0:0
End Date (yyyy-mm-dd hh:mm): 2020-04-11 0:0
File Name: my_file.txt
{'result': 'SUCCESS', 'msg': 'Login Success'}
Field Names:  ['device_name', 'device_use_type', 'customer_email', 'use_date', 'use_time']
New_Device, CONTROL/SENSOR, TEST53680@GMAIL.COM, 2020-04-07, 08:01,
New_Device, CONTROL/SENSOR, TEST53680@GMAIL.COM, 2020-04-07, 07:59,
New_Device, CONTROL/SENSOR, TEST53680@GMAIL.COM, 2020-04-07, 07:59,
New_Device, CONTROL/SENSOR, TEST53680@GMAIL.COM, 2020-04-06, 23:10,
New_Device, CONTROL/SENSOR, TEST53680@GMAIL.COM, 2020-04-06, 23:10,
New_Device, CONTROL/SENSOR, TEST53680@GMAIL.COM, 2020-04-06, 23:09,
New_Device, CONTROL/SENSOR, TEST53680@GMAIL.COM, 2020-04-06, 23:09,
New_Device, CONTROL/SENSOR, TEST53680@GMAIL.COM, 2020-04-06, 23:08,
New_Device, CONTROL/SENSOR, TEST53680@GMAIL.COM, 2020-04-06, 23:08,
New_Device, CONTROL/SENSOR, TEST53680@GMAIL.COM, 2020-04-06, 23:06,
New_Device, CONTROL/SENSOR, TEST53680@GMAIL.COM, 2020-04-06, 23:06,
New_Device, CONTROL/SENSOR, TEST53680@GMAIL.COM, 2020-04-06, 23:06,
New_Device, CONTROL/SENSOR, TEST53680@GMAIL.COM, 2020-04-06, 23:06,
New_Device, CONTROL/SENSOR, TEST53680@GMAIL.COM, 2020-04-06, 23:04,
New_Device, CONTROL/SENSOR, TEST53680@GMAIL.COM, 2020-04-06, 23:00,
The above program makes a call to the server. And, it prints the records on the terminal of your computer. It also appends the same data to the specified file on your local computer. Note that it appends the data to the file instead of creating a new file so that all previously read data are retained in the file. This data in the file will help you analyse it using any of your sophisticated tools. Keep in mid that the system keeps records for 30 days only. So, you will have to copy the records, say, every 15 days or so giving the start date as the end date given when copying data last time. As the program appends the data to the same file, it will have all the previously read data as well. That way, your file will have all the records for a much longer time.

8  Copying Customer Use Records

Customer use records are the records of a customer's use of all the devices in the system. You can see your use records of any devices in the system in Dashboard by clicking 'My Use Records' under 'User Admin' in Dashboard. If you want the same records copied into your local computer to keep the data for longer time, or to do detailed data analysis for your special needs, you need a program to make calls to the server. Given below is a program in python to get these records from the server.


#!/usr/bin/env python
import requests
import json
import getpass
import os

def main_loop():
   while True:
      email = input("Enter email : ")
      if email and email != "":
         break
   email = email.upper()
   while True:
      password = getpass.getpass()
      if password and password != "":
         break
   start_date = input("Start Date (yyyy-mm-dd hh:mm): ")
   if start_date.isspace():
      start_date = ''
   end_date = input("End Date (yyyy-mm-dd hh:mm): ")
   if end_date.isspace():
      end_date = ''
   while True:
      file_name = input("File Name: ")
      if file_name and file_name != '':
         break
   if file_name.isspace():
      print("Error.  File name cannot be blank spaces")
      exit(1)

   s = requests.session()
   n_next = 0
   url = "https://wifisecureaccess.com/access/get_useRecordsJson/"
   headers = {'Content-Type': 'application/json', 'Accept': 'application/json',}
   try:
      f = open(file_name, "a+")
   except:
      print("Unable to open the file %s" % (file_name))
      exit(1)

   while True:
            data = {'email': email, 'password': password, 'records_type': 'customer', 'start_date': start_date, 'end_date': end_date, 'n_next': n_next,}
            r = s.post(url, data=json.dumps(data), headers=headers)
            if r.status_code == requests.codes['ok']:
               res = r.json()
               if res['result'] and res['result'] == 'SUCCESS':
                  if n_next == 0:
                     print("Field Names: ", res['field_names'])
                     if os.stat(file_name).st_size == 0:
                        field_names = res['field_names']
                        for field_name in field_names:
                           f.write(field_name)
                           f.write(", ")
                        f.write("\r\n\r\n")
                  records = res['records']
                  for record in records:
                     for value in record:
                        if not value:
                           value = ''
                        print(value, end=", ")
                        f.write(value)
                        f.write(", ")
                     print()
                     f.write("\r\n")
                  n_next = res['n_next']
                  records_remaining = res['records_remaining']
                  if records_remaining == 0:
                     break
               else:
                  if 'msg' in res:
                     msg = res['msg']
                  else:
                     msg = ""
                  print("FAIL: ", msg)
                  break
            else:
               print(r)
               print("FAIL:  Communication error")
               break
   f.close()

if __name__ == '__main__':
  main_loop()
And, here is an example snapshot of a local terminal running this program.

$ python test_getCustomerUseRecords.py
Enter email : test53680@gmail.com
Password:
User Timezone (example: Australia/Sydney) deault: UTC
(Refer https://en.wikipedia.org/wiki/List_of_tz_database_time_zones): US/Pacific
Start Date (yyyy-mm-dd hh:mm): 2020-04-08 08:21
End Date (yyyy-mm-dd hh:mm): 2020-04-08 10:53
File Name: my_file.txt
{'result': 'SUCCESS', 'msg': 'Login Success'}
Field Names:  ['device_name', 'device_use_type', 'group_name', 'use_date', 'use_time']
New_Device, CONTROL/SENSOR, None, 2020-04-08, 10:52,
New_Device, CONTROL/SENSOR, None, 2020-04-08, 10:52,
New_Device, CONTROL/SENSOR, None, 2020-04-08, 10:52,
New_Device, CONTROL/SENSOR, None, 2020-04-08, 10:52,
New_Device, CONTROL/SENSOR, None, 2020-04-08, 10:52,
New_Device, CONTROL/SENSOR, None, 2020-04-08, 10:52,
New_Device, CONTROL/SENSOR, None, 2020-04-08, 10:52,
New_Device_H1.2, CONTROL/SENSOR, None, 2020-04-08, 10:52,
New_Device_H1.2, CONTROL/SENSOR, None, 2020-04-08, 10:51,
New_Device_H1.2, CONTROL/SENSOR, None, 2020-04-08, 10:51,
New_Device_H1.2, CONTROL/SENSOR, None, 2020-04-08, 10:51,
D8BFC0F2D182, CONTROL/SENSOR, None, 2020-04-08, 10:50,
A020A62FC8BD, CONTROL/SENSOR, None, 2020-04-08, 08:21,
The above program makes a call to the server. Refer to the suggestions given for reading group records in the previous section about copying records. Those comments apply here as well.

9  Copying Parking Records

If you own any parking lot, parking records of your parking lot can be copied to your local computer using a program. The following is a program in python to read parking records of any parking lot that you own.


#!/usr/bin/env python
import requests
import json
import getpass
import os

def main_loop():
   while True:
      email = input("Enter email : ")
      if email and email != "":
         break
   email = email.upper()
   while True:
      password = getpass.getpass()
      if password and password != "":
         break
   while True:
      parking_lot_name = input("Parking Lot Name: ")
      if parking_lot_name and parking_lot_name != '':
         break
   if parking_lot_name.isspace():
      print("parking lot name cannot be blank spaces")
      exit(1)
   start_date = input("Start Date (yyyy-mm-dd hh:mm): ")
   if start_date.isspace():
      start_date = ''
   end_date = input("End Date (yyyy-mm-dd hh:mm): ")
   if end_date.isspace():
      end_date = ''
   while True:
      file_name = input("File Name: ")
      if file_name and file_name != '':
         break
   if file_name.isspace():
      print("Error.  File name cannot be blank spaces")
      exit(1)

   s = requests.session()
   n_next = 0
   url = "https://wifisecureaccess.com/access/get_parkingRecordsJson/"
   headers = {'Content-Type': 'application/json', 'Accept': 'application/json',}
   try:
      f = open(file_name, "a+")
   except:
      print("Unable to open the file %s" % (file_name))
      exit(1)

   while True:
            data = {'email': email, 'password': password, 'records_type': 'parking_lot', 'parking_lot_name': parking_lot_name, 'start_date': start_date, 'end_date': end_date, 'n_next': n_next,}
            r = s.post(url, data=json.dumps(data), headers=headers)
            if r.status_code == requests.codes['ok']:
               res = r.json()
               if res['result'] and res['result'] == 'SUCCESS':
                  if n_next == 0:
                     print("Field Names: ", res['field_names'])
                     if os.stat(file_name).st_size == 0:
                        field_names = res['field_names']
                        for field_name in field_names:
                           f.write(field_name)
                           f.write(", ")
                        f.write("\r\n\r\n")
                  records = res['records']
                  for record in records:
                     for value in record:
                        if not value:
                           value = ''
                        print(value, end=", ")
                        f.write(value)
                        f.write(", ")
                     print()
                     f.write("\r\n")
                  n_next = res['n_next']
                  records_remaining = res['records_remaining']
                  if records_remaining == 0:
                     break
               else:
                  if 'msg' in res:
                     msg = res['msg']
                  else:
                     msg = ""
                  print("FAIL: ", msg)
                  break
            else:
               print(r)
               print("Fail")
               break

   f.close()

if __name__ == '__main__':
  main_loop()
And, here is an example screenshot of a terminal runnin this test program

$ python test_getLotParkingRecords.py
Enter email : test53680@gmail.com
Password:
Parking Lot Name: PARKING_LOT28265
Start Date (yyyy-mm-dd hh:mm): 2020-03-30 10:00
End Date (yyyy-mm-dd hh:mm): 2020-04-10 23:00
File Name: my_file.txt
{'result': 'SUCCESS', 'msg': 'Login Success'}
Field Names:  ['vehicle_reg_no', 'bay_no', 'entry_device_name', 'exit_device_name', 'parked_device_name', 'entry_station_name', 'exit_station_name', 'customer_email', 'parking_category', 'amount_charged', 'currency', 'Charge_id', 'park_start_date', 'park_start_time', 'park_end_date', 'park_end_time', 'Duration)Min)']
WAU 971, A1 , Entry Gate, Entry Gate, , Entry Gate, Entry Gate, TEST53680@GMAIL.COM, GENERAL, GENERAL, 0.00, AUD, , 2022-08-08, 14:44, 2022-08-08, 14:45, 1,
WAU 971, A1, Entry Gate, Entry Gate, , Entry Gate, Entry Gate,  TEST53680@GMAIL.COM, GENERAL, GENERAL, 0.00, AUD, , 2022-08-08, 14:46, 2022-08-08, 14:46, 20,
WAU 971, , , , , Entry Gate, Exit Gate, TEST53680GMAIL.COM, GENERAL, 0.00, AUD, , 2022-08-08, 10:49, 2022-08-08, 10:50, 30,
The above program makes a call to the server to get parking records. The program displays data on your local terminal. It also appends the same data to the specified file on your local computer. We recommend reading them at least once in 15 days proving the start date as the end date given in the previous reading so that you will not have overlapped data or missing data. In doing so, your file will have the complete parking records that you can maintain for a much longer time. You can use any of your sophisticated tools to analyse this data.

10  Data Collection at Periodic Time Intervals

Data from sensors of any smart device can be obtained using a python program that makes a call to https://wifisecureaccess.com. Here is a python program that will collect data and and print it on the console terminal as well as write to a file on your local computer.


#!/usr/bin/env python
import time
import requests
import json
import getpass
from threading import Timer
import os
import signal

#
def keyboardInterruptHandler(signal, frame):
    print("KeyboardInterrupt (ID: {}) has been caught. Cleaning up...".format(signal))
    ti.cancel()
    f.close()
    exit(0)


def main_loop():
   while True:
      email = input("Enter email : ")
      if email and email != "":
         break
   email = email.upper()
   while True:
      password = getpass.getpass()
      if password and password != "":
         break
   while True:
      device_name = input("Device Name: ")
      if device_name and device_name != '':
         break
   if device_name.isspace():
      print("device name cannot be empty spaces")
      exit(1)
   Error_code = 1
   while Error_code == 1:
      try:
         time_period = int(input("Time Period for data collection in seconds (no fractions, minimum 1): "))
         Error_code = 0
      except:
         Error_code = 1
   if time_period < 1:
      print(" Time period is too short for data collection through internet")
      exit(1)
   while True:
      file_name = input("File Name: ")
      if file_name and file_name != '':
         break
   if file_name.isspace():
      print("Error.  File name cannot be blank spaces")
      exit(1)

   try:
      f = open(file_name, "a+")
   except:
      print("Unable to open the file %s" % (file_name))
      exit(1)

   s = requests.session()
   url = "https://wifisecureaccess.com/access/devicePortsJson/"
   # The labels should be the changed names.  That means, if the user has changed the labels, use the changed labels.
   # Returned data will have the status of all the input ports of this device
   data = {'email': email, 'password': password, 'device_name': device_name,}
   headers = {'Content-Type': 'application/json', 'Accept': 'application/json',}
   while True:
      r = s.post(url, data=json.dumps(data), headers=headers)
      if r.status_code == requests.codes['ok']:
         res = r.json()
         #print(res)
         if res['result'] and res['result'] == 'SUCCESS':
            if 'dev_time' in res:
               print('Device_time = %s' % res['dev_time'], end=', ')
               f.write('Device_time = %s, ' % res['dev_time'])
            if 'Vin' in res:
               print('Vin = %s' % res['Vin'], end=', ')
               f.write('Vin = %s, ' % res['Vin'])
            if 'U_SOUND' in res:
               print('Ultra_sound = %s' % res['U_SOUND'], end=", ")
               f.write('Ultra_sound = %s, ' % res['U_SOUND'])
            if 'D6' in res:
               print('D6 = %s' % res['D6'], end=', ')
               f.write('D6 = %s, ' % res['D6'])
            if 'D7' in res:
               print('D7 = %s' % res['D7'], end=', ')
               f.write('D7 = %s, ' % res['D7'])
            if 'D6_temp_c' in res:
               print('D6_tem_c = %s' % res['D6_temp_c'], end=', ')
               f.write('D6_tem_c = %s, ' % res['D6_temp_c'])
            if 'D6_temp_f' in res:
               print('D6_temp_f = %s' % res['D6_temp_f'], end=', ')
               f.write('D6_temp_f = %s, ' % res['D6_temp_f'])
            if 'D6_humidity' in res:
               print('D6_humidity = %s' % res['D6_humidity'], end=', ')
               f.write('D6_humidity = %s, ' % res['D6_humidity'])
            if 'D7_temp_c' in res:
               print('D7_tem_c = %s' % res['D7_temp_c'], end=', ')
               f.write('D7_tem_c = %s, ' % res['D7_temp_c'])
            if 'D7_temp_f' in res:
               print('D7_temp_f = %s' % res['D7_temp_f'], end=', ')
               f.write('D7_temp_f = %s, ' % res['D7_temp_f'])
            if 'D7_humidity' in res:
               print('D7_humidity = %s' % res['D7_humidity'], end=', ')
               f.write('D7_humidity = %s, ' % res['D7_humidity'])
            print()
            f.write("\r\n")
            time.sleep(time_period)
         else:
            if 'msg' in res:
               msg = res['msg']
            else:
               msg = ""
            print("FAIL: ", msg)
            f.close()
            break
      else:
         print("FAIL.  Device not communicating")
         print(r)
         f.close()
         break

if __name__ == '__main__':
   main_loop()

When run, the program will prompt for your user name and password for wifisecureaccess.com. It will also ask for the file name on your local computer to save the data.
And, here is a snapshot of the screen running this test program:


$ python test_periodic_data_collection.py
Enter email : test53680@gmail.com
Password: 
Device Name: New_Device
Time Period for data collection in seconds: 10
File Name: my_file.txt
{'result': 'SUCCESS', 'msg': 'Login Success'}
Device_time = 2020-04-09 23:41:56, Vin = 0.01, D6_tem_c = 24.2, D6_temp_f = 75.56, D6_humidity = 63.0, D7_tem_c = 22.25, D7_temp_f = 72.05, 
Device_time = 2020-04-09 23:42:06, Vin = 0.01, D6_tem_c = 22.5, D6_temp_f = 72.5, D6_humidity = 69.0, D7_tem_c = 22.25, D7_temp_f = 72.05, 
Device_time = 2020-04-09 23:42:16, Vin = 0.01, D6_tem_c = 22.5, D6_temp_f = 72.5, D6_humidity = 69.0, D7_tem_c = 22.25, D7_temp_f = 72.05, 
Device_time = 2020-04-09 23:42:26, Vin = 0.01, D6_tem_c = 22.5, D6_temp_f = 72.5, D6_humidity = 69.0, D7_tem_c = 22.25, D7_temp_f = 72.05, 
Device_time = 2020-04-09 23:42:36, Vin = 0.01, D6_tem_c = 22.4, D6_temp_f = 72.32, D6_humidity = 69.0, D7_tem_c = 22.25, D7_temp_f = 72.05, 
Device_time = 2020-04-09 23:42:46, Vin = 0.01, D6_tem_c = 22.3, D6_temp_f = 72.14, D6_humidity = 69.0, D7_tem_c = 22.25, D7_temp_f = 72.05, 
Device_time = 2020-04-09 23:42:56, Vin = 0.01, D6_tem_c = 22.3, D6_temp_f = 72.14, D6_humidity = 69.0, D7_tem_c = 22.25, D7_temp_f = 72.05, 
The above program makes a call to the server at every specified time period. And, it prints out the return values in a single line. You may modify this program if you want it to write the data in any other format.
You may use any of your analytical tools to analyse the data collected in a file..

11  Reading Data From Any Port of Your devices Using Your Own Program

If you are interested in reading data from any port of your devices using your own program on your local computer, you can incorporate the following python code into your code. This python program makes a call to https://wifisecureaccess.com with your credentials. You can specify the port name as well as the device name. The python program returns the data from that port and prints it on terminal. When you incorporate this program into your codes, you can do whatever you want to do with that read data instead of printing on the terminal. This code becomes useful if you plan to write your own program to control ports of any of your devices based on other conditions which are outside the sensor values of any of your devices.


#!/usr/bin/env python
import requests
import json
import getpass

def main_loop():
   while True:
      email = input("Enter email : ")
      if email and email != "":
         break
   email = email.upper()
   while True:
      password = getpass.getpass()
      if password and password != "":
         break
   while True:
      device_name = input("Device Name: ")
      if device_name and device_name != '':
         break
   if device_name.isspace():
      print("device name cannot be empty spaces")
      exit(1)
   while True:
      port_name = input("Inport Name: ")
      if port_name and port_name != '':
         break
   if port_name.isspace():
      print("Port name cannot be empty spaces")
      exit(1)

   s = requests.session()
   url = "https://wifisecureaccess.com/access/devicePortsJson/"
   # The port_name should be the changed label name of the port.  That means, if the user has changed the labels, use the changed labels.
   #For example, if you have changed the label D6 to something like 'MyPort', you should be using 'MyPort' in these programs for inport name instead of D6
   data = {'email': email, 'password': password, 'device_name': device_name,}
   headers = {'Content-Type': 'application/json', 'Accept': 'application/json',}
   r = s.post(url, data=json.dumps(data), headers=headers)
   if r.status_code == requests.codes['ok']:
         res = r.json()
         print(res)
         if res['result'] and res['result'] == 'SUCCESS':
            if port_name in res:
               print(port_name, ': ',  res[port_name])
            else:
               print("%s does not exist in the device" % (port_name))
               print("Received Port Names and their current status are: %s" % (res))
         elif res['msg']:
            print(res['msg'])

   else:
         print("Server error or communication error")

if __name__ == '__main__':
  main_loop()
When run, the above program prompts for your email address, password, device name and port name. It then, makes a call to the server and returns the value from that port. It prints that value on your terminal. If the port name is an output port, it displays the current state of that output port (ON or OFF). If it is an input port, it displays the data read from that port.