7 package com.google.appinventor.components.runtime;
9 import android.content.Context;
10 import android.util.Log;
12 import com.physicaloid.lib.Physicaloid;
26 import java.io.UnsupportedEncodingException;
28 @DesignerComponent(version = YaVersion.SERIAL_COMPONENT_VERSION,
29 description =
"Serial component which can be used to connect to devices like Arduino",
30 category = ComponentCategory.CONNECTIVITY,
32 iconName =
"images/arduino.png",
36 @UsesLibraries(libraries =
"physicaloid.jar")
38 private static final String LOG_TAG =
"Serial Component";
40 private Context context;
42 private Physicaloid mPhysicaloid;
44 private int baudRate = 9600;
45 private int bytes = 256;
48 super(container.
$form());
50 Log.d(LOG_TAG,
"Created");
54 public
void InitializeSerial() {
55 mPhysicaloid =
new Physicaloid(context);
56 BaudRate(this.baudRate);
57 Log.d(LOG_TAG,
"Initialized");
60 @
SimpleFunction(description =
"Opens serial connection. Returns true when opened.")
61 public
boolean OpenSerial() {
62 Log.d(LOG_TAG,
"Opening connection");
63 if (mPhysicaloid ==
null) {
67 return mPhysicaloid.open();
70 @
SimpleFunction(description =
"Closes serial connection. Returns true when closed.")
71 public
boolean CloseSerial() {
72 Log.d(LOG_TAG,
"Closing connection");
73 if (mPhysicaloid ==
null) {
77 return mPhysicaloid.close();
81 public String ReadSerial() {
83 if (mPhysicaloid ==
null) {
86 byte[] buf =
new byte[this.bytes];
87 if (mPhysicaloid.read(buf) > 0) {
89 data =
new String(buf,
"UTF-8");
90 }
catch (UnsupportedEncodingException mEr) {
91 Log.e(LOG_TAG, mEr.getMessage());
99 public
void WriteSerial(String data) {
100 if (!data.isEmpty() && mPhysicaloid !=
null) {
101 byte[] buf = data.getBytes();
102 int result = mPhysicaloid.write(buf);
105 }
else if (mPhysicaloid ==
null) {
110 @
SimpleFunction(description =
"Writes given data to serial, and appends a new line at the end.")
111 public
void PrintSerial(String data) {
113 WriteSerial(data +
"\n");
117 public
boolean IsOpen() {
118 if (mPhysicaloid ==
null) {
122 return mPhysicaloid.isOpened();
126 public
boolean IsInitialized() {
127 return mPhysicaloid !=
null;
131 public
int BaudRate() {
132 return this.baudRate;
138 this.baudRate = baudRate;
139 Log.d(LOG_TAG,
"Baud Rate: " + baudRate);
140 if (mPhysicaloid !=
null)
141 mPhysicaloid.setBaudrate(baudRate);
143 Log.w(LOG_TAG,
"Could not set Serial Baud Rate to " + baudRate +
". Just saved, not applied to serial! Maybe you forgot to initialize it?");
147 public
int BufferSize() {
155 Log.d(LOG_TAG,
"Buffer Size: " + bytes);