Aplikasi Smart Green House

This commit is contained in:
afanfahreza 2026-07-22 03:19:37 +07:00
commit 3d9494a405
95 changed files with 18873 additions and 0 deletions

2
.bundle/config Normal file
View File

@ -0,0 +1,2 @@
BUNDLE_PATH: "vendor/bundle"
BUNDLE_FORCE_RUBY_PLATFORM: 1

4
.eslintrc.js Normal file
View File

@ -0,0 +1,4 @@
module.exports = {
root: true,
extends: '@react-native',
};

75
.gitignore vendored Normal file
View File

@ -0,0 +1,75 @@
# OSX
#
.DS_Store
# Xcode
#
build/
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
xcuserdata
*.xccheckout
*.moved-aside
DerivedData
*.hmap
*.ipa
*.xcuserstate
**/.xcode.env.local
# Android/IntelliJ
#
build/
.idea
.gradle
local.properties
*.iml
*.hprof
.cxx/
*.keystore
!debug.keystore
.kotlin/
# node.js
#
node_modules/
npm-debug.log
yarn-error.log
# fastlane
#
# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the
# screenshots whenever they are needed.
# For more information about the recommended setup visit:
# https://docs.fastlane.tools/best-practices/source-control/
**/fastlane/report.xml
**/fastlane/Preview.html
**/fastlane/screenshots
**/fastlane/test_output
# Bundle artifact
*.jsbundle
# Ruby / CocoaPods
**/Pods/
/vendor/bundle/
# Temporary files created by Metro to check the health of the file watcher
.metro-health-check*
# testing
/coverage
# Yarn
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/sdks
!.yarn/versions

5
.prettierrc.js Normal file
View File

@ -0,0 +1,5 @@
module.exports = {
arrowParens: 'avoid',
singleQuote: true,
trailingComma: 'all',
};

3
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,3 @@
{
"js/ts.tsdk.path": "node_modules\\typescript\\lib"
}

1
.watchmanconfig Normal file
View File

@ -0,0 +1 @@
{}

22
App.tsx Normal file
View File

@ -0,0 +1,22 @@
import React from 'react';
import {GestureHandlerRootView} from 'react-native-gesture-handler';
import {NavigationContainer} from '@react-navigation/native';
import {SafeAreaProvider} from 'react-native-safe-area-context';
import {enableScreens} from 'react-native-screens';
import AppStack from './src/Navigators/Stack';
enableScreens();
const App = () => {
return (
<GestureHandlerRootView style={{flex: 1}}>
<SafeAreaProvider>
<NavigationContainer>
<AppStack />
</NavigationContainer>
</SafeAreaProvider>
</GestureHandlerRootView>
);
};
export default App;

17
Gemfile Normal file
View File

@ -0,0 +1,17 @@
source 'https://rubygems.org'
# You may use http://rbenv.org/ or https://rvm.io/ to install and use this version
ruby ">= 2.6.10"
# Exclude problematic versions of cocoapods and activesupport that causes build failures.
gem 'cocoapods', '>= 1.13', '!= 1.15.0', '!= 1.15.1'
gem 'activesupport', '>= 6.1.7.5', '!= 7.1.0'
gem 'xcodeproj', '< 1.26.0'
gem 'concurrent-ruby', '< 1.3.4'
# Ruby 3.4.0 has removed some libraries from the standard library.
gem 'bigdecimal'
gem 'logger'
gem 'benchmark'
gem 'mutex_m'
gem 'nkf'

97
README.md Normal file
View File

@ -0,0 +1,97 @@
This is a new [**React Native**](https://reactnative.dev) project, bootstrapped using [`@react-native-community/cli`](https://github.com/react-native-community/cli).
# Getting Started
> **Note**: Make sure you have completed the [Set Up Your Environment](https://reactnative.dev/docs/set-up-your-environment) guide before proceeding.
## Step 1: Start Metro
First, you will need to run **Metro**, the JavaScript build tool for React Native.
To start the Metro dev server, run the following command from the root of your React Native project:
```sh
# Using npm
npm start
# OR using Yarn
yarn start
```
## Step 2: Build and run your app
With Metro running, open a new terminal window/pane from the root of your React Native project, and use one of the following commands to build and run your Android or iOS app:
### Android
```sh
# Using npm
npm run android
# OR using Yarn
yarn android
```
### iOS
For iOS, remember to install CocoaPods dependencies (this only needs to be run on first clone or after updating native deps).
The first time you create a new project, run the Ruby bundler to install CocoaPods itself:
```sh
bundle install
```
Then, and every time you update your native dependencies, run:
```sh
bundle exec pod install
```
For more information, please visit [CocoaPods Getting Started guide](https://guides.cocoapods.org/using/getting-started.html).
```sh
# Using npm
npm run ios
# OR using Yarn
yarn ios
```
If everything is set up correctly, you should see your new app running in the Android Emulator, iOS Simulator, or your connected device.
This is one way to run your app — you can also build it directly from Android Studio or Xcode.
## Step 3: Modify your app
Now that you have successfully run the app, let's make changes!
Open `App.tsx` in your text editor of choice and make some changes. When you save, your app will automatically update and reflect these changes — this is powered by [Fast Refresh](https://reactnative.dev/docs/fast-refresh).
When you want to forcefully reload, for example to reset the state of your app, you can perform a full reload:
- **Android**: Press the <kbd>R</kbd> key twice or select **"Reload"** from the **Dev Menu**, accessed via <kbd>Ctrl</kbd> + <kbd>M</kbd> (Windows/Linux) or <kbd>Cmd ⌘</kbd> + <kbd>M</kbd> (macOS).
- **iOS**: Press <kbd>R</kbd> in iOS Simulator.
## Congratulations! :tada:
You've successfully run and modified your React Native App. :partying_face:
### Now what?
- If you want to add this new React Native code to an existing application, check out the [Integration guide](https://reactnative.dev/docs/integration-with-existing-apps).
- If you're curious to learn more about React Native, check out the [docs](https://reactnative.dev/docs/getting-started).
# Troubleshooting
If you're having issues getting the above steps to work, see the [Troubleshooting](https://reactnative.dev/docs/troubleshooting) page.
# Learn More
To learn more about React Native, take a look at the following resources:
- [React Native Website](https://reactnative.dev) - learn more about React Native.
- [Getting Started](https://reactnative.dev/docs/environment-setup) - an **overview** of React Native and how setup your environment.
- [Learn the Basics](https://reactnative.dev/docs/getting-started) - a **guided tour** of the React Native **basics**.
- [Blog](https://reactnative.dev/blog) - read the latest official React Native **Blog** posts.
- [`@facebook/react-native`](https://github.com/facebook/react-native) - the Open Source; GitHub **repository** for React Native.

13
__tests__/App.test.tsx Normal file
View File

@ -0,0 +1,13 @@
/**
* @format
*/
import React from 'react';
import ReactTestRenderer from 'react-test-renderer';
import App from '../App';
test('renders correctly', async () => {
await ReactTestRenderer.act(() => {
ReactTestRenderer.create(<App />);
});
});

119
android/app/build.gradle Normal file
View File

@ -0,0 +1,119 @@
apply plugin: "com.android.application"
apply plugin: "org.jetbrains.kotlin.android"
apply plugin: "com.facebook.react"
/**
* This is the configuration block to customize your React Native Android app.
* By default you don't need to apply any configuration, just uncomment the lines you need.
*/
react {
/* Folders */
// The root of your project, i.e. where "package.json" lives. Default is '../..'
// root = file("../../")
// The folder where the react-native NPM package is. Default is ../../node_modules/react-native
// reactNativeDir = file("../../node_modules/react-native")
// The folder where the react-native Codegen package is. Default is ../../node_modules/@react-native/codegen
// codegenDir = file("../../node_modules/@react-native/codegen")
// The cli.js file which is the React Native CLI entrypoint. Default is ../../node_modules/react-native/cli.js
// cliFile = file("../../node_modules/react-native/cli.js")
/* Variants */
// The list of variants to that are debuggable. For those we're going to
// skip the bundling of the JS bundle and the assets. Default is "debug", "debugOptimized".
// If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants.
// debuggableVariants = ["liteDebug", "liteDebugOptimized", "prodDebug", "prodDebugOptimized"]
/* Bundling */
// A list containing the node command and its flags. Default is just 'node'.
// nodeExecutableAndArgs = ["node"]
//
// The command to run when bundling. By default is 'bundle'
// bundleCommand = "ram-bundle"
//
// The path to the CLI configuration file. Default is empty.
// bundleConfig = file(../rn-cli.config.js)
//
// The name of the generated asset file containing your JS bundle
// bundleAssetName = "MyApplication.android.bundle"
//
// The entry file for bundle generation. Default is 'index.android.js' or 'index.js'
// entryFile = file("../js/MyApplication.android.js")
//
// A list of extra flags to pass to the 'bundle' commands.
// See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle
// extraPackagerArgs = []
/* Hermes Commands */
// The hermes compiler command to run. By default it is 'hermesc'
// hermesCommand = "$rootDir/my-custom-hermesc/bin/hermesc"
//
// The list of flags to pass to the Hermes compiler. By default is "-O", "-output-source-map"
// hermesFlags = ["-O", "-output-source-map"]
/* Autolinking */
autolinkLibrariesWithApp()
}
/**
* Set this to true to Run Proguard on Release builds to minify the Java bytecode.
*/
def enableProguardInReleaseBuilds = false
/**
* The preferred build flavor of JavaScriptCore (JSC)
*
* For example, to use the international variant, you can use:
* `def jscFlavor = io.github.react-native-community:jsc-android-intl:2026004.+`
*
* The international variant includes ICU i18n library and necessary data
* allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
* give correct results when using with locales other than en-US. Note that
* this variant is about 6MiB larger per architecture than default.
*/
def jscFlavor = 'io.github.react-native-community:jsc-android:2026004.+'
android {
ndkVersion rootProject.ext.ndkVersion
buildToolsVersion rootProject.ext.buildToolsVersion
compileSdk rootProject.ext.compileSdkVersion
namespace "com.smartgreenhouseapp"
defaultConfig {
applicationId "com.smartgreenhouseapp"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "1.0"
}
signingConfigs {
debug {
storeFile file('debug.keystore')
storePassword 'android'
keyAlias 'androiddebugkey'
keyPassword 'android'
}
}
buildTypes {
debug {
signingConfig signingConfigs.debug
}
release {
// Caution! In production, you need to generate your own keystore file.
// see https://reactnative.dev/docs/signed-apk-android.
signingConfig signingConfigs.debug
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
}
}
}
dependencies {
// The version of react-native is set by the React Native Gradle Plugin
implementation("com.facebook.react:react-android")
if (hermesEnabled.toBoolean()) {
implementation("com.facebook.react:hermes-android")
} else {
implementation jscFlavor
}
}

BIN
android/app/debug.keystore Normal file

Binary file not shown.

10
android/app/proguard-rules.pro vendored Normal file
View File

@ -0,0 +1,10 @@
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:

View File

@ -0,0 +1,27 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name=".MainApplication"
android:label="@string/app_name"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:allowBackup="false"
android:theme="@style/AppTheme"
android:usesCleartextTraffic="true"
android:supportsRtl="true">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode"
android:launchMode="singleTask"
android:windowSoftInputMode="adjustResize"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,22 @@
package com.smartgreenhouseapp
import com.facebook.react.ReactActivity
import com.facebook.react.ReactActivityDelegate
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled
import com.facebook.react.defaults.DefaultReactActivityDelegate
class MainActivity : ReactActivity() {
/**
* Returns the name of the main component registered from JavaScript. This is used to schedule
* rendering of the component.
*/
override fun getMainComponentName(): String = "SmartGreenhouseApp"
/**
* Returns the instance of the [ReactActivityDelegate]. We use [DefaultReactActivityDelegate]
* which allows you to enable New Architecture with a single boolean flags [fabricEnabled]
*/
override fun createReactActivityDelegate(): ReactActivityDelegate =
DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled)
}

View File

@ -0,0 +1,27 @@
package com.smartgreenhouseapp
import android.app.Application
import com.facebook.react.PackageList
import com.facebook.react.ReactApplication
import com.facebook.react.ReactHost
import com.facebook.react.ReactNativeApplicationEntryPoint.loadReactNative
import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost
class MainApplication : Application(), ReactApplication {
override val reactHost: ReactHost by lazy {
getDefaultReactHost(
context = applicationContext,
packageList =
PackageList(this).packages.apply {
// Packages that cannot be autolinked yet can be added manually here, for example:
// add(MyReactNativePackage())
},
)
}
override fun onCreate() {
super.onCreate()
loadReactNative(this)
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 100 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 653 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 220 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 141 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 258 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 134 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 334 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 201 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 483 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 167 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 502 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 266 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 728 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 207 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 645 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 332 B

View File

@ -0,0 +1,37 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2014 The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<inset xmlns:android="http://schemas.android.com/apk/res/android"
android:insetLeft="@dimen/abc_edit_text_inset_horizontal_material"
android:insetRight="@dimen/abc_edit_text_inset_horizontal_material"
android:insetTop="@dimen/abc_edit_text_inset_top_material"
android:insetBottom="@dimen/abc_edit_text_inset_bottom_material"
>
<selector>
<!--
This file is a copy of abc_edit_text_material (https://bit.ly/3k8fX7I).
The item below with state_pressed="false" and state_focused="false" causes a NullPointerException.
NullPointerException:tempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable(android.content.res.Resources)'
<item android:state_pressed="false" android:state_focused="false" android:drawable="@drawable/abc_textfield_default_mtrl_alpha"/>
For more info, see https://bit.ly/3CdLStv (react-native/pull/29452) and https://bit.ly/3nxOMoR.
-->
<item android:state_enabled="false" android:drawable="@drawable/abc_textfield_default_mtrl_alpha"/>
<item android:drawable="@drawable/abc_textfield_activated_mtrl_alpha"/>
</selector>
</inset>

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View File

@ -0,0 +1 @@
<resources xmlns:tools="http://schemas.android.com/tools" tools:keep="@drawable/node_modules_reactnavigation_elements_lib_module_assets_searchicon,@drawable/node_modules_reactnavigation_elements_lib_module_assets_backicon,@drawable/node_modules_reactnavigation_elements_lib_module_assets_backiconmask,@drawable/node_modules_reactnavigation_elements_lib_module_assets_clearicon,@drawable/node_modules_reactnavigation_elements_lib_module_assets_closeicon" />

View File

@ -0,0 +1,3 @@
<resources>
<string name="app_name">SmartGreenhouseApp</string>
</resources>

View File

@ -0,0 +1,9 @@
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.DayNight.NoActionBar">
<!-- Customize your theme here. -->
<item name="android:editTextBackground">@drawable/rn_edit_text_material</item>
</style>
</resources>

21
android/build.gradle Normal file
View File

@ -0,0 +1,21 @@
buildscript {
ext {
buildToolsVersion = "36.0.0"
minSdkVersion = 24
compileSdkVersion = 36
targetSdkVersion = 36
ndkVersion = "27.1.12297006"
kotlinVersion = "2.1.20"
}
repositories {
google()
mavenCentral()
}
dependencies {
classpath("com.android.tools.build:gradle")
classpath("com.facebook.react:react-native-gradle-plugin")
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin")
}
}
apply plugin: "com.facebook.react.rootproject"

44
android/gradle.properties Normal file
View File

@ -0,0 +1,44 @@
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
# Default value: -Xmx512m -XX:MaxMetaspaceSize=256m
org.gradle.jvmargs=-Xmx2048m -XX:MaxMetaspaceSize=512m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app's APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
# Use this property to specify which architecture you want to build.
# You can also override it from the CLI using
# ./gradlew <task> -PreactNativeArchitectures=x86_64
reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64
# Use this property to enable support to the new architecture.
# This will allow you to use TurboModules and the Fabric render in
# your application. You should enable this flag either if you want
# to write custom TurboModules/Fabric components OR use libraries that
# are providing them.
newArchEnabled=true
# Use this property to enable or disable the Hermes JS engine.
# If set to false, you will be using JSC instead.
hermesEnabled=true
# Use this property to enable edge-to-edge display support.
# This allows your app to draw behind system bars for an immersive UI.
# Note: Only works with ReactActivity and should not be used with custom Activity.
edgeToEdgeEnabled=false

Binary file not shown.

View File

@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

248
android/gradlew vendored Normal file
View File

@ -0,0 +1,248 @@
#!/bin/sh
#
# Copyright © 2015 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

98
android/gradlew.bat vendored Normal file
View File

@ -0,0 +1,98 @@
@REM Copyright (c) Meta Platforms, Inc. and affiliates.
@REM
@REM This source code is licensed under the MIT license found in the
@REM LICENSE file in the root directory of this source tree.
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

6
android/settings.gradle Normal file
View File

@ -0,0 +1,6 @@
pluginManagement { includeBuild("../node_modules/@react-native/gradle-plugin") }
plugins { id("com.facebook.react.settings") }
extensions.configure(com.facebook.react.ReactSettingsExtension){ ex -> ex.autolinkLibrariesFromCommand() }
rootProject.name = 'SmartGreenhouseApp'
include ':app'
includeBuild('../node_modules/@react-native/gradle-plugin')

4
app.json Normal file
View File

@ -0,0 +1,4 @@
{
"name": "SmartGreenhouseApp",
"displayName": "SmartGreenhouseApp"
}

3
babel.config.js Normal file
View File

@ -0,0 +1,3 @@
module.exports = {
presets: ['module:@react-native/babel-preset'],
};

9
index.js Normal file
View File

@ -0,0 +1,9 @@
/**
* @format
*/
import { AppRegistry } from 'react-native';
import App from './App';
import { name as appName } from './app.json';
AppRegistry.registerComponent(appName, () => App);

11
ios/.xcode.env Normal file
View File

@ -0,0 +1,11 @@
# This `.xcode.env` file is versioned and is used to source the environment
# used when running script phases inside Xcode.
# To customize your local environment, you can create an `.xcode.env.local`
# file that is not versioned.
# NODE_BINARY variable contains the PATH to the node executable.
#
# Customize the NODE_BINARY variable here.
# For example, to use nvm with brew, add the following line
# . "$(brew --prefix nvm)/nvm.sh" --no-use
export NODE_BINARY=$(command -v node)

34
ios/Podfile Normal file
View File

@ -0,0 +1,34 @@
# Resolve react_native_pods.rb with node to allow for hoisting
require Pod::Executable.execute_command('node', ['-p',
'require.resolve(
"react-native/scripts/react_native_pods.rb",
{paths: [process.argv[1]]},
)', __dir__]).strip
platform :ios, min_ios_version_supported
prepare_react_native_project!
linkage = ENV['USE_FRAMEWORKS']
if linkage != nil
Pod::UI.puts "Configuring Pod with #{linkage}ally linked Frameworks".green
use_frameworks! :linkage => linkage.to_sym
end
target 'SmartGreenhouseApp' do
config = use_native_modules!
use_react_native!(
:path => config[:reactNativePath],
# An absolute path to your application root.
:app_path => "#{Pod::Config.instance.installation_root}/.."
)
post_install do |installer|
react_native_post_install(
installer,
config[:reactNativePath],
:mac_catalyst_enabled => false,
# :ccache_enabled => true
)
end
end

View File

@ -0,0 +1,475 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 54;
objects = {
/* Begin PBXBuildFile section */
0C80B921A6F3F58F76C31292 /* libPods-SmartGreenhouseApp.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 5DCACB8F33CDC322A6C60F78 /* libPods-SmartGreenhouseApp.a */; };
13B07FBF1A68108700A75B9A /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 13B07FB51A68108700A75B9A /* Images.xcassets */; };
761780ED2CA45674006654EE /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 761780EC2CA45674006654EE /* AppDelegate.swift */; };
81AB9BB82411601600AC10FF /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 81AB9BB72411601600AC10FF /* LaunchScreen.storyboard */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
13B07F961A680F5B00A75B9A /* SmartGreenhouseApp.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = SmartGreenhouseApp.app; sourceTree = BUILT_PRODUCTS_DIR; };
13B07FB51A68108700A75B9A /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Images.xcassets; path = SmartGreenhouseApp/Images.xcassets; sourceTree = "<group>"; };
13B07FB61A68108700A75B9A /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = Info.plist; path = SmartGreenhouseApp/Info.plist; sourceTree = "<group>"; };
13B07FB81A68108700A75B9A /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = PrivacyInfo.xcprivacy; path = SmartGreenhouseApp/PrivacyInfo.xcprivacy; sourceTree = "<group>"; };
3B4392A12AC88292D35C810B /* Pods-SmartGreenhouseApp.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SmartGreenhouseApp.debug.xcconfig"; path = "Target Support Files/Pods-SmartGreenhouseApp/Pods-SmartGreenhouseApp.debug.xcconfig"; sourceTree = "<group>"; };
5709B34CF0A7D63546082F79 /* Pods-SmartGreenhouseApp.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-SmartGreenhouseApp.release.xcconfig"; path = "Target Support Files/Pods-SmartGreenhouseApp/Pods-SmartGreenhouseApp.release.xcconfig"; sourceTree = "<group>"; };
5DCACB8F33CDC322A6C60F78 /* libPods-SmartGreenhouseApp.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = "libPods-SmartGreenhouseApp.a"; sourceTree = BUILT_PRODUCTS_DIR; };
761780EC2CA45674006654EE /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = AppDelegate.swift; path = SmartGreenhouseApp/AppDelegate.swift; sourceTree = "<group>"; };
81AB9BB72411601600AC10FF /* LaunchScreen.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; name = LaunchScreen.storyboard; path = SmartGreenhouseApp/LaunchScreen.storyboard; sourceTree = "<group>"; };
ED297162215061F000B7C4FE /* JavaScriptCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = JavaScriptCore.framework; path = System/Library/Frameworks/JavaScriptCore.framework; sourceTree = SDKROOT; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
13B07F8C1A680F5B00A75B9A /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
0C80B921A6F3F58F76C31292 /* libPods-SmartGreenhouseApp.a in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
13B07FAE1A68108700A75B9A /* SmartGreenhouseApp */ = {
isa = PBXGroup;
children = (
13B07FB51A68108700A75B9A /* Images.xcassets */,
761780EC2CA45674006654EE /* AppDelegate.swift */,
13B07FB61A68108700A75B9A /* Info.plist */,
81AB9BB72411601600AC10FF /* LaunchScreen.storyboard */,
13B07FB81A68108700A75B9A /* PrivacyInfo.xcprivacy */,
);
name = SmartGreenhouseApp;
sourceTree = "<group>";
};
2D16E6871FA4F8E400B85C8A /* Frameworks */ = {
isa = PBXGroup;
children = (
ED297162215061F000B7C4FE /* JavaScriptCore.framework */,
5DCACB8F33CDC322A6C60F78 /* libPods-SmartGreenhouseApp.a */,
);
name = Frameworks;
sourceTree = "<group>";
};
832341AE1AAA6A7D00B99B32 /* Libraries */ = {
isa = PBXGroup;
children = (
);
name = Libraries;
sourceTree = "<group>";
};
83CBB9F61A601CBA00E9B192 = {
isa = PBXGroup;
children = (
13B07FAE1A68108700A75B9A /* SmartGreenhouseApp */,
832341AE1AAA6A7D00B99B32 /* Libraries */,
83CBBA001A601CBA00E9B192 /* Products */,
2D16E6871FA4F8E400B85C8A /* Frameworks */,
BBD78D7AC51CEA395F1C20DB /* Pods */,
);
indentWidth = 2;
sourceTree = "<group>";
tabWidth = 2;
usesTabs = 0;
};
83CBBA001A601CBA00E9B192 /* Products */ = {
isa = PBXGroup;
children = (
13B07F961A680F5B00A75B9A /* SmartGreenhouseApp.app */,
);
name = Products;
sourceTree = "<group>";
};
BBD78D7AC51CEA395F1C20DB /* Pods */ = {
isa = PBXGroup;
children = (
3B4392A12AC88292D35C810B /* Pods-SmartGreenhouseApp.debug.xcconfig */,
5709B34CF0A7D63546082F79 /* Pods-SmartGreenhouseApp.release.xcconfig */,
);
path = Pods;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
13B07F861A680F5B00A75B9A /* SmartGreenhouseApp */ = {
isa = PBXNativeTarget;
buildConfigurationList = 13B07F931A680F5B00A75B9A /* Build configuration list for PBXNativeTarget "SmartGreenhouseApp" */;
buildPhases = (
C38B50BA6285516D6DCD4F65 /* [CP] Check Pods Manifest.lock */,
13B07F871A680F5B00A75B9A /* Sources */,
13B07F8C1A680F5B00A75B9A /* Frameworks */,
13B07F8E1A680F5B00A75B9A /* Resources */,
00DD1BFF1BD5951E006B06BC /* Bundle React Native code and images */,
00EEFC60759A1932668264C0 /* [CP] Embed Pods Frameworks */,
E235C05ADACE081382539298 /* [CP] Copy Pods Resources */,
);
buildRules = (
);
dependencies = (
);
name = SmartGreenhouseApp;
productName = SmartGreenhouseApp;
productReference = 13B07F961A680F5B00A75B9A /* SmartGreenhouseApp.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
83CBB9F71A601CBA00E9B192 /* Project object */ = {
isa = PBXProject;
attributes = {
LastUpgradeCheck = 1210;
TargetAttributes = {
13B07F861A680F5B00A75B9A = {
LastSwiftMigration = 1120;
};
};
};
buildConfigurationList = 83CBB9FA1A601CBA00E9B192 /* Build configuration list for PBXProject "SmartGreenhouseApp" */;
compatibilityVersion = "Xcode 12.0";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = 83CBB9F61A601CBA00E9B192;
productRefGroup = 83CBBA001A601CBA00E9B192 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
13B07F861A680F5B00A75B9A /* SmartGreenhouseApp */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
13B07F8E1A680F5B00A75B9A /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
81AB9BB82411601600AC10FF /* LaunchScreen.storyboard in Resources */,
13B07FBF1A68108700A75B9A /* Images.xcassets in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
00DD1BFF1BD5951E006B06BC /* Bundle React Native code and images */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
"$(SRCROOT)/.xcode.env.local",
"$(SRCROOT)/.xcode.env",
);
name = "Bundle React Native code and images";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "set -e\n\nWITH_ENVIRONMENT=\"$REACT_NATIVE_PATH/scripts/xcode/with-environment.sh\"\nREACT_NATIVE_XCODE=\"$REACT_NATIVE_PATH/scripts/react-native-xcode.sh\"\n\n/bin/sh -c \"\\\"$WITH_ENVIRONMENT\\\" \\\"$REACT_NATIVE_XCODE\\\"\"\n";
};
00EEFC60759A1932668264C0 /* [CP] Embed Pods Frameworks */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-SmartGreenhouseApp/Pods-SmartGreenhouseApp-frameworks-${CONFIGURATION}-input-files.xcfilelist",
);
name = "[CP] Embed Pods Frameworks";
outputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-SmartGreenhouseApp/Pods-SmartGreenhouseApp-frameworks-${CONFIGURATION}-output-files.xcfilelist",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-SmartGreenhouseApp/Pods-SmartGreenhouseApp-frameworks.sh\"\n";
showEnvVarsInLog = 0;
};
C38B50BA6285516D6DCD4F65 /* [CP] Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
);
inputPaths = (
"${PODS_PODFILE_DIR_PATH}/Podfile.lock",
"${PODS_ROOT}/Manifest.lock",
);
name = "[CP] Check Pods Manifest.lock";
outputFileListPaths = (
);
outputPaths = (
"$(DERIVED_FILE_DIR)/Pods-SmartGreenhouseApp-checkManifestLockResult.txt",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
showEnvVarsInLog = 0;
};
E235C05ADACE081382539298 /* [CP] Copy Pods Resources */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-SmartGreenhouseApp/Pods-SmartGreenhouseApp-resources-${CONFIGURATION}-input-files.xcfilelist",
);
name = "[CP] Copy Pods Resources";
outputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-SmartGreenhouseApp/Pods-SmartGreenhouseApp-resources-${CONFIGURATION}-output-files.xcfilelist",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-SmartGreenhouseApp/Pods-SmartGreenhouseApp-resources.sh\"\n";
showEnvVarsInLog = 0;
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
13B07F871A680F5B00A75B9A /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
761780ED2CA45674006654EE /* AppDelegate.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin XCBuildConfiguration section */
13B07F941A680F5B00A75B9A /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 3B4392A12AC88292D35C810B /* Pods-SmartGreenhouseApp.debug.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CURRENT_PROJECT_VERSION = 1;
ENABLE_BITCODE = NO;
INFOPLIST_FILE = SmartGreenhouseApp/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 15.1;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.0;
OTHER_LDFLAGS = (
"$(inherited)",
"-ObjC",
"-lc++",
);
PRODUCT_BUNDLE_IDENTIFIER = "org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = SmartGreenhouseApp;
SUPPORTED_PLATFORMS = "iphoneos iphonesimulator";
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
VERSIONING_SYSTEM = "apple-generic";
};
name = Debug;
};
13B07F951A680F5B00A75B9A /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 5709B34CF0A7D63546082F79 /* Pods-SmartGreenhouseApp.release.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CURRENT_PROJECT_VERSION = 1;
INFOPLIST_FILE = SmartGreenhouseApp/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 15.1;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
MARKETING_VERSION = 1.0;
OTHER_LDFLAGS = (
"$(inherited)",
"-ObjC",
"-lc++",
);
PRODUCT_BUNDLE_IDENTIFIER = "org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)";
PRODUCT_NAME = SmartGreenhouseApp;
SUPPORTED_PLATFORMS = "iphoneos iphonesimulator";
SWIFT_VERSION = 5.0;
TARGETED_DEVICE_FAMILY = "1,2";
VERSIONING_SYSTEM = "apple-generic";
};
name = Release;
};
83CBBA201A601CBA00E9B192 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;
CLANG_CXX_LANGUAGE_STANDARD = "c++20";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
"EXCLUDED_ARCHS[sdk=iphonesimulator*]" = "";
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_SYMBOLS_PRIVATE_EXTERN = NO;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 15.1;
LD_RUNPATH_SEARCH_PATHS = (
/usr/lib/swift,
"$(inherited)",
);
LIBRARY_SEARCH_PATHS = (
"\"$(SDKROOT)/usr/lib/swift\"",
"\"$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)\"",
"\"$(inherited)\"",
);
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
OTHER_CPLUSPLUSFLAGS = (
"$(OTHER_CFLAGS)",
"-DFOLLY_NO_CONFIG",
"-DFOLLY_MOBILE=1",
"-DFOLLY_USE_LIBCPP=1",
"-DFOLLY_CFG_NO_COROUTINES=1",
"-DFOLLY_HAVE_CLOCK_GETTIME=1",
);
SDKROOT = iphoneos;
};
name = Debug;
};
83CBBA211A601CBA00E9B192 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;
CLANG_CXX_LANGUAGE_STANDARD = "c++20";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_COMMA = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_STRICT_PROTOTYPES = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CLANG_WARN_UNREACHABLE_CODE = YES;
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = YES;
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
"EXCLUDED_ARCHS[sdk=iphonesimulator*]" = "";
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNDECLARED_SELECTOR = YES;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 15.1;
LD_RUNPATH_SEARCH_PATHS = (
/usr/lib/swift,
"$(inherited)",
);
LIBRARY_SEARCH_PATHS = (
"\"$(SDKROOT)/usr/lib/swift\"",
"\"$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)\"",
"\"$(inherited)\"",
);
MTL_ENABLE_DEBUG_INFO = NO;
OTHER_CPLUSPLUSFLAGS = (
"$(OTHER_CFLAGS)",
"-DFOLLY_NO_CONFIG",
"-DFOLLY_MOBILE=1",
"-DFOLLY_USE_LIBCPP=1",
"-DFOLLY_CFG_NO_COROUTINES=1",
"-DFOLLY_HAVE_CLOCK_GETTIME=1",
);
SDKROOT = iphoneos;
VALIDATE_PRODUCT = YES;
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
13B07F931A680F5B00A75B9A /* Build configuration list for PBXNativeTarget "SmartGreenhouseApp" */ = {
isa = XCConfigurationList;
buildConfigurations = (
13B07F941A680F5B00A75B9A /* Debug */,
13B07F951A680F5B00A75B9A /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
83CBB9FA1A601CBA00E9B192 /* Build configuration list for PBXProject "SmartGreenhouseApp" */ = {
isa = XCConfigurationList;
buildConfigurations = (
83CBBA201A601CBA00E9B192 /* Debug */,
83CBBA211A601CBA00E9B192 /* Release */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 83CBB9F71A601CBA00E9B192 /* Project object */;
}

View File

@ -0,0 +1,88 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1210"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "13B07F861A680F5B00A75B9A"
BuildableName = "SmartGreenhouseApp.app"
BlueprintName = "SmartGreenhouseApp"
ReferencedContainer = "container:SmartGreenhouseApp.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "00E356ED1AD99517003FC87E"
BuildableName = "SmartGreenhouseAppTests.xctest"
BlueprintName = "SmartGreenhouseAppTests"
ReferencedContainer = "container:SmartGreenhouseApp.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "13B07F861A680F5B00A75B9A"
BuildableName = "SmartGreenhouseApp.app"
BlueprintName = "SmartGreenhouseApp"
ReferencedContainer = "container:SmartGreenhouseApp.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "13B07F861A680F5B00A75B9A"
BuildableName = "SmartGreenhouseApp.app"
BlueprintName = "SmartGreenhouseApp"
ReferencedContainer = "container:SmartGreenhouseApp.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>

View File

@ -0,0 +1,48 @@
import UIKit
import React
import React_RCTAppDelegate
import ReactAppDependencyProvider
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var reactNativeDelegate: ReactNativeDelegate?
var reactNativeFactory: RCTReactNativeFactory?
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
) -> Bool {
let delegate = ReactNativeDelegate()
let factory = RCTReactNativeFactory(delegate: delegate)
delegate.dependencyProvider = RCTAppDependencyProvider()
reactNativeDelegate = delegate
reactNativeFactory = factory
window = UIWindow(frame: UIScreen.main.bounds)
factory.startReactNative(
withModuleName: "SmartGreenhouseApp",
in: window,
launchOptions: launchOptions
)
return true
}
}
class ReactNativeDelegate: RCTDefaultReactNativeFactoryDelegate {
override func sourceURL(for bridge: RCTBridge) -> URL? {
self.bundleURL()
}
override func bundleURL() -> URL? {
#if DEBUG
RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index")
#else
Bundle.main.url(forResource: "main", withExtension: "jsbundle")
#endif
}
}

View File

@ -0,0 +1,53 @@
{
"images" : [
{
"idiom" : "iphone",
"scale" : "2x",
"size" : "20x20"
},
{
"idiom" : "iphone",
"scale" : "3x",
"size" : "20x20"
},
{
"idiom" : "iphone",
"scale" : "2x",
"size" : "29x29"
},
{
"idiom" : "iphone",
"scale" : "3x",
"size" : "29x29"
},
{
"idiom" : "iphone",
"scale" : "2x",
"size" : "40x40"
},
{
"idiom" : "iphone",
"scale" : "3x",
"size" : "40x40"
},
{
"idiom" : "iphone",
"scale" : "2x",
"size" : "60x60"
},
{
"idiom" : "iphone",
"scale" : "3x",
"size" : "60x60"
},
{
"idiom" : "ios-marketing",
"scale" : "1x",
"size" : "1024x1024"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}

View File

@ -0,0 +1,6 @@
{
"info" : {
"version" : 1,
"author" : "xcode"
}
}

View File

@ -0,0 +1,59 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CADisableMinimumFrameDurationOnPhone</key>
<true/>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleDisplayName</key>
<string>SmartGreenhouseApp</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>$(MARKETING_VERSION)</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>NSAppTransportSecurity</key>
<dict>
<!-- Do not change NSAllowsArbitraryLoads to true, or you will risk app rejection! -->
<key>NSAllowsArbitraryLoads</key>
<false/>
<key>NSAllowsLocalNetworking</key>
<true/>
</dict>
<key>NSLocationWhenInUseUsageDescription</key>
<string></string>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>arm64</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
</array>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
</dict>
</plist>

View File

@ -0,0 +1,47 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="15702" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
<device id="retina4_7" orientation="portrait" appearance="light"/>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="15704"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="EHf-IW-A2E">
<objects>
<viewController id="01J-lp-oVM" sceneMemberID="viewController">
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<label opaque="NO" clipsSubviews="YES" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="SmartGreenhouseApp" textAlignment="center" lineBreakMode="middleTruncation" baselineAdjustment="alignBaselines" minimumFontSize="18" translatesAutoresizingMaskIntoConstraints="NO" id="GJd-Yh-RWb">
<rect key="frame" x="0.0" y="202" width="375" height="43"/>
<fontDescription key="fontDescription" type="boldSystem" pointSize="36"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" clipsSubviews="YES" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Powered by React Native" textAlignment="center" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" minimumFontSize="9" translatesAutoresizingMaskIntoConstraints="NO" id="MN2-I3-ftu">
<rect key="frame" x="0.0" y="626" width="375" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<nil key="highlightedColor"/>
</label>
</subviews>
<color key="backgroundColor" systemColor="systemBackgroundColor" cocoaTouchSystemColor="whiteColor"/>
<constraints>
<constraint firstItem="Bcu-3y-fUS" firstAttribute="bottom" secondItem="MN2-I3-ftu" secondAttribute="bottom" constant="20" id="OZV-Vh-mqD"/>
<constraint firstItem="Bcu-3y-fUS" firstAttribute="centerX" secondItem="GJd-Yh-RWb" secondAttribute="centerX" id="Q3B-4B-g5h"/>
<constraint firstItem="MN2-I3-ftu" firstAttribute="centerX" secondItem="Bcu-3y-fUS" secondAttribute="centerX" id="akx-eg-2ui"/>
<constraint firstItem="MN2-I3-ftu" firstAttribute="leading" secondItem="Bcu-3y-fUS" secondAttribute="leading" id="i1E-0Y-4RG"/>
<constraint firstItem="GJd-Yh-RWb" firstAttribute="centerY" secondItem="Ze5-6b-2t3" secondAttribute="bottom" multiplier="1/3" constant="1" id="moa-c2-u7t"/>
<constraint firstItem="GJd-Yh-RWb" firstAttribute="leading" secondItem="Bcu-3y-fUS" secondAttribute="leading" symbolic="YES" id="x7j-FC-K8j"/>
</constraints>
<viewLayoutGuide key="safeArea" id="Bcu-3y-fUS"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="52.173913043478265" y="375"/>
</scene>
</scenes>
</document>

View File

@ -0,0 +1,37 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSPrivacyAccessedAPITypes</key>
<array>
<dict>
<key>NSPrivacyAccessedAPIType</key>
<string>NSPrivacyAccessedAPICategoryFileTimestamp</string>
<key>NSPrivacyAccessedAPITypeReasons</key>
<array>
<string>C617.1</string>
</array>
</dict>
<dict>
<key>NSPrivacyAccessedAPIType</key>
<string>NSPrivacyAccessedAPICategoryUserDefaults</string>
<key>NSPrivacyAccessedAPITypeReasons</key>
<array>
<string>CA92.1</string>
</array>
</dict>
<dict>
<key>NSPrivacyAccessedAPIType</key>
<string>NSPrivacyAccessedAPICategorySystemBootTime</string>
<key>NSPrivacyAccessedAPITypeReasons</key>
<array>
<string>35F9.1</string>
</array>
</dict>
</array>
<key>NSPrivacyCollectedDataTypes</key>
<array/>
<key>NSPrivacyTracking</key>
<false/>
</dict>
</plist>

3
jest.config.js Normal file
View File

@ -0,0 +1,3 @@
module.exports = {
preset: '@react-native/jest-preset',
};

11
metro.config.js Normal file
View File

@ -0,0 +1,11 @@
const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config');
/**
* Metro configuration
* https://reactnative.dev/docs/metro
*
* @type {import('@react-native/metro-config').MetroConfig}
*/
const config = {};
module.exports = mergeConfig(getDefaultConfig(__dirname), config);

13198
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

52
package.json Normal file
View File

@ -0,0 +1,52 @@
{
"name": "SmartGreenhouseApp",
"version": "0.0.1",
"private": true,
"scripts": {
"android": "react-native run-android",
"ios": "react-native run-ios",
"lint": "eslint .",
"start": "react-native start",
"test": "jest"
},
"dependencies": {
"@react-native-community/datetimepicker": "^9.1.0",
"@react-native-community/netinfo": "^12.0.1",
"@react-native/new-app-screen": "0.85.1",
"@react-navigation/native": "^7.2.2",
"@react-navigation/native-stack": "^7.14.11",
"mqtt": "^5.15.1",
"react": "19.2.3",
"react-native": "0.85.1",
"react-native-chart-kit": "^6.12.0",
"react-native-gesture-handler": "^2.31.1",
"react-native-safe-area-context": "^5.7.0",
"react-native-screens": "^4.24.0",
"react-native-svg": "^15.15.4"
},
"devDependencies": {
"@babel/core": "^7.25.2",
"@babel/preset-env": "^7.25.3",
"@babel/runtime": "^7.25.0",
"@react-native-community/cli": "20.1.0",
"@react-native-community/cli-platform-android": "20.1.0",
"@react-native-community/cli-platform-ios": "20.1.0",
"@react-native/babel-preset": "0.85.1",
"@react-native/eslint-config": "0.85.1",
"@react-native/jest-preset": "0.85.1",
"@react-native/metro-config": "0.85.1",
"@react-native/typescript-config": "0.85.1",
"@types/jest": "^29.5.13",
"@types/react": "^19.2.0",
"@types/react-test-renderer": "^19.1.0",
"babel-plugin-module-resolver": "^5.0.3",
"eslint": "^8.19.0",
"jest": "^29.6.3",
"prettier": "2.8.8",
"react-test-renderer": "19.2.3",
"typescript": "^5.9.3"
},
"engines": {
"node": ">= 22.11.0"
}
}

View File

@ -0,0 +1,51 @@
import React from 'react';
import {View, Text, TouchableOpacity, StyleSheet} from 'react-native';
import RouteName from '../Constants/RouteName.constants';
const tabs = [
{label: 'Beranda', icon: '🏠', route: RouteName.DashboardNavigation},
{label: 'Kontrol', icon: '⚙️', route: RouteName.KontrolNavigation},
{label: 'Laporan', icon: '📊', route: RouteName.LaporanNavigation},
{label: 'Notifikasi', icon: '🔔', route: RouteName.NotifikasiNavigation},
];
const BottomNav = ({active, navigation}: {active: string; navigation: any}) => {
return (
<View style={styles.container}>
{tabs.map(tab => (
<TouchableOpacity
key={tab.label}
style={styles.tab}
onPress={() => navigation.navigate(tab.route as never)}>
<Text style={styles.icon}>{tab.icon}</Text>
<Text style={[styles.label, active === tab.label && styles.activeLabel]}>
{tab.label}
</Text>
{active === tab.label && <View style={styles.activeDot} />}
</TouchableOpacity>
))}
</View>
);
};
const styles = StyleSheet.create({
container: {
flexDirection: 'row',
backgroundColor: '#1A3A28',
paddingVertical: 10,
paddingHorizontal: 8,
borderTopWidth: 1,
borderTopColor: '#2D5A3D',
position: 'absolute',
bottom: 0,
left: 0,
right: 0,
},
tab: {alignItems: 'center', flex: 1},
icon: {fontSize: 20},
label: {fontSize: 10, color: '#6B9E7A', marginTop: 2},
activeLabel: {color: '#4ADE80', fontWeight: '700'},
activeDot: {width: 4, height: 4, borderRadius: 2, backgroundColor: '#4ADE80', marginTop: 2},
});
export default BottomNav;

View File

@ -0,0 +1,9 @@
const RouteName = {
LoginNavigation: 'LoginNavigation',
DashboardNavigation: 'DashboardNavigation',
KontrolNavigation: 'KontrolNavigation',
LaporanNavigation: 'LaporanNavigation',
NotifikasiNavigation: 'NotifikasiNavigation',
} as const;
export default RouteName;

View File

@ -0,0 +1,8 @@
import RouteName from './RouteName.constants';
export type RootStackParamList = {
[RouteName.LoginNavigation]: undefined;
[RouteName.DashboardNavigation]: undefined;
[RouteName.KontrolNavigation]: undefined;
[RouteName.LaporanNavigation]: undefined;
[RouteName.NotifikasiNavigation]: undefined;
};

View File

@ -0,0 +1,3 @@
const API_BASE_URL = 'http://202.10.40.129:3000/api';
export default API_BASE_URL;

View File

@ -0,0 +1,103 @@
import React from 'react';
import {
ActivityIndicator,
KeyboardAvoidingView,
Platform,
Pressable,
ScrollView,
Text,
TextInput,
View,
} from 'react-native';
import styles from './styles';
import useLogin from './useLogin';
const LoginScreen: React.FC = () => {
const {
email,
setEmail,
password,
setPassword,
showPassword,
toggleShowPassword,
loading,
onLogin,
} = useLogin();
return (
<KeyboardAvoidingView
style={styles.container}
behavior={Platform.OS === 'ios' ? 'padding' : undefined}
>
<ScrollView
contentContainerStyle={styles.content}
keyboardShouldPersistTaps="handled"
>
{/* Logo */}
<View style={styles.logoContainer}>
<Text style={styles.logoIcon}>🌿</Text>
</View>
{/* Title */}
<Text style={styles.title}>
Smart <Text style={styles.titleGreen}>GreenHouse</Text>
</Text>
<Text style={styles.subtitle}>Sistem Otomatisasi Greenhouse</Text>
<Text style={styles.company}>PT AGROFILIA PERMATA</Text>
{/* Form */}
<View style={styles.formContainer}>
<Text style={styles.label}>USERNAME</Text>
<View style={styles.inputRow}>
<Text style={styles.inputIcon}>👤</Text>
<TextInput
value={email}
onChangeText={(text) => setEmail(text)}
placeholder="Email"
placeholderTextColor="#6B9E7A"
keyboardType="email-address"
autoCapitalize="none"
autoCorrect={false}
style={styles.inputField}
/>
</View>
<Text style={styles.label}>PASSWORD</Text>
<View style={styles.inputRow}>
<Text style={styles.inputIcon}>🔒</Text>
<TextInput
value={password}
onChangeText={(text) => setPassword(text)}
placeholder="Password"
placeholderTextColor="#6B9E7A"
secureTextEntry={!showPassword}
autoCapitalize="none"
autoCorrect={false}
style={styles.inputField}
/>
<Pressable onPress={toggleShowPassword}>
<Text style={styles.toggleText}>
{showPassword ? 'Hide' : 'Show'}
</Text>
</Pressable>
</View>
<Pressable
style={[styles.button, loading ? styles.buttonDisabled : null]}
onPress={onLogin}
disabled={loading}
>
{loading ? (
<ActivityIndicator color="#FFFFFF" />
) : (
<Text style={styles.buttonText}>Masuk ke Dashboard</Text>
)}
</Pressable>
</View>
</ScrollView>
</KeyboardAvoidingView>
);
};
export default LoginScreen;

View File

@ -0,0 +1,118 @@
import {StyleSheet} from 'react-native';
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#0D2818',
},
content: {
flexGrow: 1,
justifyContent: 'center',
paddingHorizontal: 28,
paddingVertical: 40,
alignItems: 'center',
},
logoContainer: {
width: 80,
height: 80,
borderRadius: 20,
backgroundColor: '#1A4D2E',
alignItems: 'center',
justifyContent: 'center',
marginBottom: 20,
},
logoIcon: {
fontSize: 40,
},
title: {
fontSize: 28,
fontWeight: '700',
color: '#FFFFFF',
marginBottom: 6,
},
titleGreen: {
color: '#4ADE80',
},
subtitle: {
fontSize: 13,
color: '#A3C4A8',
marginBottom: 4,
},
company: {
fontSize: 12,
color: '#4ADE80',
fontWeight: '700',
marginBottom: 32,
letterSpacing: 1,
},
formContainer: {
width: '100%',
backgroundColor: '#1A3A28',
borderRadius: 16,
padding: 20,
marginBottom: 24,
},
label: {
fontSize: 11,
fontWeight: '700',
color: '#A3C4A8',
letterSpacing: 1.5,
marginBottom: 8,
marginTop: 4,
},
inputRow: {
flexDirection: 'row',
alignItems: 'center',
backgroundColor: '#0D2818',
borderRadius: 10,
paddingHorizontal: 14,
height: 50,
marginBottom: 16,
},
inputIcon: {
fontSize: 16,
marginRight: 10,
},
inputField: {
flex: 1,
fontSize: 15,
color: '#FFFFFF',
},
toggleText: {
fontSize: 13,
fontWeight: '600',
color: '#4ADE80',
marginLeft: 8,
},
button: {
height: 52,
borderRadius: 12,
backgroundColor: '#22C55E',
alignItems: 'center',
justifyContent: 'center',
marginTop: 8,
},
buttonDisabled: {
opacity: 0.7,
},
buttonText: {
color: '#FFFFFF',
fontSize: 16,
fontWeight: '700',
},
footerRow: {
flexDirection: 'row',
justifyContent: 'center',
},
footerText: {
fontSize: 13,
color: '#A3C4A8',
},
footerLink: {
fontSize: 13,
color: '#4ADE80',
fontWeight: '700',
},
});
export default styles;

View File

@ -0,0 +1,60 @@
import {useState} from 'react';
import {Alert} from 'react-native';
import {useNavigation} from '@react-navigation/native';
import {NativeStackNavigationProp} from '@react-navigation/native-stack';
import RouteName from '../../../Constants/RouteName.constants';
import {RootStackParamList} from '../../../Constants/RouteParamsList.constants';
import {loginService} from '../../../Services/auth.service';
type LoginNavProp = NativeStackNavigationProp<RootStackParamList>;
const useLogin = () => {
const navigation = useNavigation<LoginNavProp>();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [showPassword, setShowPassword] = useState(false);
const [loading, setLoading] = useState(false);
const toggleShowPassword = () => setShowPassword(prev => !prev);
const onLogin = async () => {
if (!email.trim()) {
Alert.alert('Validasi', 'Email wajib diisi');
return;
}
if (!password.trim()) {
Alert.alert('Validasi', 'Password wajib diisi');
return;
}
setLoading(true);
try {
const result = await loginService(email, password);
if (result.success) {
navigation.replace(RouteName.DashboardNavigation);
} else {
Alert.alert('Gagal', result.message || 'Email atau password salah');
}
} catch (error) {
Alert.alert('Error', 'Tidak dapat terhubung ke server');
} finally {
setLoading(false);
}
};
return {
email,
setEmail,
password,
setPassword,
showPassword,
toggleShowPassword,
loading,
onLogin,
};
};
export default useLogin;

View File

@ -0,0 +1,258 @@
import React from 'react';
import {
ScrollView,
View,
Text,
StyleSheet,
StatusBar,
SafeAreaView,
ActivityIndicator,
TouchableOpacity,
} from 'react-native';
import {useNavigation} from '@react-navigation/native';
import {NativeStackNavigationProp} from '@react-navigation/native-stack';
import {RootStackParamList} from '../../../Constants/RouteParamsList.constants';
import BottomNav from '../../../Components/BottomNav';
import useDashboard from './useDashboard';
type NavProp = NativeStackNavigationProp<RootStackParamList>;
const fmt = (val: any, dec = 1): string => {
if (val === null || val === undefined) return '-';
const num = parseFloat(val);
return isNaN(num) ? '-' : num.toFixed(dec);
};
const DashboardScreen: React.FC = () => {
const navigation = useNavigation<NavProp>();
const {data, loading, error, lastUpdate, refreshing, refetch} = useDashboard();
const soil1 = [
['SUHU TANAH', data ? `${fmt(data.suhu_soil)}°C` : '-'],
['KELEMBABAN', data ? `${fmt(data.lembab_soil)}%` : '-'],
['CONDUCTIVITY', data ? `${fmt(data.conductivity)} mS/cm` : '-'],
['PH TANAH', data ? `${fmt(data.ph)}` : '-'],
['NITROGEN (N)', data ? `${fmt(data.n, 0)} mg/kg` : '-'],
['PHOSPHORUS (P)', data ? `${fmt(data.p, 0)} mg/kg` : '-'],
['KALIUM (K)', data ? `${fmt(data.k, 0)} mg/kg` : '-'],
];
const soil2 = [
['SUHU TANAH', data ? `${fmt(data.suhu_soil2)}°C` : '-'],
['KELEMBABAN', data ? `${fmt(data.lembab_soil2)}%` : '-'],
['CONDUCTIVITY', data ? `${fmt(data.conductivity2)} mS/cm` : '-'],
['PH TANAH', data ? `${fmt(data.ph2)}` : '-'],
['NITROGEN (N)', data ? `${fmt(data.n2, 0)} mg/kg` : '-'],
['PHOSPHORUS (P)', data ? `${fmt(data.p2, 0)} mg/kg` : '-'],
['KALIUM (K)', data ? `${fmt(data.k2, 0)} mg/kg` : '-'],
];
const soilSensors = [
{title: '🌱 Soil Sensor 1 (Blok A)', data: soil1},
{title: '🌱 Soil Sensor 2 (Blok B)', data: soil2},
];
return (
<SafeAreaView style={styles.container}>
<StatusBar barStyle="light-content" backgroundColor="#071A12" />
<ScrollView
contentContainerStyle={styles.scroll}
showsVerticalScrollIndicator={false}>
{/* HEADER */}
<View style={styles.headerRow}>
<Text style={styles.headerTitle}>Dashboard Utama</Text>
<TouchableOpacity
onPress={refetch}
style={[styles.refreshBtn, refreshing && styles.refreshBtnDisabled]}
disabled={refreshing}>
<Text style={styles.refreshText}>
{refreshing ? '⏳ Loading...' : '↻ Refresh'}
</Text>
</TouchableOpacity>
</View>
<Text style={styles.lastUpdate}>Update terakhir: {lastUpdate}</Text>
{/* LOADING */}
{loading && (
<ActivityIndicator color="#4ADE80" style={{marginVertical: 20}} />
)}
{/* ERROR */}
{!!error && !loading && (
<View style={styles.errorCard}>
<Text style={styles.errorText}> {error}</Text>
<TouchableOpacity onPress={refetch} style={styles.retryBtn}>
<Text style={styles.retryText}>Coba Lagi</Text>
</TouchableOpacity>
</View>
)}
{/* EMPTY STATE */}
{!loading && !error && !data && (
<View style={styles.emptyCard}>
<Text style={styles.emptyIcon}>📡</Text>
<Text style={styles.emptyTitle}>Belum Ada Data</Text>
<Text style={styles.emptyDesc}>
Menunggu data dari sensor. Pastikan perangkat IoT sudah aktif dan terhubung.
</Text>
<TouchableOpacity onPress={refetch} style={styles.retryBtn}>
<Text style={styles.retryText}>Refresh</Text>
</TouchableOpacity>
</View>
)}
{/* INFO GREENHOUSE */}
<View style={styles.infoCard}>
<View style={styles.statusRow}>
<View style={[styles.statusDot, {backgroundColor: error ? '#EF4444' : '#4ADE80'}]} />
<Text style={[styles.statusText, {color: error ? '#EF4444' : '#4ADE80'}]}>
{error ? 'Koneksi Terputus' : data ? 'Sistem Aktif' : 'Menunggu Data'}
</Text>
</View>
<Text style={styles.greenhouseName}>Greenhouse Vanili Blok A</Text>
<Text style={styles.greenhouseDesc}>
Semua sensor terhubung via RS485. Mode otomatis aktif.
</Text>
<View style={styles.statsRow}>
<View style={styles.statItem}>
<Text style={styles.statValue}>4/4</Text>
<Text style={styles.statLabel}>Sensor OK</Text>
</View>
<View style={styles.statItem}>
<Text style={styles.statValue}>3/3</Text>
<Text style={styles.statLabel}>Aktuator</Text>
</View>
<View style={styles.statItem}>
<Text style={styles.statValue}>2.4k</Text>
<Text style={styles.statLabel}>Data/Jam</Text>
</View>
</View>
</View>
{/* SOIL SENSOR 1 & 2 */}
{soilSensors.map((sensor, idx) => (
<View key={idx} style={styles.card}>
<View style={styles.cardHeader}>
<Text style={styles.cardTitle}>{sensor.title}</Text>
<View style={[styles.liveBadge, {backgroundColor: data ? '#143524' : '#2D2D2D'}]}>
<Text style={[styles.liveText, {color: data ? '#4ADE80' : '#6B7280'}]}>
{data ? 'LIVE' : 'OFFLINE'}
</Text>
</View>
</View>
<View style={styles.grid}>
{sensor.data.slice(0, 6).map((item, index) => (
<View key={index} style={styles.box}>
<Text style={styles.label}>{item[0]}</Text>
<Text style={styles.value}>{item[1]}</Text>
</View>
))}
<View style={[styles.box, {width: '100%'}]}>
<Text style={styles.label}>{sensor.data[6][0]}</Text>
<Text style={styles.value}>{sensor.data[6][1]}</Text>
</View>
</View>
</View>
))}
{/* LIGHT SENSOR */}
<View style={styles.card}>
<View style={styles.cardHeader}>
<Text style={styles.cardTitle}> Light Sensor RS-485</Text>
<View style={[styles.liveBadge, {backgroundColor: data ? '#143524' : '#2D2D2D'}]}>
<Text style={[styles.liveText, {color: data ? '#4ADE80' : '#6B7280'}]}>
{data ? 'LIVE' : 'OFFLINE'}
</Text>
</View>
</View>
<View style={styles.grid}>
{[
['SUHU UDARA', data ? `${fmt(data.suhu_light)}°C` : '-'],
['KELEMBABAN', data ? `${fmt(data.lembab_light)}%` : '-'],
['CAHAYA', data ? `${fmt(data.intensitas, 0)} lux` : '-'],
].map((item, index) => (
<View key={index} style={styles.box}>
<Text style={styles.label}>{item[0]}</Text>
<Text style={styles.value}>{item[1]}</Text>
</View>
))}
</View>
</View>
{/* ULTRASONIC */}
<View style={styles.card}>
<View style={styles.cardHeader}>
<Text style={styles.cardTitle}>💧 Ultrasonic RS-485</Text>
<View style={[styles.liveBadge, {backgroundColor: data ? '#143524' : '#2D2D2D'}]}>
<Text style={[styles.liveText, {color: data ? '#4ADE80' : '#6B7280'}]}>
{data ? 'LIVE' : 'OFFLINE'}
</Text>
</View>
</View>
<View style={styles.row}>
<View>
<Text style={styles.label}>LEVEL</Text>
<Text style={styles.valueBig}>
{data ? `${fmt(data.jarak)}%` : '-'}
</Text>
</View>
<View>
<Text style={styles.label}>TINGGI AIR</Text>
<Text style={styles.valueBig}>
{data ? `${fmt(parseFloat(fmt(data.jarak)) / 100, 2)} m` : '-'}
</Text>
</View>
</View>
</View>
</ScrollView>
<BottomNav active="Beranda" navigation={navigation} />
</SafeAreaView>
);
};
export default DashboardScreen;
const styles = StyleSheet.create({
container: {flex: 1, backgroundColor: '#03170F'},
scroll: {padding: 16, paddingBottom: 120},
headerRow: {flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: 4},
headerTitle: {fontSize: 22, fontWeight: '700', color: '#FFFFFF'},
refreshBtn: {backgroundColor: '#143524', paddingHorizontal: 12, paddingVertical: 6, borderRadius: 20},
refreshBtnDisabled: {opacity: 0.5},
refreshText: {color: '#4ADE80', fontSize: 12, fontWeight: '600'},
lastUpdate: {fontSize: 11, color: '#8ECFAE', marginBottom: 16},
errorCard: {backgroundColor: '#3B1C1C', borderRadius: 12, padding: 14, marginBottom: 16, borderWidth: 1, borderColor: '#7F1D1D'},
errorText: {color: '#FCA5A5', fontSize: 13, marginBottom: 10},
emptyCard: {backgroundColor: '#0F2A1D', borderRadius: 16, padding: 24, marginBottom: 16, alignItems: 'center', borderWidth: 1, borderColor: '#1F3D2B'},
emptyIcon: {fontSize: 40, marginBottom: 12},
emptyTitle: {fontSize: 16, fontWeight: '700', color: '#FFFFFF', marginBottom: 6},
emptyDesc: {fontSize: 13, color: '#8ECFAE', textAlign: 'center', lineHeight: 20, marginBottom: 16},
retryBtn: {backgroundColor: '#143524', paddingHorizontal: 20, paddingVertical: 10, borderRadius: 20, borderWidth: 1, borderColor: '#2D5A3D'},
retryText: {color: '#4ADE80', fontWeight: '700', fontSize: 13},
infoCard: {backgroundColor: '#0F2A1D', borderRadius: 20, padding: 16, marginBottom: 20, borderWidth: 1, borderColor: '#1F3D2B'},
statusRow: {flexDirection: 'row', alignItems: 'center', marginBottom: 6},
statusDot: {width: 8, height: 8, borderRadius: 4, marginRight: 6},
statusText: {fontSize: 12, fontWeight: '600'},
greenhouseName: {color: '#FFFFFF', fontSize: 16, fontWeight: '700', marginBottom: 4},
greenhouseDesc: {color: '#9ED8B5', fontSize: 12, marginBottom: 14},
statsRow: {flexDirection: 'row', justifyContent: 'space-between'},
statItem: {alignItems: 'center', backgroundColor: '#143524', paddingVertical: 10, paddingHorizontal: 14, borderRadius: 12, minWidth: 70},
statValue: {color: '#FFFFFF', fontWeight: '700', fontSize: 16},
statLabel: {color: '#8ECFAE', fontSize: 10},
card: {backgroundColor: '#0F2A1D', borderRadius: 20, padding: 16, marginBottom: 16, borderWidth: 1, borderColor: '#1F3D2B'},
cardHeader: {flexDirection: 'row', justifyContent: 'space-between', marginBottom: 14},
cardTitle: {color: '#FFFFFF', fontSize: 16, fontWeight: '700'},
liveBadge: {paddingHorizontal: 10, paddingVertical: 4, borderRadius: 20},
liveText: {fontSize: 10, fontWeight: '700'},
grid: {flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'space-between'},
box: {width: '48%', backgroundColor: '#143524', borderRadius: 16, padding: 12, marginBottom: 10, borderWidth: 1, borderColor: '#1F3D2B'},
row: {flexDirection: 'row', justifyContent: 'space-between'},
label: {color: '#8ECFAE', fontSize: 11, marginBottom: 4},
value: {color: '#FFFFFF', fontSize: 18, fontWeight: '700'},
valueBig: {color: '#FFFFFF', fontSize: 20, fontWeight: '700'},
});

View File

@ -0,0 +1,117 @@
import {useState, useEffect, useCallback} from 'react';
import API_BASE_URL from '../../../Constants/api.constans';
let globalData: any = null;
let globalLastUpdate = '-';
type Listener = (data: any) => void;
const listeners = new Set<Listener>();
const notifyListeners = (data: any) => {
listeners.forEach(fn => fn(data));
};
const formatTime = (dateString: string) => {
if (!dateString) return '-';
const createdAt = new Date(dateString);
if (Number.isNaN(createdAt.getTime())) return '-';
return `${createdAt.getHours().toString().padStart(2, '0')}:${createdAt
.getMinutes()
.toString()
.padStart(2, '0')}`;
};
const fetchLatestFromDB = async () => {
try {
const response = await fetch(`${API_BASE_URL}/get-data`);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const json = await response.json();
if (!Array.isArray(json) || json.length === 0) {
return null;
}
const latest = json[json.length - 1];
globalData = latest;
globalLastUpdate = formatTime(latest.created_at);
notifyListeners(globalData);
return latest;
} catch (err: any) {
console.error('❌ Fetch DB error:', err?.message || err);
return null;
}
};
const useDashboard = () => {
const [data, setData] = useState<any>(globalData);
const [lastUpdate, setLastUpdate] = useState(globalLastUpdate);
const [refreshing, setRefreshing] = useState(false);
const [loading, setLoading] = useState(!globalData);
const [error, setError] = useState<string | null>(null);
const loadData = useCallback(async () => {
setError(null);
const result = await fetchLatestFromDB();
if (!result) {
setError('Data sensor belum tersedia');
}
setLoading(false);
}, []);
useEffect(() => {
const listener: Listener = newData => {
setData(newData ? {...newData} : null);
setLastUpdate(globalLastUpdate);
};
listeners.add(listener);
if (globalData) {
setData({...globalData});
setLastUpdate(globalLastUpdate);
setLoading(false);
} else {
loadData();
}
const pollingInterval = setInterval(() => {
fetchLatestFromDB();
}, 5000);
return () => {
listeners.delete(listener);
clearInterval(pollingInterval);
};
}, [loadData]);
const refetch = async () => {
setRefreshing(true);
await loadData();
setRefreshing(false);
};
return {
data,
connected: !!data,
loading,
error,
lastUpdate,
refreshing,
refetch,
};
};
export default useDashboard;

View File

@ -0,0 +1,351 @@
import React, {useState, useRef, useEffect, useCallback} from 'react';
import {
View, Text, StyleSheet, SafeAreaView, StatusBar,
ScrollView, Switch, TextInput, Alert, ActivityIndicator,
} from 'react-native';
import {useNavigation, useFocusEffect} from '@react-navigation/native';
import {NativeStackNavigationProp} from '@react-navigation/native-stack';
import {RootStackParamList} from '../../../Constants/RouteParamsList.constants';
import BottomNav from '../../../Components/BottomNav';
import API_BASE_URL from '../../../Constants/api.constans';
type NavProp = NativeStackNavigationProp<RootStackParamList>;
interface AktuatorState {
active: boolean;
duration: string;
remaining: number;
}
interface Aktuator {
key: string;
jenis: string;
icon: string;
label: string;
desc: string;
}
const aktuatorList: Aktuator[] = [
{key: 'pompa_tanah', jenis: 'tanah', icon: '💧', label: 'Pemupukan Tanah', desc: 'Penyiraman pupuk ke area akar/tanah'},
{key: 'pompa_daun', jenis: 'daun', icon: '🌿', label: 'Pemupukan Daun', desc: 'Penyiraman pupuk ke area daun & batang'},
];
const initialStates: Record<string, AktuatorState> = {
pompa_tanah: {active: false, duration: '5', remaining: 0},
pompa_daun: {active: false, duration: '5', remaining: 0},
};
const KontrolScreen: React.FC = () => {
const navigation = useNavigation<NavProp>();
const [states, setStates] = useState<Record<string, AktuatorState>>(initialStates);
const [loadingStatus, setLoadingStatus] = useState(true);
const intervalsRef = useRef<Record<string, ReturnType<typeof setInterval> | null>>({});
// Fetch status dari backend setiap kali halaman difokus
useFocusEffect(
useCallback(() => {
fetchStatus();
}, [])
);
const fetchStatus = async () => {
try {
setLoadingStatus(true);
const response = await fetch(`${API_BASE_URL}/kontrol/status`);
const result = await response.json();
if (result.success) {
const newStates = {...initialStates};
result.data.forEach((row: any) => {
if (newStates[row.aktuator] !== undefined) {
let remaining = 0;
if (row.status === 1 && row.started_at && row.durasi > 0) {
// Hitung sisa waktu berdasarkan started_at dan durasi
const startedAt = new Date(row.started_at).getTime();
const now = new Date().getTime();
const elapsed = Math.floor((now - startedAt) / 1000);
remaining = Math.max(row.durasi - elapsed, 0);
}
newStates[row.aktuator] = {
active: row.status === 1 && remaining > 0,
duration: row.durasi > 0 ? String(Math.ceil(row.durasi / 60)) : '5',
remaining,
};
// Kalau masih aktif, jalankan timer
if (newStates[row.aktuator].active && remaining > 0) {
if (intervalsRef.current[row.aktuator]) {
clearInterval(intervalsRef.current[row.aktuator]!);
}
const key = row.aktuator;
const jenis = key === 'pompa_tanah' ? 'tanah' : 'daun';
const interval = setInterval(() => {
setStates(prev => {
const rem = prev[key].remaining - 1;
if (rem <= 0) {
if (intervalsRef.current[key]) {
clearInterval(intervalsRef.current[key]!);
intervalsRef.current[key] = null;
}
sendKontrol(jenis, 'done');
return {...prev, [key]: {...prev[key], active: false, remaining: 0}};
}
return {...prev, [key]: {...prev[key], remaining: rem}};
});
}, 1000);
intervalsRef.current[row.aktuator] = interval;
}
}
});
setStates(newStates);
}
} catch (error) {
console.error('Fetch status error:', error);
} finally {
setLoadingStatus(false);
}
};
useEffect(() => {
return () => {
Object.values(intervalsRef.current).forEach(interval => {
if (interval) clearInterval(interval);
});
};
}, []);
const sendKontrol = async (jenis: string, action: string, duration?: number) => {
try {
const response = await fetch(`${API_BASE_URL}/kontrol/pupuk`, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({jenis, action, duration}),
});
const result = await response.json();
console.log('Kontrol:', result.message);
} catch (error) {
console.error('KONTROL ERROR:', error);
}
};
const toggleAktuator = (key: string, jenis: string) => {
const current = states[key];
if (current.active) {
if (intervalsRef.current[key]) {
clearInterval(intervalsRef.current[key]!);
intervalsRef.current[key] = null;
}
setStates(prev => ({...prev, [key]: {...prev[key], active: false, remaining: 0}}));
sendKontrol(jenis, 'stop');
} else {
const dur = parseInt(current.duration);
if (isNaN(dur) || dur <= 0) {
Alert.alert('Validasi', 'Masukkan durasi yang valid (menit)');
return;
}
const durSec = dur * 60;
setStates(prev => ({...prev, [key]: {...prev[key], active: true, remaining: durSec}}));
sendKontrol(jenis, 'start', durSec);
const interval = setInterval(() => {
setStates(prev => {
const rem = prev[key].remaining - 1;
if (rem <= 0) {
if (intervalsRef.current[key]) {
clearInterval(intervalsRef.current[key]!);
intervalsRef.current[key] = null;
}
sendKontrol(jenis, 'done');
return {...prev, [key]: {...prev[key], active: false, remaining: 0}};
}
return {...prev, [key]: {...prev[key], remaining: rem}};
});
}, 1000);
intervalsRef.current[key] = interval;
}
};
const formatTime = (seconds: number) => {
const m = Math.floor(seconds / 60);
const s = seconds % 60;
return `${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;
};
const activeCount = Object.values(states).filter(s => s.active).length;
if (loadingStatus) {
return (
<SafeAreaView style={styles.container}>
<ActivityIndicator color="#4ADE80" style={{flex: 1}} />
<BottomNav active="Kontrol" navigation={navigation} />
</SafeAreaView>
);
}
return (
<SafeAreaView style={styles.container}>
<StatusBar barStyle="light-content" backgroundColor="#0D2818" />
<ScrollView contentContainerStyle={styles.scroll}>
<Text style={styles.pageTitle}>Kontrol Pemupukan</Text>
{/* Status Bar */}
<View style={styles.statusCard}>
<View style={styles.statusLeft}>
<View style={[styles.statusDot, {backgroundColor: activeCount > 0 ? '#4ADE80' : '#6B7280'}]} />
<Text style={styles.statusText}>
{activeCount > 0 ? `${activeCount} pompa aktif` : 'Semua pompa OFF'}
</Text>
</View>
<Text style={styles.statusMode}>Mode Manual</Text>
</View>
{/* Info */}
<View style={styles.infoCard}>
<Text style={styles.infoText}>
💡 Set durasi pemupukan lalu aktifkan pompa. Pompa akan mati otomatis setelah waktu habis.
</Text>
</View>
{/* Aktuator Cards */}
{aktuatorList.map(item => {
const state = states[item.key];
if (!state) return null;
const progressPct = state.active
? (state.remaining / (parseInt(state.duration) * 60)) * 100
: 0;
return (
<View key={item.key} style={[styles.card, state.active && styles.cardActive]}>
<View style={styles.cardTop}>
<View style={styles.cardLeft}>
<Text style={styles.cardIcon}>{item.icon}</Text>
<View>
<Text style={styles.cardLabel}>{item.label}</Text>
<Text style={styles.cardDesc}>{item.desc}</Text>
</View>
</View>
<View style={styles.cardRight}>
<Text style={[styles.statusLabel, {color: state.active ? '#4ADE80' : '#6B7280'}]}>
{state.active ? 'ON' : 'OFF'}
</Text>
<Switch
value={state.active}
onValueChange={() => toggleAktuator(item.key, item.jenis)}
trackColor={{false: '#2D5A3D', true: '#4ADE80'}}
thumbColor={state.active ? '#FFFFFF' : '#9CA3AF'}
/>
</View>
</View>
<View style={styles.cardBottom}>
<View style={styles.durationRow}>
<Text style={styles.durationLabel}>Durasi (menit):</Text>
<TextInput
style={styles.durationInput}
value={state.duration}
onChangeText={val =>
setStates(prev => ({...prev, [item.key]: {...prev[item.key], duration: val}}))
}
keyboardType="numeric"
editable={!state.active}
placeholderTextColor="#6B9E7A"
/>
</View>
{state.active && (
<View style={styles.timerRow}>
<Text style={styles.timerLabel}>Sisa waktu:</Text>
<Text style={styles.timerValue}>{formatTime(state.remaining)}</Text>
</View>
)}
</View>
{state.active && (
<View style={styles.progressBg}>
<View style={[styles.progressFill, {width: `${progressPct}%`}]} />
</View>
)}
<View style={styles.mqttRow}>
<View style={[styles.mqttDot, {backgroundColor: state.active ? '#4ADE80' : '#2D5A3D'}]} />
<Text style={styles.mqttText}>
{state.active ? 'Perintah terkirim ke ESP32 via MQTT' : 'Topic: iot/kontrol/manual'}
</Text>
</View>
</View>
);
})}
{/* Info Otomasi */}
<View style={styles.autoCard}>
<Text style={styles.autoTitle}> Sistem Otomasi Aktif</Text>
<Text style={styles.autoDesc}>Perangkat berikut dikelola otomatis oleh sistem:</Text>
{[
'🌀 Kipas — kontrol suhu otomatis',
'🌫️ Spray Kabut — kontrol kelembaban',
'🔧 Valve Tandon — pengisian air otomatis',
'💧 Penyiraman Tanah — jadwal otomatis',
'💧 Penyiraman Daun — jadwal otomatis',
].map((item, index) => (
<View key={index} style={styles.autoItem}>
<Text style={styles.autoItemText}>{item}</Text>
</View>
))}
</View>
</ScrollView>
<BottomNav active="Kontrol" navigation={navigation} />
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {flex: 1, backgroundColor: '#0D2818'},
scroll: {paddingHorizontal: 16, paddingTop: 16, paddingBottom: 100},
pageTitle: {fontSize: 22, fontWeight: '700', color: '#FFFFFF', marginBottom: 12},
statusCard: {flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', backgroundColor: '#1A3A28', borderRadius: 12, padding: 12, marginBottom: 12, borderWidth: 1, borderColor: '#2D5A3D'},
statusLeft: {flexDirection: 'row', alignItems: 'center', gap: 8},
statusDot: {width: 8, height: 8, borderRadius: 4},
statusText: {fontSize: 13, color: '#FFFFFF', fontWeight: '600'},
statusMode: {fontSize: 11, color: '#4ADE80', fontWeight: '700', backgroundColor: '#0D3320', paddingHorizontal: 10, paddingVertical: 4, borderRadius: 20},
infoCard: {backgroundColor: '#1A3A28', borderRadius: 12, padding: 12, marginBottom: 16, borderLeftWidth: 3, borderLeftColor: '#4ADE80'},
infoText: {fontSize: 12, color: '#A3C4A8', lineHeight: 18},
card: {backgroundColor: '#1A3A28', borderRadius: 14, padding: 14, marginBottom: 12, borderWidth: 1, borderColor: '#2D5A3D'},
cardActive: {borderColor: '#4ADE80'},
cardTop: {flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12},
cardLeft: {flexDirection: 'row', alignItems: 'center', flex: 1, gap: 12},
cardIcon: {fontSize: 28},
cardLabel: {fontSize: 15, fontWeight: '700', color: '#FFFFFF'},
cardDesc: {fontSize: 11, color: '#A3C4A8', marginTop: 2},
cardRight: {alignItems: 'center'},
statusLabel: {fontSize: 11, fontWeight: '700', marginBottom: 4},
cardBottom: {borderTopWidth: 1, borderTopColor: '#2D5A3D', paddingTop: 10},
durationRow: {flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between'},
durationLabel: {fontSize: 12, color: '#A3C4A8'},
durationInput: {backgroundColor: '#0D2818', borderRadius: 8, borderWidth: 1, borderColor: '#2D5A3D', paddingHorizontal: 12, paddingVertical: 6, fontSize: 14, fontWeight: '700', color: '#FFFFFF', width: 70, textAlign: 'center'},
timerRow: {flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', marginTop: 8},
timerLabel: {fontSize: 12, color: '#A3C4A8'},
timerValue: {fontSize: 20, fontWeight: '700', color: '#4ADE80'},
progressBg: {height: 6, backgroundColor: '#0D2818', borderRadius: 3, marginTop: 10, overflow: 'hidden'},
progressFill: {height: 6, backgroundColor: '#4ADE80', borderRadius: 3},
mqttRow: {flexDirection: 'row', alignItems: 'center', gap: 6, marginTop: 10, paddingTop: 8, borderTopWidth: 1, borderTopColor: '#2D5A3D'},
mqttDot: {width: 6, height: 6, borderRadius: 3},
mqttText: {fontSize: 10, color: '#6B9E7A'},
autoCard: {backgroundColor: '#1A3A28', borderRadius: 14, padding: 16, marginTop: 4, borderWidth: 1, borderColor: '#2D5A3D'},
autoTitle: {fontSize: 14, fontWeight: '700', color: '#FFFFFF', marginBottom: 8},
autoDesc: {fontSize: 12, color: '#A3C4A8', marginBottom: 10},
autoItem: {paddingVertical: 6, borderBottomWidth: 0.5, borderBottomColor: '#2D5A3D'},
autoItemText: {fontSize: 12, color: '#6B9E7A'},
});
export default KontrolScreen;

View File

@ -0,0 +1,626 @@
import React, {useMemo, useState} from 'react';
import {
ScrollView,
View,
Text,
StyleSheet,
SafeAreaView,
StatusBar,
TouchableOpacity,
Dimensions,
ActivityIndicator,
Alert,
Modal,
FlatList,
Platform,
} from 'react-native';
import {useNavigation} from '@react-navigation/native';
import {NativeStackNavigationProp} from '@react-navigation/native-stack';
import {LineChart} from 'react-native-chart-kit';
import DateTimePicker, {DateTimePickerEvent} from '@react-native-community/datetimepicker';
import {RootStackParamList} from '../../../Constants/RouteParamsList.constants';
import BottomNav from '../../../Components/BottomNav';
import {useLaporan} from './useLaporan';
type NavProp = NativeStackNavigationProp<RootStackParamList>;
const screenWidth = Dimensions.get('window').width - 32;
const filters = ['Hari Ini', 'Minggu Ini', 'Bulan Ini'] as const;
type FilterType = (typeof filters)[number];
const sensors = [
{key: 'soil1', label: 'Soil 1', icon: '🌱'},
{key: 'soil2', label: 'Soil 2', icon: '🌱'},
{key: 'light', label: 'Light', icon: '☀️'},
{key: 'ultrasonic', label: 'Water', icon: '🌊'},
] as const;
type SensorKey = (typeof sensors)[number]['key'];
const sensorParams: Record<
SensorKey,
{label: string; unit: string; color: string; key: string}[]
> = {
soil1: [
{label: 'Suhu Tanah 1', unit: '°C', color: '#4ADE80', key: 'suhu_soil'},
{label: 'Kelembaban 1', unit: '%', color: '#60A5FA', key: 'lembab_soil'},
{label: 'Conductivity 1', unit: 'mS/cm', color: '#FBBF24', key: 'conductivity'},
{label: 'pH 1', unit: '', color: '#F97316', key: 'ph'},
{label: 'Nitrogen 1 (N)', unit: 'mg/kg', color: '#A78BFA', key: 'n'},
{label: 'Phosphorus 1 (P)', unit: 'mg/kg', color: '#F472B6', key: 'p'},
{label: 'Kalium 1 (K)', unit: 'mg/kg', color: '#34D399', key: 'k'},
],
soil2: [
{label: 'Suhu Tanah 2', unit: '°C', color: '#4ADE80', key: 'suhu_soil2'},
{label: 'Kelembaban 2', unit: '%', color: '#60A5FA', key: 'lembab_soil2'},
{label: 'Conductivity 2', unit: 'mS/cm', color: '#FBBF24', key: 'conductivity2'},
{label: 'pH 2', unit: '', color: '#F97316', key: 'ph2'},
{label: 'Nitrogen 2 (N)', unit: 'mg/kg', color: '#A78BFA', key: 'n2'},
{label: 'Phosphorus 2 (P)', unit: 'mg/kg', color: '#F472B6', key: 'p2'},
{label: 'Kalium 2 (K)', unit: 'mg/kg', color: '#34D399', key: 'k2'},
],
light: [
{label: 'Suhu Udara', unit: '°C', color: '#4ADE80', key: 'suhu_light'},
{label: 'Kelembaban Udara', unit: '%', color: '#60A5FA', key: 'lembab_light'},
{label: 'Intensitas Cahaya', unit: 'lux', color: '#F97316', key: 'intensitas'},
],
ultrasonic: [
{label: 'Ketinggian Air', unit: 'cm', color: '#818CF8', key: 'jarak'},
],
};
interface ModalData {
label: string;
unit: string;
color: string;
values: number[];
labels: string[];
rawLabels: string[];
}
interface ByDateSensorData {
[key: string]: number[];
}
interface ByDateData {
soil1: ByDateSensorData;
soil2: ByDateSensorData;
light: ByDateSensorData;
ultrasonic: ByDateSensorData;
labels: string[];
rawLabels: string[];
}
const API_BASE_URL = 'http://202.10.40.129:3000/api';
const DAILY_API_URL = `${API_BASE_URL}/sensor/daily`;
const BY_DATE_API_URL = `${API_BASE_URL}/sensor/by-date`;
const API_URL = `${API_BASE_URL}/get-data`;
const safeNumber = (v: any): number => {
const parsed = parseFloat(v);
return v !== null && v !== undefined && isFinite(parsed) && !isNaN(parsed) ? parsed : 0;
};
const formatDateParam = (date: Date): string => {
const y = date.getFullYear();
const m = String(date.getMonth() + 1).padStart(2, '0');
const d = String(date.getDate()).padStart(2, '0');
return `${y}-${m}-${d}`;
};
const formatDateDisplay = (date: Date): string => {
const d = String(date.getDate()).padStart(2, '0');
const m = String(date.getMonth() + 1).padStart(2, '0');
const y = date.getFullYear();
return `${d}-${m}-${y}`;
};
const buildByDateData = (rows: any[]): ByDateData => {
const allKeys = {
soil1: ['suhu_soil','lembab_soil','conductivity','ph','n','p','k'],
soil2: ['suhu_soil2','lembab_soil2','conductivity2','ph2','n2','p2','k2'],
light: ['suhu_light','lembab_light','intensitas'],
ultrasonic: ['jarak'],
};
const result: any = {
soil1: {}, soil2: {}, light: {}, ultrasonic: {},
labels: [],
rawLabels: [],
};
result.rawLabels = rows.map((r: any) => r.waktu ?? '-');
result.labels = rows.map((r: any) => {
const t: string = r.waktu ?? '';
const match = t.match(/(\d{2}:\d{2})/);
return match ? match[1] : t;
});
(Object.keys(allKeys) as SensorKey[]).forEach(sensor => {
allKeys[sensor].forEach((key: string) => {
result[sensor][key] = rows.map((r: any) => safeNumber(r[key]));
});
});
return result as ByDateData;
};
const LaporanScreen: React.FC = () => {
const navigation = useNavigation<NavProp>();
const [activeFilter, setActiveFilter] = useState<FilterType>('Hari Ini');
const [activeSensor, setActiveSensor] = useState<SensorKey>('soil1');
const [modalVisible, setModalVisible] = useState(false);
const [modalData, setModalData] = useState<ModalData | null>(null);
const [modalLoading, setModalLoading] = useState(false);
const [selectedDate, setSelectedDate] = useState<Date | null>(null);
const [showDatePicker, setShowDatePicker] = useState(false);
const [byDateData, setByDateData] = useState<ByDateData | null>(null);
const [byDateLoading, setByDateLoading] = useState(false);
const {loading, error, data, refetch} = useLaporan(API_URL);
const isDateMode = selectedDate !== null;
const displayData = isDateMode ? byDateData : data;
const currentLoading = isDateMode ? byDateLoading : loading;
const currentError = isDateMode ? null : error;
const chartConfig = (color: string) => ({
backgroundGradientFrom: '#1A3A28',
backgroundGradientTo: '#1A3A28',
color: () => color,
labelColor: () => '#A3C4A8',
strokeWidth: 2,
decimalPlaces: 1,
propsForDots: {r: '5', strokeWidth: '1', stroke: color},
propsForBackgroundLines: {stroke: '#2D5A3D', strokeDasharray: ''},
});
const params = sensorParams[activeSensor];
const activeData = useMemo(() => {
if (!displayData) return null;
switch (activeSensor) {
case 'soil1': return displayData.soil1;
case 'soil2': return displayData.soil2;
case 'light': return displayData.light;
case 'ultrasonic': return displayData.ultrasonic;
default: return null;
}
}, [activeSensor, displayData]);
const hasData = useMemo(() => {
if (!displayData || !activeData) return false;
const firstKey = params[0]?.key;
if (!firstKey) return false;
const values = (activeData as Record<string, number[]>)[firstKey];
return Array.isArray(values) && values.length > 0 && values.some(v => v > 0);
}, [displayData, activeData, params]);
const fetchByDate = async (date: Date) => {
setByDateLoading(true);
setByDateData(null);
try {
const response = await fetch(
`${BY_DATE_API_URL}?date=${formatDateParam(date)}`,
{headers: {'Accept': 'application/json'}},
);
const result = await response.json();
if (result.success && result.data && result.data.length > 0) {
setByDateData(buildByDateData(result.data));
} else {
setByDateData(null);
Alert.alert('Info', `Tidak ada data untuk tanggal ${formatDateDisplay(date)}`);
}
} catch {
Alert.alert('Error', 'Gagal mengambil data. Periksa koneksi server.');
} finally {
setByDateLoading(false);
}
};
const onDateChange = (_event: DateTimePickerEvent, date?: Date) => {
if (Platform.OS === 'android') setShowDatePicker(false);
if (!date) return;
setSelectedDate(date);
fetchByDate(date);
};
const resetToRealtime = () => {
setSelectedDate(null);
setByDateData(null);
refetch();
};
const openModal = async (
param: {label: string; unit: string; color: string; key: string},
) => {
setModalVisible(true);
setModalLoading(true);
setModalData(null);
try {
const url = isDateMode && selectedDate
? `${BY_DATE_API_URL}?date=${formatDateParam(selectedDate)}`
: DAILY_API_URL;
const response = await fetch(url, {headers: {'Accept': 'application/json'}});
const result = await response.json();
if (result.success && result.data && result.data.length > 0) {
const rows = result.data;
const values = rows.map((row: any) => safeNumber(row[param.key]));
const labels = rows.map((row: any) => row.waktu ?? '-');
setModalData({label: param.label, unit: param.unit, color: param.color, values, labels, rawLabels: labels});
} else {
Alert.alert('Info', 'Tidak ada data');
setModalVisible(false);
}
} catch {
Alert.alert('Error', 'Gagal mengambil data');
setModalVisible(false);
} finally {
setModalLoading(false);
}
};
return (
<SafeAreaView style={styles.container}>
<StatusBar barStyle="light-content" backgroundColor="#0D2818" />
<ScrollView contentContainerStyle={styles.scroll}>
{/* Header */}
<View style={styles.headerRow}>
<Text style={styles.pageTitle}>Laporan Real-Time</Text>
<TouchableOpacity
style={[styles.datePickerBtn, isDateMode && styles.datePickerBtnActive]}
onPress={() => setShowDatePicker(true)}>
<Text style={styles.datePickerBtnText}>
{isDateMode ? `📅 ${formatDateDisplay(selectedDate!)}` : '📅 Pilih Tanggal'}
</Text>
</TouchableOpacity>
</View>
{/* Banner tanggal aktif */}
{isDateMode && (
<View style={styles.dateBanner}>
<View style={styles.dateBannerLeft}>
<Text style={styles.dateBannerIcon}>📅</Text>
<View>
<Text style={styles.dateBannerLabel}>Menampilkan data tanggal</Text>
<Text style={styles.dateBannerDate}>{formatDateDisplay(selectedDate!)}</Text>
</View>
</View>
<TouchableOpacity style={styles.resetBtn} onPress={resetToRealtime}>
<Text style={styles.resetBtnText}> Reset</Text>
</TouchableOpacity>
</View>
)}
{/* Filter */}
{!isDateMode && (
<View style={styles.filterRow}>
{filters.map(f => (
<TouchableOpacity
key={f}
style={[styles.filterBtn, activeFilter === f && styles.filterBtnActive]}
onPress={() => setActiveFilter(f)}>
<Text style={[styles.filterText, activeFilter === f && styles.filterTextActive]}>
{f}
</Text>
</TouchableOpacity>
))}
</View>
)}
{/* Pilih Sensor */}
<Text style={styles.sectionLabel}>PILIH UNIT SENSOR</Text>
<View style={styles.sensorRow}>
{sensors.map(s => (
<TouchableOpacity
key={s.key}
style={[styles.sensorBtn, activeSensor === s.key && styles.sensorBtnActive]}
onPress={() => setActiveSensor(s.key)}>
<Text style={styles.sensorIcon}>{s.icon}</Text>
<Text style={[styles.sensorLabel, activeSensor === s.key && styles.sensorLabelActive]}>
{s.label}
</Text>
</TouchableOpacity>
))}
</View>
{/* Loading */}
{currentLoading && (
<ActivityIndicator color="#4ADE80" style={{marginVertical: 20}} />
)}
{/* Error */}
{!!currentError && !currentLoading && (
<View style={styles.errorCard}>
<Text style={styles.errorText}> Gagal terhubung ke server</Text>
<Text style={[styles.errorText, {fontSize: 11, marginTop: 4}]}>{currentError}</Text>
<TouchableOpacity style={styles.retryButton} onPress={refetch}>
<Text style={styles.retryText}>Coba Lagi</Text>
</TouchableOpacity>
</View>
)}
{/* Empty State */}
{!currentLoading && !currentError && !hasData && (
<View style={styles.emptyCard}>
<Text style={styles.emptyIcon}>{isDateMode ? '🗓️' : '📡'}</Text>
<Text style={styles.emptyTitle}>
{isDateMode ? 'Tidak Ada Data' : 'Belum Ada Data'}
</Text>
<Text style={styles.emptyDesc}>
{isDateMode
? `Tidak ada data sensor pada tanggal ${formatDateDisplay(selectedDate!)}.`
: 'Belum ada data sensor yang masuk. Pastikan perangkat IoT sudah aktif dan terhubung.'}
</Text>
{!isDateMode && (
<TouchableOpacity style={styles.retryButton} onPress={refetch}>
<Text style={styles.retryText}>Refresh</Text>
</TouchableOpacity>
)}
</View>
)}
{/* Chart */}
{!currentLoading && !currentError && hasData && displayData && activeData &&
params.map(param => {
const rawValues = (activeData as Record<string, any>)[param.key];
const chartValues = Array.isArray(rawValues) && rawValues.length > 0
? rawValues.map((v: any) => safeNumber(v))
: [0];
const hasRealData = chartValues.some(v => v > 0) || chartValues.length > 1;
const avg = (chartValues.reduce((a: number, b: number) => a + b, 0) / chartValues.length).toFixed(1);
const min = Math.min(...chartValues).toFixed(1);
const max = Math.max(...chartValues).toFixed(1);
return (
<View key={param.key} style={styles.chartCard}>
<View style={styles.chartHeader}>
<Text style={[styles.chartTitle, {color: param.color}]}>
{param.label} {param.unit ? `(${param.unit})` : ''}
</Text>
<TouchableOpacity
style={styles.showFullBtn}
onPress={() => openModal(param)}>
<Text style={styles.showFullText}>Show Full </Text>
</TouchableOpacity>
</View>
<View style={styles.miniStats}>
<View style={styles.miniStatItem}>
<Text style={styles.miniStatVal}>{hasRealData ? avg : '-'}</Text>
<Text style={styles.miniStatLbl}>Rata-rata</Text>
</View>
<View style={styles.miniStatItem}>
<Text style={styles.miniStatVal}>{hasRealData ? min : '-'}</Text>
<Text style={styles.miniStatLbl}>Min</Text>
</View>
<View style={styles.miniStatItem}>
<Text style={styles.miniStatVal}>{hasRealData ? max : '-'}</Text>
<Text style={styles.miniStatLbl}>Max</Text>
</View>
</View>
{hasRealData ? (
<LineChart
data={{
labels: displayData.labels || [],
datasets: [{data: chartValues}],
}}
width={screenWidth}
height={160}
chartConfig={chartConfig(param.color)}
bezier
withVerticalLabels={false}
withHorizontalLabels={true}
style={styles.chart}
onDataPointClick={({value, index}) => {
const waktu = displayData.rawLabels ? displayData.rawLabels[index] : '-';
Alert.alert(
`${param.label}`,
`Nilai: ${value} ${param.unit}\nWaktu: ${waktu}`,
[{text: 'Tutup'}],
);
}}
/>
) : (
<View style={styles.noDataChart}>
<Text style={styles.noDataText}>📡 Menunggu data sensor...</Text>
</View>
)}
</View>
);
})}
</ScrollView>
{/* DateTimePicker */}
{showDatePicker && (
<DateTimePicker
value={selectedDate ?? new Date()}
mode="date"
display={Platform.OS === 'ios' ? 'inline' : 'calendar'}
maximumDate={new Date()}
onChange={onDateChange}
themeVariant="dark"
/>
)}
{/* Modal Show Full */}
<Modal visible={modalVisible} transparent animationType="fade">
<View style={styles.modalOverlay}>
<View style={styles.modalContainer}>
<View style={styles.modalHeader}>
<View>
<Text style={[styles.modalTitle, {color: modalData?.color ?? '#4ADE80'}]}>
{modalData?.label ?? '...'}
</Text>
<Text style={styles.modalSubtitle}>
{modalLoading
? 'Memuat data...'
: isDateMode
? `${formatDateDisplay(selectedDate!)}${modalData?.values.length ?? 0} data`
: `Data hari ini — ${modalData?.values.length ?? 0} data`}
</Text>
</View>
<TouchableOpacity style={styles.closeBtn} onPress={() => setModalVisible(false)}>
<Text style={styles.closeBtnText}></Text>
</TouchableOpacity>
</View>
{modalLoading ? (
<ActivityIndicator color="#4ADE80" style={{marginVertical: 40}} />
) : modalData && (
<>
<ScrollView horizontal showsHorizontalScrollIndicator={false} style={styles.modalChartScroll}>
<LineChart
data={{
labels: modalData.labels,
datasets: [{data: modalData.values}],
}}
width={Math.max(modalData.labels.length * 50, screenWidth)}
height={180}
chartConfig={{
backgroundGradientFrom: '#0D2818',
backgroundGradientTo: '#0D2818',
color: () => modalData.color,
labelColor: () => '#A3C4A8',
strokeWidth: 2,
decimalPlaces: 1,
propsForDots: {r: '4', strokeWidth: '1', stroke: modalData.color},
propsForBackgroundLines: {stroke: '#2D5A3D', strokeDasharray: ''},
}}
bezier
style={styles.modalChart}
withInnerLines={true}
withOuterLines={false}
/>
</ScrollView>
<Text style={styles.tableTitle}>DATA PER WAKTU</Text>
<FlatList
data={modalData.values.map((val, i) => ({
waktu: modalData.rawLabels[i] || '-',
nilai: val,
}))}
keyExtractor={(_, i) => i.toString()}
style={styles.tableList}
showsVerticalScrollIndicator={false}
renderItem={({item, index}) => (
<View style={[styles.tableRow, index % 2 === 0 && styles.tableRowEven]}>
<Text style={styles.tableWaktu}>{item.waktu}</Text>
<Text style={[styles.tableNilai, {color: modalData.color}]}>
{item.nilai} {modalData.unit}
</Text>
</View>
)}
/>
</>
)}
</View>
</View>
</Modal>
<BottomNav active="Laporan" navigation={navigation} />
</SafeAreaView>
);
};
export default LaporanScreen;
const styles = StyleSheet.create({
container: {flex: 1, backgroundColor: '#0D2818'},
scroll: {paddingHorizontal: 16, paddingTop: 16, paddingBottom: 100},
headerRow: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: 16,
},
pageTitle: {fontSize: 22, fontWeight: '700', color: '#FFFFFF'},
datePickerBtn: {
backgroundColor: '#1A3A28',
borderRadius: 10,
paddingHorizontal: 12,
paddingVertical: 7,
borderWidth: 1,
borderColor: '#2D5A3D',
},
datePickerBtnActive: {
borderColor: '#4ADE80',
backgroundColor: '#0D3320',
},
datePickerBtnText: {fontSize: 12, color: '#4ADE80', fontWeight: '700'},
dateBanner: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
backgroundColor: '#0D3320',
borderRadius: 12,
paddingHorizontal: 14,
paddingVertical: 10,
marginBottom: 14,
borderWidth: 1,
borderColor: '#4ADE80',
},
dateBannerLeft: {flexDirection: 'row', alignItems: 'center', gap: 10},
dateBannerIcon: {fontSize: 22},
dateBannerLabel: {fontSize: 10, color: '#A3C4A8', fontWeight: '600'},
dateBannerDate: {fontSize: 15, color: '#4ADE80', fontWeight: '700', marginTop: 1},
resetBtn: {
backgroundColor: '#1A3A28',
borderRadius: 8,
paddingHorizontal: 12,
paddingVertical: 6,
borderWidth: 1,
borderColor: '#4ADE80',
},
resetBtnText: {fontSize: 11, color: '#4ADE80', fontWeight: '700'},
filterRow: {flexDirection: 'row', gap: 8, marginBottom: 20},
filterBtn: {paddingHorizontal: 14, paddingVertical: 7, borderRadius: 20, backgroundColor: '#1A3A28'},
filterBtnActive: {backgroundColor: '#22C55E'},
filterText: {fontSize: 12, color: '#6B9E7A', fontWeight: '600'},
filterTextActive: {color: '#FFFFFF'},
sectionLabel: {fontSize: 10, fontWeight: '700', color: '#4ADE80', letterSpacing: 1, marginBottom: 10},
sensorRow: {flexDirection: 'row', gap: 8, marginBottom: 14},
sensorBtn: {flex: 1, backgroundColor: '#1A3A28', borderRadius: 12, paddingVertical: 10, alignItems: 'center', borderWidth: 1, borderColor: '#2D5A3D'},
sensorBtnActive: {borderColor: '#4ADE80', backgroundColor: '#0D3320'},
sensorIcon: {fontSize: 18, marginBottom: 4},
sensorLabel: {fontSize: 10, color: '#6B9E7A', fontWeight: '600'},
sensorLabelActive: {color: '#4ADE80'},
chartCard: {backgroundColor: '#1A3A28', borderRadius: 14, padding: 14, marginBottom: 12},
chartHeader: {flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10},
chartTitle: {fontSize: 12, fontWeight: '700', letterSpacing: 1, flex: 1},
showFullBtn: {backgroundColor: '#0D2818', borderRadius: 8, paddingHorizontal: 10, paddingVertical: 4, borderWidth: 1, borderColor: '#2D5A3D'},
showFullText: {fontSize: 10, color: '#4ADE80', fontWeight: '700'},
miniStats: {flexDirection: 'row', gap: 8, marginBottom: 10},
miniStatItem: {flex: 1, backgroundColor: '#0D2818', borderRadius: 8, padding: 8, alignItems: 'center'},
miniStatVal: {fontSize: 14, fontWeight: '700', color: '#FFFFFF'},
miniStatLbl: {fontSize: 9, color: '#A3C4A8', marginTop: 2},
chart: {borderRadius: 8, marginLeft: -15},
noDataChart: {height: 100, backgroundColor: '#0D2818', borderRadius: 8, alignItems: 'center', justifyContent: 'center'},
noDataText: {fontSize: 13, color: '#6B9E7A'},
emptyCard: {backgroundColor: '#1A3A28', borderRadius: 14, padding: 24, marginBottom: 16, alignItems: 'center'},
emptyIcon: {fontSize: 40, marginBottom: 12},
emptyTitle: {fontSize: 16, fontWeight: '700', color: '#FFFFFF', marginBottom: 6},
emptyDesc: {fontSize: 13, color: '#A3C4A8', textAlign: 'center', lineHeight: 20, marginBottom: 16},
errorCard: {backgroundColor: '#3B1C1C', borderRadius: 12, padding: 14, marginBottom: 16, borderWidth: 1, borderColor: '#7F1D1D'},
errorText: {color: '#FCA5A5', fontSize: 13, marginBottom: 10},
retryButton: {backgroundColor: '#DC2626', alignSelf: 'flex-start', paddingHorizontal: 14, paddingVertical: 8, borderRadius: 10},
retryText: {color: '#FFFFFF', fontWeight: '700', fontSize: 12},
modalOverlay: {flex: 1, backgroundColor: 'rgba(0,0,0,0.75)', justifyContent: 'center', alignItems: 'center', paddingHorizontal: 20},
modalContainer: {backgroundColor: '#1A3A28', borderRadius: 20, padding: 16, width: '100%', maxHeight: '80%'},
modalHeader: {flexDirection: 'row', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 12},
modalTitle: {fontSize: 15, fontWeight: '700'},
modalSubtitle: {fontSize: 11, color: '#A3C4A8', marginTop: 2},
closeBtn: {backgroundColor: '#0D2818', borderRadius: 20, width: 32, height: 32, alignItems: 'center', justifyContent: 'center'},
closeBtnText: {color: '#FFFFFF', fontSize: 14, fontWeight: '700'},
modalChartScroll: {marginBottom: 12},
modalChart: {borderRadius: 8},
tableTitle: {fontSize: 10, fontWeight: '700', color: '#A3C4A8', letterSpacing: 1.5, marginBottom: 8},
tableList: {maxHeight: 200},
tableRow: {flexDirection: 'row', justifyContent: 'space-between', paddingVertical: 8, paddingHorizontal: 8, borderRadius: 6},
tableRowEven: {backgroundColor: '#0D2818'},
tableWaktu: {fontSize: 13, color: '#A3C4A8'},
tableNilai: {fontSize: 13, fontWeight: '700'},
});

View File

@ -0,0 +1,231 @@
import {useCallback, useState} from 'react';
import {useFocusEffect} from '@react-navigation/native';
type SensorRow = {
id: number;
created_at: string;
suhu_soil: string | number | null;
lembab_soil: string | number | null;
conductivity: string | number | null;
ph: string | number | null;
n: string | number | null;
p: string | number | null;
k: string | number | null;
suhu_soil2?: string | number | null;
lembab_soil2?: string | number | null;
conductivity2?: string | number | null;
ph2?: string | number | null;
n2?: string | number | null;
p2?: string | number | null;
k2?: string | number | null;
suhu_light?: string | number | null;
lembab_light?: string | number | null;
intensitas?: string | number | null;
jarak?: string | number | null;
};
type FormattedData = {
labels: string[];
rawLabels: string[];
soil1: {
suhu_soil: number[];
lembab_soil: number[];
conductivity: number[];
ph: number[];
n: number[];
p: number[];
k: number[];
};
soil2: {
suhu_soil2: number[];
lembab_soil2: number[];
conductivity2: number[];
ph2: number[];
n2: number[];
p2: number[];
k2: number[];
};
light: {
suhu_light: number[];
lembab_light: number[];
intensitas: number[];
};
ultrasonic: {
jarak: number[];
};
};
type UseLaporanResult = {
loading: boolean;
error: string | null;
data: FormattedData | null;
refetch: () => Promise<void>;
};
const createEmptyData = (): FormattedData => ({
labels: [],
rawLabels: [],
soil1: {
suhu_soil: [],
lembab_soil: [],
conductivity: [],
ph: [],
n: [],
p: [],
k: [],
},
soil2: {
suhu_soil2: [],
lembab_soil2: [],
conductivity2: [],
ph2: [],
n2: [],
p2: [],
k2: [],
},
light: {
suhu_light: [],
lembab_light: [],
intensitas: [],
},
ultrasonic: {
jarak: [],
},
});
const toNumber = (value: unknown): number => {
if (value === null || value === undefined || value === '') return 0;
const num = Number(value);
return Number.isFinite(num) ? num : 0;
};
const sanitize = (values: number[]): number[] => {
const clean = values.filter(v => Number.isFinite(v) && !isNaN(v));
return clean.length > 0 ? clean : [0];
};
const getTime = (item: SensorRow) => {
const createdAt = item.created_at || '';
if (!createdAt) return '-';
const date = new Date(createdAt);
if (Number.isNaN(date.getTime())) return '-';
const hours = date.getHours().toString().padStart(2, '0');
const minutes = date.getMinutes().toString().padStart(2, '0');
return `${hours}:${minutes}`;
};
const sortByCreatedAtAsc = (rows: SensorRow[]) => {
return [...rows].sort((a, b) => {
const timeA = new Date(a.created_at).getTime();
const timeB = new Date(b.created_at).getTime();
return timeA - timeB;
});
};
export const useLaporan = (apiUrl: string): UseLaporanResult => {
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [data, setData] = useState<FormattedData | null>(null);
const fetchData = useCallback(async () => {
setLoading(true);
setError(null);
try {
const response = await fetch(apiUrl);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const json: SensorRow[] = await response.json();
if (!Array.isArray(json) || json.length === 0) {
setData(createEmptyData());
return;
}
// Pastikan data diurutkan dari lama ke baru
const sorted = sortByCreatedAtAsc(json);
// Ambil 10 data terbaru untuk grafik laporan
const latest10 = sorted.slice(-10);
const formatted: FormattedData = {
labels: latest10.map(() => ''),
rawLabels: latest10.map(item => getTime(item)),
soil1: {
suhu_soil: sanitize(latest10.map(item => toNumber(item.suhu_soil))),
lembab_soil: sanitize(
latest10.map(item => toNumber(item.lembab_soil)),
),
conductivity: sanitize(
latest10.map(item => toNumber(item.conductivity)),
),
ph: sanitize(latest10.map(item => toNumber(item.ph))),
n: sanitize(latest10.map(item => toNumber(item.n))),
p: sanitize(latest10.map(item => toNumber(item.p))),
k: sanitize(latest10.map(item => toNumber(item.k))),
},
soil2: {
suhu_soil2: sanitize(
latest10.map(item => toNumber(item.suhu_soil2)),
),
lembab_soil2: sanitize(
latest10.map(item => toNumber(item.lembab_soil2)),
),
conductivity2: sanitize(
latest10.map(item => toNumber(item.conductivity2)),
),
ph2: sanitize(latest10.map(item => toNumber(item.ph2))),
n2: sanitize(latest10.map(item => toNumber(item.n2))),
p2: sanitize(latest10.map(item => toNumber(item.p2))),
k2: sanitize(latest10.map(item => toNumber(item.k2))),
},
light: {
suhu_light: sanitize(
latest10.map(item => toNumber(item.suhu_light)),
),
lembab_light: sanitize(
latest10.map(item => toNumber(item.lembab_light)),
),
intensitas: sanitize(
latest10.map(item => toNumber(item.intensitas)),
),
},
ultrasonic: {
jarak: sanitize(latest10.map(item => toNumber(item.jarak))),
},
};
setData(formatted);
} catch (err: any) {
setError(err?.message || 'Gagal mengambil data laporan');
setData(null);
} finally {
setLoading(false);
}
}, [apiUrl]);
useFocusEffect(
useCallback(() => {
fetchData();
}, [fetchData]),
);
return {
loading,
error,
data,
refetch: fetchData,
};
};

View File

@ -0,0 +1,70 @@
import React, {useState} from 'react';
import {View, Text, StyleSheet, SafeAreaView, StatusBar, TouchableOpacity} from 'react-native';
import {useNavigation} from '@react-navigation/native';
import {NativeStackNavigationProp} from '@react-navigation/native-stack';
import {RootStackParamList} from '../../../Constants/RouteParamsList.constants';
import BottomNav from '../../../Components/BottomNav';
import NotifTab from '../components/NotifTab';
import BotTab from '../components/BotTab';
type NavProp = NativeStackNavigationProp<RootStackParamList>;
const NotifikasiScreen: React.FC = () => {
const navigation = useNavigation<NavProp>();
const [activeTab, setActiveTab] = useState<'notif' | 'bot'>('notif');
return (
<SafeAreaView style={styles.container}>
<StatusBar barStyle="light-content" backgroundColor="#0D2818" />
{/* Header */}
<View style={styles.header}>
<Text style={styles.headerTitle}>
{activeTab === 'notif' ? 'Notifikasi' : 'Bot Assistant'}
</Text>
<Text style={styles.headerSubtitle}>
{activeTab === 'notif'
? 'Log aktivitas & peringatan sistem'
: 'Asisten perawatan greenhouse'}
</Text>
</View>
{/* Tab */}
<View style={styles.tabRow}>
<TouchableOpacity
style={[styles.tabBtn, activeTab === 'notif' && styles.tabBtnActive]}
onPress={() => setActiveTab('notif')}>
<Text style={[styles.tabText, activeTab === 'notif' && styles.tabTextActive]}>
🔔 Notifikasi
</Text>
</TouchableOpacity>
<TouchableOpacity
style={[styles.tabBtn, activeTab === 'bot' && styles.tabBtnActive]}
onPress={() => setActiveTab('bot')}>
<Text style={[styles.tabText, activeTab === 'bot' && styles.tabTextActive]}>
🤖 Bot Assistant
</Text>
</TouchableOpacity>
</View>
{/* Content */}
{activeTab === 'notif' ? <NotifTab /> : <BotTab />}
<BottomNav active="Notifikasi" navigation={navigation} />
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {flex: 1, backgroundColor: '#0D2818'},
header: {paddingHorizontal: 16, paddingTop: 16, paddingBottom: 12},
headerTitle: {fontSize: 22, fontWeight: '700', color: '#FFFFFF'},
headerSubtitle: {fontSize: 12, color: '#A3C4A8', marginTop: 2},
tabRow: {flexDirection: 'row', paddingHorizontal: 16, gap: 10, marginBottom: 12},
tabBtn: {flex: 1, paddingVertical: 10, borderRadius: 12, backgroundColor: '#1A3A28', alignItems: 'center', borderWidth: 1, borderColor: '#2D5A3D'},
tabBtnActive: {backgroundColor: '#22C55E', borderColor: '#22C55E'},
tabText: {fontSize: 13, color: '#6B9E7A', fontWeight: '600'},
tabTextActive: {color: '#FFFFFF'},
});
export default NotifikasiScreen;

View File

@ -0,0 +1,207 @@
import React, {useState, useRef} from 'react';
import {
View,
Text,
StyleSheet,
TouchableOpacity,
FlatList,
KeyboardAvoidingView,
Platform,
ActivityIndicator,
TextInput,
Alert,
} from 'react-native';
interface ChatMessage {
id: string;
from: 'user' | 'bot';
text: string;
time: string;
}
const QUICK_REPLIES = [
{id: 'status', label: '📊 Kondisi Hari Ini'},
{id: 'perawatan', label: '🌿 Saran Perawatan'},
{id: 'nutrisi', label: '🌾 Cek Nutrisi'},
{id: 'suhu', label: '🌡️ Cek Suhu'},
];
/**
* PENTING: Gunakan HTTPS untuk Ngrok.
* Tambahkan 'ngrok-skip-browser-warning': 'true' di headers agar APK bisa tembus.
*/
const BOT_API_URL = 'http://202.10.40.129:3000/api/bot/chat';
const BotTab: React.FC = () => {
const [messages, setMessages] = useState<ChatMessage[]>([
{
id: '1',
from: 'bot',
text: 'Halo! Saya Bot Greenhouse PT Agrofilia Permata 🌱\n\nAda yang bisa saya bantu terkait budidaya vanili Anda hari ini?',
time: new Date().toLocaleTimeString('id-ID', {hour: '2-digit', minute: '2-digit'}),
},
]);
const [inputText, setInputText] = useState('');
const [isTyping, setIsTyping] = useState(false);
const flatListRef = useRef<FlatList>(null);
const handleChat = async (input: string) => {
if (!input.trim()) return;
const now = new Date().toLocaleTimeString('id-ID', {hour: '2-digit', minute: '2-digit'});
const userMsg: ChatMessage = {
id: Date.now().toString(),
from: 'user',
text: input,
time: now,
};
setMessages(prev => [...prev, userMsg]);
setInputText('');
setIsTyping(true);
try {
// Menambahkan timeout agar aplikasi tidak hang jika sinyal buruk
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 15000);
const response = await fetch(BOT_API_URL, {
method: 'POST',
signal: controller.signal,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
// Header Wajib untuk Ngrok agar tidak kena blokir halaman peringatan
'ngrok-skip-browser-warning': 'true',
},
body: JSON.stringify({message: input}),
});
clearTimeout(timeoutId);
if (!response.ok) {
throw new Error(`Server Error: ${response.status}`);
}
const result = await response.json();
const botMsg: ChatMessage = {
id: (Date.now() + 1).toString(),
from: 'bot',
text: result.reply || 'Maaf, saya tidak mendapatkan jawaban.',
time: now,
};
setMessages(prev => [...prev, botMsg]);
} catch (err: any) {
console.error('Connection Error:', err);
let errorText = '⚠️ Koneksi gagal. Pastikan server laptop aktif dan Ngrok berjalan.';
if (err.name === 'AbortError') {
errorText = '⚠️ Request Timeout. Koneksi internet terlalu lambat.';
}
const errMsg: ChatMessage = {
id: (Date.now() + 1).toString(),
from: 'bot',
text: errorText,
time: now,
};
setMessages(prev => [...prev, errMsg]);
} finally {
setIsTyping(false);
setTimeout(() => flatListRef.current?.scrollToEnd({animated: true}), 100);
}
};
return (
<KeyboardAvoidingView
style={styles.container}
behavior={Platform.OS === 'ios' ? 'padding' : undefined}
keyboardVerticalOffset={90}>
<FlatList
ref={flatListRef}
data={messages}
keyExtractor={item => item.id}
contentContainerStyle={styles.chatList}
onContentSizeChange={() => flatListRef.current?.scrollToEnd({animated: true})}
renderItem={({item}) => (
<View style={[styles.bubbleWrapper, item.from === 'user' ? styles.bubbleRight : styles.bubbleLeft]}>
{item.from === 'bot' && (
<View style={styles.botAvatar}>
<Text>🤖</Text>
</View>
)}
<View style={[styles.bubble, item.from === 'user' ? styles.bubbleUser : styles.bubbleBot]}>
<Text style={styles.chatText}>{item.text}</Text>
<Text style={styles.chatTime}>{item.time}</Text>
</View>
</View>
)}
/>
{isTyping && (
<View style={styles.typingIndicator}>
<ActivityIndicator size="small" color="#4ADE80" />
<Text style={styles.typingText}>Bot sedang menganalisis...</Text>
</View>
)}
<View style={styles.quickReplyContainer}>
<FlatList
horizontal
showsHorizontalScrollIndicator={false}
data={QUICK_REPLIES}
keyExtractor={item => item.id}
renderItem={({item}) => (
<TouchableOpacity
style={styles.quickReplyBtn}
onPress={() => handleChat(item.label)}>
<Text style={styles.quickReplyText}>{item.label}</Text>
</TouchableOpacity>
)}
/>
</View>
<View style={styles.inputSection}>
<TextInput
style={styles.input}
placeholder="Tanya kondisi vanili..."
placeholderTextColor="#6B9E7A"
value={inputText}
onChangeText={setInputText}
onSubmitEditing={() => handleChat(inputText)}
/>
<TouchableOpacity style={styles.sendBtn} onPress={() => handleChat(inputText)}>
<Text style={styles.sendBtnText}>Kirim</Text>
</TouchableOpacity>
</View>
</KeyboardAvoidingView>
);
};
const styles = StyleSheet.create({
container: {flex: 1, backgroundColor: '#0D1A12', paddingBottom: 80},
chatList: {padding: 16, paddingBottom: 20},
bubbleWrapper: {flexDirection: 'row', marginBottom: 15, alignItems: 'flex-end'},
bubbleLeft: {justifyContent: 'flex-start'},
bubbleRight: {justifyContent: 'flex-end'},
botAvatar: {width: 30, height: 30, borderRadius: 15, backgroundColor: '#1A3A28', alignItems: 'center', justifyContent: 'center', marginRight: 8},
bubble: {maxWidth: '80%', borderRadius: 15, padding: 12},
bubbleBot: {backgroundColor: '#1A3A28', borderBottomLeftRadius: 2},
bubbleUser: {backgroundColor: '#22C55E', borderBottomRightRadius: 2},
chatText: {color: '#FFFFFF', fontSize: 14, lineHeight: 20},
chatTime: {color: '#6B9E7A', fontSize: 10, marginTop: 4, textAlign: 'right'},
typingIndicator: {flexDirection: 'row', alignItems: 'center', paddingHorizontal: 16, marginBottom: 10, gap: 8},
typingText: {color: '#4ADE80', fontSize: 12, fontStyle: 'italic'},
quickReplyContainer: {paddingVertical: 10, borderTopWidth: 0.5, borderTopColor: '#2D5A3D'},
quickReplyBtn: {backgroundColor: '#14532D', paddingHorizontal: 15, paddingVertical: 8, borderRadius: 20, marginLeft: 12, borderWidth: 1, borderColor: '#2D5A3D'},
quickReplyText: {color: '#4ADE80', fontSize: 12, fontWeight: '600'},
inputSection: {flexDirection: 'row', padding: 12, backgroundColor: '#1A3A28', alignItems: 'center'},
input: {flex: 1, backgroundColor: '#0D1A12', borderRadius: 25, paddingHorizontal: 15, color: '#FFF', height: 45},
sendBtn: {marginLeft: 10, backgroundColor: '#22C55E', paddingVertical: 10, paddingHorizontal: 20, borderRadius: 25},
sendBtnText: {color: '#FFF', fontWeight: 'bold'},
});
export default BotTab;

View File

@ -0,0 +1,294 @@
import React, {useState, useEffect, useCallback} from 'react';
import {
ScrollView, View, Text, StyleSheet, TouchableOpacity,
RefreshControl, ActivityIndicator, Alert,
} from 'react-native';
import API_BASE_URL from '../../../Constants/api.constans';
type NotifType = 'sensor' | 'aktuator' | 'sistem' | 'info';
interface Notifikasi {
id: string;
tipe: NotifType;
judul: string;
deskripsi: string;
time: string;
durasi: string | null;
sumber: string;
}
const notifConfig = {
sensor: {icon: '📡', color: '#4ADE80', bg: '#0D3320'},
aktuator: {icon: '⚙️', color: '#60A5FA', bg: '#152030'},
sistem: {icon: '⚠️', color: '#F59E0B', bg: '#2D2015'},
info: {icon: '', color: '#94A3B8', bg: '#1E293B'},
};
const filterOptions = ['Semua', 'Log Sensor', 'Aktuator', 'Masalah'];
const NotifTab: React.FC = () => {
const [activeFilter, setActiveFilter] = useState('Semua');
const [logs, setLogs] = useState<Notifikasi[]>([]);
const [loading, setLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
const [selectMode, setSelectMode] = useState(false);
const fetchLogs = useCallback(async () => {
try {
const response = await fetch(`${API_BASE_URL}/logs`);
const json = await response.json();
if (json.success) {
setLogs(json.data);
}
} catch (error) {
console.error('Error fetch logs:', error);
} finally {
setLoading(false);
setRefreshing(false);
}
}, []);
useEffect(() => {
fetchLogs();
const interval = setInterval(fetchLogs, 30000);
return () => clearInterval(interval);
}, [fetchLogs]);
const onRefresh = () => {
setRefreshing(true);
fetchLogs();
};
const toggleSelect = (id: string) => {
setSelectedIds(prev => {
const next = new Set(prev);
if (next.has(id)) {
next.delete(id);
} else {
next.add(id);
}
return next;
});
};
const selectAll = () => {
const allIds = new Set(filteredNotif.map(n => n.id));
setSelectedIds(allIds);
};
const clearSelection = () => {
setSelectedIds(new Set());
setSelectMode(false);
};
const deleteSelected = async () => {
if (selectedIds.size === 0) return;
Alert.alert(
'Hapus Notifikasi',
`Hapus ${selectedIds.size} notifikasi yang dipilih?`,
[
{text: 'Batal', style: 'cancel'},
{
text: 'Hapus',
style: 'destructive',
onPress: async () => {
try {
const ids = Array.from(selectedIds).join(',');
const response = await fetch(`${API_BASE_URL}/logs/delete`, {
method: 'DELETE',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({ids: Array.from(selectedIds)}),
});
const result = await response.json();
if (result.success) {
setLogs(prev => prev.filter(n => !selectedIds.has(n.id)));
clearSelection();
}
} catch (error) {
console.error('Delete error:', error);
}
},
},
]
);
};
const filteredNotif = logs.filter(n => {
if (activeFilter === 'Semua') return true;
if (activeFilter === 'Log Sensor') return n.tipe === 'sensor';
if (activeFilter === 'Aktuator') return n.tipe === 'aktuator';
if (activeFilter === 'Masalah') return n.tipe === 'sistem';
return true;
});
if (loading && !refreshing) {
return (
<View style={styles.center}>
<ActivityIndicator size="large" color="#4ADE80" />
<Text style={styles.loadingText}>Menghubungkan ke Greenhouse...</Text>
</View>
);
}
return (
<ScrollView
contentContainerStyle={styles.scroll}
refreshControl={
<RefreshControl refreshing={refreshing} onRefresh={onRefresh} tintColor="#4ADE80" />
}>
<View style={styles.headerInfo}>
<Text style={styles.headerTitle}>Log Aktivitas & Status Sistem</Text>
<Text style={styles.headerSubtitle}>Monitoring pengiriman data RS485 & WhatsApp.</Text>
</View>
{/* Action Bar */}
<View style={styles.actionBar}>
{!selectMode ? (
<TouchableOpacity
style={styles.actionBtn}
onPress={() => setSelectMode(true)}>
<Text style={styles.actionBtnText}> Pilih</Text>
</TouchableOpacity>
) : (
<View style={styles.selectActions}>
<TouchableOpacity style={styles.actionBtn} onPress={selectAll}>
<Text style={styles.actionBtnText}> Pilih Semua</Text>
</TouchableOpacity>
<TouchableOpacity
style={[styles.actionBtn, styles.deleteBtn]}
onPress={deleteSelected}
disabled={selectedIds.size === 0}>
<Text style={styles.actionBtnText}>🗑 Hapus ({selectedIds.size})</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.actionBtn} onPress={clearSelection}>
<Text style={styles.actionBtnText}> Batal</Text>
</TouchableOpacity>
</View>
)}
</View>
{/* Filter */}
<View style={styles.filterRow}>
{filterOptions.map(f => (
<TouchableOpacity
key={f}
style={[
styles.filterBtn,
activeFilter === f && styles.filterBtnActive,
f === 'Log Sensor' && activeFilter === f && {backgroundColor: '#065F46'},
f === 'Aktuator' && activeFilter === f && {backgroundColor: '#1E40AF'},
f === 'Masalah' && activeFilter === f && {backgroundColor: '#991B1B'},
]}
onPress={() => setActiveFilter(f)}>
<Text style={[styles.filterText, activeFilter === f && styles.filterTextActive]}>
{f}
</Text>
</TouchableOpacity>
))}
</View>
{filteredNotif.length === 0 ? (
<View style={styles.emptyBox}>
<Text style={styles.emptyText}>Belum ada aktivitas tercatat.</Text>
</View>
) : (
filteredNotif.map(notif => {
const config = notifConfig[notif.tipe] || notifConfig.info;
const isSelected = selectedIds.has(notif.id);
return (
<TouchableOpacity
key={notif.id}
activeOpacity={selectMode ? 0.7 : 1}
onPress={() => selectMode && toggleSelect(notif.id)}
onLongPress={() => {
setSelectMode(true);
toggleSelect(notif.id);
}}
style={[
styles.notifCard,
{backgroundColor: config.bg},
isSelected && styles.notifCardSelected,
]}>
{/* Checkbox */}
{selectMode && (
<View style={[styles.checkbox, isSelected && styles.checkboxSelected]}>
{isSelected && <Text style={styles.checkmark}></Text>}
</View>
)}
<View style={styles.notifLeft}>
<View style={[styles.iconCircle, {borderColor: config.color}]}>
<Text style={styles.notifIcon}>{config.icon}</Text>
</View>
</View>
<View style={styles.notifContent}>
<View style={styles.notifTitleRow}>
<Text style={[styles.notifTitle, {color: config.color}]}>{notif.judul}</Text>
</View>
<Text style={styles.notifDesc}>{notif.deskripsi}</Text>
{notif.durasi && (
<View style={styles.durationBadge}>
<Text style={styles.durationText}> Durasi: {notif.durasi}</Text>
</View>
)}
<View style={styles.footerRow}>
<Text style={styles.notifMeta}>{notif.time}</Text>
<View style={styles.sourceBadge}>
<Text style={styles.sourceText}>{notif.sumber}</Text>
</View>
</View>
</View>
</TouchableOpacity>
);
})
)}
</ScrollView>
);
};
const styles = StyleSheet.create({
center: {flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#0A1A10'},
loadingText: {marginTop: 10, color: '#6B9E7A', fontSize: 12},
scroll: {paddingHorizontal: 16, paddingBottom: 100, paddingTop: 10},
headerInfo: {marginBottom: 16},
headerTitle: {fontSize: 18, fontWeight: '800', color: '#F3F4F6', marginBottom: 4},
headerSubtitle: {fontSize: 12, color: '#6B9E7A'},
actionBar: {marginBottom: 12},
selectActions: {flexDirection: 'row', gap: 8, flexWrap: 'wrap'},
actionBtn: {backgroundColor: '#1A3A28', paddingHorizontal: 14, paddingVertical: 8, borderRadius: 10, borderWidth: 1, borderColor: '#2D5A3D'},
deleteBtn: {backgroundColor: '#3B1C1C', borderColor: '#7F1D1D'},
actionBtnText: {fontSize: 12, color: '#A3C4A8', fontWeight: '700'},
filterRow: {flexDirection: 'row', flexWrap: 'wrap', gap: 8, marginBottom: 16},
filterBtn: {paddingHorizontal: 14, paddingVertical: 8, borderRadius: 10, backgroundColor: '#1A3A28'},
filterBtnActive: {backgroundColor: '#22C55E'},
filterText: {fontSize: 12, color: '#A3C4A8', fontWeight: '700'},
filterTextActive: {color: '#FFFFFF'},
notifCard: {borderRadius: 16, padding: 16, marginBottom: 12, flexDirection: 'row', gap: 14},
notifCardSelected: {borderWidth: 2, borderColor: '#4ADE80'},
notifLeft: {alignItems: 'center'},
iconCircle: {width: 45, height: 45, borderRadius: 22.5, alignItems: 'center', justifyContent: 'center', borderWidth: 1},
notifIcon: {fontSize: 20},
notifContent: {flex: 1},
notifTitleRow: {flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6},
notifTitle: {fontSize: 14, fontWeight: '800', flex: 1},
notifDesc: {fontSize: 12, color: '#E2E8F0', lineHeight: 18, marginBottom: 10},
durationBadge: {backgroundColor: 'rgba(0,0,0,0.3)', padding: 6, borderRadius: 6, alignSelf: 'flex-start', marginBottom: 10},
durationText: {fontSize: 10, color: '#60A5FA', fontWeight: 'bold'},
footerRow: {flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between'},
notifMeta: {fontSize: 11, color: '#94A3B8', fontWeight: '600'},
sourceBadge: {backgroundColor: 'rgba(255,255,255,0.05)', paddingHorizontal: 8, paddingVertical: 2, borderRadius: 4},
sourceText: {fontSize: 10, color: '#6B9E7A', fontWeight: '700', textTransform: 'uppercase'},
emptyBox: {alignItems: 'center', marginTop: 50},
emptyText: {color: '#6B9E7A', fontSize: 14},
checkbox: {width: 22, height: 22, borderRadius: 11, borderWidth: 2, borderColor: '#2D5A3D', alignItems: 'center', justifyContent: 'center', marginRight: 4, alignSelf: 'center'},
checkboxSelected: {backgroundColor: '#4ADE80', borderColor: '#4ADE80'},
checkmark: {fontSize: 12, color: '#0D2818', fontWeight: '700'},
});
export default NotifTab;

View File

@ -0,0 +1,127 @@
// src/Containers/notifikasi/hooks/useSensorLatest.ts
import {useState, useCallback, useEffect} from 'react';
export type SensorLatest = {
suhuTanah: number;
kelembaban: number;
conductivity: number;
ph: number;
nitrogen: number;
phosphorus: number;
kalium: number;
suhuUdara: number;
kelembabanUdara: number;
cahaya: number;
levelAir: number;
};
// Pastikan URL Ngrok ini sesuai dengan yang aktif saat ini
const API_BASE_URL = 'https://numerator-clubbed-hardened.ngrok-free.dev/api';
const API_URL = `${API_BASE_URL}/get-data`;
export const useSensorLatest = () => {
const [data, setData] = useState<SensorLatest | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const fetchData = useCallback(async () => {
setLoading(true);
setError(null);
try {
const controller = new AbortController();
// Timeout 10 detik agar lebih toleran terhadap jaringan seluler saat pakai APK
const timeoutId = setTimeout(() => controller.abort(), 10000);
const response = await fetch(API_URL, {
signal: controller.signal,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
// Header WAJIB agar APK tidak terblokir halaman peringatan Ngrok
'ngrok-skip-browser-warning': 'true',
},
});
clearTimeout(timeoutId);
console.log('STATUS SENSOR:', response.status);
if (!response.ok) {
throw new Error(`Server Error: ${response.status}`);
}
const json = await response.json();
const rawData = Array.isArray(json) ? json : (json.data || []);
if (rawData.length === 0) {
setData(null);
setError('Database sensor masih kosong');
return;
}
// Hitung tanggal hari ini dalam WIB (UTC+7)
const now = new Date();
const wib = new Date(now.getTime() + 7 * 60 * 60 * 1000);
const today = wib.toISOString().split('T')[0];
// Filter data hari ini
const todayData = rawData.filter((row: any) => {
if (!row.created_at) return false;
const rowDate = new Date(row.created_at);
const rowWib = new Date(rowDate.getTime() + 7 * 60 * 60 * 1000);
return rowWib.toISOString().split('T')[0] === today;
});
if (todayData.length === 0) {
setData(null);
setError('Belum ada data sensor masuk untuk hari ini');
return;
}
// Helper Fungsi Rata-rata
const avg = (key: string) => {
const values = todayData
.map((row: any) => Number(row[key]))
.filter((v: number) => !isNaN(v) && isFinite(v));
if (values.length === 0) return 0;
// Tambahkan tipe data number pada a dan b di sini
return Math.round((values.reduce((a: number, b: number) => a + b, 0) / values.length) * 10) / 10;
};
const avgTwo = (key1: string, key2: string) => {
const values: number[] = todayData // Tambahkan : number[] di sini
.flatMap((row: any) => [Number(row[key1]), Number(row[key2])])
.filter((v: number) => !isNaN(v) && isFinite(v));
if (values.length === 0) return 0;
return Math.round((values.reduce((a: number, b: number) => a + b, 0) / values.length) * 10) / 10;
};
setData({
suhuTanah: avgTwo('suhu_soil', 'suhu_soil2'),
kelembaban: avgTwo('lembab_soil', 'lembab_soil2'),
conductivity: avgTwo('conductivity', 'conductivity2'),
ph: avgTwo('ph', 'ph2'),
nitrogen: avgTwo('n', 'n2'),
phosphorus: avgTwo('p', 'p2'),
kalium: avgTwo('k', 'k2'),
suhuUdara: avg('suhu_light'),
kelembabanUdara: avg('lembab_light'),
cahaya: avg('intensitas'),
levelAir: avg('jarak'),
});
} catch (err: any) {
if (err.name === 'AbortError') {
setError('Koneksi lambat (Timeout). Pastikan Ngrok & Internet stabil.');
} else {
console.log('ERROR FETCH SENSOR:', err?.message);
setError('Gagal terhubung ke server. Cek status Ngrok di laptop.');
}
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
fetchData();
}, [fetchData]);
return {data, loading, error, refetch: fetchData};
};

34
src/Navigators/Stack.tsx Normal file
View File

@ -0,0 +1,34 @@
import React from 'react';
import {createNativeStackNavigator} from '@react-navigation/native-stack';
import RouteName from '../Constants/RouteName.constants';
import {RootStackParamList} from '../Constants/RouteParamsList.constants';
import {UnauthorizedScreens, AuthorizedScreens} from './config';
const Stack = createNativeStackNavigator<RootStackParamList>();
const AppStack = () => {
return (
<Stack.Navigator
initialRouteName={RouteName.LoginNavigation}
screenOptions={{headerShown: false}}>
{UnauthorizedScreens.map(screen => (
<Stack.Screen
key={screen.name}
name={screen.name as keyof RootStackParamList}
component={screen.component}
options={screen.options}
/>
))}
{AuthorizedScreens.map(screen => (
<Stack.Screen
key={screen.name}
name={screen.name as keyof RootStackParamList}
component={screen.component}
options={screen.options}
/>
))}
</Stack.Navigator>
);
};
export default AppStack;

24
src/Navigators/config.ts Normal file
View File

@ -0,0 +1,24 @@
import React from 'react';
import RouteName from '../Constants/RouteName.constants';
import LoginScreen from '../Containers/auth/Loginscreen';
import DashboardScreen from '../Containers/dashboard/DashboardScreen';
import KontrolScreen from '../Containers/kontrol/KontrolScreen';
import LaporanScreen from '../Containers/laporan/LaporanScreen';
import NotifikasiScreen from '../Containers/notifikasi/NotifikasiScreen';
interface IScreen {
name: string;
component: React.ComponentType<any>;
options?: any;
}
export const UnauthorizedScreens: IScreen[] = [
{name: RouteName.LoginNavigation, component: LoginScreen, options: {headerShown: false}},
];
export const AuthorizedScreens: IScreen[] = [
{name: RouteName.DashboardNavigation, component: DashboardScreen, options: {headerShown: false}},
{name: RouteName.KontrolNavigation, component: KontrolScreen, options: {headerShown: false}},
{name: RouteName.LaporanNavigation, component: LaporanScreen, options: {headerShown: false}},
{name: RouteName.NotifikasiNavigation, component: NotifikasiScreen, options: {headerShown: false}},
];

View File

@ -0,0 +1,10 @@
import API_BASE_URL from "../Constants/api.constans";
export const loginService = async (email: string, password: string) => {
const response = await fetch(`${API_BASE_URL}/auth/login`, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({email, password}),
});
return response.json();
};

View File

@ -0,0 +1,6 @@
import API_BASE_URL from "../Constants/api.constans";
export const getDailyData = async () => {
const response = await fetch(`${API_BASE_URL}/sensor/daily`);
return response.json();
};

18
src/babel.config.js Normal file
View File

@ -0,0 +1,18 @@
module.exports = {
presets: ['module:@react-native/babel-preset'],
plugins: [
[
'module-resolver',
{
root: ['./'],
extensions: ['.ios.js', '.android.js', '.js', '.ts', '.tsx', '.json'],
alias: {
'@Constants': './src/Constants',
'@Containers': './src/Containers',
'@Navigators': './src/Navigators',
'@Dummy': './src/Dummy',
},
},
],
],
};

5
src/index.js Normal file
View File

@ -0,0 +1,5 @@
import 'react-native-gesture-handler'; // paling atas
import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';
AppRegistry.registerComponent(appName, () => App);

21
src/tsconfig.json Normal file
View File

@ -0,0 +1,21 @@
{
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"jsx": "react-jsx",
"baseUrl": ".",
"paths": {
"@Constants/*": ["src/Constants/*"],
"@Containers/*": ["src/Containers/*"],
"@Dummy/*": ["src/Dummy/*"],
"@Navigators/*": ["src/Navigators/*"],
"@Navigators": ["src/Navigators/index"]
},
"allowJs": true,
"esModuleInterop": true,
"skipLibCheck": true,
"strict": false,
"moduleResolution": "node"
},
"include": ["src", "App.tsx"]
}