Searching Events in Open Event Android

In the Open Event Android App searching events from the list of hundreds of events that are stored in the server is indeed an important task. As in the future there will be more events and the user might not be able to see a particular event that he might want to attend. So let’s see how the searching functionality was implemented in the app.

API endpoint?

The API endpoint which we are using looks something like this

https://open-event-api-dev.herokuapp.com/v1/events?sort=name&filter=[{“name”:”name”,”op”:”ilike”,”val”:”%Test Event%”}]

This endpoint returns all the events whose “name” field contains the words “Test Event” in ascending order and since the “ilike” operator is used the results are not case sensitive.

Android Implementation

The following lines are used to send a GET request to the server. We have two query parameters that is sort and filter. They are required so that we can get the list of events in ascending order and filter out the correct events. The function returns a list of events.

@GET("events")
fun searchEvents(@Query("sort") sort: String, @Query("filter") eventName: String): Single<List<Event>>

 

Now this is where the magic happens. This function returns the list of events that have the same name as the user has searched and stores it in the database. So all these events are stored offline as well.

fun getSearchEvents(eventName: String): Single<List<Event>> {
return eventApi.searchEvents("name", eventName)
.map {
eventDao.insertEvents(it)
it
}
}

 

We are using a SearchView to search the events. What happens here is that the user searches somethings and presses search, onQueryTextSubmit method gets called and it passes the search query to the ViewModel and loads the events.

searchView?.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String): Boolean {
//Do your search
searchViewModel.searchEvent = query
searchViewModel.loadEvents()
loadEventsAgain = true
return false
}
}

 

To add the search icon in the toolbar we just need to add the following code in the XML file. We specify the id of the searchView so that we can reference it in our code. The value of showAsAction is “always” which means the searchView icon will always be visible in the toolbar.

<group android:id="@+id/search_menu">
<item
android:id="@+id/search_item"
android:icon="@drawable/ic_search_grey_24dp"
android:title="@string/search"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="always" />
</group>

 

That’s all that we require to search events in the app.

Resources

  1. SearchView Official Android Documentation https://developer.android.com/training/search/setup
  2. ViewModel Official Android Documentation https://developer.android.com/topic/libraries/architecture/viewmodel
  3. Retrofit Official Documentation  http://square.github.io/retrofit/
Continue ReadingSearching Events in Open Event Android

Implementing Search User Feature for Admins

The users tab of admin panel of SUSI.AI provides a list of all users registered on SUSI. This helps admins to get an overview of users and also provides the admins option like change user roles and delete accounts. The list of users is displayed in a table which also uses pagination to handle larger number of users. But to find a particular user can be a difficult task if the user base is large. Therefore a feature to search for users by their email has been implement which searches for users on SUSI server and then sends the searched users to the client. In this post we will discuss both about the server and client side implementation of this feature.

Continue ReadingImplementing Search User Feature for Admins

Adding Data Point Markers to OSM

PSLab Android app supports multiple sensors external and internal. Users can view sensor readings and record them into a csv file for later use. They can also have their location embedded into the data set they are recording. Saving the location related to each sensor reading is important. Say in a school experiment teacher can ask the student to measure dust particle concentration in city and inside his house. If the data set didn’t have any reference to the location where it was recorded, it is just incomplete. To facilitate this feature, we have enabled location in data recordings.

Enabling location is just not enough. User should be able to view the locations. Probably on a map itself would be a good idea. With the use of Open Street Maps, we can add markers to specific locations. These markers can be used as a point to show on map where a specific data set had been recorded by the user. This can be implemented further to add additional features such as standardized labels to view which data set is at which location etc.

Figure 1: Markers on Map

Unlike Google Maps API, in Open Street Maps there is no direct implementation to add a marker. But it is not a hard implementation either. We can simply create a class extending map overlays and use that as a base to add markers.

We can start by creating a new class that extends ItemizedOverlay<OverlayItem> class as follows. In this class, it would be wise to have an array list full of markers we are using in the map to modularize the whole markers related tasks into this one class rather than implementing in every place where map is used.

public class MapOverlay extends ItemizedOverlay<OverlayItem> {

    private ArrayList<OverlayItem> overlayItemList = new   ArrayList<OverlayItem>();

}

 

Once the class is initiated, have the following methods implemented. The following method will add markers to the array list we have created at the beginning.

public void addItem(GeoPoint p, String title, String snippet){
  OverlayItem newItem = new OverlayItem(title, snippet, p);
  overlayItemList.add(newItem);
  populate(); 
}

 

This method will be used to handle focusing events related to map markers.

@Override
public boolean onSnapToItem(int arg0, int arg1, Point arg2, IMapView arg3){
  return false;
}

 

Following method is used by the map itself to generate markers from the marker list.

@Override
protected OverlayItem createItem(int arg0) {
  return overlayItemList.get(arg0);
}

 

This method is an overriden method we will have to include in the class body.

@Override
public int size() {
  return overlayItemList.size();
}

 

Once the overlay class is completed, we can move on to actual implementation of a map on Openstreetmap view.

From the main activity where the map is viewed, initiate the marker overlay class and pass the drawable that needs to be shown as the marker to the class constructor as follows:

MapOverlay mapoverlay = null;
Drawable marker=getResources().getDrawable(android.R.drawable.map_hand);
int markerWidth = marker.getIntrinsicWidth();
int markerHeight = marker.getIntrinsicHeight();
marker.setBounds(0, markerHeight, markerWidth, 0);

ResourceProxy resourceProxy = new DefaultResourceProxyImpl(getApplicationContext());
mapoverlay = new MapOverlay(marker, resourceProxy);
mapView.getOverlays().add(mapoverlay);
         
GeoPoint point = new GeoPoint(55.75, 37.616667);
mapoverlay.addItem(point, "Russia", "Russia");

 

We can add as many GeoPoints as we want to markers list and they all will be displayed on the map like this;

Figure 2: Final Output of Markers

Reference:

http://android-coding.blogspot.com/2012/06/example-of-implementing-openstreetmap.html

Continue ReadingAdding Data Point Markers to OSM

How to get the database of a running container from gcloud kubernetes

Dumping Databases with Kubernetes from Google Cloud

We have the eventyay version 1 currently running on Google Cloud, inside gcloud, I did not find documentation on this from open event, so what must be done is, we must first understand how this system is set up. This is probably easier there is already some overall knowledge of how kubernetes or gcloud actually works, but of course it takes time if there isn’t great knowledge on this topic.

This is the google cloud interface

There are many buttons many things that can be done, so while exploring with them..

There is a console button!

When clicked on this button, this appears

You get a fully integrated terminal emulator with access to a virtual linux environment where your project is, and this is actually super because you get full control of your project and what you can do. It is no longer needed to learn how to navigate through the google cloud GUI and configure everything, because you already have your own shell!

So the first things to care about is know what commands are available that help us for our purpose there are 2 important commands, and those are, “kubectl” and “gcloud” shell commands.

Right now gcloud commands won’t be particularly useful, what we need to know right now is we need to know the pods that are being run, right now. (Pods are little virtual machines, like the containers in Docker)

Awesome, we can find a list of the pods that we have available to view, I assume that web-1299653859-mq59r is the pod where open event is stored

We can confirm this by doing  kubectl get services, we then get the ports in which the services are open, we see that web is port 8080 so, that’s probably were open-event is

Through kubectl exec -it web-1299653859-mq59r — /bin/bash we can get inside the container! Great so now that we’re on the open event container, we try to look up how to connect to the database, the environment variables just show the ports and the ip address but the configuration file where the password actually is it doesn’t seem it can be found in plain view.. What to do?

Getting inside postgres container directly

After some time digging around the container, I give up trying to look for the username and password and just get the idea to go to the container directly.

So there you go. A list of the databases running on postgres.

We now use pg_dump to dump the database.

kubectl exec -it postgres — su postgres -c “pg_dump opev”

We pipe the output to a file.

Then we can download it from here, and that’s how to get the dump from the database.

References:

  1. https://kubernetes.io/docs/reference/kubectl/cheatsheet/
  2. https://kubernetes.io/docs/tasks/debug-application-cluster/get-shell-running-container/
Continue ReadingHow to get the database of a running container from gcloud kubernetes

Adding Open Street Maps to PSLab Android

PSLab Android app is an open source app that uses fully open libraries and tools so that the community can use all it’s features without any compromises related to pricing or feature constraints. This will brings us to the topic how to implement a map feature in PSLab Android app without using proprietary tools and libraries. This is really important as now the app is available on Fdroid and they don’t allow apps to have proprietary tools in them if they are published there. In other words, it simply says we cannot use Google Maps APIs no matter how powerful they are in usage.

There is a workaround and that is using Open Street Maps (OSM). OSM is an open source project which is supported by a number of developers all around the globe to develop an open source alternative to Google Maps. It supports plenty of features we need in PSLab Android app as well. Starting from displaying a high resolution map along with caching the places user has viewed, we can add markers to show data points and locations in sensor data logging implementations.

All these features can be made available once we add the following dependencies in gradle build file. Make sure to use the latest version as there will be improvements and bug fixes in each newer version

implementation "org.osmdroid:osmdroid-android:$rootProject.osmVersion"
implementation "org.osmdroid:osmdroid-mapsforge:$rootProject.mapsforgeVersion"
implementation "org.osmdroid:osmdroid-geopackage:$rootProject.geoPackageVersion"

 

OSM will be functional only after the following permission states were granted.

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"  />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

 

In a view xml file, add the layout org.osmdroid.views.MapView to initiate the map view. There is a known issue in OSM library. That is during the initiation, if the zoom factor is set to a small value, there will be multiple instances of maps as shown in Fig 1. The solution is to have a higher zoom value when the map is loaded.

Figure 1: Multiple map tiles in OSM

Once we initialize the map view inside an activity, a zoom level can be easily set using a map controller as follows;

map = findViewById(R.id.osmmap);
map.setTileSource(TileSourceFactory.MAPNIK);
map.setBuiltInZoomControls(true);
map.setMultiTouchControls(true);

IMapController mapController = map.getController();
mapController.setZoom((double) 9);
GeoPoint startPoint = new GeoPoint(0.00, 0.00);
mapController.setCenter(startPoint);

 

After successfully implementing the map view, we can develop the business logic to add markers and descriptions to improve the usability of OS Maps. They will be available in the upcoming blog posts.

Reference:

  1. https://github.com/osmdroid/osmdroid/wiki/How-to-add-the-osmdroid-library-via-Gradle
  2. https://www.openstreetmap.org/
Continue ReadingAdding Open Street Maps to PSLab Android

Device wise Usage Statistics of a Skill in SUSI.AI

The device wise usage distribution in SUSI.AI helps in understanding what kind of skills are used more on which type of devices, so that the skill creator can harness the core features of that device to enhance the skills or make the user experience smoother. For example, music playing skill may be used mostly on Smart Speakers whereas Android devices may have higher usage of alarm setting skill.

Sending the device type (ex, web client)

  1. Send the device type parameter as “Web Client” along with the query while fetching reply from SUSI server in chat.json API. The parameter is device_type.

// Add the type of device in the query
{
url += '&device_type=Web Client';
}

Storage of Device Wise Skill Usage Data on SUSI Server

  1. Create a deviceWiseSkillUsage.json file to store the device wise skill usage stats and make a JSONTray object for that in src/ai/susi/DAO.java file. The JSON file contains the device type and the usage count on that type of device (like Android, iOS, Web Client, Smart Speaker and others).
  2. Modify the src/ai/susi/server/api/susi/SusiService.java file to fetch device_type from the query parameters and pass them SusiCognition constructor.

public ServiceResponse serviceImpl(Query post, HttpServletResponse response, Authorization user, final JsonObjectWithDefault permissions) throws APIException {
	...
	String deviceType = post.get("device_type", "Others");
	...
	SusiCognition cognition = new SusiCognition(q, timezoneOffset, latitude, longitude, countryCode, countryName, language, deviceType, count, user.getIdentity(), minds.toArray(new SusiMind[minds.size()]));
	...
}
  1. Modify the src/ai/susi/mind/SusiCognition.java file to accept the deviceType in the constructor parameters. Check which skill is being currently used for the response and update the skill’s usage stats for the current device in deviceWiseSkillUsage.json. Call the function updateDeviceWiseUsageData() to update the skill usage data.

List<String> skills = dispute.get(0).getSkills();
for (String skill : skills) {
    updateDeviceWiseUsageData(skill, deviceType);
}

The updateDeviceWiseUsageData() function accepts the skill path and type of device. It parses the skill path to get the skill metadata like its model name, group name, language etc. The function then checks if the device already exists in the JSON file or not. If it exists then it increments the usage count by 1 else it creates an entry for the device in the JSON file and initializes it with the usage count 1.

for (int i = 0; i < deviceWiseUsageData.length(); i++) {
  deviceUsage = deviceWiseUsageData.getJSONObject(i);
  if (deviceUsage.get("device_type").equals(deviceType)) {
    deviceUsage.put("count", deviceUsage.getInt("count") + 1);
    deviceWiseUsageData.put(i,deviceUsage);
  }
}

API to access the Device Wise Skill Usage Data

  1. Create GetDeviceWiseSkillUsageService.java file to return the usage stats stored in deviceWiseSkillUsage.json

public ServiceResponse serviceImpl(Query call, HttpServletResponse response, Authorization rights, final JsonObjectWithDefault permissions) {        
  ...  // Fetch the query parameters
  JSONArray deviceWiseSkillUsage = languageName.getJSONArray(skill_name);
  result.put("skill_name", skill_name);
  result.put("skill_usage", deviceWiseSkillUsage);
  result.put("accepted", true);
  result.put("message", "Device wise skill usage fetched"); 
  return new ServiceResponse(result);    
}
  1. Add the API file to src/ai/susi/server/api/susi/SusiServer.java

services = new Class[]{
	...

	//Skill usage data
	GetDeviceWiseSkillUsageService.class
	
	...
}

 

Endpoint : /cms/getDeviceWiseSkillUsage.json

Parameters

  • model
  • group
  • language
  • Skill

Sample query: /cms/getDeviceWiseSkillUsage.json?model=general&group=Knowledge&language=en&skill=aboutsusi

Sample response:

{  
   "skill_usage":[  
    {
      "device_type": "Web Client",
      "count": 1
    },
    {
        "device_type": "Android",
        "count": 4
    },
    {
        "device_type": "iOS",
        "count": 2
    },
    {
        "device_type": "Smart Speaker",
        "count": 1
    },
    {
        "device_type": "Others",
        "count": 2
    }
   ],
   "session":{  
      "identity":{  
         "type":"host",
         "name":"162.158.154.147_81c88a10",
         "anonymous":true
      }
   },
   "skill_name":"ceo",
   "accepted":true,
   "message":"Device wise skill usage fetched"
}

Resources

Continue ReadingDevice wise Usage Statistics of a Skill in SUSI.AI

Capturing Position Data with PSLab Android App

PSLab Android app by FOSSASIA can be used to visualize different waveforms, signal levels and patterns. Many of them involve logging data from different instruments. These data sets can be unique and the user might want them to be specific to a location or a time. To facilitate this feature, PSLab Android app offers a feature to save user’s current location along with the data points.

This implementation can be done in two ways. One is to use Google Maps APIs and the other one is to use LocationManager classes provided by Android itself. The first one is more on to proprietary libraries and it will give errors when used in an open source publishing platform like Fdroid as they require all the libraries used in an app to be open. So we have to go with the latter, using LocationManager classes.

As first step, we will have to request permission from the user to allow the app access his current location. This can be easily done by adding a permission tag in the Manifest.xml file.

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

 

Since we are not using Google Maps APIs, capturing the current location will take a little while and that can be considered as the only downfall of using this method. We have to constantly check for a location change to capture the data related to current location. This can be easily done by attaching a LocationListener as it will do the very thing for us.

private LocationListener locationListener = new LocationListener() {
   @Override
   public void onLocationChanged(Location location) {
       locationAvailable = true;
   }

   @Override
   public void onStatusChanged(String s, int i, Bundle bundle) {/**/}

   @Override
   public void onProviderEnabled(String s) {/**/}

   @Override
   public void onProviderDisabled(String s) {
       // TODO: Handle GPS turned on/off situations
   }
};

 

In case if the user has turned off GPS in his device, this method wouldn’t work. We will have to request him to turn the feature on using a simple dialog box or a bottom sheet dialog.

We can also customize how frequent the locationlistener should check for a location using another class named LocationManager. This class can be instantiated as follows:

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

 

Then we can easily set the time interval using requestLocationUpdates method. Here I have requested location updates in every one second. That is a quite reasonable rate.

locationManager.requestLocationUpdates(provider, 1000, 1, locationListener);

 

Once we have set all this up, we can capture the current location assuming that the user has turned on the GPS option from his device settings and the LocationManager class has a new location as we checked earlier.

if (locationAvailable) {
   Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}

 

Each location will contain details related to its position such as latitudes and longitudes. We can log these data using the CSVLogger class implementation in PSLab Android app and let user have this option while doing his experiments.

Reference:

  1. An open source implementation : https://github.com/borneq/HereGPSLocation/blob/master/app/src/main/java/com/borneq/heregpslocation/MainActivity.java

Google Maps: https://developers.google.com/maps/documentation/android-sdk/intro

Continue ReadingCapturing Position Data with PSLab Android App

Setting up environment to build PSLab Android app using Fdroid Build

Fdroid is a place for open source enthusiasts and developers to host their Free and Open Source Software (FOSS) for free and get more people onboard into their community. In order to host an app in their repository, one has to go through a several steps of builds and tests. This is to ensure that the software provided by them are as quality and safe as they can ever be. They are not allowing proprietary libraries or tools to integrate into any app or they will  be published outside the Fdroid main repository (fdroid-data) so that the users will know what they are downloading.

In a normal Linux computer where we are developing Android apps and have setup Android Studio will not be able to run the build command using:

$ fdroid build -v -l org.fossasia.pslab

The reason behind this is that we have not installed gradle and build tools required by the “fdroid build” because they are not useful in our day today activities for standalone activities. First thing we need to do is, install gradle separately. This will include adding gradle to $PATH as well.

Download the latest gradle version zip file or the version your project is using with the following command. In PSLab Android app, we are using 4.5.1 version and the snippet below include that version.

$ wget https://services.gradle.org/distributions/gradle-4.5.1-bin.zip

Next step is to install this in a local folder. We can select any path we want, but /opt/ folder is generally used in such scenarios.

sudo mkdir /opt/gradle
sudo unzip -d /opt/gradle gradle-4.5.1-bin.zip

Then we can add gradle to our $PATH variable using the following command:

$ export PATH=$PATH:/opt/gradle/gradle-4.5.1/bin

Now we are all set with gradle settings. Next step is to verify that the fdroid server is properly configured and up to date. When you run the build command after setting up the gradle in PC, it will throw an error similar to “failed to find any output apks”. This causes if the installed fdroid server version is old.

Fdroid server is running on python 3 and it will require some additional libraries pre-installed to properly function.

$ sudo apt-get install vagrant virtualbox git python3-certifi python3-libvirt python3-requestbuilder python3-yaml python3-clint python3-vagrant python3-paramiko python3-pyasn1 python3-pyasn1-modules

Once these libraries are installed, remove the previous instance of fdroidserver by using the following command:

$ sudo apt-get remove fdroidserver

Then we can reinstall the latest version of fdroid server from git using the following command:

$ git clone https://gitlab.com/fdroid/fdroidserver.git
export PATH="$PATH:$PWD/fdroidserver"

Now we are all set to do a brand new lint build on our PC to make our app ready to be published in Fdroid repository!

Reference:

  1. Install gradle : https://www.vultr.com/docs/how-to-install-gradle-on-ubuntu-16-10
  2. Gradle versions : https://gradle.org/releases
  3. Setting up Fdroid-server : https://f-droid.org/en/docs/Build_Server_Setup/

Installing fdroidserver : https://gitlab.com/fdroid/fdroiddata/blob/master/README.md#quickstart

Continue ReadingSetting up environment to build PSLab Android app using Fdroid Build

Ember js as a web development framework.

Ember js as a web development framework.

Open Event on the frontend side uses a framework called Ember-js, and it is very necessary to understand it, if one has to contribute to the frontend, otherwise it will be extremely hard considering how big and complex ember can actually be, this is a collection of quick facts I’ve collected about ember.js, knowing this might also aid you in contributing to open-event even faster!

Ember.js is a very opinionated web framework that uses a lot of the new ES6/ES7 features that provides a MVC workflow for devs to create websites in a more organized way, and introduces many new concepts, into designing user interfaces.

Ember.js is better to create webapps, as it is to create a blog for example. Since it uses the MVC perspective of creating user interfaces. Another point I can mention is that ember.js is very non-intuitive, it has a big learning curve, and that means, editing ember.js webapps has an investment cost for every person that wants to edit them.

This is independently if they already have knowledge of JavaScript, HTML, CSS, the reason is, ember.js has its own internal language, so if you read the output of the code it generates, you’re obliged to learn how the entire system works. It works not very differently from a node.js application converted into web  (browserify), the HTML code the user agent downloads is very small, it downloads two javascript files, one just defines functions with all your user data, (your routes, templates, compiled handlebars files), and another one that controls the other, it has the virtual machine interpreter, and boots the website up so to say. And that’s mainly one of the reasons why big websites that use ember.js take so much to load. Because every time you enter the website you download the entire website in a single javascript file, (of course once it is cached this should be done quicker, so the first time will usually last very long compared to others), it isn’t surprising because most modern web frameworks actually do this.

I think it’s very important to know some details about how this specific framework works.

As for the user side (the developer) is pretty much wonderful. You have an application.hbs file where your main app (the main user interface) is there, and you can just use commands to generate routes, when you add routes and they’re not assigned to any parent, they’re added as “children” of the main app.

Before we get lost in the new Jargon, let me explain quickly what a route is, when you’re visiting a website you have in your URL a path of the website to whatever current file you’re looking, every new URL you visit might get added on your history if you have it enabled, and you’re allowed to go back and forth in history! 

Every address is also a part of the website, a website is traditionally organized as a file system structure, there are directories, and there are files, which you can download. You can have subdirectores in directories, and nest and organize things according to what you think it’s important.

When you load an ember.js with a different url, say you’re on the main page “scheme://host:port/” and then you click on settings “/settings”, what usually happens is that your browser will be redirected to “scheme://host:port/settings” and will usually reload a new page, in ember.js you actually download the same page no matter which url you visit, but ember.js notices which route are you seeing and provides the right interface for that, and when you click on a link from the same website you don’t actually reload the website, the site manipulates the history so that the history thinks, you’re visiting another part of the website, and you actually do. This is done with the history api[1]

So when you add routes, you can see it as some sort of  “subdirectories” on your ember.js web application. We also have components, and a component is a part of the application you can reuse through your website, like a template (a controller template, not an HTML template), there are also HTML templates as well, these are the handlebar files, ember.js compiles these into its own bytecode, when they’re loaded, they’re loaded by the virtual machine in ember.js.

There are many rules in ember in how to do things, and things are organized very specific according to some guidelines, that means ember projects won’t be the best in getting people involved many quickly, but hopefully it will reduce the number of errors, or bad practices, if people stick to the guidelines ember provides.

Resources

http://emberjs.jsbin.com/?html,css,js,output 

 


[1] http://html5doctor.com/history-api/

Continue ReadingEmber js as a web development framework.

Using external UART modules to debug PSLab operations

Pocket Science Lab by FOSSASIA is a compact tool that can be used for circuit analytics and debugging. To make things more interesting, this device can be accessed via the user interface using an Android app or also a desktop app. Both these apps use the UART protocol (Universal Asynchronous Receiver-Transmitter) to transmit commands to the PSLab device from mobile phone or PC and receive commands vice versa. The peculiar thing about hardware is that the developer cannot simply log data just like developing and debugging a software program. He needs some kind of an external mechanism or a tool to visualize those data packets travelling through the wires.

Figure 1: UART Interface in PSLab

PSLab has a UART interface extracted out simply for this reason and also to connect external sensors that use the UART protocol. With this, a developer who is debugging any of the Android app or the desktop app can view the command and data packets transmitted between the device and the user end application.

This  requires some additional components. UART interface has two communication related pins: Rx(Receiver) and Tx(Transmitter). We will need to monitor both these pin signals for input and output data packets. It should be kept in mind that PSLab is using 3.3V signals. This voltage level is important to mention here because if someone uses 5V signals on these pins, it will damage the main IC. There are FTDI modules available in market. FTDI stands for Future Technology Devices International which is a company name and their main product is this USB transceiver chip. These chips play a major role in electronic industry due to product reliability and multiple voltage support. PSLab uses 3.3V USB Tx Rx pins and modules other than FTDI wouldn’t support it.

Figure 2: FTDI Module from SparkFun

The module shown in Fig.2 is a FTDI module which you can simply plug in to computer and have a serial monitor interface. There are cheaper versions in shopping websites like eBay or Alibaba and they will also work fine. Both Tx and Rx pins will require two of these modules and connectivity is as follows;

PSLab [Rx Pin] → FTDI Module 1 [Rx Pin]
PSLab [Tx Pin] → FTDI Module 2 [Rx Pin]

This might look strange because everywhere we see a UART module is connected Rx → Tx and Tx → Rx. Notice that our idea is to monitor data packets. Not communicate with PSLab device directly. We want to see if our mobile phone Android app is sending correct commands to PSLab device or not and if PSLab device is transmitting back the expected result or not. This method helped a lot when debugging resistance measurement application in PSLab Android app.

Monitoring these UART data packets can be done simply using a serial monitor. You can either download and install some already built serial monitors or you can simply write a python script as follows which does the trick.

import serial

ser = serial.Serial(
    port='/dev/ttyUSB1',
    baudrate=1000000000
)

ser.isOpen()
while 1 :
    data = ''
    while ser.inWaiting() > 0:
        data += ser.read(1)

    if data != '':
        print ">>" + data

Once you are getting commands and responses, it will look like debugging a software using console.

References:

  1. PySerial Library : http://pyserial.readthedocs.io/en/latest/shortintro.html
  2. UART Protocol : https://en.wikipedia.org/wiki/Universal_asynchronous_receiver-transmitter
  3. FTDI : https://en.wikipedia.org/wiki/FTDI
Continue ReadingUsing external UART modules to debug PSLab operations