박권수

Merge branch 'master' into server

Showing 163 changed files with 8857 additions and 37 deletions
{
// IntelliSense를 사용하여 가능한 특성에 대해 알아보세요.
// 기존 특성에 대한 설명을 보려면 가리킵니다.
// 자세한 내용을 보려면 https://go.microsoft.com/fwlink/?linkid=830387을(를) 방문하세요.
"version": "0.2.0",
"configurations": [
{
"name": "flutter_application_1",
"cwd": "frontend\\flutter_application_1",
"request": "launch",
"type": "dart"
}
]
}
\ No newline at end of file
{
"dart.previewFlutterUiGuides": true
}
\ No newline at end of file
......@@ -17,7 +17,7 @@
각 개발자의 작업사항을 보시려면 개발자의 이름을 클릭하세요.
- [고원빈 : 프론트엔드, Native Android Application 개발](http://khuhub.khu.ac.kr/2021-1-capstone-design1/RIT_Project1/tree/frontend/frontend)
1. Framework : Flutter 1.6.2
1. Framework : Flutter 1.22.6
2. 언어 : Dart
3. 주요 통신 : HTTP Request, Response(Server와 통신)
......
# 스마트 약병 IoT FRONTEND 개발
## 지도교수
+ 유인태 교수님
## 팀원
+ 2016104102 컴퓨터공학과 고원빈
## 일정
+ 2021-04-27 : Flutter 앱 생성 및 개발 환경 설정
+ 2021-04-27 : 시작화면 router 생성
### 2021-04-28
+ flutter version 변경 작업
### 2021-04-29
+ Main 화면 작업 완료
![로그인_화면](/uploads/d12f35739c9263e37009cc9b3bbe06d4/로그인_화면.PNG)
+ 로그인 페이지 작업 완료
![222](/uploads/8cc867cd159e28c04ff2a09e3a42c2d6/222.PNG)
### 2021-05-09
+ Appbar 기능 구현
appbar 관련 디자인은 추후 구현 예정
### 2021-05-10
+ Appbar 디자인 변경 및 Navgation Bar 구현
+ Setting은 별도의 페이지로 구성
### 2021-05-11
+ Inside Information 화면 구성
<img src = "https://user-images.githubusercontent.com/56704722/117849827-aadc6400-b2bf-11eb-8cdb-2c7f37833d01.png" width="400">
+ Outside Information 화면 구성
<img src ="https://user-images.githubusercontent.com/56704722/117849959-cd6e7d00-b2bf-11eb-86b7-bc97356c7665.png" width="400">
+ Setting Page 화면 구성
<img src = "https://user-images.githubusercontent.com/56704722/117850038-e24b1080-b2bf-11eb-8dcd-5cb96a9056e0.png" width="400">
### 2021-05-13
+ flutter notification 추가 알람 설정 완료
+ datetime picker widget을 이용하여 시간 선택 구현 예정
+ 알람 설정을 위한 Android Mainfest 설정 , 사용자 권한 요구
### 2021-05-14
+ datetime picker 를 이용하여 알람 설정 완료
+ 현재 알람 페이지와 알람 수정 페이지가 같은 곳에 위치 이에 따라 보이는 데이터만 존재하고 수정 여부를 묻는 것을 만들지 고민중
### 2021-05-15
+ 회원 정보 수정 Page 구현
+ API 연동 중에 추가로 개발 예정
+ build용 파일 구현
### 2021-05-17
+ server test 완료
### 2021-05-18
+ 회원 가입 SERVER 연동
### 2021-05-19
+ Login 연동
+ 약병 등록 ,허브 등록 구현
### 2021-05-20
+ 시나리오 수정
### 2021-05-21
+ 약병 ,허브 리스트 출력 구현
### 2021-05-22
+ 약병 검색 기능 구현 중
### 2021-05-23
+ 로그인 하여 메인페이지 과정 구현 완료
+ 폴더 정리
### 2021-05-24
회원 가입 --> 허브 등록 --> 약병 등록 -->로그인 페이지로
로그인 --> 허브 리스트 --> 약병 리스트 --> 메인 페이지
+ 시나리오 수정 완료
+ 메인 페이지 데이터 출력 완료
### 2021-05-25
+ 로그인 권한 문제 해결
### 2021-05-26
+ future buillder 변경
### 2021-05-27
+ app 뒤로가기 설정 변경
### 2021-05-29
+ 약병 리스트 ui 변경
+ DashBoard 새로고침
### 2021-05-30
+ Sqlite 생성
### 2021-06-01
+ datetime 형식 한국 시간으로 변경
### 2021-06-02
+ 약병 , 허브 추가 제거 관리 페이지 구현
SERVER_URL=http://192.168.0.3:4717/api/
\ No newline at end of file
# Miscellaneous
*.class
*.log
*.pyc
*.swp
.DS_Store
.atom/
.buildlog/
.history
.svn/
# IntelliJ related
*.iml
*.ipr
*.iws
.idea/
# The .vscode folder contains launch configuration and tasks you configure in
# VS Code which you may wish to be included in version control, so this line
# is commented out by default.
#.vscode/
# Flutter/Dart/Pub related
**/doc/api/
**/ios/Flutter/.last_build_id
.dart_tool/
.flutter-plugins
.flutter-plugins-dependencies
.packages
.pub-cache/
.pub/
/build/
# Web related
lib/generated_plugin_registrant.dart
# Symbolication related
app.*.symbols
# Obfuscation related
app.*.map.json
# This file tracks properties of this Flutter project.
# Used by Flutter tool to assess capabilities and perform upgrades etc.
#
# This file should be version controlled and should not be manually edited.
version:
revision: 9b2d32b605630f28625709ebd9d78ab3016b2bf6
channel: stable
project_type: app
# flutter_application_1
A new Flutter project.
## Getting Started
This project is a starting point for a Flutter application.
A few resources to get you started if this is your first Flutter project:
- [Lab: Write your first Flutter app](https://flutter.dev/docs/get-started/codelab)
- [Cookbook: Useful Flutter samples](https://flutter.dev/docs/cookbook)
For help getting started with Flutter, view our
[online documentation](https://flutter.dev/docs), which offers tutorials,
samples, guidance on mobile development, and a full API reference.
gradle-wrapper.jar
/.gradle
/captures/
/gradlew
/gradlew.bat
/local.properties
GeneratedPluginRegistrant.java
# Remember to never publicly share your keystore.
# See https://flutter.dev/docs/deployment/android#reference-the-keystore-from-the-app
key.properties
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}
def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}
def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
flutterVersionCode = '1'
}
def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
flutterVersionName = '1.0'
}
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
android {
compileSdkVersion 29
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
lintOptions {
disable 'InvalidPackage'
}
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.example.Smart_Medicine_Box"
minSdkVersion 19
targetSdkVersion 29
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
}
buildTypes {
release {
// TODO: Add your own signing config for the release build.
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig signingConfigs.debug
}
}
}
flutter {
source '../..'
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.flutter_application_1">
<!-- Flutter needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.flutter_application_1">
<!-- io.flutter.app.FlutterApplication is an android.app.Application that
calls FlutterMain.startInitialization(this); in its onCreate method.
In most cases you can leave this as-is, but you if you want to provide
additional functionality it is fine to subclass or reimplement
FlutterApplication and put your custom class here. -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<application
android:name="io.flutter.app.FlutterApplication"
android:label="Smart_Medicine_Box"
android:icon="@mipmap/ic_launcher">
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:theme="@style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<!-- Specifies an Android theme to apply to this Activity as soon as
the Android process has started. This theme is visible to the user
while the Flutter UI initializes. After that, this theme continues
to determine the Window background behind the Flutter UI. -->
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="@style/NormalTheme"
/>
<!-- Displays an Android View that continues showing the launch screen
Drawable until Flutter paints its first frame, then this splash
screen fades out. A splash screen is useful to avoid any visual
gap between the end of Android's launch screen and the painting of
Flutter's first frame. -->
<meta-data
android:name="io.flutter.embedding.android.SplashScreenDrawable"
android:resource="@drawable/launch_background"
/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.MY_PACKAGE_REPLACED"/>
</intent-filter>
</receiver>
<receiver android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationReceiver" />
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
</manifest>
package com.example.flutter_application_1
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
<?xml version="1.0" encoding="utf-8"?>
<!-- Modify this file to customize your launch splash screen -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@android:color/white" />
<!-- You can insert your own image assets here -->
<!-- <item>
<bitmap
android:gravity="center"
android:src="@mipmap/launch_image" />
</item> -->
</layer-list>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Theme applied to the Android Window while the process is starting -->
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
<!-- Show a splash screen on the activity. Automatically removed when
Flutter draws its first frame -->
<item name="android:windowBackground">@drawable/launch_background</item>
</style>
<!-- Theme applied to the Android Window as soon as the process has started.
This theme determines the color of the Android Window while your
Flutter UI initializes, as well as behind your Flutter UI while its
running.
This Theme is only used starting with V2 of Flutter's Android embedding. -->
<style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">
<item name="android:windowBackground">@android:color/white</item>
</style>
</resources>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.flutter_application_1">
<!-- Flutter needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
buildscript {
ext.kotlin_version = '1.3.50'
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.5.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
allprojects {
repositories {
google()
jcenter()
}
}
rootProject.buildDir = '../build'
subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
project.evaluationDependsOn(':app')
}
task clean(type: Delete) {
delete rootProject.buildDir
}
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
android.enableR8=true
#Fri Jun 23 08:50:38 CEST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.2-all.zip
include ':app'
def localPropertiesFile = new File(rootProject.projectDir, "local.properties")
def properties = new Properties()
assert localPropertiesFile.exists()
localPropertiesFile.withReader("UTF-8") { reader -> properties.load(reader) }
def flutterSdkPath = properties.getProperty("flutter.sdk")
assert flutterSdkPath != null, "flutter.sdk not set in local.properties"
apply from: "$flutterSdkPath/packages/flutter_tools/gradle/app_plugin_loader.gradle"
*.mode1v3
*.mode2v3
*.moved-aside
*.pbxuser
*.perspectivev3
**/*sync/
.sconsign.dblite
.tags*
**/.vagrant/
**/DerivedData/
Icon?
**/Pods/
**/.symlinks/
profile
xcuserdata
**/.generated/
Flutter/App.framework
Flutter/Flutter.framework
Flutter/Flutter.podspec
Flutter/Generated.xcconfig
Flutter/app.flx
Flutter/app.zip
Flutter/flutter_assets/
Flutter/flutter_export_environment.sh
ServiceDefinitions.json
Runner/GeneratedPluginRegistrant.*
# Exceptions to above rules.
!default.mode1v3
!default.mode2v3
!default.pbxuser
!default.perspectivev3
<?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>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>App</string>
<key>CFBundleIdentifier</key>
<string>io.flutter.flutter.app</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>App</string>
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1.0</string>
<key>MinimumOSVersion</key>
<string>8.0</string>
</dict>
</plist>
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 46;
objects = {
/* Begin PBXBuildFile section */
1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; };
3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; };
74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; };
97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; };
97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; };
97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; };
/* End PBXBuildFile section */
/* Begin PBXCopyFilesBuildPhase section */
9705A1C41CF9048500538489 /* Embed Frameworks */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
dstPath = "";
dstSubfolderSpec = 10;
files = (
);
name = "Embed Frameworks";
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = "<group>"; };
1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = "<group>"; };
3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = "<group>"; };
74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = "<group>"; };
74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = "<group>"; };
9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = "<group>"; };
9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = "<group>"; };
97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; };
97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = "<group>"; };
97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = "<group>"; };
97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
97C146EB1CF9000F007C117D /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
9740EEB11CF90186004384FC /* Flutter */ = {
isa = PBXGroup;
children = (
3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */,
9740EEB21CF90195004384FC /* Debug.xcconfig */,
7AFA3C8E1D35360C0083082E /* Release.xcconfig */,
9740EEB31CF90195004384FC /* Generated.xcconfig */,
);
name = Flutter;
sourceTree = "<group>";
};
97C146E51CF9000F007C117D = {
isa = PBXGroup;
children = (
9740EEB11CF90186004384FC /* Flutter */,
97C146F01CF9000F007C117D /* Runner */,
97C146EF1CF9000F007C117D /* Products */,
);
sourceTree = "<group>";
};
97C146EF1CF9000F007C117D /* Products */ = {
isa = PBXGroup;
children = (
97C146EE1CF9000F007C117D /* Runner.app */,
);
name = Products;
sourceTree = "<group>";
};
97C146F01CF9000F007C117D /* Runner */ = {
isa = PBXGroup;
children = (
97C146FA1CF9000F007C117D /* Main.storyboard */,
97C146FD1CF9000F007C117D /* Assets.xcassets */,
97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */,
97C147021CF9000F007C117D /* Info.plist */,
1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */,
1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */,
74858FAE1ED2DC5600515810 /* AppDelegate.swift */,
74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */,
);
path = Runner;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
97C146ED1CF9000F007C117D /* Runner */ = {
isa = PBXNativeTarget;
buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */;
buildPhases = (
9740EEB61CF901F6004384FC /* Run Script */,
97C146EA1CF9000F007C117D /* Sources */,
97C146EB1CF9000F007C117D /* Frameworks */,
97C146EC1CF9000F007C117D /* Resources */,
9705A1C41CF9048500538489 /* Embed Frameworks */,
3B06AD1E1E4923F5004D2608 /* Thin Binary */,
);
buildRules = (
);
dependencies = (
);
name = Runner;
productName = Runner;
productReference = 97C146EE1CF9000F007C117D /* Runner.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
97C146E61CF9000F007C117D /* Project object */ = {
isa = PBXProject;
attributes = {
LastUpgradeCheck = 1020;
ORGANIZATIONNAME = "";
TargetAttributes = {
97C146ED1CF9000F007C117D = {
CreatedOnToolsVersion = 7.3.1;
LastSwiftMigration = 1100;
};
};
};
buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */;
compatibilityVersion = "Xcode 9.3";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = 97C146E51CF9000F007C117D;
productRefGroup = 97C146EF1CF9000F007C117D /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
97C146ED1CF9000F007C117D /* Runner */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
97C146EC1CF9000F007C117D /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */,
3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */,
97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */,
97C146FC1CF9000F007C117D /* Main.storyboard in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
3B06AD1E1E4923F5004D2608 /* Thin Binary */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "Thin Binary";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin";
};
9740EEB61CF901F6004384FC /* Run Script */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "Run Script";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build";
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
97C146EA1CF9000F007C117D /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */,
1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXVariantGroup section */
97C146FA1CF9000F007C117D /* Main.storyboard */ = {
isa = PBXVariantGroup;
children = (
97C146FB1CF9000F007C117D /* Base */,
);
name = Main.storyboard;
sourceTree = "<group>";
};
97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = {
isa = PBXVariantGroup;
children = (
97C147001CF9000F007C117D /* Base */,
);
name = LaunchScreen.storyboard;
sourceTree = "<group>";
};
/* End PBXVariantGroup section */
/* Begin XCBuildConfiguration section */
249021D3217E4FDB00AE95B9 /* Profile */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
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_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;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
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 = 9.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SUPPORTED_PLATFORMS = iphoneos;
TARGETED_DEVICE_FAMILY = "1,2";
VALIDATE_PRODUCT = YES;
};
name = Profile;
};
249021D4217E4FDB00AE95B9 /* Profile */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
ENABLE_BITCODE = NO;
FRAMEWORK_SEARCH_PATHS = (
"$(inherited)",
"$(PROJECT_DIR)/Flutter",
);
INFOPLIST_FILE = Runner/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
LIBRARY_SEARCH_PATHS = (
"$(inherited)",
"$(PROJECT_DIR)/Flutter",
);
PRODUCT_BUNDLE_IDENTIFIER = com.example.flutterApplication1;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
SWIFT_VERSION = 5.0;
VERSIONING_SYSTEM = "apple-generic";
};
name = Profile;
};
97C147031CF9000F007C117D /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
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_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;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
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_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 = 9.0;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
TARGETED_DEVICE_FAMILY = "1,2";
};
name = Debug;
};
97C147041CF9000F007C117D /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
CLANG_ANALYZER_NONNULL = YES;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
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_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;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
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 = 9.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SUPPORTED_PLATFORMS = iphoneos;
SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
TARGETED_DEVICE_FAMILY = "1,2";
VALIDATE_PRODUCT = YES;
};
name = Release;
};
97C147061CF9000F007C117D /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
ENABLE_BITCODE = NO;
FRAMEWORK_SEARCH_PATHS = (
"$(inherited)",
"$(PROJECT_DIR)/Flutter",
);
INFOPLIST_FILE = Runner/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
LIBRARY_SEARCH_PATHS = (
"$(inherited)",
"$(PROJECT_DIR)/Flutter",
);
PRODUCT_BUNDLE_IDENTIFIER = com.example.flutterApplication1;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0;
VERSIONING_SYSTEM = "apple-generic";
};
name = Debug;
};
97C147071CF9000F007C117D /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)";
ENABLE_BITCODE = NO;
FRAMEWORK_SEARCH_PATHS = (
"$(inherited)",
"$(PROJECT_DIR)/Flutter",
);
INFOPLIST_FILE = Runner/Info.plist;
LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
LIBRARY_SEARCH_PATHS = (
"$(inherited)",
"$(PROJECT_DIR)/Flutter",
);
PRODUCT_BUNDLE_IDENTIFIER = com.example.flutterApplication1;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h";
SWIFT_VERSION = 5.0;
VERSIONING_SYSTEM = "apple-generic";
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = {
isa = XCConfigurationList;
buildConfigurations = (
97C147031CF9000F007C117D /* Debug */,
97C147041CF9000F007C117D /* Release */,
249021D3217E4FDB00AE95B9 /* Profile */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = {
isa = XCConfigurationList;
buildConfigurations = (
97C147061CF9000F007C117D /* Debug */,
97C147071CF9000F007C117D /* Release */,
249021D4217E4FDB00AE95B9 /* Profile */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 97C146E61CF9000F007C117D /* Project object */;
}
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "group:Runner.xcodeproj">
</FileRef>
</Workspace>
<?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>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
<?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>PreviewsEnabled</key>
<false/>
</dict>
</plist>
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1020"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "97C146ED1CF9000F007C117D"
BuildableName = "Runner.app"
BlueprintName = "Runner"
ReferencedContainer = "container:Runner.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
</Testables>
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "97C146ED1CF9000F007C117D"
BuildableName = "Runner.app"
BlueprintName = "Runner"
ReferencedContainer = "container:Runner.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</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 = "97C146ED1CF9000F007C117D"
BuildableName = "Runner.app"
BlueprintName = "Runner"
ReferencedContainer = "container:Runner.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Profile"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "97C146ED1CF9000F007C117D"
BuildableName = "Runner.app"
BlueprintName = "Runner"
ReferencedContainer = "container:Runner.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "group:Runner.xcodeproj">
</FileRef>
</Workspace>
<?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>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
<?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>PreviewsEnabled</key>
<false/>
</dict>
</plist>
import UIKit
import Flutter
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
{
"images" : [
{
"size" : "20x20",
"idiom" : "iphone",
"filename" : "Icon-App-20x20@2x.png",
"scale" : "2x"
},
{
"size" : "20x20",
"idiom" : "iphone",
"filename" : "Icon-App-20x20@3x.png",
"scale" : "3x"
},
{
"size" : "29x29",
"idiom" : "iphone",
"filename" : "Icon-App-29x29@1x.png",
"scale" : "1x"
},
{
"size" : "29x29",
"idiom" : "iphone",
"filename" : "Icon-App-29x29@2x.png",
"scale" : "2x"
},
{
"size" : "29x29",
"idiom" : "iphone",
"filename" : "Icon-App-29x29@3x.png",
"scale" : "3x"
},
{
"size" : "40x40",
"idiom" : "iphone",
"filename" : "Icon-App-40x40@2x.png",
"scale" : "2x"
},
{
"size" : "40x40",
"idiom" : "iphone",
"filename" : "Icon-App-40x40@3x.png",
"scale" : "3x"
},
{
"size" : "60x60",
"idiom" : "iphone",
"filename" : "Icon-App-60x60@2x.png",
"scale" : "2x"
},
{
"size" : "60x60",
"idiom" : "iphone",
"filename" : "Icon-App-60x60@3x.png",
"scale" : "3x"
},
{
"size" : "20x20",
"idiom" : "ipad",
"filename" : "Icon-App-20x20@1x.png",
"scale" : "1x"
},
{
"size" : "20x20",
"idiom" : "ipad",
"filename" : "Icon-App-20x20@2x.png",
"scale" : "2x"
},
{
"size" : "29x29",
"idiom" : "ipad",
"filename" : "Icon-App-29x29@1x.png",
"scale" : "1x"
},
{
"size" : "29x29",
"idiom" : "ipad",
"filename" : "Icon-App-29x29@2x.png",
"scale" : "2x"
},
{
"size" : "40x40",
"idiom" : "ipad",
"filename" : "Icon-App-40x40@1x.png",
"scale" : "1x"
},
{
"size" : "40x40",
"idiom" : "ipad",
"filename" : "Icon-App-40x40@2x.png",
"scale" : "2x"
},
{
"size" : "76x76",
"idiom" : "ipad",
"filename" : "Icon-App-76x76@1x.png",
"scale" : "1x"
},
{
"size" : "76x76",
"idiom" : "ipad",
"filename" : "Icon-App-76x76@2x.png",
"scale" : "2x"
},
{
"size" : "83.5x83.5",
"idiom" : "ipad",
"filename" : "Icon-App-83.5x83.5@2x.png",
"scale" : "2x"
},
{
"size" : "1024x1024",
"idiom" : "ios-marketing",
"filename" : "Icon-App-1024x1024@1x.png",
"scale" : "1x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
{
"images" : [
{
"idiom" : "universal",
"filename" : "LaunchImage.png",
"scale" : "1x"
},
{
"idiom" : "universal",
"filename" : "LaunchImage@2x.png",
"scale" : "2x"
},
{
"idiom" : "universal",
"filename" : "LaunchImage@3x.png",
"scale" : "3x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
# Launch Screen Assets
You can customize the launch screen with your own desired assets by replacing the image files in this directory.
You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images.
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="12121" systemVersion="16G29" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" colorMatched="YES" initialViewController="01J-lp-oVM">
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12089"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="EHf-IW-A2E">
<objects>
<viewController id="01J-lp-oVM" sceneMemberID="viewController">
<layoutGuides>
<viewControllerLayoutGuide type="top" id="Ydg-fD-yQy"/>
<viewControllerLayoutGuide type="bottom" id="xbc-2k-c8Z"/>
</layoutGuides>
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<imageView opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" image="LaunchImage" translatesAutoresizingMaskIntoConstraints="NO" id="YRO-k0-Ey4">
</imageView>
</subviews>
<color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<constraints>
<constraint firstItem="YRO-k0-Ey4" firstAttribute="centerX" secondItem="Ze5-6b-2t3" secondAttribute="centerX" id="1a2-6s-vTC"/>
<constraint firstItem="YRO-k0-Ey4" firstAttribute="centerY" secondItem="Ze5-6b-2t3" secondAttribute="centerY" id="4X2-HB-R7a"/>
</constraints>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="53" y="375"/>
</scene>
</scenes>
<resources>
<image name="LaunchImage" width="168" height="185"/>
</resources>
</document>
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="10117" systemVersion="15F34" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" initialViewController="BYZ-38-t0r">
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="10085"/>
</dependencies>
<scenes>
<!--Flutter View Controller-->
<scene sceneID="tne-QT-ifu">
<objects>
<viewController id="BYZ-38-t0r" customClass="FlutterViewController" sceneMemberID="viewController">
<layoutGuides>
<viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/>
<viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/>
</layoutGuides>
<view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
<rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
</objects>
</scene>
</scenes>
</document>
<?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>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</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>flutter_application_1</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>$(FLUTTER_BUILD_NAME)</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>$(FLUTTER_BUILD_NUMBER)</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
<string>Main</string>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
</dict>
</plist>
import 'package:flutter/material.dart';
import './src/screens/Homepage.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
Future main() async {
await DotEnv().load('.env');
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'SMART MEDICINE BOX',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomePage(),
);
}
}
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:intl/intl.dart';
import '../utils/user_secure_stoarge.dart';
import 'models/Bottle.dart';
import 'models/Medicine.dart';
import 'package:Smart_Medicine_Box/src/screens/SettingPage.dart';
import 'Register/BottleList.dart';
import 'Register/SearchMedicine.dart';
import 'package:intl/date_symbol_data_local.dart';
class DashBoard extends StatefulWidget {
int pageNumber;
DashBoard({
Key key,
this.pageNumber,
}) : super(key: key);
@override
_DashBoardState createState() => _DashBoardState();
}
class _DashBoardState extends State<DashBoard> {
int _selectedIndex = 0;
List<Bottle> _bottleList = new List<Bottle>();
//Get BottleList
Future<String> getBottleList() async {
String usertoken = await UserSecureStorage.getUserToken();
String hubid = await UserSecureStorage.getHubId();
http.Response response = await http.get(
Uri.encodeFull(DotEnv().env['SERVER_URL'] + 'bottle/hub/' + hubid),
headers: {"authorization": usertoken},
);
if (_bottleList.length != 0) {
_bottleList.clear();
}
if (response.statusCode == 200) {
List<dynamic> values = new List<dynamic>();
values = json.decode(response.body);
for (int i = 0; i < values.length; i++) {
Map<String, dynamic> map = values[i];
_bottleList.add(Bottle.fromJson(map));
return "GET";
}
} else if (response.statusCode == 404) {
return "Not Found";
} else {
return "Error";
}
return "Error";
}
Widget build(BuildContext context) {
_selectedIndex = widget.pageNumber;
var _tabs = [
ineerInformationpage(context),
mainpage(context),
outerInformationpage(context),
];
return WillPopScope(
child: Scaffold(
backgroundColor: Color(0xffe5f4ff),
appBar: AppBar(
iconTheme: IconThemeData(color: Colors.black),
backgroundColor: Colors.white,
title: Text(
'Smart Medicine Box',
style: TextStyle(
color: Colors.black,
fontSize: 20,
fontFamily: 'Noto',
fontWeight: FontWeight.bold),
),
actions: [
IconButton(
icon: Icon(
Icons.settings,
color: Colors.black,
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) => SettingPage(),
));
},
)
],
),
drawer: Drawer(
child: ListView(
children: [
DrawerHeader(
child: Text('Drawer Header'),
decoration: BoxDecoration(
color: Colors.blue,
),
),
],
),
),
body: _tabs[_selectedIndex],
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {});
},
child: const Icon(Icons.refresh_outlined),
backgroundColor: Colors.blue,
),
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
backgroundColor: Colors.grey,
selectedItemColor: Colors.blue,
unselectedItemColor: Colors.white.withOpacity(.60),
selectedFontSize: 14,
unselectedFontSize: 14,
currentIndex: _selectedIndex,
onTap: (int index) => {
setState(() {
_onItemTapped(index);
})
},
items: [
BottomNavigationBarItem(
icon: Icon(Icons.device_thermostat), label: 'In'),
BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
BottomNavigationBarItem(
label: 'Out',
icon: Icon(Icons.access_time),
)
],
),
),
onWillPop: () async {
await getBottleList();
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) => BottleList(),
));
},
);
}
void _onItemTapped(int index) {
setState(() {
widget.pageNumber = index;
});
}
}
Widget mainpage(BuildContext context) {
Medicine _medicineInformation = new Medicine();
Future<Medicine> _getmedicine() async {
String usertoken = await UserSecureStorage.getUserToken();
String medicineid = await UserSecureStorage.getMedicineId();
http.Response medicineresponse = await http.get(
Uri.encodeFull(
DotEnv().env['SERVER_URL'] + 'medicine/' + medicineid.toString()),
headers: {"authorization": usertoken},
);
if (medicineresponse.statusCode == 200) {
Map<String, dynamic> data = jsonDecode(medicineresponse.body);
_medicineInformation = Medicine.fromJson(data);
}
return _medicineInformation;
}
final Size size = MediaQuery.of(context).size;
return Scaffold(
backgroundColor: Colors.white,
body: SingleChildScrollView(
child: FutureBuilder(
future: _getmedicine(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData == false) {
return CircularProgressIndicator();
} else if (snapshot.hasError) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'Error: ${snapshot.error}',
style: TextStyle(fontSize: 15),
),
);
} else {
return Container(
margin: EdgeInsets.fromLTRB(0, 30, 0, 0),
padding: EdgeInsets.fromLTRB(5, 0, 5, 5),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
SizedBox(height: 20),
Container(
width: size.width,
padding: EdgeInsets.fromLTRB(5, 0, 5, 5),
margin: EdgeInsets.all(15),
decoration: BoxDecoration(
border: Border.all(),
borderRadius: BorderRadius.all(Radius.circular(
25.0) // <--- border radius here
),
),
child: Column(
children: [
SizedBox(height: 30),
Container(
child: Center(
child: Text(
'${snapshot.data.name}' == null
? '-'
: '${snapshot.data.name}',
style: TextStyle(
color: Colors.black,
fontSize: 24,
fontFamily: 'NotoSansKR',
fontWeight: FontWeight.w700)),
),
),
SizedBox(height: 30),
Container(
width: size.width,
alignment: Alignment(0.9, 0),
child: Wrap(
children: [
Text(
'제조사: ',
style: TextStyle(
color: Colors.grey,
fontSize: 14,
),
),
Text(
_medicineInformation.company == null
? '-'
: _medicineInformation.company,
style: TextStyle(
color: Colors.grey,
fontSize: 14,
),
),
],
),
),
SizedBox(height: 30),
Container(
width: size.width,
padding: EdgeInsets.fromLTRB(5, 0, 5, 0),
alignment: Alignment(-1, 0),
child: Wrap(
children: [
Text(
'타겟 층 : ',
style: TextStyle(
color: Colors.grey,
fontSize: 14,
),
),
Text(
_medicineInformation.target == null
? '-'
: _medicineInformation.target,
style: TextStyle(
color: Colors.grey,
fontSize: 14,
),
),
],
),
),
SizedBox(height: 15),
Container(
width: size.width,
padding: EdgeInsets.fromLTRB(5, 0, 5, 0),
alignment: Alignment(-1, 0),
child: Wrap(
children: [
Text(
'복약 정보 : ',
style: TextStyle(
color: Colors.grey,
fontSize: 14,
),
),
Text(
_medicineInformation.dosage == null
? '-'
: _medicineInformation.dosage,
style: TextStyle(
color: Colors.grey,
fontSize: 14,
),
),
],
),
),
SizedBox(height: 10),
Container(
width: size.width,
padding: EdgeInsets.fromLTRB(5, 10, 5, 10),
alignment: Alignment(-1, 0),
child: Column(
children: [
SizedBox(
height: 12,
),
Container(
width: size.width,
child: Text(
'경고',
style: TextStyle(
color: Colors.redAccent, fontSize: 14),
),
),
SizedBox(height: 12),
Container(
width: size.width,
child: Text(
_medicineInformation.warn == null
? '-'
: _medicineInformation.warn,
style: TextStyle(
color: Colors.redAccent, fontSize: 14),
),
),
],
),
),
],
),
),
GestureDetector(
child: Container(
width: size.width * 0.8,
height: 46,
margin: EdgeInsets.only(bottom: 0),
child: FlatButton(
padding: EdgeInsets.fromLTRB(0, 5, 0, 5),
onPressed: () async {
String bottleid =
await UserSecureStorage.getBottleId();
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) => SearchMedicine(
bottleId: bottleid,
),
),
);
},
child: Text(
'약 검색',
textScaleFactor: 1.0,
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontFamily: 'Noto',
fontWeight: FontWeight.bold),
),
color: Color(0xff1674f6),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50)),
),
),
),
],
),
);
}
},
),
),
);
}
Widget ineerInformationpage(BuildContext context) {
//get bottle
Future<Bottle> _getbottle() async {
String usertoken = await UserSecureStorage.getUserToken();
String bottleid = await UserSecureStorage.getBottleId();
Bottle _bottleinformation = new Bottle();
http.Response response = await http.get(
Uri.encodeFull(DotEnv().env['SERVER_URL'] + 'bottle/' + bottleid),
headers: {"authorization": usertoken});
if (response.statusCode == 200) {
Map<String, dynamic> jsonData = jsonDecode(response.body);
_bottleinformation = Bottle.fromJson(jsonData);
}
return _bottleinformation;
}
final Size size = MediaQuery.of(context).size;
return Scaffold(
backgroundColor: Colors.white,
body: FutureBuilder(
future: _getbottle(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData == false) {
return CircularProgressIndicator();
} else if (snapshot.hasError) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'Error: ${snapshot.error}',
style: TextStyle(fontSize: 15),
),
);
} else {
return Container(
height: size.height * 0.9,
margin: EdgeInsets.fromLTRB(0, 30, 0, 0),
padding: EdgeInsets.fromLTRB(5, 0, 5, 5),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
padding: EdgeInsets.fromLTRB(5, 5, 5, 5),
height: size.height * 0.08,
width: size.width,
child: Center(
child: Text(
'Inside Information',
textAlign: TextAlign.center,
textScaleFactor: 1.0,
style: TextStyle(
color: Colors.black,
fontSize: 32,
fontFamily: 'NotoSansKR',
fontWeight: FontWeight.w700),
),
),
),
Container(
padding: EdgeInsets.fromLTRB(5, 0, 5, 5),
margin: EdgeInsets.fromLTRB(0, 10, 0, 0),
height: size.height * 0.25,
width: size.width,
child: Column(
children: <Widget>[
Flexible(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
width: size.width * 0.43,
height: size.width * 0.45,
margin: const EdgeInsets.all(5.0),
padding: const EdgeInsets.fromLTRB(10, 5, 10, 10),
decoration: BoxDecoration(
color: Color(0xff8E97FD),
borderRadius: BorderRadius.circular(10.0),
),
child: Column(
children: [
Container(
width: size.width,
height: size.height * 0.05,
child: Center(
child: Text(
'약병 내부 온도',
textAlign: TextAlign.center,
textScaleFactor: 1.0,
style: TextStyle(
color: Colors.white,
fontSize: 24,
fontFamily: 'NotoSansKR',
fontWeight: FontWeight.w800),
),
),
),
Container(
width: size.width,
height: size.height * 0.145,
child: Center(
child: Row(
mainAxisAlignment:
MainAxisAlignment.center,
children: [
Text(
'${snapshot.data.temperature}' ==
null
? '-'
: '${snapshot.data.temperature}',
textAlign: TextAlign.center,
textScaleFactor: 1.0,
style: TextStyle(
color: Colors.white,
fontSize: 50,
fontFamily: 'NotoSansKR',
fontWeight: FontWeight.w800),
),
Text(
'℃',
textAlign: TextAlign.center,
textScaleFactor: 1.0,
style: TextStyle(
color: Colors.white,
fontSize: 50,
fontFamily: 'NotoSansKR',
fontWeight: FontWeight.w800),
)
],
),
),
),
],
),
),
Container(
width: size.width * 0.43,
height: size.width * 0.45,
margin: const EdgeInsets.all(5.0),
padding: const EdgeInsets.fromLTRB(10, 5, 10, 10),
decoration: BoxDecoration(
color: Color(0xff8E97FD),
borderRadius: BorderRadius.circular(10.0),
),
child: Column(
children: [
Container(
width: size.width,
height: size.height * 0.05,
child: Center(
child: Text(
'약병 내부 습도',
textAlign: TextAlign.center,
textScaleFactor: 1.0,
style: TextStyle(
color: Colors.white,
fontSize: 24,
fontFamily: 'NotoSansKR',
fontWeight: FontWeight.w800),
),
),
),
Container(
width: size.width,
height: size.height * 0.14,
child: Center(
child: Row(
mainAxisAlignment:
MainAxisAlignment.center,
children: [
Text(
snapshot.data.humidity.toString() ==
null
? '-'
: snapshot.data.humidity
.toString(),
textAlign: TextAlign.center,
textScaleFactor: 1.0,
style: TextStyle(
color: Colors.white,
fontSize: 50,
fontFamily: 'NotoSansKR',
fontWeight: FontWeight.w800),
),
Text(
'%',
textAlign: TextAlign.center,
textScaleFactor: 1.0,
style: TextStyle(
color: Colors.white,
fontSize: 50,
fontFamily: 'NotoSansKR',
fontWeight: FontWeight.w800),
)
],
),
),
),
],
),
),
],
),
),
],
),
),
Container(
padding: EdgeInsets.fromLTRB(5, 0, 5, 5),
margin: EdgeInsets.fromLTRB(0, 0, 0, 0),
height: size.height * 0.3,
width: size.width,
child: Column(
children: <Widget>[
Flexible(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
width: size.width * 0.43,
height: size.width * 0.45,
margin: const EdgeInsets.all(5.0),
padding: const EdgeInsets.fromLTRB(10, 5, 10, 10),
decoration: BoxDecoration(
color: Color(0xff8E97FD),
borderRadius: BorderRadius.circular(10.0),
),
child: Column(
children: [
Container(
width: size.width,
height: size.height * 0.05,
child: Center(
child: Text(
'약병 내부 잔량',
textAlign: TextAlign.center,
textScaleFactor: 1.0,
style: TextStyle(
color: Colors.white,
fontSize: 24,
fontFamily: 'NotoSansKR',
fontWeight: FontWeight.w800),
),
),
),
Container(
width: size.width,
height: size.height * 0.14,
child: Center(
child: Row(
mainAxisAlignment:
MainAxisAlignment.center,
children: [
Text(
snapshot.data.balance.toString() ==
null
? '-'
: snapshot.data.balance
.toString(),
textAlign: TextAlign.center,
textScaleFactor: 1.0,
style: TextStyle(
color: Colors.white,
fontSize: 80,
fontFamily: 'NotoSansKR',
fontWeight: FontWeight.w800),
),
Text(
'%',
textAlign: TextAlign.center,
textScaleFactor: 1.0,
style: TextStyle(
color: Colors.white,
fontSize: 60,
fontFamily: 'NotoSansKR',
fontWeight: FontWeight.w800),
)
],
),
),
),
],
),
),
Container(
width: size.width * 0.43,
height: size.width * 0.45,
margin: const EdgeInsets.all(5.0),
padding: const EdgeInsets.fromLTRB(10, 5, 10, 10),
decoration: BoxDecoration(
color: Color(0xff8E97FD),
borderRadius: BorderRadius.circular(10.0),
),
child: Column(
children: [
Container(
width: size.width,
height: size.height * 0.05,
child: Center(
child: Text(
'최근 개폐 시간',
textAlign: TextAlign.center,
textScaleFactor: 1.0,
style: TextStyle(
color: Colors.white,
fontSize: 24,
fontFamily: 'NotoSansKR',
fontWeight: FontWeight.w800),
),
),
),
Container(
width: size.width,
height: size.height * 0.14,
child: Center(
child: Text(
snapshot.data.recentOpen == null
? '-'
: DateFormat.Hm().format(
snapshot.data.recentOpen),
textAlign: TextAlign.center,
textScaleFactor: 1.0,
style: TextStyle(
color: Colors.white,
fontSize: 60,
fontFamily: 'NotoSansKR',
fontWeight: FontWeight.w800),
),
),
),
],
),
),
],
),
),
],
),
),
],
),
);
}
},
),
);
}
Widget outerInformationpage(BuildContext context) {
Bottle _bottleinformation = new Bottle();
//get bottle
Future<Bottle> _getbottle() async {
String usertoken = await UserSecureStorage.getUserToken();
String bottleid = await UserSecureStorage.getBottleId();
Bottle _bottleinformation = new Bottle();
http.Response response = await http.get(
Uri.encodeFull(DotEnv().env['SERVER_URL'] + 'bottle/' + bottleid),
headers: {"authorization": usertoken});
if (response.statusCode == 200) {
Map<String, dynamic> jsonData = jsonDecode(response.body);
_bottleinformation = Bottle.fromJson(jsonData);
}
return _bottleinformation;
}
final Size size = MediaQuery.of(context).size;
return Scaffold(
backgroundColor: Colors.white,
body: FutureBuilder(
future: _getbottle(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData == false) {
return CircularProgressIndicator();
} else if (snapshot.hasError) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'Error: ${snapshot.error}',
style: TextStyle(fontSize: 15),
),
);
} else {
return Container(
height: size.height * 0.9,
margin: EdgeInsets.fromLTRB(0, 30, 0, 0),
padding: EdgeInsets.fromLTRB(5, 0, 5, 5),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
padding: EdgeInsets.fromLTRB(5, 5, 5, 5),
height: size.height * 0.08,
width: size.width,
child: Center(
child: Text(
'Outside Information',
textAlign: TextAlign.center,
textScaleFactor: 1.0,
style: TextStyle(
color: Colors.black,
fontSize: 32,
fontFamily: 'NotoSansKR',
fontWeight: FontWeight.w700),
),
),
),
Container(
padding: EdgeInsets.fromLTRB(5, 0, 5, 5),
margin: EdgeInsets.fromLTRB(0, 10, 0, 0),
height: size.height * 0.20,
width: size.width,
child: Column(
children: <Widget>[
Flexible(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
padding: EdgeInsets.fromLTRB(5, 5, 5, 0),
width: size.width * 0.9,
height: size.height * 0.18,
decoration: BoxDecoration(
color: Color(0xff8E97FD),
borderRadius: BorderRadius.circular(10.0),
),
child: Column(
children: [
Container(
width: size.width,
height: size.height * 0.05,
child: Center(
child: Text(
'권장 약 복용량',
textAlign: TextAlign.center,
textScaleFactor: 1.0,
style: TextStyle(
color: Colors.white,
fontSize: 28,
fontFamily: 'NotoSansKR',
fontWeight: FontWeight.w800),
),
),
),
Container(
width: size.width,
height: size.height * 0.12,
child: Row(
mainAxisAlignment:
MainAxisAlignment.center,
children: [
Text(
snapshot.data.dosage == null
? '-'
: snapshot.data.dosage
.toString(),
textAlign: TextAlign.center,
textScaleFactor: 1.0,
style: TextStyle(
color: Colors.white,
fontSize: 80,
fontFamily: 'NotoSansKR',
fontWeight: FontWeight.w800),
),
Text(
' 개',
textScaleFactor: 1.0,
style: TextStyle(
color: Colors.white,
fontSize: 64,
fontFamily: 'NotoSansKR',
fontWeight: FontWeight.w800),
)
],
),
),
],
),
),
],
),
),
],
),
),
],
),
);
}
}),
);
}
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../shared/colors.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import './Register/SignInPage.dart';
import 'Register/SignUpLocal.dart';
class HomePage extends StatefulWidget {
HomePage({Key key}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
/// first page class
class _HomePageState extends State<HomePage> {
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
final Size size = MediaQuery.of(context).size;
return Scaffold(
body: GestureDetector(
child: Container(
color: Colors.white,
height: size.height,
child: Center(
child: MediaQuery(
data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
height: size.height * 0.5,
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'SMART MEDICINE BOX',
textScaleFactor: 1.0,
style: TextStyle(
color: Color(0xff004ca2),
fontSize: 30,
fontFamily: 'Noto',
fontWeight: FontWeight.bold),
),
],
),
AnimatedOpacity(
opacity: 1,
duration: Duration(milliseconds: 500),
child: Container(
padding: EdgeInsets.fromLTRB(0, 0, 0, 20),
child: Image.asset('images/main_logo.png',
width: 200, height: 250)),
),
],
),
),
Container(
height: size.height * 0.3,
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
GestureDetector(
child: Container(
width: size.width * 0.8,
height: 46,
margin: EdgeInsets.only(bottom: 0),
child: FlatButton(
padding: EdgeInsets.fromLTRB(0, 5, 0, 5),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) =>
SignInPage(),
),
);
},
child: Text(
'로그인',
textScaleFactor: 1.0,
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontFamily: 'Noto',
fontWeight: FontWeight.bold),
),
color: Color(0xff1674f6),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50)),
),
),
),
GestureDetector(
child: Container(
width: size.width * 0.8,
padding: EdgeInsets.all(0),
child: OutlineButton(
padding: EdgeInsets.fromLTRB(0, 25, 0, 15),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) =>
SignUpLocal(),
),
);
},
child: Text(
'회원 가입',
textScaleFactor: 1.0,
style:
TextStyle(fontSize: 16, fontFamily: 'Noto'),
),
textColor: Colors.black,
highlightedBorderColor: highlightColor,
borderSide: BorderSide.none,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50)),
),
),
),
],
),
),
],
),
)),
),
),
backgroundColor: bgColor,
);
}
}
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'package:flutter_dotenv/flutter_dotenv.dart';
import '../models/Bottle.dart';
import '../DashBoard.dart';
import '../../utils/user_secure_stoarge.dart';
class BottleList extends StatefulWidget {
BottleList({Key key}) : super(key: key);
@override
_BottleListState createState() => _BottleListState();
}
class _BottleListState extends State<BottleList> {
String valueText;
List<Bottle> _bottleList = new List<Bottle>();
TextEditingController _textFieldController = TextEditingController();
Future<String> getBottleList() async {
String hubid = await UserSecureStorage.getHubId();
String usertoken = await UserSecureStorage.getUserToken();
http.Response response = await http.get(
Uri.encodeFull(
DotEnv().env['SERVER_URL'] + 'bottle/hub/' + hubid.toString()),
headers: {"authorization": usertoken},
);
if (_bottleList.length != 0) {
_bottleList.clear();
}
if (response.statusCode == 200) {
List<dynamic> values = new List<dynamic>();
values = json.decode(response.body);
for (int i = 0; i < values.length; i++) {
Map<String, dynamic> map = values[i];
_bottleList.add(Bottle.fromJson(map));
}
return "GET";
} else if (response.statusCode == 404) {
return "Not Found";
} else {
return "Error";
}
}
Widget build(BuildContext context) {
final Size size = MediaQuery.of(context).size;
return WillPopScope(
child: Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
leading: new Icon(Icons.medical_services_rounded,
color: Colors.black, size: 45.0),
title: Text(
'Smart Medicine Box',
style: TextStyle(
color: Colors.black,
fontSize: 23,
fontFamily: 'Noto',
fontWeight: FontWeight.bold),
),
),
body: FutureBuilder(
future: getBottleList(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData == false) {
return CircularProgressIndicator();
} else if (snapshot.hasError) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'Error: ${snapshot.error}',
style: TextStyle(fontSize: 15),
),
);
} else {
return Container(
height: size.height,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SizedBox(height: 10),
Container(
height: size.height * 0.07,
width: size.width,
child: Center(
child: Text(
'등록된 약병 리스트',
textScaleFactor: 1.0,
style: TextStyle(
fontSize: 28,
fontFamily: 'Noto',
fontWeight: FontWeight.bold),
),
),
),
SizedBox(height: 10),
Expanded(
child: GridView.builder(
padding: const EdgeInsets.all(30),
itemCount:
_bottleList.length == null ? 0 : _bottleList.length,
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 200,
crossAxisSpacing: 10,
mainAxisSpacing: 10,
),
itemBuilder: (BuildContext context, int index) {
return InkResponse(
splashColor: Colors.transparent,
child: Container(
height: 140,
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
border: Border.all(),
borderRadius: BorderRadius.all(
Radius.circular(16.0),
),
),
child: Column(
children: [
Container(
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: Colors.black,
width: 1,
style: BorderStyle.solid),
),
),
height: 40,
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Container(
height: 40,
child: Center(
child: Text(
'${_bottleList[index].bottleId}',
style: TextStyle(
color: Colors.black,
fontSize: 20,
fontFamily: 'Noto',
fontWeight: FontWeight.bold),
),
),
),
Container(
child: IconButton(
alignment: Alignment(0.9, 0),
icon: Icon(
Icons.create_sharp,
color: Colors.black,
),
onPressed: () {},
),
),
],
),
),
SizedBox(height: 10),
Container(
height: 90,
child: Icon(
Icons.medical_services_outlined,
size: 100,
),
)
],
),
),
onTap: () {
UserSecureStorage.setBottleId(
_bottleList[index].bottleId.toString());
UserSecureStorage.setMedicineId(
_bottleList[index].medicineId.toString());
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) => DashBoard(
pageNumber: 0,
),
),
);
},
);
},
),
)
],
),
);
}
},
),
),
onWillPop: () {
SystemNavigator.pop();
},
);
}
}
import 'package:Smart_Medicine_Box/src/screens/DashBoard.dart';
import 'package:Smart_Medicine_Box/src/screens/Homepage.dart';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter_dotenv/flutter_dotenv.dart';
import '../models/Medicine.dart';
import '../../utils/user_secure_stoarge.dart';
class DetailMedicine extends StatefulWidget {
Medicine searchMedicine;
String bottleId;
DetailMedicine({Key key, this.searchMedicine, this.bottleId})
: super(key: key);
@override
_DetailMedicineState createState() => _DetailMedicineState();
}
class _DetailMedicineState extends State<DetailMedicine> {
final medicineDosageController = TextEditingController();
//약 등록
Future<String> patchMedcine() async {
String usertoken = await UserSecureStorage.getUserToken();
http.Response response = await http.patch(
Uri.encodeFull(
DotEnv().env['SERVER_URL'] + 'bottle/' + widget.bottleId),
headers: {
"Content-Type": "application/json",
"authorization": usertoken
},
body: jsonEncode({
'medicineId': widget.searchMedicine.medicineId,
'dosage': medicineDosageController.text
}));
if (response.statusCode == 200) {
String usertoken = await UserSecureStorage.setMedicineId(
widget.searchMedicine.medicineId.toString());
return "Complete";
} else if (response.statusCode == 404) {
return "약병이 존재하지 않습니다.";
} else if (response.statusCode == 403) {
return "약병에 접근할 권한이 없습니다.";
} else {
return "알 수 없는 오류";
}
}
Widget build(BuildContext context) {
final Size size = MediaQuery.of(context).size;
return MaterialApp(
home: Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
leading: new Icon(Icons.medical_services_rounded,
color: Colors.black, size: 45.0),
title: Text(
'Smart Medicine Box',
style: TextStyle(
color: Colors.black,
fontSize: 23,
fontFamily: 'Noto',
fontWeight: FontWeight.bold),
),
),
body: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
SizedBox(height: 30),
Container(
padding: EdgeInsets.fromLTRB(5, 5, 5, 5),
height: size.height * 0.08,
width: size.width,
child: Center(
child: Text(
'세부 약 정보',
textAlign: TextAlign.center,
textScaleFactor: 1.0,
style: TextStyle(
color: Colors.black,
fontSize: 36,
fontFamily: 'NotoSansKR',
fontWeight: FontWeight.w700),
),
),
),
SizedBox(height: 5),
Container(
width: size.width,
padding: EdgeInsets.fromLTRB(5, 0, 5, 5),
margin: EdgeInsets.all(15),
decoration: BoxDecoration(
border: Border.all(),
borderRadius: BorderRadius.all(
Radius.circular(25.0) // <--- border radius here
),
),
child: Column(
children: [
SizedBox(height: 40),
Container(
child: Center(
child: Text(widget.searchMedicine.name,
style: TextStyle(
color: Colors.black,
fontSize: 24,
fontFamily: 'NotoSansKR',
fontWeight: FontWeight.w700)),
),
),
SizedBox(height: 15),
Container(
width: size.width,
alignment: Alignment(0.9, 0),
child: Text(
'제조사: ' + widget.searchMedicine.company,
style: TextStyle(
color: Colors.grey,
fontSize: 20,
),
),
),
SizedBox(height: 30),
Container(
width: size.width,
padding: EdgeInsets.fromLTRB(5, 0, 5, 0),
alignment: Alignment(-1, 0),
child: Text(
'타겟 층 : ' + widget.searchMedicine.target,
style: TextStyle(color: Colors.black, fontSize: 16),
),
),
SizedBox(height: 15),
Container(
width: size.width,
padding: EdgeInsets.fromLTRB(5, 0, 5, 0),
alignment: Alignment(-1, 0),
child: Text(
'복약 정보 : ' + widget.searchMedicine.dosage,
style: TextStyle(color: Colors.black, fontSize: 16),
),
),
SizedBox(height: 10),
Container(
width: size.width,
padding: EdgeInsets.fromLTRB(5, 10, 5, 10),
alignment: Alignment(-1, 0),
child: Column(
children: [
SizedBox(
height: 12,
),
Container(
width: size.width,
child: Text(
'경고',
style: TextStyle(
color: Colors.redAccent, fontSize: 14),
),
),
SizedBox(height: 12),
Container(
width: size.width,
child: Text(
widget.searchMedicine.warn,
style: TextStyle(
color: Colors.redAccent, fontSize: 14),
),
),
],
),
),
],
),
),
SizedBox(height: 12),
Container(
height: size.height * 0.1,
padding: const EdgeInsets.fromLTRB(20, 10, 20, 5),
child: TextFormField(
keyboardType: TextInputType.text,
controller: medicineDosageController,
decoration: InputDecoration(
border: OutlineInputBorder(),
errorBorder: InputBorder.none,
disabledBorder: InputBorder.none,
hintText: '하루에 섭취할 적정 복용량을 숫자만 입력하세요',
),
style: TextStyle(
fontSize: 16,
fontFamily: 'NotoSansKR',
fontWeight: FontWeight.w600)),
),
SizedBox(height: 12),
Container(
height: size.height * 0.07,
width: size.width * 0.8,
child: FlatButton(
padding: EdgeInsets.fromLTRB(0, 5, 0, 5),
onPressed: () async {
String saveMessage = await patchMedcine();
if (saveMessage == "Complete") {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: new Text('약 등록'),
content: new Text('약 등록이 완료 되었습니다.'),
actions: <Widget>[
new FlatButton(
child: new Text('Close'),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) =>
DashBoard(
pageNumber: 1,
),
),
);
})
],
);
});
}
},
child: Text(
'약 등록',
textScaleFactor: 1.0,
style: TextStyle(
color: Colors.white,
fontSize: 20,
fontFamily: 'Noto',
fontWeight: FontWeight.bold),
),
color: Color(0xff1674f6),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50)),
),
),
SizedBox(height: 30)
],
),
),
),
);
}
}
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter_dotenv/flutter_dotenv.dart';
// Screen import
import 'RegisterBottle.dart';
import '../models/Bottle.dart';
import 'BottleList.dart';
import '../../utils/user_secure_stoarge.dart';
class HubList extends StatefulWidget {
List<int> hublist;
HubList({Key key, this.hublist}) : super(key: key);
@override
_HubListState createState() => _HubListState();
}
class _HubListState extends State<HubList> {
List<Bottle> _bottleList = new List<Bottle>();
//Get BottleList
Future<String> getBottleList(int hubid) async {
String usertoken = await UserSecureStorage.getUserToken();
http.Response response = await http.get(
Uri.encodeFull(
DotEnv().env['SERVER_URL'] + 'bottle/hub/' + hubid.toString()),
headers: {"authorization": usertoken},
);
if (_bottleList.length != 0) {
_bottleList.clear();
}
if (response.statusCode == 200) {
List<dynamic> values = new List<dynamic>();
values = json.decode(response.body);
for (int i = 0; i < values.length; i++) {
Map<String, dynamic> map = values[i];
_bottleList.add(Bottle.fromJson(map));
return "GET";
}
} else if (response.statusCode == 404) {
return "Not Found";
} else {
return "Error";
}
return "Error";
}
Widget build(BuildContext context) {
final Size size = MediaQuery.of(context).size;
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
leading: new Icon(Icons.medical_services_rounded,
color: Colors.black, size: 45.0),
title: Text(
'Smart Medicine Box',
style: TextStyle(
color: Colors.black,
fontSize: 23,
fontFamily: 'Noto',
fontWeight: FontWeight.bold),
),
),
body: Container(
height: size.height,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
height: size.height * 0.1,
width: size.width,
child: Center(
child: Text(
'등록된 허브 리스트',
textScaleFactor: 1.0,
style: TextStyle(
fontSize: 28,
fontFamily: 'Noto',
fontWeight: FontWeight.bold),
),
),
decoration: BoxDecoration(border: Border.all()),
),
SizedBox(height: 30),
Expanded(
child: ListView.separated(
padding: const EdgeInsets.all(30),
itemCount: widget.hublist.length,
itemBuilder: (BuildContext context, int index) {
return Container(
padding: EdgeInsets.all(8.0),
decoration: BoxDecoration(
border: Border.all(),
borderRadius: BorderRadius.all(Radius.circular(25.0)),
),
child: ListTile(
title: Text(
'HUB ID: ' + '${widget.hublist[index]}',
style: TextStyle(
color: Colors.black,
fontSize: 20,
fontFamily: 'Noto',
fontWeight: FontWeight.bold),
),
trailing: Icon(Icons.arrow_forward),
onTap: () async {
//허브 id로 가져와서 있으면 바로 넘기기
var result =
await getBottleList(widget.hublist[index]);
if (result == "GET") {
UserSecureStorage.setHubId(
widget.hublist[index].toString());
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) =>
BottleList(),
));
} else if (result == "Not Found") {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: new Text('Error'),
content: new Text('등록된 약병이 없습니다.'),
actions: <Widget>[
new FlatButton(
child: new Text('등록'),
onPressed: () {
UserSecureStorage.setHubId(
widget.hublist[index].toString());
Navigator.push(
context,
MaterialPageRoute(
builder:
(BuildContext context) =>
RegisterBottle(),
));
})
],
);
},
);
}
},
),
);
},
separatorBuilder: (BuildContext contetx, int index) =>
const Divider(),
),
)
],
)),
);
}
}
import 'package:Smart_Medicine_Box/src/screens/DashBoard.dart';
import 'package:Smart_Medicine_Box/src/screens/Register/BottleList.dart';
import 'package:flutter/cupertino.dart';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'SearchMedicine.dart';
import '../../utils/user_secure_stoarge.dart';
class RegisterBottle extends StatefulWidget {
final String hubid;
final bool modify_bottle;
RegisterBottle({Key key, this.hubid, this.modify_bottle}) : super(key: key);
@override
_RegisterBottleState createState() => _RegisterBottleState();
}
class _RegisterBottleState extends State<RegisterBottle> {
final medicineBottleIDController = TextEditingController();
Future<String> registerhub_Validate() async {
String usertoken = await UserSecureStorage.getUserToken();
String hubid = await UserSecureStorage.getHubId();
http.Response bottleresponse = await http.post(
Uri.encodeFull(DotEnv().env['SERVER_URL'] + 'bottle'),
headers: {
"Content-Type": "application/json",
"authorization": usertoken
},
body: jsonEncode(
{'bottleId': medicineBottleIDController.text, 'hubId': hubid}));
if (bottleresponse.statusCode == 201) {
return "등록 완료";
} else if (bottleresponse.statusCode == 404) {
return "Hub 없음";
} else if (bottleresponse.statusCode == 403) {
return "유저 정보 없음 ";
} else if (bottleresponse.statusCode == 404) {
return "HOST 없음";
} else {
return "오류";
}
}
Widget build(BuildContext context) {
final Size size = MediaQuery.of(context).size;
// int goals = 60;
// int points = 75;
return Scaffold(
backgroundColor: Colors.white,
body: ListView(
children: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(20, 25, 20, 0),
child: Row(
children: <Widget>[
Text(
'약병 등록',
textScaleFactor: 1.0,
style: TextStyle(fontSize: 34),
)
],
),
),
Padding(
padding: const EdgeInsets.fromLTRB(20, 10, 20, 0),
child: Row(
children: <Widget>[
Text(
'SmartMedicine 회원가입',
textScaleFactor: 1.0,
style: TextStyle(fontSize: 16),
)
],
),
),
MediaQuery(
data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
child: Container(
height: size.height * 0.6,
child: Padding(
padding: const EdgeInsets.fromLTRB(20, 5, 20, 20),
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextFormField(
keyboardType: TextInputType.text,
controller: medicineBottleIDController,
decoration: InputDecoration(
labelText: '약병 ID',
helperText: '현재 사용하시는 약병의 고유번호를 입력하세요',
),
),
],
),
),
),
),
Container(
height: 80,
padding: const EdgeInsets.fromLTRB(20, 20, 20, 20),
child: RaisedButton(
onPressed: () async {
String saveMessage = await registerhub_Validate();
print(saveMessage);
print(widget.modify_bottle);
if (saveMessage == "등록 완료" && widget.modify_bottle == false) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: new Text('약병 등록'),
content: new Text('약병 등록이 완료 되었습니다.'),
actions: <Widget>[
new FlatButton(
child: new Text('Close'),
onPressed: () {
UserSecureStorage.setBottleId(
medicineBottleIDController.text);
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) =>
SearchMedicine(
bottleId: medicineBottleIDController.text,
),
),
);
},
),
],
);
},
);
} else if (saveMessage == "등록 완료" &&
widget.modify_bottle == true) {
print('asdg');
await showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: new Text('약병 등록'),
content: new Text('약병 등록이 완료 되었습니다.'),
actions: <Widget>[
new FlatButton(
child: new Text('Close'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
Navigator.of(context).pop();
} else {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: new Text('오류'),
content: new Text(saveMessage),
actions: <Widget>[
new FlatButton(
child: new Text('Close'),
onPressed: () {
Navigator.of(context).pop();
},
)
],
);
},
);
}
},
shape: RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(18.0),
side: BorderSide(color: Colors.blue)),
color: Color(0xff1674f6),
child: Text(
'약병 등록',
textScaleFactor: 1.0,
style: TextStyle(
fontSize: 16,
color: Colors.white,
fontWeight: FontWeight.bold),
),
),
)
],
),
);
}
}
import 'package:Smart_Medicine_Box/src/screens/SettingPage/HubModifyList.dart';
import 'package:flutter/cupertino.dart';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'RegisterBottle.dart';
import '../../utils/user_secure_stoarge.dart';
class RegisterHub extends StatefulWidget {
final int modify_hub;
RegisterHub({Key key, this.modify_hub}) : super(key: key);
@override
_RegisterHubState createState() => _RegisterHubState();
}
class _RegisterHubState extends State<RegisterHub> {
final medicineBottleIDController = TextEditingController();
final medicineHubIDController = TextEditingController();
final medicineHubPortController = TextEditingController();
final medicineHubHostController = TextEditingController();
Future<String> registerhub_Validate() async {
String usertoken = await UserSecureStorage.getUserToken();
http.Response hubresponse = await http.post(
Uri.encodeFull(DotEnv().env['SERVER_URL'] + 'hub'),
headers: {
"Content-Type": "application/json",
"authorization": usertoken
},
body: jsonEncode({
'hubId': medicineHubIDController.text,
'host': medicineHubHostController.text,
'port': medicineHubPortController.text,
}));
print(hubresponse.statusCode);
if (hubresponse.statusCode == 201) {
return "허브 등록 완료";
} else if (hubresponse.statusCode == 409) {
return "이미 존재하는 hub";
} else {
return "오류";
}
}
Widget build(BuildContext context) {
final Size size = MediaQuery.of(context).size;
// int goals = 60;
// int points = 75;
return Scaffold(
backgroundColor: Colors.white,
body: ListView(
children: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(20, 25, 20, 0),
child: Row(
children: <Widget>[
Text(
'허브 등록',
textScaleFactor: 1.0,
style: TextStyle(fontSize: 34),
)
],
),
),
Padding(
padding: const EdgeInsets.fromLTRB(20, 10, 20, 0),
child: Row(
children: <Widget>[
Text(
'SmartMedicine 허브 등록',
textScaleFactor: 1.0,
style: TextStyle(fontSize: 16),
)
],
),
),
MediaQuery(
data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
child: Container(
height: size.height * 0.6,
child: Padding(
padding: const EdgeInsets.fromLTRB(20, 5, 20, 20),
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextFormField(
keyboardType: TextInputType.text,
controller: medicineHubIDController,
decoration: InputDecoration(
labelText: '허브 ID',
helperText: '현자 등록하시는 허브의 고유 번호를 입력하세요',
),
),
TextFormField(
keyboardType: TextInputType.text,
controller: medicineHubHostController,
decoration: InputDecoration(
labelText: 'Host',
helperText: '현재 사용하시는 허브의 HOST를 입력하세요',
),
),
TextFormField(
keyboardType: TextInputType.text,
controller: medicineHubPortController,
decoration: InputDecoration(
labelText: 'Port',
helperText: '현재 사용하시는 허브의 PORT를 입력하세요',
),
),
],
),
),
),
),
Container(
height: 80,
padding: const EdgeInsets.fromLTRB(20, 20, 20, 20),
child: RaisedButton(
onPressed: () async {
String saveMessage = await registerhub_Validate();
print(saveMessage);
print(widget.modify_hub);
if (saveMessage == "허브 등록 완료" && widget.modify_hub == 0) {
UserSecureStorage.setHubId(medicineHubIDController.text);
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) => RegisterBottle(
hubid: medicineHubIDController.text,
modify_bottle: false,
),
),
);
} else if (saveMessage == "허브 등록 완료" &&
widget.modify_hub == 1) {
Navigator.of(context).pop();
} else {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: new Text('오류'),
content: new Text(saveMessage),
actions: <Widget>[
new FlatButton(
child: new Text('close'),
onPressed: () {
Navigator.of(context).pop();
},
)
],
);
},
);
}
},
shape: RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(18.0),
side: BorderSide(color: Colors.blue)),
color: Color(0xff1674f6),
child: Text(
'허브 등록 ',
textScaleFactor: 1.0,
style: TextStyle(
fontSize: 16,
color: Colors.white,
fontWeight: FontWeight.bold),
),
),
)
],
),
);
}
}
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'package:flutter_dotenv/flutter_dotenv.dart';
import '../models/Medicine.dart';
import 'DetailMedicine.dart';
import '../../utils/user_secure_stoarge.dart';
class SearchMedicine extends StatefulWidget {
String bottleId;
SearchMedicine({Key key, this.bottleId}) : super(key: key);
@override
_SearchMedicineState createState() => _SearchMedicineState();
}
class _SearchMedicineState extends State<SearchMedicine> {
List<Medicine> _medicineList = new List<Medicine>();
final medicineNameController = TextEditingController();
final medicineCompanyController = TextEditingController();
Future<String> postMeicineList() async {
String usertoken = await UserSecureStorage.getUserToken();
http.Response response = await http.post(
Uri.encodeFull(DotEnv().env['SERVER_URL'] + 'medicine'),
headers: {
"Content-Type": "application/json",
"authorization": usertoken
},
body: jsonEncode({
'name': medicineNameController.text,
'company': medicineCompanyController.text,
}));
if (_medicineList.length != 0) {
_medicineList.clear();
}
if (response.statusCode == 200) {
List<dynamic> values = new List<dynamic>();
values = json.decode(response.body);
for (int i = 0; i < values.length; i++) {
Map<String, dynamic> map = values[i];
_medicineList.add(Medicine.fromJson(map));
}
return "GET";
} else {
return "Not Found";
}
}
Widget build(BuildContext context) {
bool isForward = false;
final Size size = MediaQuery.of(context).size;
// int goals = 60;
// int points = 75;
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
leading: new Icon(Icons.medical_services_rounded,
color: Colors.black, size: 45.0),
title: Text(
'Smart Medicine Box',
style: TextStyle(
color: Colors.black,
fontSize: 23,
fontFamily: 'Noto',
fontWeight: FontWeight.bold),
),
),
body: Container(
height: size.height,
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
border: Border.all(),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
SizedBox(height: 20),
Container(
height: size.height * 0.13,
decoration: BoxDecoration(
border: Border.all(),
color: Colors.white,
borderRadius: BorderRadius.circular(25),
),
child: Row(
children: [
Column(
children: [
Container(
height: size.height * 0.0635,
width: size.width * 0.75,
child: Row(
children: [
Container(
width: size.width * 0.16,
padding: const EdgeInsets.fromLTRB(10, 0, 0, 0),
child: Text('약이름:',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 16,
fontFamily: 'NotoSansKR',
fontWeight: FontWeight.w600)),
),
Container(
padding: const EdgeInsets.fromLTRB(5, 0, 0, 0),
width: size.width * 0.55,
child: TextFormField(
keyboardType: TextInputType.text,
controller: medicineNameController,
decoration: InputDecoration(
border: InputBorder.none,
focusedBorder: InputBorder.none,
enabledBorder: InputBorder.none,
errorBorder: InputBorder.none,
disabledBorder: InputBorder.none,
hintText: '약 이름을 입력하세요',
),
style: TextStyle(
fontSize: 16,
fontFamily: 'NotoSansKR',
fontWeight: FontWeight.w600)),
)
],
),
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: Colors.black,
width: 1,
style: BorderStyle.solid),
right: BorderSide(
color: Colors.black,
width: 1,
style: BorderStyle.solid),
),
),
),
Container(
height: size.height * 0.0635,
width: size.width * 0.75,
child: Row(
children: [
Container(
width: size.width * 0.16,
padding: const EdgeInsets.fromLTRB(5, 0, 0, 3),
child: Text('제조사:',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 16,
fontFamily: 'NotoSansKR',
fontWeight: FontWeight.w600)),
),
Container(
padding: const EdgeInsets.fromLTRB(6, 0, 0, 0),
width: size.width * 0.50,
child: TextFormField(
keyboardType: TextInputType.text,
controller: medicineCompanyController,
decoration: InputDecoration(
border: InputBorder.none,
focusedBorder: InputBorder.none,
enabledBorder: InputBorder.none,
errorBorder: InputBorder.none,
disabledBorder: InputBorder.none,
hintText: '약 제조사 이름을 입력하세요',
),
style: TextStyle(
fontSize: 16,
fontFamily: 'NotoSansKR',
fontWeight: FontWeight.w600)),
)
],
),
decoration: BoxDecoration(
border: Border(
right: BorderSide(
color: Colors.black,
width: 1,
style: BorderStyle.solid),
),
),
),
],
),
Container(
height: size.height * 0.0635 * 2,
width: size.width * 0.14,
padding: const EdgeInsets.fromLTRB(10, 0, 0, 0),
child: IconButton(
icon: Icon(Icons.search, size: 40),
onPressed: () async {
String saveMessage = await postMeicineList();
if (saveMessage == "GET") {
setState(() {});
}
//검색 함수를 여기다가
},
),
),
],
),
),
SizedBox(height: 20),
Expanded(
child: ListView.separated(
itemBuilder: (BuildContext context, int index) {
return Container(
padding: EdgeInsets.all(8.0),
decoration: BoxDecoration(border: Border.all()),
child: ListTile(
title: Text(
'Medicine: ' + _medicineList[index].name,
style: TextStyle(
color: Colors.black,
fontSize: 20,
fontFamily: 'Noto',
fontWeight: FontWeight.bold),
),
trailing: Icon(Icons.arrow_forward),
onTap: () async {
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) =>
DetailMedicine(
searchMedicine: _medicineList[index],
bottleId: widget.bottleId,
),
));
}),
);
},
separatorBuilder: (BuildContext contetx, int index) =>
const Divider(),
itemCount: _medicineList.length == null
? 0
: _medicineList.length))
],
),
),
);
}
}
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'package:flutter_dotenv/flutter_dotenv.dart';
import '../../utils/user_secure_stoarge.dart';
import 'HubList.dart';
import 'RegsiterHub.dart';
import '../models/User.dart';
class SignInPage extends StatefulWidget {
@override
_SignInPageState createState() => _SignInPageState();
}
///
class _SignInPageState extends State<SignInPage> {
bool passwordVisible = false;
bool _validateEmail = false;
bool _validatePassword = false;
final emailController = TextEditingController();
final passwordController = TextEditingController();
User user;
List<int> _hublist = new List<int>(); //허브이름을 만들어야 할 것 같은데 임시로 허브 id만 고르게 함
//Login 함수
Future<String> login(String _email, String _password) async {
http.Response response = await http.post(
Uri.encodeFull(DotEnv().env['SERVER_URL'] + 'auth/login'),
headers: {"Content-Type": "application/json"},
body: jsonEncode(
{
'userId': _email,
'password': _password,
},
),
);
if (response.statusCode == 200) {
Map<String, dynamic> data = jsonDecode(response.body);
user = User.fromJson(data);
UserSecureStorage.setUserToken(user.token);
UserSecureStorage.setUserId(user.userId);
return "로그인 성공";
} else if (response.statusCode == 400) {
return "올바르지 않은 아이디 및 패스워드";
} else {
return "존재하지 않는 아이디 이거나 비밀번호가 불일치 합니다.";
}
}
//Get Hub List 함수
Future<String> getHubList() async {
String usertoken = await UserSecureStorage.getUserToken();
http.Response response = await http.get(
Uri.encodeFull(DotEnv().env['SERVER_URL'] + 'hub'),
headers: {"authorization": usertoken},
);
List<dynamic> values = new List<dynamic>();
if (_hublist.length != 0) {
_hublist.clear();
}
if (response.statusCode == 200) {
values = json.decode(response.body);
for (int i = 0; i < values.length; i++) {
_hublist.add(values[i]['hubId']);
}
return "get완료";
} else if (response.statusCode == 404) {
return "Not Found";
} else {
return "Error";
}
}
Widget build(BuildContext context) {
final Size size = MediaQuery.of(context).size;
final mqData = MediaQuery.of(context);
final mqDataScale = mqData.copyWith(textScaleFactor: 1.0);
return WillPopScope(
onWillPop: () {
if (Navigator.canPop(context)) {
//Navigator.pop(context);
Navigator.of(context).pop();
} else {
SystemNavigator.pop();
}
},
child: Scaffold(
body: Builder(
builder: (BuildContext context) {
return ListView(
children: <Widget>[
Padding(
padding: EdgeInsets.only(top: 25, left: 18, right: 18),
child: Stack(
children: <Widget>[
Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(20, 0, 0, 0),
child: Text('로그인',
textScaleFactor: 1.0,
style: TextStyle(
fontSize: 34,
fontFamily: 'Noto',
fontWeight: FontWeight.bold)),
),
SizedBox(
height: 40,
),
Padding(
padding: const EdgeInsets.fromLTRB(20, 0, 20, 0),
child: new Column(
children: <Widget>[
MediaQuery(
data: mqDataScale,
child: TextFormField(
keyboardType: TextInputType.text,
controller: emailController,
decoration: InputDecoration(
labelText: '이메일',
helperText: '이메일 주소를 입력해주세요.',
contentPadding:
EdgeInsets.fromLTRB(0, 5, 0, 5),
errorText: _validateEmail
? '등록되지 않은 아이디입니다.'
: null,
labelStyle: TextStyle(
fontSize: 14,
color: Color(0xff000000)),
helperStyle: TextStyle(
fontSize: 12,
color: Color(0xffb2b2b2)),
// Here is key idea
),
),
)
],
),
),
Padding(
padding: const EdgeInsets.fromLTRB(20, 0, 20, 20),
child: new Column(
children: <Widget>[
MediaQuery(
data: mqDataScale,
child: TextFormField(
keyboardType: TextInputType.text,
controller: passwordController,
obscureText:
!passwordVisible, //This will obscure text dynamically
decoration: InputDecoration(
labelText: '비밀번호',
helperText: '비밀번호를 입력해 주세요.',
errorText: _validatePassword
? '비밀번호가 일치하지 않습니다.'
: null,
labelStyle: TextStyle(
fontSize: 14,
color: Color(0xff000000)),
helperStyle: TextStyle(
fontSize: 12,
color: Color(0xffb2b2b2)),
// Here is key idea
suffixIcon: IconButton(
icon: Icon(
// Based on passwordVisible state choose the icon
passwordVisible
? Icons.visibility
: Icons.visibility_off,
color: Color(0xff2c2c2c),
),
onPressed: () {
// Update the state i.e. toogle the state of passwordVisible variable
setState(() {
passwordVisible = !passwordVisible;
});
},
),
),
),
)
],
),
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
width: size.width * 0.8,
height: 46,
child: RaisedButton(
color: Color(0xff1674f6),
child: Text("로그인",
textScaleFactor: 1.0,
style: TextStyle(
color: Colors.white,
fontSize: 16,
fontFamily: 'Noto',
fontWeight: FontWeight.bold)),
onPressed: () async {
String saveMessage = await login(
emailController.text,
passwordController.text);
if (emailController.text.isEmpty ||
passwordController.text.isEmpty) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: new Text('이메일 & 비밀번호'),
content: new Text(
'이메일과 비밀번호를 입력해주세요.'),
actions: <Widget>[
new FlatButton(
child: new Text('Close'),
onPressed: () {
Navigator.of(context)
.pop();
})
],
);
});
} else {
if (saveMessage == "로그인 성공") {
var result = await getHubList();
if (result == "Not Found") {
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext
context) =>
RegisterHub(modify_hub: 0),
));
} else if (result == "get완료") {
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) =>
HubList(hublist: _hublist),
),
);
} else {}
} else {
print('Error');
}
}
},
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)),
),
),
],
),
],
),
],
),
),
],
);
},
),
),
);
}
}
import 'dart:convert';
import 'package:Smart_Medicine_Box/src/screens/Homepage.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'RegsiterHub.dart';
class SignUpLocal extends StatefulWidget {
@override
_SignUpLocalState createState() => _SignUpLocalState();
}
class _SignUpLocalState extends State<SignUpLocal> {
final emailController = TextEditingController();
final passwordController = TextEditingController();
final passwordValidController = TextEditingController();
bool _validate = false;
int userRole = 0;
// Initially password is obscure
bool passwordVisible = false;
bool passwordValidationVisible = false;
Future<String> signup_Validate() async {
http.Response response = await http.post(
Uri.encodeFull(DotEnv().env['SERVER_URL'] + 'auth/register'),
headers: {"Content-Type": "application/json"},
body: jsonEncode(
{
'userId': emailController.text,
'password': passwordController.text,
'passwordCheck': passwordValidController.text
},
),
);
if (response.statusCode == 201) {
return "정보 입력 완료";
} else {
return "오류";
}
}
@override
Widget build(BuildContext context) {
final Size size = MediaQuery.of(context).size;
// int goals = 60;
// int points = 75;
return Scaffold(
backgroundColor: Colors.white,
body: ListView(
children: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(20, 25, 20, 0),
child: Row(
children: <Widget>[
Text(
'회원 가입',
textScaleFactor: 1.0,
style: TextStyle(fontSize: 34),
)
],
),
),
Padding(
padding: const EdgeInsets.fromLTRB(20, 10, 20, 0),
child: Row(
children: <Widget>[
Text(
'SmartMedicine 회원가입',
textScaleFactor: 1.0,
style: TextStyle(fontSize: 16),
)
],
),
),
MediaQuery(
data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
child: Container(
height: size.height * 0.6,
child: Padding(
padding: const EdgeInsets.fromLTRB(20, 5, 20, 20),
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextFormField(
controller: emailController,
keyboardType: TextInputType.text,
decoration: InputDecoration(
labelText: '이메일',
helperText: '아아디로 사용할 이메일 주소를 입력해주세요.',
),
),
TextFormField(
keyboardType: TextInputType.text,
controller: passwordController,
obscureText:
!passwordVisible, //This will obscure text dynamically
decoration: InputDecoration(
labelText: '비밀번호',
helperText: '비밀번호를 입력해주세요',
// Here is key idea
suffixIcon: IconButton(
icon: Icon(
// Based on passwordVisible state choose the icon
passwordVisible
? Icons.visibility
: Icons.visibility_off,
color: Theme.of(context).primaryColorDark,
),
onPressed: () {
// Update the state i.e. toogle the state of passwordVisible variable
setState(() {
passwordVisible = !passwordVisible;
});
},
),
),
),
TextFormField(
onChanged: (text) {
if (passwordController.text == text) {
setState(() {
_validate = false;
});
} else {
setState(() {
_validate = true;
});
}
},
keyboardType: TextInputType.text,
controller: passwordValidController,
obscureText:
!passwordValidationVisible, //This will obscure text dynamically
decoration: InputDecoration(
labelText: '비밀번호 확인',
helperText: '비밀번호를 확인해주세요',
errorText:
_validate ? '두 비밀번호가 다릅니다. 다시 확인해주세요.' : null,
// Here is key idea
suffixIcon: IconButton(
icon: Icon(
// Based on passwordVisible state choose the icon
passwordValidationVisible
? Icons.visibility
: Icons.visibility_off,
color: Theme.of(context).primaryColorDark,
),
onPressed: () {
// Update the state i.e. toogle the state of passwordVisible variable
setState(() {
passwordValidationVisible =
!passwordValidationVisible;
});
},
),
),
),
],
),
),
),
),
Container(
height: 80,
padding: const EdgeInsets.fromLTRB(20, 20, 20, 20),
child: RaisedButton(
onPressed: () async {
String saveMessage = await signup_Validate();
if (saveMessage == "정보 입력 완료") {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: new Text('회원 가입'),
content: new Text('회원 가입이 완료 되었습니다.'),
actions: <Widget>[
new FlatButton(
child: new Text('Close'),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) =>
HomePage()));
})
],
);
});
} else {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: new Text('회원 가입 오류'),
content: new Text('정확한 이메일, 비밀번호를 입력해 주세요.'),
actions: <Widget>[
new FlatButton(
child: new Text('Close'),
onPressed: () {
Navigator.of(context).pop();
})
],
);
});
}
},
shape: RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(18.0),
side: BorderSide(color: Colors.blue)),
color: Color(0xff1674f6),
child: Text(
'회원 가입',
textScaleFactor: 1.0,
style: TextStyle(
fontSize: 16,
color: Colors.white,
fontWeight: FontWeight.bold),
),
),
)
],
),
bottomNavigationBar: BottomAppBar(
elevation: 0,
child: Container(
height: 70,
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Padding(
padding: const EdgeInsets.fromLTRB(70, 0, 70, 0),
child: Text(
'회원 가입시, 이용 약관 및 개인정보 처리 방침에 동의하는 것으로 간주합니다..',
style: TextStyle(fontSize: 12, color: Color(0xff747474)),
textAlign: TextAlign.center,
),
)
],
),
),
),
);
}
}
import 'package:Smart_Medicine_Box/src/screens/SettingPage/HubModifyList.dart';
import 'package:flutter/material.dart';
import 'package:Smart_Medicine_Box/src/screens/DashBoard.dart';
import 'package:Smart_Medicine_Box/src/screens/SettingPage/Alarm.dart';
import 'package:Smart_Medicine_Box/src/screens/SettingPage/DEVInformation.dart';
import 'package:Smart_Medicine_Box/src/screens/SettingPage/BottleModifyList.dart';
class SettingPage extends StatefulWidget {
@override
_SettingPageState createState() => _SettingPageState();
}
class _SettingPageState extends State<SettingPage> {
Widget build(BuildContext context) {
final Size size = MediaQuery.of(context).size;
return MaterialApp(
title: 'Welcome to Flutter',
home: Scaffold(
appBar: AppBar(
iconTheme: IconThemeData(color: Colors.black),
backgroundColor: Colors.white,
title: Text(
'Smart Medicine Box',
style: TextStyle(
color: Colors.black,
fontSize: 20,
fontFamily: 'Noto',
fontWeight: FontWeight.bold),
),
actions: [
IconButton(
icon: Icon(
Icons.settings,
color: Colors.black,
),
onPressed: () {},
)
],
),
drawer: Drawer(
child: ListView(
children: [
DrawerHeader(
child: Text('Drawer Header'),
decoration: BoxDecoration(
color: Colors.blue,
),
),
ListTile(
title: Text('Test 1'),
onTap: () {},
),
ListTile(
title: Text('Test 2'),
onTap: () {},
),
ListTile(
title: Text('Test 3'),
onTap: () {},
),
],
),
),
body: Container(
height: size.height * 0.9,
margin: EdgeInsets.fromLTRB(0, 30, 0, 0),
padding: EdgeInsets.fromLTRB(5, 0, 5, 5),
child: Column(
children: <Widget>[
Container(
padding: EdgeInsets.fromLTRB(5, 5, 5, 5),
height: size.height * 0.08,
width: size.width,
child: Center(
child: Text(
'Setting',
textAlign: TextAlign.center,
textScaleFactor: 1.0,
style: TextStyle(
color: Colors.black,
fontSize: 32,
fontFamily: 'NotoSansKR',
fontWeight: FontWeight.w700),
),
),
),
Container(
height: size.height * 0.6,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Container(
padding: EdgeInsets.fromLTRB(0, 20, 0, 20),
width: size.width * 0.8,
height: size.height * 0.13,
margin: EdgeInsets.only(bottom: 0),
child: FlatButton(
height: size.height * 0.07,
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) => Alarm(),
));
},
child: Text(
'알림 설정',
textScaleFactor: 1.0,
style: TextStyle(
color: Colors.white,
fontSize: 24,
fontFamily: 'Noto',
fontWeight: FontWeight.bold),
),
color: Color(0xff0B1E33),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50)),
),
),
Container(
padding: EdgeInsets.fromLTRB(0, 20, 0, 20),
width: size.width * 0.8,
height: size.height * 0.13,
margin: EdgeInsets.only(bottom: 0),
child: FlatButton(
height: size.height * 0.07,
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) =>
HubModifyList(),
));
},
child: Text(
'허브 관리',
textScaleFactor: 1.0,
style: TextStyle(
color: Colors.white,
fontSize: 24,
fontFamily: 'Noto',
fontWeight: FontWeight.bold),
),
color: Color(0xff0B1E33),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50)),
),
),
Container(
padding: EdgeInsets.fromLTRB(0, 20, 0, 20),
width: size.width * 0.8,
height: size.height * 0.13,
margin: EdgeInsets.only(bottom: 0),
child: FlatButton(
height: size.height * 0.07,
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) =>
BottleModifyList(),
));
},
child: Text(
'약병 관리',
textScaleFactor: 1.0,
style: TextStyle(
color: Colors.white,
fontSize: 24,
fontFamily: 'Noto',
fontWeight: FontWeight.bold),
),
color: Color(0xff0B1E33),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50)),
),
),
],
),
),
],
),
),
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
backgroundColor: Colors.grey,
selectedItemColor: Colors.white.withOpacity(.60),
unselectedItemColor: Colors.white.withOpacity(.60),
selectedFontSize: 14,
unselectedFontSize: 14,
currentIndex: 0,
onTap: (int index) => {
setState(
() {
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) =>
DashBoard(pageNumber: index),
),
);
},
)
},
items: [
BottomNavigationBarItem(
icon: Icon(Icons.device_thermostat), label: 'In'),
BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
BottomNavigationBarItem(
label: 'Out',
icon: Icon(Icons.access_time),
)
],
),
),
);
}
}
import 'package:flutter/material.dart';
import 'package:rxdart/subjects.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:Smart_Medicine_Box/src/screens/SettingPage.dart';
import 'package:Smart_Medicine_Box/src/screens/SettingPage/customTimepicker.dart';
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();
// Streams are created so that app can respond to notification-related events since the plugin is initialised in the `main` function
final BehaviorSubject<ReceivedNotification> didReceiveLocalNotificationSubject =
BehaviorSubject<ReceivedNotification>();
final BehaviorSubject<String> selectNotificationSubject =
BehaviorSubject<String>();
NotificationAppLaunchDetails notificationAppLaunchDetails;
class ReceivedNotification {
final int id;
final String title;
final String body;
final String payload;
ReceivedNotification({
@required this.id,
@required this.title,
@required this.body,
@required this.payload,
});
}
class Alarm extends StatefulWidget {
@override
_AlarmnState createState() => _AlarmnState();
}
class _AlarmnState extends State<Alarm> {
FlutterLocalNotificationsPlugin fltrNotification;
List<Widget> alarmList = [];
List<dynamic> weekdays = [];
List<String> times = [];
List<int> timesHours = [];
List<int> timesMinutes = [];
List<dynamic> saveIndex = [];
List<dynamic> isSwitched = [];
List<bool> _weekday = [false, false, false, false, false, false, false];
void initState() {
super.initState();
main();
}
Future<void> main() async {
// needed if you intend to initialize in the `main` function
WidgetsFlutterBinding.ensureInitialized();
// NOTE: if you want to find out if the app was launched via notification then you could use the following call and then do something like
// change the default route of the app
// var notificationAppLaunchDetails =
// await flutterLocalNotificationsPlugin.getNotificationAppLaunchDetails();
var initializationSettingsAndroid =
new AndroidInitializationSettings('app_icon');
var initializationSettingsIOS = IOSInitializationSettings(
requestAlertPermission: true,
requestBadgePermission: true,
requestSoundPermission: true,
onDidReceiveLocalNotification:
(int id, String title, String body, String payload) async {});
var initializationSettings = InitializationSettings(
initializationSettingsAndroid, initializationSettingsIOS);
await flutterLocalNotificationsPlugin.initialize(initializationSettings,
onSelectNotification: (String payload) async {
if (payload != null) {
debugPrint('notification payload: ' + payload);
}
});
}
void _requestIOSPermissions() {
flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
IOSFlutterLocalNotificationsPlugin>()
?.requestPermissions(
alert: true,
badge: true,
sound: true,
);
}
void insertAlarm() {
setState(() {
weekdays.add([false, false, false, false, false, false, false]);
times.add(' ');
timesHours.add(0);
timesMinutes.add(0);
isSwitched.add(false);
var length = saveIndex.length;
if (saveIndex.length == 0) {
saveIndex.add(1);
} else {
saveIndex.add(saveIndex[length - 1] + 1);
}
length = saveIndex.length;
/*
_prefs.setString('alarmList', weekdays.toString());
for (var i = 0; i < times.length; i++) {
_prefs.setString('time' + (saveIndex[i]).toString(),
'${timesHours[i]}:${timesMinutes[i]}');
}
_prefs.setString('timeIndex', saveIndex.toString());
_prefs.setString('toggle', isSwitched.toString());
*/
print(saveIndex);
});
}
void rerendering() {
print(weekdays);
print(times);
print(timesHours);
print(timesMinutes);
setState(() {});
}
void _configureDidReceiveLocalNotificationSubject() {
didReceiveLocalNotificationSubject.stream
.listen((ReceivedNotification receivedNotification) async {
await showDialog(
context: context,
builder: (BuildContext context) => CupertinoAlertDialog(
title: receivedNotification.title != null
? Text(receivedNotification.title)
: null,
content: receivedNotification.body != null
? Text(receivedNotification.body)
: null,
actions: [
CupertinoDialogAction(
isDefaultAction: true,
child: Text('Ok'),
onPressed: () async {
Navigator.of(context, rootNavigator: true).pop();
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
SecondScreen(receivedNotification.payload),
),
);
},
)
],
),
);
});
}
void _configureSelectNotificationSubject() {
selectNotificationSubject.stream.listen((String payload) async {
await Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondScreen(payload)),
);
});
}
@override
void dispose() {
didReceiveLocalNotificationSubject.close();
selectNotificationSubject.close();
super.dispose();
}
Widget build(BuildContext context) {
final Size size = MediaQuery.of(context).size;
return MaterialApp(
title: 'Welcome to Flutter',
home: Scaffold(
appBar: AppBar(
iconTheme: IconThemeData(color: Colors.black),
backgroundColor: Colors.white,
title: Text(
'Smart Medicine Box',
style: TextStyle(
color: Colors.black,
fontSize: 20,
fontFamily: 'Noto',
fontWeight: FontWeight.bold),
),
actions: [
IconButton(
icon: Icon(
Icons.settings,
color: Colors.black,
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) => SettingPage(),
));
},
)
],
),
drawer: Drawer(
child: ListView(
children: [
DrawerHeader(
child: Text('Drawer Header'),
decoration: BoxDecoration(
color: Colors.blue,
),
),
ListTile(
title: Text('Test 1'),
onTap: () {},
),
ListTile(
title: Text('Test 2'),
onTap: () {},
),
ListTile(
title: Text('Test 3'),
onTap: () {},
),
],
),
),
body: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Padding(
padding: EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
width: 180,
height: 80,
padding: const EdgeInsets.all(20.0),
child: RaisedButton(
onPressed: () async {
insertAlarm();
},
shape: RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(30.0),
side: BorderSide(color: Colors.blue)),
color: Color(0xff1674f6),
child: Text(
'알람 추가',
textScaleFactor: 1.0,
style: TextStyle(
fontSize: 16,
color: Colors.white,
fontWeight: FontWeight.bold),
),
),
),
],
),
for (var i = 0; i < weekdays.length; i++)
inAlarmData(
context,
weekdays,
weekdays[i],
_showWeeklyAtDayAndTime,
times[i],
timesHours[i],
timesMinutes[i],
i + 1,
rerendering,
size,
)
],
),
),
),
),
);
}
Widget inAlarmData(
BuildContext context,
var allweekddata,
var weekdayArray,
var activeFunctions,
var timeString,
var timeHour,
var timesMinite,
var index,
var rerendering,
Size size,
) {
SharedPreferences _prefs;
var savetimeStrings;
var setDaysString = ['월', '화', '수', '목', '금', '토', '일'];
return Container(
margin: EdgeInsets.fromLTRB(0, 0, 0, 20),
decoration: BoxDecoration(
border: Border.all(
color: Color(0xffd0d0d0),
),
borderRadius: BorderRadius.all(Radius.circular(5)),
),
child: Column(
children: <Widget>[
Container(
alignment: Alignment.center,
width: size.width,
height: 50.0,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
for (var i = 0; i < weekdayArray.length; i++)
GestureDetector(
onTap: () async {
_prefs = await SharedPreferences.getInstance();
if (weekdayArray[i] == false) {
weekdayArray[i] = true;
} else {
weekdayArray[i] = false;
}
_prefs.setString(
'alarmList', allweekddata.toString());
rerendering();
},
child: Container(
margin: EdgeInsets.fromLTRB(15, 0, 0, 0),
width: size.width * 0.09,
child: Text(
setDaysString[i],
style: TextStyle(
color: weekdayArray[i] == false
? Colors.teal
: Colors.red,
fontWeight: FontWeight.bold,
fontSize: 20.0),
)),
),
],
)
],
),
color: Colors.white,
),
RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(5.0)),
elevation: 4.0,
onPressed: () async {
_prefs = await SharedPreferences.getInstance();
var abc = await DatePicker.showPicker(
context,
theme: DatePickerTheme(
containerHeight: 210.0,
),
showTitleActions: true,
onConfirm: (time) {
print('confirm $time');
// realTime = new DateTime(time.hour, time.minute);
timeHour = time.hour;
timesMinite = time.minute;
savetimeStrings = '${time.hour}:${time.minute}';
var minutString;
if (timesMinite.toString().length == 1) {
minutString = '0' + timesMinite.toString();
} else {
minutString = timesMinite.toString();
}
if (timeHour - 12 < 0) {
timeString = '오전 ${time.hour}:' + minutString;
} else {
if (timeHour == 12) {
timeString = '오후 ${time.hour}:' + minutString;
} else {
timeString = '오후 ${time.hour - 12}:' + minutString;
}
}
},
pickerModel: CustomPicker(
currentTime: DateTime.now(), locale: LocaleType.ko),
);
times[index - 1] = timeString;
timesHours[index - 1] = timeHour;
timesMinutes[index - 1] = timesMinite;
_prefs.setString('time' + (saveIndex[index - 1]).toString(),
savetimeStrings);
print(savetimeStrings);
setState(() {
savetimeStrings = savetimeStrings;
});
// rerendering();
},
child: Container(
alignment: Alignment.center,
height: 50.0,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Icon(
Icons.access_time,
size: 18.0,
color: Colors.teal,
),
Text(
" " + timeString,
textAlign: TextAlign.center,
style: TextStyle(
color: Colors.teal,
fontWeight: FontWeight.bold,
fontSize: 18.0),
),
],
),
)
],
),
],
),
),
color: Colors.white,
),
Container(
padding: EdgeInsets.fromLTRB(20, 0, 20, 0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(5.0),
color: Colors.white),
child: Container(
alignment: Alignment.center,
height: 50.0,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Text(
"알람 설정",
style: TextStyle(
color: Colors.teal,
fontWeight: FontWeight.bold,
fontSize: 18.0),
),
Switch(
value: isSwitched[index - 1],
onChanged: (value) async {
print(savetimeStrings);
if (value == true) {
_prefs = await SharedPreferences.getInstance();
int count = 1;
bool allDayFalse = true;
for (var i = 0; i < weekdayArray.length; i++) {
if (weekdayArray[i] == true) {
await activeFunctions(timeHour, timesMinite,
i + 1, index * 10, count);
count++;
allDayFalse = false;
}
}
if (allDayFalse == true) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: new Text('요일 선택 오류'),
content:
new Text('선택된 요일이 없습니다. 요일을 선택해주세요.'),
actions: <Widget>[
new FlatButton(
child: new Text('닫기'),
onPressed: () {
Navigator.of(context).pop();
})
],
);
});
} else if (_prefs.getString('time' +
(saveIndex[index - 1]).toString()) ==
null) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: new Text('시간 설정 오류'),
content:
new Text('설정된 시간이 없습니다. 시간을 설정해주세요.'),
actions: <Widget>[
new FlatButton(
child: new Text('닫기'),
onPressed: () {
Navigator.of(context).pop();
})
],
);
});
} else {
setState(() {
print(value);
isSwitched[index - 1] = value;
_prefs.setString(
'alarmList', allweekddata.toString());
// _prefs.setString(
// 'time' + saveIndex[index - 1].toString(),
// savetimeStrings);
_prefs.setString(
'timeIndex', saveIndex.toString());
_prefs.setString(
'toggle', isSwitched.toString());
print('time' + index.toString());
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: new Text('알람'),
content: new Text('알람 설정을 완료 하였습니다.'),
actions: <Widget>[
new FlatButton(
child: new Text('확인'),
onPressed: () {
Navigator.of(context).pop();
})
],
);
});
});
}
} else {
_prefs = await SharedPreferences.getInstance();
int count = 1;
for (var i = 0; i < weekdayArray.length; i++) {
if (weekdayArray[i] == true) {
await flutterLocalNotificationsPlugin
.cancel((index * 10) + count);
count++;
}
}
setState(() {
isSwitched[index - 1] = value;
_prefs.setString('toggle', isSwitched.toString());
});
}
}),
GestureDetector(
onTap: () async {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: new Text('알람 삭제'),
content: new Text('선택한 알람을 삭제하시겠습니까?'),
actions: <Widget>[
new FlatButton(
child: new Text('취소'),
onPressed: () {
Navigator.of(context).pop();
}),
new FlatButton(
child: new Text('삭제'),
onPressed: () async {
_prefs = await SharedPreferences
.getInstance();
int count = 1;
for (var i = 0;
i < weekdayArray.length;
i++) {
if (weekdayArray[i] == true) {
await flutterLocalNotificationsPlugin
.cancel((index * 10) + count);
count++;
}
}
print(saveIndex);
allweekddata.removeAt(index - 1);
_prefs.remove('time' +
saveIndex[index - 1].toString());
times.removeAt(index - 1);
saveIndex.removeAt(index - 1);
isSwitched.removeAt(index - 1);
_prefs.setString('alarmList',
allweekddata.toString());
_prefs.setString('timeIndex',
saveIndex.toString());
_prefs.setString(
'toggle', isSwitched.toString());
rerendering();
Navigator.of(context).pop();
})
],
);
});
},
child: Icon(
Icons.close,
))
],
),
),
),
],
));
}
/// weekday 가 1부터 7순으로 일 월 화 수 목 금 토 일 순서로 구성이 되어 있음 이에 따라 설정한 Weekday time 에 학습 알람을 뛰어주는 역할을 해주는 함수
Future<void> _showWeeklyAtDayAndTime(
int a, int b, int weekday, int index, int idindex) async {
Day setDay;
if (weekday == 1) {
setDay = Day.Monday;
} else if (weekday == 2) {
setDay = Day.Tuesday;
} else if (weekday == 3) {
setDay = Day.Wednesday;
} else if (weekday == 4) {
setDay = Day.Thursday;
} else if (weekday == 5) {
setDay = Day.Friday;
} else if (weekday == 6) {
setDay = Day.Saturday;
} else if (weekday == 7) {
setDay = Day.Sunday;
}
print('dd');
var time = Time(a, b, 0);
var androidPlatformChannelSpecifics = AndroidNotificationDetails(
'show weekly channel id',
'show weekly channel name',
'show weekly description');
var iOSPlatformChannelSpecifics = IOSNotificationDetails();
var platformChannelSpecifics = NotificationDetails(
androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.showWeeklyAtDayAndTime(
index + idindex,
'약통 알람 ',
'알약 섭취 시간인 ${_toTwoDigitString(time.hour)}:${_toTwoDigitString(time.minute)}이 되었습니다.',
setDay,
time,
platformChannelSpecifics);
}
String _toTwoDigitString(int value) {
return value.toString().padLeft(2, '0');
}
Future<void> onDidReceiveLocalNotification(
int id, String title, String body, String payload) async {
// display a dialog with the notification details, tap ok to go to another page
await showDialog(
context: context,
builder: (BuildContext context) => CupertinoAlertDialog(
title: title != null ? Text(title) : null,
content: body != null ? Text(body) : null,
actions: [
CupertinoDialogAction(
isDefaultAction: true,
child: Text('Ok'),
onPressed: () async {
Navigator.of(context, rootNavigator: true).pop();
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SecondScreen(payload),
),
);
},
)
],
),
);
}
}
class SecondScreen extends StatefulWidget {
SecondScreen(this.payload);
final String payload;
@override
State<StatefulWidget> createState() => SecondScreenState();
}
class SecondScreenState extends State<SecondScreen> {
String _payload;
@override
void initState() {
super.initState();
_payload = widget.payload;
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Second Screen with payload: ${(_payload ?? '')}'),
),
body: Center(
child: RaisedButton(
onPressed: () {
Navigator.pop(context);
},
child: Text('Go back!'),
),
),
);
}
}
import 'dart:convert';
import 'package:Smart_Medicine_Box/src/screens/Register/RegisterBottle.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'package:flutter_dotenv/flutter_dotenv.dart';
import '../models/Bottle.dart';
import '../../utils/user_secure_stoarge.dart';
class BottleModifyList extends StatefulWidget {
BottleModifyList({Key key}) : super(key: key);
@override
_BottleModifyListState createState() => _BottleModifyListState();
}
class _BottleModifyListState extends State<BottleModifyList> {
List<Bottle> _bottleList = new List<Bottle>();
Future<String> getBottleList() async {
String hubid = await UserSecureStorage.getHubId();
String usertoken = await UserSecureStorage.getUserToken();
http.Response response = await http.get(
Uri.encodeFull(
DotEnv().env['SERVER_URL'] + 'bottle/hub/' + hubid.toString()),
headers: {"authorization": usertoken},
);
if (_bottleList.length != 0) {
_bottleList.clear();
}
if (response.statusCode == 200) {
List<dynamic> values = new List<dynamic>();
values = json.decode(response.body);
for (int i = 0; i < values.length; i++) {
Map<String, dynamic> map = values[i];
_bottleList.add(Bottle.fromJson(map));
}
return "GET";
} else if (response.statusCode == 404) {
return "Not Found";
} else {
return "Error";
}
}
Future<String> deleteBottle(int index) async {
String usertoken = await UserSecureStorage.getUserToken();
http.Response response = await http.delete(
Uri.encodeFull(DotEnv().env['SERVER_URL'] + 'bottle/' + index.toString()),
headers: {"authorization": usertoken},
);
print('asdgasdga');
print(response.statusCode);
if (response.statusCode == 204) {
return "Delete";
} else {
return "Error";
}
}
Widget build(BuildContext context) {
final Size size = MediaQuery.of(context).size;
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
leading: new Icon(Icons.medical_services_rounded,
color: Colors.black, size: 45.0),
title: Text(
'Smart Medicine Box',
style: TextStyle(
color: Colors.black,
fontSize: 23,
fontFamily: 'Noto',
fontWeight: FontWeight.bold),
),
),
body: FutureBuilder(
future: getBottleList(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData == false) {
return CircularProgressIndicator();
} else if (snapshot.hasError) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'Error: ${snapshot.error}',
style: TextStyle(fontSize: 15),
),
);
} else {
return Container(
height: size.height,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SizedBox(height: 10),
Container(
height: size.height * 0.07,
width: size.width,
child: Center(
child: Text(
'등록된 약병 리스트',
textScaleFactor: 1.0,
style: TextStyle(
fontSize: 28,
fontFamily: 'Noto',
fontWeight: FontWeight.bold),
),
),
),
SizedBox(height: 10),
Expanded(
child: GridView.builder(
padding: const EdgeInsets.all(30),
itemCount:
_bottleList.length == null ? 0 : _bottleList.length,
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 200,
crossAxisSpacing: 10,
mainAxisSpacing: 10,
),
itemBuilder: (BuildContext context, int index) {
return InkResponse(
splashColor: Colors.transparent,
child: Container(
height: 140,
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
border: Border.all(),
borderRadius: BorderRadius.all(
Radius.circular(16.0),
),
),
child: Column(
children: [
Container(
decoration: BoxDecoration(
border: Border(
bottom: BorderSide(
color: Colors.black,
width: 1,
style: BorderStyle.solid),
),
),
height: 40,
child: Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Container(
height: 40,
child: Center(
child: Text(
'${_bottleList[index].bottleId}',
style: TextStyle(
color: Colors.black,
fontSize: 20,
fontFamily: 'Noto',
fontWeight: FontWeight.bold),
),
),
),
Container(
child: IconButton(
alignment: Alignment(0.9, 0),
icon: Icon(
Icons.create_sharp,
color: Colors.black,
),
onPressed: () {},
),
),
],
),
),
SizedBox(height: 10),
Container(
height: 90,
child: Icon(
Icons.medical_services_outlined,
size: 100,
),
)
],
),
),
onTap: () {
if (_bottleList.length == 1) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: new Text('약병 삭제'),
content:
new Text('등록된 약병이 하나이므로 해제가 불가능 합니다.'),
actions: <Widget>[
new FlatButton(
child: new Text('Cloes'),
onPressed: () {
Navigator.of(context).pop();
}),
],
);
},
);
} else {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: new Text('약병 삭제'),
content: new Text(
_bottleList[index].bottleId.toString() +
'을 삭제 하시겠습니까?'),
actions: <Widget>[
new FlatButton(
child: new Text('삭제'),
onPressed: () async {
print('dfg');
await deleteBottle(
_bottleList[index].bottleId);
setState(() {});
Navigator.of(context).pop();
},
),
new FlatButton(
child: new Text('취소'),
onPressed: () {
Navigator.of(context).pop();
},
)
],
);
},
);
}
},
);
},
),
),
Container(
padding: EdgeInsets.fromLTRB(0, 20, 0, 20),
width: size.width * 0.8,
height: size.height * 0.13,
margin: EdgeInsets.only(bottom: 0),
child: FlatButton(
height: size.height * 0.06,
onPressed: () async {
await Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) =>
RegisterBottle(modify_bottle: true),
),
);
setState(() {});
},
child: Text(
'약병 추가',
textScaleFactor: 1.0,
style: TextStyle(
color: Colors.white,
fontSize: 24,
fontFamily: 'Noto',
fontWeight: FontWeight.bold),
),
color: Color(0xff0B1E33),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50)),
),
),
],
),
);
}
},
),
);
}
}
import 'package:flutter/material.dart';
import 'package:Smart_Medicine_Box/src/screens/SettingPage.dart';
class DEVInformation extends StatefulWidget {
@override
_DEVInformationState createState() => _DEVInformationState();
}
class _DEVInformationState extends State<DEVInformation> {
Widget build(BuildContext context) {
final Size size = MediaQuery.of(context).size;
return Scaffold(
appBar: AppBar(
iconTheme: IconThemeData(color: Colors.black),
backgroundColor: Colors.white,
title: Text(
'Smart Medicine Box',
style: TextStyle(
color: Colors.black,
fontSize: 20,
fontFamily: 'Noto',
fontWeight: FontWeight.bold),
),
actions: [
IconButton(
icon: Icon(
Icons.settings,
color: Colors.black,
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) => SettingPage(),
));
},
)
],
),
body: Text('1234'),
);
}
}
import 'package:Smart_Medicine_Box/src/screens/Register/RegsiterHub.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:flutter_dotenv/flutter_dotenv.dart';
// Screen import
import '../../utils/user_secure_stoarge.dart';
class HubModifyList extends StatefulWidget {
List<int> hublist;
HubModifyList({Key key, this.hublist}) : super(key: key);
@override
_HubModifyListState createState() => _HubModifyListState();
}
class _HubModifyListState extends State<HubModifyList> {
List<int> _hublist = new List<int>();
//Get Hub List 함수
Future<String> getHubList() async {
String usertoken = await UserSecureStorage.getUserToken();
http.Response response = await http.get(
Uri.encodeFull(DotEnv().env['SERVER_URL'] + 'hub'),
headers: {"authorization": usertoken},
);
List<dynamic> values = new List<dynamic>();
if (_hublist.length != 0) {
_hublist.clear();
}
if (response.statusCode == 200) {
values = json.decode(response.body);
for (int i = 0; i < values.length; i++) {
_hublist.add(values[i]['hubId']);
}
print(_hublist);
return "get완료";
} else if (response.statusCode == 404) {
return "Not Found";
} else {
return "Error";
}
}
Future<String> deleteHub(int index) async {
String usertoken = await UserSecureStorage.getUserToken();
http.Response response = await http.delete(
Uri.encodeFull(DotEnv().env['SERVER_URL'] + 'hub/' + index.toString()),
headers: {"authorization": usertoken},
);
if (response.statusCode == 204) {
return "Delete";
} else {
return "Error";
}
}
Widget build(BuildContext context) {
final Size size = MediaQuery.of(context).size;
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
leading: new Icon(Icons.medical_services_rounded,
color: Colors.black, size: 45.0),
title: Text(
'Smart Medicine Box',
style: TextStyle(
color: Colors.black,
fontSize: 23,
fontFamily: 'Noto',
fontWeight: FontWeight.bold),
),
),
body: FutureBuilder(
future: getHubList(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData == false) {
return CircularProgressIndicator();
} else if (snapshot.hasError) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
'Error: ${snapshot.error}',
style: TextStyle(fontSize: 15),
),
);
} else {
return Container(
height: size.height,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
height: size.height * 0.1,
width: size.width,
child: Center(
child: Text(
'등록된 허브 리스트',
textScaleFactor: 1.0,
style: TextStyle(
fontSize: 28,
fontFamily: 'Noto',
fontWeight: FontWeight.bold),
),
),
decoration: BoxDecoration(border: Border.all()),
),
SizedBox(height: 30),
Expanded(
child: ListView.separated(
padding: const EdgeInsets.all(30),
itemCount:
_hublist.length == null ? 0 : _hublist.length,
itemBuilder: (BuildContext context, int index) {
return Container(
padding: EdgeInsets.all(8.0),
decoration: BoxDecoration(
border: Border.all(),
borderRadius:
BorderRadius.all(Radius.circular(25.0)),
),
child: ListTile(
title: Text(
'HUB ID: ' + '${_hublist[index]}',
style: TextStyle(
color: Colors.black,
fontSize: 20,
fontFamily: 'Noto',
fontWeight: FontWeight.bold),
),
trailing: Icon(Icons.highlight_remove),
onTap: () async {
if (_hublist.length == 1) {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: new Text('허브 삭제'),
content: new Text(
'등록된 허브가 하나이므로 해제가 불가능 합니다.'),
actions: <Widget>[
new FlatButton(
child: new Text('Cloes'),
onPressed: () {
Navigator.of(context).pop();
}),
],
);
},
);
} else {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: new Text('허브 삭제'),
content: new Text(
_hublist[index].toString() +
'을 삭제 하시겠습니까?'),
actions: <Widget>[
new FlatButton(
child: new Text('삭제'),
onPressed: () async {
await deleteHub(_hublist[index]);
setState(() {});
Navigator.of(context).pop();
},
),
new FlatButton(
child: new Text('취소'),
onPressed: () {
Navigator.of(context).pop();
},
)
],
);
},
);
}
},
),
);
},
separatorBuilder: (BuildContext contetx, int index) =>
const Divider(),
),
),
Container(
padding: EdgeInsets.fromLTRB(0, 20, 0, 20),
width: size.width * 0.8,
height: size.height * 0.13,
margin: EdgeInsets.only(bottom: 0),
child: FlatButton(
height: size.height * 0.07,
onPressed: () async {
await Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) =>
RegisterHub(modify_hub: 1),
),
);
setState(() {});
},
child: Text(
'허브 추가',
textScaleFactor: 1.0,
style: TextStyle(
color: Colors.white,
fontSize: 24,
fontFamily: 'Noto',
fontWeight: FontWeight.bold),
),
color: Color(0xff0B1E33),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(50)),
),
),
],
),
);
}
}),
);
}
}
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:Smart_Medicine_Box/src/screens/SettingPage.dart';
class InformationModify extends StatefulWidget {
@override
_InformationModifyState createState() => _InformationModifyState();
}
class _InformationModifyState extends State<InformationModify> {
final passwordController = TextEditingController();
final passwordValidController = TextEditingController();
final medicineNameController = TextEditingController();
final medicineFactureController = TextEditingController();
bool _validate = false;
int userRole = 0;
// Initially password is obscure
bool passwordVisible = false;
bool passwordValidationVisible = true;
Widget build(BuildContext context) {
final Size size = MediaQuery.of(context).size;
return Scaffold(
appBar: AppBar(
iconTheme: IconThemeData(color: Colors.black),
backgroundColor: Colors.white,
title: Text(
'Smart Medicine Box',
style: TextStyle(
color: Colors.black,
fontSize: 20,
fontFamily: 'Noto',
fontWeight: FontWeight.bold),
),
actions: [
IconButton(
icon: Icon(
Icons.settings,
color: Colors.black,
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (BuildContext context) => SettingPage(),
));
},
)
],
),
body: ListView(
children: <Widget>[
Container(
height: size.height * 0.9,
margin: EdgeInsets.fromLTRB(0, 10, 0, 0),
padding: EdgeInsets.fromLTRB(5, 0, 5, 5),
child: Column(
children: <Widget>[
Container(
padding: EdgeInsets.fromLTRB(5, 5, 5, 5),
height: size.height * 0.08,
width: size.width,
child: Center(
child: Text(
'회원 정보 수정',
textAlign: TextAlign.center,
textScaleFactor: 1.0,
style: TextStyle(
color: Colors.black,
fontSize: 32,
fontFamily: 'NotoSansKR',
fontWeight: FontWeight.w700),
),
),
),
MediaQuery(
data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
child: Container(
height: size.height * 0.6,
child: Padding(
padding: const EdgeInsets.fromLTRB(20, 5, 20, 20),
child: new Column(
children: <Widget>[
SizedBox(height: 15),
Container(
height: size.height * 0.091,
padding: const EdgeInsets.fromLTRB(5, 10, 5, 5),
child: Container(
width: size.width * 0.85,
padding: const EdgeInsets.fromLTRB(5, 16, 5, 3),
decoration: BoxDecoration(
color: Color(0xffBDBDBD),
border: Border.all(),
borderRadius:
BorderRadius.all(Radius.circular(5))),
child: Text(
'test@naver.com',
textScaleFactor: 1.0,
style: TextStyle(
color: Colors.black,
fontSize: 18,
fontFamily: 'NotoSansKR',
),
),
),
),
SizedBox(height: 15),
Container(
height: size.height * 0.13,
padding: const EdgeInsets.fromLTRB(5, 10, 5, 5),
child: TextFormField(
keyboardType: TextInputType.text,
controller: passwordController,
obscureText:
!passwordVisible, //This will obscure text dynamically
decoration: InputDecoration(
border: OutlineInputBorder(
borderSide:
BorderSide(color: Colors.black)),
labelText: '비밀번호',
helperText: '비밀번호를 입력해주세요',
// Here is key idea
suffixIcon: IconButton(
icon: Icon(
// Based on passwordVisible state choose the icon
passwordVisible
? Icons.visibility
: Icons.visibility_off,
color: Theme.of(context).primaryColorDark,
),
onPressed: () {
// Update the state i.e. toogle the state of passwordVisible variable
setState(() {
passwordVisible = !passwordVisible;
});
},
),
),
),
),
Container(
height: size.height * 0.13,
padding: const EdgeInsets.fromLTRB(5, 10, 5, 5),
child: TextFormField(
keyboardType: TextInputType.text,
controller: medicineNameController,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: '약 이름',
helperText: '약의 이름을 읿력하세요',
),
),
),
Container(
height: size.height * 0.13,
padding: const EdgeInsets.fromLTRB(5, 10, 5, 5),
child: TextFormField(
keyboardType: TextInputType.text,
controller: medicineFactureController,
decoration: InputDecoration(
border: OutlineInputBorder(),
labelText: '약 제조사 이름',
helperText: '약 제조사의 이름을 읿력하세요',
),
),
),
],
),
),
),
),
Container(
height: 100,
width: size.width * 0.7,
padding: const EdgeInsets.fromLTRB(20, 20, 20, 20),
child: RaisedButton(
onPressed: () async {},
shape: RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(20.0),
side: BorderSide(color: Colors.blue)),
color: Color(0xff1674f6),
child: Text(
'회원 정보 수정',
textScaleFactor: 1.0,
style: TextStyle(
fontSize: 16,
color: Colors.white,
fontWeight: FontWeight.bold),
),
),
)
],
),
),
],
),
);
}
}
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
class CustomPicker extends CommonPickerModel {
var indexs;
String digits(int value, int length) {
return '$value'.padLeft(length, "0");
}
CustomPicker({DateTime currentTime, LocaleType locale})
: super(locale: LocaleType.ko) {
this.currentTime = currentTime ?? DateTime.now();
var _dayPeriod = 0;
this.setLeftIndex(this.currentTime.hour);
this.setMiddleIndex(this.currentTime.minute);
this.setRightIndex(_dayPeriod);
_fillRightList();
}
@override
String leftStringAtIndex(int index) {
if (index >= 1 && index < 13) {
return this.digits(index, 2);
} else {
return null;
}
}
@override
String middleStringAtIndex(int index) {
if (index >= 0 && index < 60) {
return this.digits(index, 2);
} else {
return null;
}
}
@override
String rightStringAtIndex(int index) {
if (index == 0) {
return 'AM';
} else if (index == 1) {
return 'PM';
}
return null;
}
void _fillRightList() {
this.rightList = List.generate(2, (int index) {
return '$index';
});
}
@override
void setRightIndex(int index) {
super.setRightIndex(index);
indexs = index;
_fillRightList();
}
@override
String leftDivider() {
return ":";
}
@override
String rightDivider() {
return " ";
}
@override
List<int> layoutProportions() {
return [1, 1, 1];
}
@override
DateTime finalTime() {
var leftindex;
if (indexs == 1) {
if (this.currentLeftIndex() == 12) {
leftindex = 12;
} else {
leftindex = this.currentLeftIndex() + 12;
}
} else if (indexs == 0) {
if (this.currentLeftIndex() == 12) {
leftindex = 0;
} else {
leftindex = this.currentLeftIndex();
}
}
return currentTime.isUtc
? DateTime.utc(currentTime.year, currentTime.month, currentTime.day,
leftindex, this.currentMiddleIndex(), this.currentRightIndex())
: DateTime(currentTime.year, currentTime.month, currentTime.day,
leftindex, this.currentMiddleIndex(), this.currentRightIndex());
}
}
class Bottle {
final int bottleId;
final String temperature;
final String humidity;
final String balance;
final DateTime recentOpen;
final int medicineId;
final int hubId;
final int dosage;
Bottle(
{this.bottleId,
this.temperature,
this.humidity,
this.balance,
this.recentOpen,
this.medicineId,
this.hubId,
this.dosage});
factory Bottle.fromJson(Map<String, dynamic> parsedJson) {
return Bottle(
bottleId: parsedJson['bottleId'],
temperature: parsedJson['temperature'].toString(),
humidity: parsedJson['humidity'].toString(),
balance: parsedJson['balance'].toString(),
recentOpen: DateTime.parse(parsedJson['recentOpen']).toLocal(),
medicineId: parsedJson['medicineId'],
hubId: parsedJson['hubId'],
dosage: parsedJson['dosage'],
);
}
Map<String, dynamic> toJson() => {
"bottleId": bottleId,
"temperature": temperature,
"humidity:": humidity,
"balance": balance,
"recentOpen": recentOpen,
"medicineId": medicineId,
"hubId": hubId,
"dosage": dosage,
};
}
import 'Medicine.dart';
class Data {
final int totalItem;
final List<Medicine> result;
Data({this.totalItem, this.result});
factory Data.fromJson(Map<String, dynamic> parsedJson) {
var list = parsedJson['result'] as List;
List<Medicine> resultList = list.map((i) => Medicine.fromJson(i)).toList();
return Data(
totalItem: parsedJson['totalItem'],
result: resultList,
);
}
Map<String, dynamic> toJson() => {
"totalItem": totalItem,
"result": result,
};
}
class Medicine {
final int medicineId;
final String antiEffect;
final String company;
final String dosage;
final String name;
final String target;
final String warn;
Medicine(
{this.medicineId,
this.antiEffect,
this.company,
this.dosage,
this.name,
this.target,
this.warn});
factory Medicine.fromJson(Map<String, dynamic> parsedJson) {
return Medicine(
medicineId: parsedJson['medicineId'],
antiEffect: parsedJson['antiEffect'],
company: parsedJson['company'],
dosage: parsedJson['dosage'],
name: parsedJson['name'],
target: parsedJson['target'],
warn: parsedJson['warn'],
);
}
Map<String, dynamic> toJson() => {
"medicineId": medicineId,
"antiEffect": antiEffect,
"company": company,
"dosage": dosage,
"name": name,
"target": target,
"warn": warn,
};
}
class User {
final String userId;
final String token;
User({this.userId, this.token});
factory User.fromJson(Map<String, dynamic> parsedJson) {
return User(
userId: parsedJson['userId'],
token: parsedJson['token'],
);
}
Map<String, dynamic> toJson() => {
"userId": userId,
"token": token,
};
}
import 'package:flutter/material.dart';
const Color bgColor = Color(0xffF4F7FA);
// const Color primaryColor = Colors.green;
const Color primaryColor = Color(0xff44c662);
const Color white = Colors.white;
const Color darkText = Colors.black54;
const Color highlightColor = Colors.green;
import 'package:flutter/material.dart';
import './colors.dart';
import './styles.dart';
Container fryoTextInput(String hintText,
{onTap, onChanged, onEditingComplete, onSubmitted}) {
return Container(
margin: EdgeInsets.only(top: 13),
child: TextField(
onTap: onTap,
onChanged: onChanged,
onEditingComplete: onEditingComplete,
onSubmitted: onSubmitted,
cursorColor: primaryColor,
style: inputFieldTextStyle,
decoration: InputDecoration(
hintText: hintText,
hintStyle: inputFieldHintTextStyle,
focusedBorder: inputFieldFocusedBorderStyle,
contentPadding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
border: inputFieldDefaultBorderStyle),
),
);
}
Container fryoEmailInput(String hintText,
{onTap, onChanged, onEditingComplete, onSubmitted}) {
return Container(
margin: EdgeInsets.only(top: 13),
child: TextField(
onTap: onTap,
onChanged: onChanged,
onEditingComplete: onEditingComplete,
onSubmitted: onSubmitted,
keyboardType: TextInputType.emailAddress,
cursorColor: primaryColor,
style: inputFieldTextStyle,
decoration: InputDecoration(
hintText: hintText,
hintStyle: inputFieldHintTextStyle,
focusedBorder: inputFieldFocusedBorderStyle,
contentPadding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
border: inputFieldDefaultBorderStyle),
),
);
}
Container fryoPasswordInput(String hintText,
{onTap, onChanged, onEditingComplete, onSubmitted}) {
return Container(
margin: EdgeInsets.only(top: 13),
child: TextField(
onTap: onTap,
onChanged: onChanged,
onEditingComplete: onEditingComplete,
onSubmitted: onSubmitted,
obscureText: true,
cursorColor: primaryColor,
style: inputFieldHintPaswordTextStyle,
decoration: InputDecoration(
hintText: hintText,
hintStyle: inputFieldHintPaswordTextStyle,
focusedBorder: inputFieldFocusedBorderStyle,
contentPadding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
border: inputFieldDefaultBorderStyle),
),
);
}
import 'package:flutter/material.dart';
import './colors.dart';
/////////////////////////////////
/// TEXT STYLES
////////////////////////////////
const logoStyle = TextStyle(
fontFamily: 'Pacifico',
fontSize: 30,
color: Colors.black54,
letterSpacing: 2);
const logoWhiteStyle = TextStyle(
fontFamily: 'Pacifico',
fontSize: 21,
letterSpacing: 2,
color: Colors.white);
const whiteText = TextStyle(color: Colors.white, fontFamily: 'Poppins');
const disabledText = TextStyle(color: Colors.grey, fontFamily: 'Poppins');
const contrastText = TextStyle(color: primaryColor, fontFamily: 'Poppins');
const contrastTextBold = TextStyle(
color: primaryColor, fontFamily: 'Poppins', fontWeight: FontWeight.w600);
const h3 = TextStyle(
color: Colors.black,
fontSize: 24,
fontWeight: FontWeight.w800,
fontFamily: 'Poppins');
const h4 = TextStyle(
color: Colors.black,
fontSize: 18,
fontWeight: FontWeight.w700,
fontFamily: 'Poppins');
const h5 = TextStyle(
color: Colors.black,
fontSize: 18,
fontWeight: FontWeight.w500,
fontFamily: 'Poppins');
const h6 = TextStyle(
color: Colors.black,
fontSize: 16,
fontWeight: FontWeight.w500,
fontFamily: 'Poppins');
const priceText = TextStyle(
color: Colors.black,
fontSize: 19,
fontWeight: FontWeight.w800,
fontFamily: 'Poppins');
const foodNameText = TextStyle(
color: Colors.black,
fontSize: 17,
fontWeight: FontWeight.w600,
fontFamily: 'Poppins');
const tabLinkStyle =
TextStyle(fontWeight: FontWeight.w500);
const taglineText = TextStyle(color: Colors.grey, fontFamily: 'Poppins');
const categoryText = TextStyle(
color: Color(0xff444444),
fontWeight: FontWeight.w700,
fontFamily: 'Poppins');
const inputFieldTextStyle =
TextStyle(fontFamily: 'Poppins', fontWeight: FontWeight.w500);
const inputFieldHintTextStyle =
TextStyle(fontFamily: 'Poppins', color: Color(0xff444444));
const inputFieldPasswordTextStyle = TextStyle(
fontFamily: 'Poppins', fontWeight: FontWeight.w500, letterSpacing: 3);
const inputFieldHintPaswordTextStyle = TextStyle(
fontFamily: 'Poppins', color: Color(0xff444444), letterSpacing: 2);
///////////////////////////////////
/// BOX DECORATION STYLES
//////////////////////////////////
const authPlateDecoration = BoxDecoration(
color: white,
boxShadow: [
BoxShadow(
color: Color.fromRGBO(0, 0, 0, .1),
blurRadius: 10,
spreadRadius: 5,
offset: Offset(0, 1))
],
borderRadius: BorderRadiusDirectional.only(
bottomEnd: Radius.circular(20), bottomStart: Radius.circular(20)));
/////////////////////////////////////
/// INPUT FIELD DECORATION STYLES
////////////////////////////////////
const inputFieldFocusedBorderStyle = OutlineInputBorder(
borderRadius: BorderRadius.all(Radius.circular(6)),
borderSide: BorderSide(
color: primaryColor,
));
const inputFieldDefaultBorderStyle = OutlineInputBorder(
gapPadding: 0, borderRadius: BorderRadius.all(Radius.circular(6)));
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
class UserSecureStorage {
static final _storage = FlutterSecureStorage();
static const _keyToken = 'usertoken';
static const _keyUserId = 'userid';
static const _keyBottleId = 'bottleid';
static const _keyMedicineId = 'medicineid';
static const _keyhubId = 'hubid';
static Future setUserId(String userid) async =>
await _storage.write(key: _keyUserId, value: userid);
static Future<String> getUserID() async =>
await _storage.read(key: _keyUserId);
static Future setUserToken(String userToken) async =>
await _storage.write(key: _keyToken, value: userToken);
static Future<String> getUserToken() async =>
await _storage.read(key: _keyToken);
static Future setBottleId(String bottleid) async =>
await _storage.write(key: _keyBottleId, value: bottleid);
static Future<String> getBottleId() async =>
await _storage.read(key: _keyBottleId);
static Future setMedicineId(String medicineid) async =>
await _storage.write(key: _keyMedicineId, value: medicineid);
static Future<String> getMedicineId() async =>
await _storage.read(key: _keyMedicineId);
static Future setHubId(String hubid) async =>
await _storage.write(key: _keyhubId, value: hubid);
static Future<String> getHubId() async => await _storage.read(key: _keyhubId);
}
# Generated by pub
# See https://dart.dev/tools/pub/glossary#lockfile
packages:
async:
dependency: transitive
description:
name: async
url: "https://pub.dartlang.org"
source: hosted
version: "2.5.0-nullsafety.1"
boolean_selector:
dependency: transitive
description:
name: boolean_selector
url: "https://pub.dartlang.org"
source: hosted
version: "2.1.0-nullsafety.1"
characters:
dependency: transitive
description:
name: characters
url: "https://pub.dartlang.org"
source: hosted
version: "1.1.0-nullsafety.3"
charcode:
dependency: transitive
description:
name: charcode
url: "https://pub.dartlang.org"
source: hosted
version: "1.2.0-nullsafety.1"
clock:
dependency: transitive
description:
name: clock
url: "https://pub.dartlang.org"
source: hosted
version: "1.1.0-nullsafety.1"
collection:
dependency: transitive
description:
name: collection
url: "https://pub.dartlang.org"
source: hosted
version: "1.15.0-nullsafety.3"
convert:
dependency: transitive
description:
name: convert
url: "https://pub.dartlang.org"
source: hosted
version: "2.1.1"
cupertino_icons:
dependency: "direct main"
description:
name: cupertino_icons
url: "https://pub.dartlang.org"
source: hosted
version: "0.1.3"
fake_async:
dependency: transitive
description:
name: fake_async
url: "https://pub.dartlang.org"
source: hosted
version: "1.2.0-nullsafety.1"
ffi:
dependency: transitive
description:
name: ffi
url: "https://pub.dartlang.org"
source: hosted
version: "0.1.3"
file:
dependency: transitive
description:
name: file
url: "https://pub.dartlang.org"
source: hosted
version: "5.2.1"
fixnum:
dependency: transitive
description:
name: fixnum
url: "https://pub.dartlang.org"
source: hosted
version: "0.10.11"
flutter:
dependency: "direct main"
description: flutter
source: sdk
version: "0.0.0"
flutter_blue:
dependency: "direct main"
description:
name: flutter_blue
url: "https://pub.dartlang.org"
source: hosted
version: "0.7.2"
flutter_datetime_picker:
dependency: "direct main"
description:
name: flutter_datetime_picker
url: "https://pub.dartlang.org"
source: hosted
version: "1.5.0"
flutter_dotenv:
dependency: "direct main"
description:
name: flutter_dotenv
url: "https://pub.dartlang.org"
source: hosted
version: "2.1.0"
flutter_local_notifications:
dependency: "direct main"
description:
name: flutter_local_notifications
url: "https://pub.dartlang.org"
source: hosted
version: "1.5.0+1"
flutter_local_notifications_platform_interface:
dependency: transitive
description:
name: flutter_local_notifications_platform_interface
url: "https://pub.dartlang.org"
source: hosted
version: "1.0.1"
flutter_screenutil:
dependency: "direct main"
description:
name: flutter_screenutil
url: "https://pub.dartlang.org"
source: hosted
version: "0.7.0"
flutter_secure_storage:
dependency: "direct main"
description:
name: flutter_secure_storage
url: "https://pub.dartlang.org"
source: hosted
version: "3.3.5"
flutter_test:
dependency: "direct dev"
description: flutter
source: sdk
version: "0.0.0"
flutter_web_plugins:
dependency: transitive
description: flutter
source: sdk
version: "0.0.0"
http:
dependency: "direct main"
description:
name: http
url: "https://pub.dartlang.org"
source: hosted
version: "0.12.2"
http_parser:
dependency: transitive
description:
name: http_parser
url: "https://pub.dartlang.org"
source: hosted
version: "3.1.4"
infinite_listview:
dependency: transitive
description:
name: infinite_listview
url: "https://pub.dartlang.org"
source: hosted
version: "1.0.1+1"
intl:
dependency: "direct main"
description:
name: intl
url: "https://pub.dartlang.org"
source: hosted
version: "0.16.1"
logging:
dependency: transitive
description:
name: logging
url: "https://pub.dartlang.org"
source: hosted
version: "0.11.4"
mailer:
dependency: "direct main"
description:
name: mailer
url: "https://pub.dartlang.org"
source: hosted
version: "3.3.0"
matcher:
dependency: transitive
description:
name: matcher
url: "https://pub.dartlang.org"
source: hosted
version: "0.12.10-nullsafety.1"
meta:
dependency: transitive
description:
name: meta
url: "https://pub.dartlang.org"
source: hosted
version: "1.3.0-nullsafety.3"
mime:
dependency: transitive
description:
name: mime
url: "https://pub.dartlang.org"
source: hosted
version: "0.9.7"
numberpicker:
dependency: "direct main"
description:
name: numberpicker
url: "https://pub.dartlang.org"
source: hosted
version: "1.3.0"
page_transition:
dependency: "direct main"
description:
name: page_transition
url: "https://pub.dartlang.org"
source: hosted
version: "1.1.7+6"
path:
dependency: transitive
description:
name: path
url: "https://pub.dartlang.org"
source: hosted
version: "1.8.0-nullsafety.1"
path_provider:
dependency: "direct main"
description:
name: path_provider
url: "https://pub.dartlang.org"
source: hosted
version: "1.6.28"
path_provider_linux:
dependency: transitive
description:
name: path_provider_linux
url: "https://pub.dartlang.org"
source: hosted
version: "0.0.1+2"
path_provider_macos:
dependency: transitive
description:
name: path_provider_macos
url: "https://pub.dartlang.org"
source: hosted
version: "0.0.4+8"
path_provider_platform_interface:
dependency: transitive
description:
name: path_provider_platform_interface
url: "https://pub.dartlang.org"
source: hosted
version: "1.0.4"
path_provider_windows:
dependency: transitive
description:
name: path_provider_windows
url: "https://pub.dartlang.org"
source: hosted
version: "0.0.4+3"
pedantic:
dependency: transitive
description:
name: pedantic
url: "https://pub.dartlang.org"
source: hosted
version: "1.9.0"
platform:
dependency: transitive
description:
name: platform
url: "https://pub.dartlang.org"
source: hosted
version: "2.2.1"
plugin_platform_interface:
dependency: transitive
description:
name: plugin_platform_interface
url: "https://pub.dartlang.org"
source: hosted
version: "1.0.3"
process:
dependency: transitive
description:
name: process
url: "https://pub.dartlang.org"
source: hosted
version: "3.0.13"
protobuf:
dependency: transitive
description:
name: protobuf
url: "https://pub.dartlang.org"
source: hosted
version: "1.1.3"
rxdart:
dependency: "direct main"
description:
name: rxdart
url: "https://pub.dartlang.org"
source: hosted
version: "0.24.1"
shared_preferences:
dependency: "direct main"
description:
name: shared_preferences
url: "https://pub.dartlang.org"
source: hosted
version: "0.5.12+4"
shared_preferences_linux:
dependency: transitive
description:
name: shared_preferences_linux
url: "https://pub.dartlang.org"
source: hosted
version: "0.0.2+4"
shared_preferences_macos:
dependency: transitive
description:
name: shared_preferences_macos
url: "https://pub.dartlang.org"
source: hosted
version: "0.0.1+11"
shared_preferences_platform_interface:
dependency: transitive
description:
name: shared_preferences_platform_interface
url: "https://pub.dartlang.org"
source: hosted
version: "1.0.4"
shared_preferences_web:
dependency: transitive
description:
name: shared_preferences_web
url: "https://pub.dartlang.org"
source: hosted
version: "0.1.2+7"
shared_preferences_windows:
dependency: transitive
description:
name: shared_preferences_windows
url: "https://pub.dartlang.org"
source: hosted
version: "0.0.2+3"
sky_engine:
dependency: transitive
description: flutter
source: sdk
version: "0.0.99"
source_span:
dependency: transitive
description:
name: source_span
url: "https://pub.dartlang.org"
source: hosted
version: "1.8.0-nullsafety.2"
sqflite:
dependency: "direct main"
description:
name: sqflite
url: "https://pub.dartlang.org"
source: hosted
version: "1.3.1+2"
sqflite_common:
dependency: transitive
description:
name: sqflite_common
url: "https://pub.dartlang.org"
source: hosted
version: "1.0.3+3"
stack_trace:
dependency: transitive
description:
name: stack_trace
url: "https://pub.dartlang.org"
source: hosted
version: "1.10.0-nullsafety.1"
stream_channel:
dependency: transitive
description:
name: stream_channel
url: "https://pub.dartlang.org"
source: hosted
version: "2.1.0-nullsafety.1"
string_scanner:
dependency: transitive
description:
name: string_scanner
url: "https://pub.dartlang.org"
source: hosted
version: "1.1.0-nullsafety.1"
synchronized:
dependency: transitive
description:
name: synchronized
url: "https://pub.dartlang.org"
source: hosted
version: "2.2.0+2"
term_glyph:
dependency: transitive
description:
name: term_glyph
url: "https://pub.dartlang.org"
source: hosted
version: "1.2.0-nullsafety.1"
test_api:
dependency: transitive
description:
name: test_api
url: "https://pub.dartlang.org"
source: hosted
version: "0.2.19-nullsafety.2"
timezone:
dependency: "direct main"
description:
name: timezone
url: "https://pub.dartlang.org"
source: hosted
version: "0.6.1"
typed_data:
dependency: transitive
description:
name: typed_data
url: "https://pub.dartlang.org"
source: hosted
version: "1.3.0-nullsafety.3"
vector_math:
dependency: transitive
description:
name: vector_math
url: "https://pub.dartlang.org"
source: hosted
version: "2.1.0-nullsafety.3"
win32:
dependency: transitive
description:
name: win32
url: "https://pub.dartlang.org"
source: hosted
version: "1.7.4+1"
xdg_directories:
dependency: transitive
description:
name: xdg_directories
url: "https://pub.dartlang.org"
source: hosted
version: "0.1.0"
sdks:
dart: ">=2.10.0-110 <2.11.0"
flutter: ">=1.20.0 <2.0.0"
name: Smart_Medicine_Box
description: A new Flutter project.
# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1
environment:
sdk: ">=2.7.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
flutter_screenutil: ^0.7.0
page_transition: '^1.1.5'
mailer: '^3.0.4'
flutter_local_notifications: ^1.4.4+5
rxdart: ^0.24.0
flutter_datetime_picker: ^1.3.4
timezone: ^0.6.0
intl : ^0.16.1
shared_preferences: ^0.5.12+2
flutter_blue: ^0.7.2
cupertino_icons: ^0.1.3
http: ^0.12.0+4
flutter_dotenv: ^2.1.0
numberpicker: ^1.3.0
flutter_secure_storage: ^3.3.5
sqflite: ^1.1.6
path_provider: ^1.2.0
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
assets:
- .env
- images/
- images/main_logo.png
- images/setting.png
fonts:
# - family: Raleway
# fonts:
# - asset: fonts/Raleway-Regular.ttf
# - asset: fonts/Raleway-Italic.ttf
# style: italic
- family: NotoSansKR
fonts:
- asset: assets/fonts/NotoSansKR-Regular.otf
- asset: assets/fonts/NotoSansKR-Bold.otf
weight: 500
- asset: assets/fonts/NotoSansKR-Black.otf
weight: 700
\ No newline at end of file
// This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:Smart_Medicine_Box/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
# 스마트 약병 IoT 하드웨어 및 연결단 개발
## 지도교수
+ 유인태 교수님
## 개발담당자
+ 2015100552 컴퓨터공학과 윤형선
## 일정
+ 2021.05.03: Init(개인 아두이노 코드 git에서 이전)
+ 2021.05.11: Arduino 개발 중단, RaspberryPi Pico로 플랫폼 이전, C++ -> MicroPython
+ 2021.05.12: RaspberryPi Pico v0.1 code complete. Now working on rpi4 with MQTT.
+ 2021.05.13: RaspberryPi4 v0.1 code complete. with MQTT. + Pico code bug fix.
+ 2021.05.13: Fritzing design add.
+ 2021.05.16: RPI4 Code update
+ 2021.05.22: 3D Modeling file add.(Ender3 Pro)
+ 2021.05.25: 3D Printer gcode file updated.(Ender3 Pro+PLA)
\ No newline at end of file
No preview for this file type
This diff could not be displayed because it is too large.
No preview for this file type
This diff could not be displayed because it is too large.
No preview for this file type
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
No preview for this file type
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
No preview for this file type
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
No preview for this file type
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
No preview for this file type
# RaspberryPi4용 코드
- rpi.py
```
라즈베리파이 메인코드
```
- serverside_mqtt_stest.py
```
server에서 데이터 보낼 예제
```
- serverside_mqtt_rtest.py
```
server에서 수신한 데이터
```
python rpi.py동작 후, test코드 활용해서 테스트 가능
paho-mqtt
\ No newline at end of file
import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
from bluetooth import *
import time
MQTT_BLOCK = False
BT_MAC_ADDRESS = '00:18:91:D8:24:39'
MED_BOTT_NO = '1'
client_socket = BluetoothSocket( RFCOMM )
client_mqtt = mqtt.Client()
# --------------------------------------------------- #
# INTERNAL FUNCTIONS
# --------------------------------------------------- #
def _send_data(msg:str):
''' Bluetooth를 통해 데이터를 송신한다
'''
client_socket.send(msg)
def _recv_data():
''' Bluetooth를 통해 데이터를 수신한다
'''
# 소켓에 2초간 받을 수 있는 시간을 준다
client_socket.settimeout(2)
# 데이터 받을 변수
data = ''
try:
timeout_start = time.time()
timeout = 2
while time.time() < timeout_start + timeout:
data += client_socket.recv(1024).decode('utf-8')
except:
print('INFO: DATA RECV TIMEOUT')
finally:
return data
def _sub_mqtt(client, userdata, flags, rc):
''' MQTT에서 subscribe한다
'''
print("Connected with result code "+str(rc))
client.subscribe(f'bottle/1/stb')
def _work_mqtt(client, userdata, msg):
''' MQTT에서 데이터를 받으면 알맞게 로직을 수행한다
'''
print('DOING SOMETHING')
global MQTT_BLOCK
MQTT_BLOCK = True
received_msg = msg.payload.decode('utf-8')
data = ''
data_list = []
# 만약 req메시지를 받았다면
if received_msg == 'req':
# 데이터가 손실되어 왔을 경우 에러 처리
if len(data_list[0]) == 0:
data_list = []
elif len(data_list[3]) == 0:
data_list = []
while len(data_list) != 4:
_send_data('REQ')
data = _recv_data()
data_list = data.split('/')
# 데이터가 손실되어 왔을 경우 에러 처리
if len(data_list[0]) == 0:
data_list = []
elif len(data_list[3]) == 0:
data_list = []
# 데이터를 Publish한다
_pub_mqtt(f'bottle/{MED_BOTT_NO}/bts', data, 'localhost')
# 만약 res메시지를 받았다면
elif received_msg.split('/')[0] == 'res':
_send_data(received_msg.split('/')[1])
data = _recv_data()
data_list = data.split('/')
# 데이터가 손실되어 왔을 경우 에러 처리
if len(data_list[0]) == 0:
data_list = []
elif len(data_list[3]) == 0:
data_list = []
while len(data_list) != 4:
_send_data('REQ')
data = _recv_data()
data_list = data.split('/')
# 데이터가 손실되어 왔을 경우 에러 처리
if len(data_list[0]) == 0:
data_list = []
elif len(data_list[3]) == 0:
data_list = []
# 데이터를 Publish한다
# _pub_mqtt(f'bottle/{MED_BOTT_NO}/bts', data, 'localhost')
print("DEBUG")
print(data)
print(data_list)
print(received_msg)
MQTT_BLOCK = False
def _pub_mqtt(topic:str, payload:str, hostname:str):
''' MQTT를 통해 데이터를 publish한다
'''
publish.single(
topic=topic,
payload=payload,
hostname=hostname)
# --------------------------------------------------- #
# MAIN
# --------------------------------------------------- #
def _run():
# CONNECT BT
client_socket.connect((BT_MAC_ADDRESS, 1))
print('bluetooth connected!')
# SUBSCRIBE MQTT
client_mqtt.on_connect = _sub_mqtt
client_mqtt.on_message = _work_mqtt
client_mqtt.connect_async("localhost")
client_mqtt.loop_start()
while True:
if MQTT_BLOCK is False:
# 항상 데이터를 받을 상태로 있는다
data = _recv_data()
# 만약 데이터가 ''가 아니면 무언가 온 것이므로 처리한다
if data != '':
print('DATA IN')
data_list = data.split('/')
# 데이터가 손실되어 왔을 경우 에러 처리
if len(data_list[0]) == 0:
data_list = []
elif len(data_list[3]) == 0:
data_list = []
# 만약 데이터가 불량하게 왔을 경우, 제대로 올때까지 반복시도한다
while len(data_list) != 4:
data = _recv_data()
data_list = data.split('/')
# 데이터가 손실되어 왔을 경우 에러 처리
if len(data_list[0]) == 0:
data_list = []
elif len(data_list[3]) == 0:
data_list = []
# 데이터를 Publish한다
_pub_mqtt(f'bottle/{MED_BOTT_NO}/bts', data, 'localhost')
client_socket.close()
if __name__ == '__main__':
_run()
\ No newline at end of file
import paho.mqtt.client as mqtt
import time
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.subscribe("bottle/1/bts") # 요거 수정해서 확인하세요
def on_message(client, userdata, msg):
print(msg.topic)
print(msg.payload.decode('utf-8'))
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect_async("localhost")
client.loop_start()
while True:
print("TESTing")
time.sleep(1)
\ No newline at end of file
import paho.mqtt.publish as publish
# hub -> server
# msgs = \
# [
# {
# 'topic':"bottle/1/bts",
# 'payload':"1/30.4/32.2/1"
# }
# ]
# server -> hub with date
# msgs = \
# [
# {
# 'topic':"bottle/1/stb",
# 'payload':"res/0513"
# }
# ]
# server -> hub without date
msgs = \
[
{
'topic':"bottle/1/stb",
'payload':"req"
}
]
publish.multiple(msgs, hostname="localhost")
"""
MicroPython TM1637 quad 7-segment LED display driver
https://github.com/mcauser/micropython-tm1637
MIT License
Copyright (c) 2016 Mike Causer
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
from micropython import const
from machine import Pin
from time import sleep_us, sleep_ms
TM1637_CMD1 = const(64) # 0x40 data command
TM1637_CMD2 = const(192) # 0xC0 address command
TM1637_CMD3 = const(128) # 0x80 display control command
TM1637_DSP_ON = const(8) # 0x08 display on
TM1637_DELAY = const(10) # 10us delay between clk/dio pulses
TM1637_MSB = const(128) # msb is the decimal point or the colon depending on your display
# 0-9, a-z, blank, dash, star
_SEGMENTS = bytearray(b'\x3F\x06\x5B\x4F\x66\x6D\x7D\x07\x7F\x6F\x77\x7C\x39\x5E\x79\x71\x3D\x76\x06\x1E\x76\x38\x55\x54\x3F\x73\x67\x50\x6D\x78\x3E\x1C\x2A\x76\x6E\x5B\x00\x40\x63')
class TM1637(object):
"""Library for quad 7-segment LED modules based on the TM1637 LED driver."""
def __init__(self, clk, dio, brightness=7):
self.clk = clk
self.dio = dio
if not 0 <= brightness <= 7:
raise ValueError("Brightness out of range")
self._brightness = brightness
self.clk.init(Pin.OUT, value=0)
self.dio.init(Pin.OUT, value=0)
sleep_us(TM1637_DELAY)
self._write_data_cmd()
self._write_dsp_ctrl()
def _start(self):
self.dio(0)
sleep_us(TM1637_DELAY)
self.clk(0)
sleep_us(TM1637_DELAY)
def _stop(self):
self.dio(0)
sleep_us(TM1637_DELAY)
self.clk(1)
sleep_us(TM1637_DELAY)
self.dio(1)
def _write_data_cmd(self):
# automatic address increment, normal mode
self._start()
self._write_byte(TM1637_CMD1)
self._stop()
def _write_dsp_ctrl(self):
# display on, set brightness
self._start()
self._write_byte(TM1637_CMD3 | TM1637_DSP_ON | self._brightness)
self._stop()
def _write_byte(self, b):
for i in range(8):
self.dio((b >> i) & 1)
sleep_us(TM1637_DELAY)
self.clk(1)
sleep_us(TM1637_DELAY)
self.clk(0)
sleep_us(TM1637_DELAY)
self.clk(0)
sleep_us(TM1637_DELAY)
self.clk(1)
sleep_us(TM1637_DELAY)
self.clk(0)
sleep_us(TM1637_DELAY)
def brightness(self, val=None):
"""Set the display brightness 0-7."""
# brightness 0 = 1/16th pulse width
# brightness 7 = 14/16th pulse width
if val is None:
return self._brightness
if not 0 <= val <= 7:
raise ValueError("Brightness out of range")
self._brightness = val
self._write_data_cmd()
self._write_dsp_ctrl()
def write(self, segments, pos=0):
"""Display up to 6 segments moving right from a given position.
The MSB in the 2nd segment controls the colon between the 2nd
and 3rd segments."""
if not 0 <= pos <= 5:
raise ValueError("Position out of range")
self._write_data_cmd()
self._start()
self._write_byte(TM1637_CMD2 | pos)
for seg in segments:
self._write_byte(seg)
self._stop()
self._write_dsp_ctrl()
def encode_digit(self, digit):
"""Convert a character 0-9, a-f to a segment."""
return _SEGMENTS[digit & 0x0f]
def encode_string(self, string):
"""Convert an up to 4 character length string containing 0-9, a-z,
space, dash, star to an array of segments, matching the length of the
source string."""
segments = bytearray(len(string))
for i in range(len(string)):
segments[i] = self.encode_char(string[i])
return segments
def encode_char(self, char):
"""Convert a character 0-9, a-z, space, dash or star to a segment."""
o = ord(char)
if o == 32:
return _SEGMENTS[36] # space
if o == 42:
return _SEGMENTS[38] # star/degrees
if o == 45:
return _SEGMENTS[37] # dash
if o >= 65 and o <= 90:
return _SEGMENTS[o-55] # uppercase A-Z
if o >= 97 and o <= 122:
return _SEGMENTS[o-87] # lowercase a-z
if o >= 48 and o <= 57:
return _SEGMENTS[o-48] # 0-9
raise ValueError("Character out of range: {:d} '{:s}'".format(o, chr(o)))
def hex(self, val):
"""Display a hex value 0x0000 through 0xffff, right aligned."""
string = '{:04x}'.format(val & 0xffff)
self.write(self.encode_string(string))
def number(self, num):
"""Display a numeric value -999 through 9999, right aligned."""
# limit to range -999 to 9999
num = max(-999, min(num, 9999))
string = '{0: >4d}'.format(num)
self.write(self.encode_string(string))
def numbers(self, num1, num2, colon=True):
"""Display two numeric values -9 through 99, with leading zeros
and separated by a colon."""
num1 = max(-9, min(num1, 99))
num2 = max(-9, min(num2, 99))
segments = self.encode_string('{0:0>2d}{1:0>2d}'.format(num1, num2))
if colon:
segments[1] |= 0x80 # colon on
self.write(segments)
def temperature(self, num):
if num < -9:
self.show('lo') # low
elif num > 99:
self.show('hi') # high
else:
string = '{0: >2d}'.format(num)
self.write(self.encode_string(string))
self.write([_SEGMENTS[38], _SEGMENTS[12]], 2) # degrees C
def show(self, string, colon=False):
segments = self.encode_string(string)
if len(segments) > 1 and colon:
segments[1] |= 128
self.write(segments[:4])
def scroll(self, string, delay=250):
segments = string if isinstance(string, list) else self.encode_string(string)
data = [0] * 8
data[4:0] = list(segments)
for i in range(len(segments) + 5):
self.write(data[0+i:4+i])
sleep_ms(delay)
class TM1637Decimal(TM1637):
"""Library for quad 7-segment LED modules based on the TM1637 LED driver.
This class is meant to be used with decimal display modules (modules
that have a decimal point after each 7-segment LED).
"""
def encode_string(self, string):
"""Convert a string to LED segments.
Convert an up to 4 character length string containing 0-9, a-z,
space, dash, star and '.' to an array of segments, matching the length of
the source string."""
segments = bytearray(len(string.replace('.','')))
j = 0
for i in range(len(string)):
if string[i] == '.' and j > 0:
segments[j-1] |= TM1637_MSB
continue
segments[j] = self.encode_char(string[i])
j += 1
return segments
import uos
import machine
import utime
uart0 = machine.UART(0,baudrate=9600)
# --------------------------------------------------- #
# INTERNAL FUNCTIONS
# --------------------------------------------------- #
def _clartBuf(uart=uart0):
''' Clear Buffer
'''
while uart.any():
print(uart.read(1))
# --------------------------------------------------- #
# FUNCTIONS
# --------------------------------------------------- #
def send_data_bt(sdata:str):
''' Send string data using Bluetooth
'''
_clartBuf()
uart0.write(sdata)
def recv_data_bt():
''' Receive string data using Bluetooth
'''
_clartBuf()
prvMills = utime.ticks_ms()
received_data = ''
while (utime.ticks_ms()-prvMills)<2000:
if uart0.any():
single_data = uart0.read(1)
received_data += single_data.decode('utf-8')
return received_data
\ No newline at end of file
''' Original code from https://www.raspberrypi.org/forums/viewtopic.php?t=303606
'''
import utime
import rp2
from rp2 import PIO, asm_pio
from machine import Pin
# --------------------------------------------------- #
# INIT
# --------------------------------------------------- #
# For VCC
dht_pwr = Pin(14, Pin.OUT)
# For data
dht_data = Pin(15, Pin.IN, Pin.PULL_UP)
# Power on
dht_pwr.value(1)
# Create empty state
sm=rp2.StateMachine(1)
# Wait for DHT22 to start up
utime.sleep(2)
# --------------------------------------------------- #
# INIT2
# --------------------------------------------------- #
@asm_pio(set_init=(PIO.OUT_HIGH),autopush=True, push_thresh=8) #output one byte at a time
def DHT22():
#drive output low for at least 20ms
set(pindirs,1) #set pin to output
set(pins,0) #set pin low
set(y,31) #prepare countdown, y*x*100cycles
label ('waity')
set(x,31)
label ('waitx')
nop() [30]
jmp(x_dec,'waitx') #decrement x reg every 100 cycles
jmp(y_dec,'waity') #decrement y reg every time x reaches zero
#begin reading from device
set(pindirs,0) #set pin to input
wait(1,pin,0) #check pin is high before starting
wait(0,pin,0)
wait(1,pin,0)
wait(0,pin,0) #wait for start of data
#read databit
label('readdata')
set(x,21) #reset x register to count down from 20
wait(1,pin,0) #wait for high signal
label('countdown')
jmp(pin,'continue') #if pin still high continue counting
#pin is low before countdown is complete - bit '0' detected
set(y,0)
in_(y, 1) #shift '0' into the isr
jmp('readdata') #read the next bit
label('continue')
jmp(x_dec,'countdown') #decrement x reg and continue counting if x!=0
#pin is still high after countdown complete - bit '1' detected
set(y,1)
in_(y, 1) #shift one bit into the isr
wait(0,pin,0) #wait for low signal (next bit)
jmp('readdata') #read the next bit
# --------------------------------------------------- #
# FUNCTIONS
# --------------------------------------------------- #
def work_dht():
data=[]
total=0
sm.init(DHT22,freq=1600000,set_base=dht_data,in_base=dht_data,jmp_pin=dht_data)
sm.active(1)
for i in range(5): #data should be 40 bits (5 bytes) long
data.append(sm.get()) #read byte
#check checksum (lowest 8 bits of the sum of the first 4 bytes)
for i in range(4):
total=total+data[i]
if((total & 255) == data[4]):
humidity=((data[0]<<8) + data[1])/10.0
temperature=(((data[2] &0x7f) << 8) + data[3]) /10.0
if (data[2] & 0x80) == 0x80:
temperature = -temperature
return [humidity, temperature]
else:
return False
\ No newline at end of file
import tm1637
from machine import Pin
from utime import sleep
display4 = tm1637.TM1637(clk=Pin(12), dio=Pin(13))
# --------------------------------------------------- #
# FUNCTIONS
# --------------------------------------------------- #
def work_tm1637(data:str):
display4.show(data)
def off_tm1637():
display4.show(' ')
# # Show a word
# mydisplay.show("Pico")
# sleep(1)
# #blank the screen
# mydisplay.show(" ")
# sleep(1)
# #show numbers
# mydisplay.number(-123)
# sleep(1)
# #show a time with colon
# mydisplay.numbers(12,59)
# sleep(1)
# #adjust the brightness to make it lower
# mydisplay.brightness(0)
# sleep(1)
# #show scrolling text
# mydisplay.scroll("Hello World 123", delay=200)
# sleep(1)
# #show temperature
# mydisplay.temperature(99)
# sleep(1)
# #blank the screen again
# mydisplay.show(" ")
\ No newline at end of file
import array, utime
from machine import Pin
import rp2
import neopixel
import dht
import bluetoooth as bto
import ultrasonic
import reed
import display4
# --------------------------------------------------- #
# FUNCTIONS
# --------------------------------------------------- #
def _collect_sensor_datas(reed_data:int) -> str:
# Collect Humidity, Temperature
dht_data = dht.work_dht()
if dht_data == False:
dht_data = [0,0]
# Collect Ultrasonic distance
ultrasonic_data = ultrasonic.work_sr04()
# Make data string
send_data_str = str(reed_data) + '/' + str(dht_data[1]) + '/' + str(dht_data[0]) + '/' + str(ultrasonic_data)
return send_data_str
# --------------------------------------------------- #
# LOOP ENTRYPOINT
# --------------------------------------------------- #
def _run():
# INIT REED STATE
reed_data = -1
# LOOP
while True:
# ------------------------------------------- #
# DEFAULT LOOP
# ------------------------------------------- #
# Get data using BT(Standby)
input_data = bto.recv_data_bt()
# Get reed data from reed sensor
current_reed_data = reed.work_reed()
# ------------------------------------------- #
# IF CONDITION MET
# ------------------------------------------- #
if input_data != '' or reed_data != current_reed_data:
# Refine BT data
input_data = input_data.strip()
# Test code
print('INPUT FOUND ', input_data)
# IF INPUT MEANS GET MESSAGE or MEDICINE LID STATUS CHANGED
if input_data == 'REQ' or reed_data != current_reed_data:
# Send data using BT
bto.send_data_bt(_collect_sensor_datas(current_reed_data))
else:
# Refine BT data
input_data = input_data.strip()
display4.work_tm1637(input_data)
neopixel.work_led()
display4.off_tm1637()
# Send data using BT
bto.send_data_bt(_collect_sensor_datas(current_reed_data))
# Update reed state
reed_data = current_reed_data
if __name__ == '__main__':
_run()
\ No newline at end of file
''' Original code from https://core-electronics.com.au/tutorials/how-to-use-ws2812b-rgb-leds-with-raspberry-pi-pico.html
'''
import array, utime
from machine import Pin
import rp2
# --------------------------------------------------- #
# INIT
# --------------------------------------------------- #
NUM_LEDS = 8
PIN_NUM = 22
BLACK = (0, 0, 0)
RED = (255, 0, 0)
YELLOW = (255, 150, 0)
GREEN = (0, 255, 0)
CYAN = (0, 255, 255)
BLUE = (0, 0, 255)
PURPLE = (180, 0, 255)
WHITE = (255, 255, 255)
COLORS = (BLACK, RED, YELLOW, GREEN, CYAN, BLUE, PURPLE, WHITE, BLACK)
# --------------------------------------------------- #
# INIT2
# --------------------------------------------------- #
@rp2.asm_pio(sideset_init=rp2.PIO.OUT_LOW, out_shiftdir=rp2.PIO.SHIFT_LEFT, autopull=True, pull_thresh=24)
def ws2812():
T1 = 2
T2 = 5
T3 = 3
wrap_target()
label("bitloop")
out(x, 1) .side(0) [T3 - 1]
jmp(not_x, "do_zero") .side(1) [T1 - 1]
jmp("bitloop") .side(1) [T2 - 1]
label("do_zero")
nop() .side(0) [T2 - 1]
wrap()
# Create the StateMachine with the ws2812 program, outputting on pin
sm = rp2.StateMachine(0, ws2812, freq=8_000_000, sideset_base=Pin(PIN_NUM))
# Start the StateMachine, it will wait for data on its FIFO.
sm.active(1)
# Display a pattern on the LEDs via an array of LED RGB values.
ar = array.array("I", [0 for _ in range(NUM_LEDS)])
# --------------------------------------------------- #
# INTERNAL FUNCTIONS
# --------------------------------------------------- #
def _pixels_show(brightness:int = 0.2):
dimmer_ar = array.array("I", [0 for _ in range(NUM_LEDS)])
for i,c in enumerate(ar):
r = int(((c >> 8) & 0xFF) * brightness)
g = int(((c >> 16) & 0xFF) * brightness)
b = int((c & 0xFF) * brightness)
dimmer_ar[i] = (g<<16) + (r<<8) + b
sm.put(dimmer_ar, 8)
utime.sleep_ms(10)
def _pixels_set(i, color):
ar[i] = (color[1]<<16) + (color[0]<<8) + color[2]
def _pixels_fill(color):
for i in range(len(ar)):
_pixels_set(i, color)
# --------------------------------------------------- #
# FUNCTIONS
# --------------------------------------------------- #
def work_led(brightness:int = 0.2):
for color in COLORS:
_pixels_fill(color)
_pixels_show(brightness)
utime.sleep(0.4)
from machine import Pin, Signal
data_pin = Pin(16, Pin.IN)
# --------------------------------------------------- #
# FUNCTIONS
# --------------------------------------------------- #
def work_reed() -> int:
# 1 = Lid opened, 0 = Lid closed
return data_pin.value()
''' Original code from https://www.iottrends.tech/blog/how-to-use-ultrasonic-sensor-with-raspberry-pi-pico/
'''
from machine import Pin
import utime
trigger = Pin(26, Pin.OUT)
echo = Pin(27, Pin.IN)
# --------------------------------------------------- #
# FUNCTIONS
# --------------------------------------------------- #
def work_sr04():
trigger.low()
utime.sleep_us(2)
trigger.high()
utime.sleep_us(5)
trigger.low()
while echo.value() == 0:
signaloff = utime.ticks_us()
while echo.value() == 1:
signalon = utime.ticks_us()
timepassed = signalon - signaloff
distance = (timepassed * 0.0330) / 2
return distance
import uos
import machine
import utime
uart0 = machine.UART(0,baudrate=9600)
def _clartBuf(uart=uart0):
print("Clear UART buffer "+ str(uart))
while uart.any():
print(uart.read(1))
def send_data_bt(sdata:str):
_clartBuf()
uart0.write(sdata)
def recv_data_bt():
_clartBuf()
prvMills = utime.ticks_ms()
received_data = ''
while (utime.ticks_ms()-prvMills)<2000:
if uart0.any():
single_data = uart0.read(1)
received_data += single_data.decode('utf-8')
return received_data
import utime
import rp2
from rp2 import PIO, asm_pio
from machine import Pin
dht_pwr = Pin(14, Pin.OUT) #connect GPIO 14 to '+' on DHT11
dht_data = Pin(15, Pin.IN, Pin.PULL_UP) #connect GPIO 15 to 'out' on DHT11
dht_pwr.value(1) #power on DHT11
sm=rp2.StateMachine(1) #create empty state machine
utime.sleep(2) #wait for DHT11 to start up
@asm_pio(set_init=(PIO.OUT_HIGH),autopush=True, push_thresh=8) #output one byte at a time
def DHT22():
#drive output low for at least 20ms
set(pindirs,1) #set pin to output
set(pins,0) #set pin low
set(y,31) #prepare countdown, y*x*100cycles
label ('waity')
set(x,31)
label ('waitx')
nop() [30]
jmp(x_dec,'waitx') #decrement x reg every 100 cycles
jmp(y_dec,'waity') #decrement y reg every time x reaches zero
#begin reading from device
set(pindirs,0) #set pin to input
wait(1,pin,0) #check pin is high before starting
wait(0,pin,0)
wait(1,pin,0)
wait(0,pin,0) #wait for start of data
#read databit
label('readdata')
set(x,21) #reset x register to count down from 20
wait(1,pin,0) #wait for high signal
label('countdown')
jmp(pin,'continue') #if pin still high continue counting
#pin is low before countdown is complete - bit '0' detected
set(y,0)
in_(y, 1) #shift '0' into the isr
jmp('readdata') #read the next bit
label('continue')
jmp(x_dec,'countdown') #decrement x reg and continue counting if x!=0
#pin is still high after countdown complete - bit '1' detected
set(y,1)
in_(y, 1) #shift one bit into the isr
wait(0,pin,0) #wait for low signal (next bit)
jmp('readdata') #read the next bit
# --------------------------------------------------- #
# ENTRYPOINT
# --------------------------------------------------- #
def work_dht():
print("DHT22 WORKING")
data=[]
total=0
sm.init(DHT22,freq=1600000,set_base=dht_data,in_base=dht_data,jmp_pin=dht_data) #start state machine
#state machine frequency adjusted so that PIO countdown during 'readdata' ends somewhere between the
#duration of a '0' and a '1' high signal
sm.active(1)
for i in range(5): #data should be 40 bits (5 bytes) long
data.append(sm.get()) #read byte
print("data: " + str(data))
#check checksum (lowest 8 bits of the sum of the first 4 bytes)
for i in range(4):
total=total+data[i]
if((total & 255) == data[4]):
humidity=((data[0]<<8) + data[1])/10.0 #DHT11 provides integer humidity (no decimal part)
temperature=(((data[2] &0x7f) << 8) + data[3]) /10.0 #DHT11 provides signed integer temperature (no decimal part)
if (data[2] & 0x80) == 0x80:
temperature = -temperature
return [humidity, temperature]
else:
return False
import tm1637
from machine import Pin
from utime import sleep
display4 = tm1637.TM1637(clk=Pin(12), dio=Pin(13))
# --------------------------------------------------- #
# FUNCTIONS
# --------------------------------------------------- #
def work_tm1637(data:str):
display4.show(data)
def off_tm1637():
display4.show(' ')
import array, utime
from machine import Pin
import rp2
import neopixel
import dht
import bluetoooth as bto
import ultrasonic
import reed
import display4
# --------------------------------------------------- #
# FUNCTIONS
# --------------------------------------------------- #
def _collect_sensor_datas(reed_data:int) -> str:
# Collect Humidity, Temperature
dht_data = dht.work_dht()
if dht_data == False:
dht_data = [0,0]
# Collect Ultrasonic distance
ultrasonic_data = ultrasonic.work_sr04()
# Make data string
send_data_str = str(reed_data) + '/' + str(dht_data[1]) + '/' + str(dht_data[0]) + '/' + str(ultrasonic_data)
return send_data_str
# --------------------------------------------------- #
# LOOP ENTRYPOINT
# --------------------------------------------------- #
def _run():
# INIT REED STATE
reed_data = -1
display4.off_tm1637()
# LOOP
while True:
# ------------------------------------------- #
# DEFAULT LOOP
# ------------------------------------------- #
# Get data using BT(Standby)
input_data = bto.recv_data_bt()
# Get reed data from reed sensor
current_reed_data = reed.work_reed()
# ------------------------------------------- #
# IF CONDITION MET
# ------------------------------------------- #
if input_data != '' or reed_data != current_reed_data:
# Refine BT data
input_data = input_data.strip()
# Test code
print('INPUT FOUND ', input_data)
# IF INPUT MEANS GET MESSAGE or MEDICINE LID STATUS CHANGED
if input_data == 'REQ' or reed_data != current_reed_data:
# Send data using BT
bto.send_data_bt(_collect_sensor_datas(reed_data))
else:
# Refine BT data
input_data = input_data.strip()
display4.work_tm1637(input_data)
neopixel.work_led()
display4.off_tm1637()
# Send data using BT
bto.send_data_bt(_collect_sensor_datas(reed_data))
# Update reed state
reed_data = current_reed_data
if __name__ == '__main__':
_run()
import array, utime
from machine import Pin
import rp2
NUM_LEDS = 8
PIN_NUM = 22
BLACK = (0, 0, 0)
RED = (255, 0, 0)
YELLOW = (255, 150, 0)
GREEN = (0, 255, 0)
CYAN = (0, 255, 255)
BLUE = (0, 0, 255)
PURPLE = (180, 0, 255)
WHITE = (255, 255, 255)
COLORS = (BLACK, RED, YELLOW, GREEN, CYAN, BLUE, PURPLE, WHITE, BLACK)
@rp2.asm_pio(sideset_init=rp2.PIO.OUT_LOW, out_shiftdir=rp2.PIO.SHIFT_LEFT, autopull=True, pull_thresh=24)
def ws2812():
T1 = 2
T2 = 5
T3 = 3
wrap_target()
label("bitloop")
out(x, 1) .side(0) [T3 - 1]
jmp(not_x, "do_zero") .side(1) [T1 - 1]
jmp("bitloop") .side(1) [T2 - 1]
label("do_zero")
nop() .side(0) [T2 - 1]
wrap()
# Create the StateMachine with the ws2812 program, outputting on pin
sm = rp2.StateMachine(0, ws2812, freq=8_000_000, sideset_base=Pin(PIN_NUM))
# Start the StateMachine, it will wait for data on its FIFO.
sm.active(1)
# Display a pattern on the LEDs via an array of LED RGB values.
ar = array.array("I", [0 for _ in range(NUM_LEDS)])
# --------------------------------------------------- #
# FUNCTIONS
# --------------------------------------------------- #
def _pixels_show(brightness:int = 0.2):
dimmer_ar = array.array("I", [0 for _ in range(NUM_LEDS)])
for i,c in enumerate(ar):
r = int(((c >> 8) & 0xFF) * brightness)
g = int(((c >> 16) & 0xFF) * brightness)
b = int((c & 0xFF) * brightness)
dimmer_ar[i] = (g<<16) + (r<<8) + b
sm.put(dimmer_ar, 8)
utime.sleep_ms(10)
def _pixels_set(i, color):
ar[i] = (color[1]<<16) + (color[0]<<8) + color[2]
def _pixels_fill(color):
for i in range(len(ar)):
_pixels_set(i, color)
# --------------------------------------------------- #
# ENTRYPOINT
# --------------------------------------------------- #
def work_led(brightness:int = 0.2):
print("WS2812B WORKING")
for color in COLORS:
_pixels_fill(color)
_pixels_show(brightness)
utime.sleep(0.4)
from machine import Pin, Signal
data_pin = Pin(16, Pin.IN)
# --------------------------------------------------- #
# FUNCTIONS
# --------------------------------------------------- #
def work_reed() -> int:
# 1 = Lid opened, 0 = Lid closed
return data_pin.value()
"""
MicroPython TM1637 quad 7-segment LED display driver
https://github.com/mcauser/micropython-tm1637
MIT License
Copyright (c) 2016 Mike Causer
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
from micropython import const
from machine import Pin
from time import sleep_us, sleep_ms
TM1637_CMD1 = const(64) # 0x40 data command
TM1637_CMD2 = const(192) # 0xC0 address command
TM1637_CMD3 = const(128) # 0x80 display control command
TM1637_DSP_ON = const(8) # 0x08 display on
TM1637_DELAY = const(10) # 10us delay between clk/dio pulses
TM1637_MSB = const(128) # msb is the decimal point or the colon depending on your display
# 0-9, a-z, blank, dash, star
_SEGMENTS = bytearray(b'\x3F\x06\x5B\x4F\x66\x6D\x7D\x07\x7F\x6F\x77\x7C\x39\x5E\x79\x71\x3D\x76\x06\x1E\x76\x38\x55\x54\x3F\x73\x67\x50\x6D\x78\x3E\x1C\x2A\x76\x6E\x5B\x00\x40\x63')
class TM1637(object):
"""Library for quad 7-segment LED modules based on the TM1637 LED driver."""
def __init__(self, clk, dio, brightness=7):
self.clk = clk
self.dio = dio
if not 0 <= brightness <= 7:
raise ValueError("Brightness out of range")
self._brightness = brightness
self.clk.init(Pin.OUT, value=0)
self.dio.init(Pin.OUT, value=0)
sleep_us(TM1637_DELAY)
self._write_data_cmd()
self._write_dsp_ctrl()
def _start(self):
self.dio(0)
sleep_us(TM1637_DELAY)
self.clk(0)
sleep_us(TM1637_DELAY)
def _stop(self):
self.dio(0)
sleep_us(TM1637_DELAY)
self.clk(1)
sleep_us(TM1637_DELAY)
self.dio(1)
def _write_data_cmd(self):
# automatic address increment, normal mode
self._start()
self._write_byte(TM1637_CMD1)
self._stop()
def _write_dsp_ctrl(self):
# display on, set brightness
self._start()
self._write_byte(TM1637_CMD3 | TM1637_DSP_ON | self._brightness)
self._stop()
def _write_byte(self, b):
for i in range(8):
self.dio((b >> i) & 1)
sleep_us(TM1637_DELAY)
self.clk(1)
sleep_us(TM1637_DELAY)
self.clk(0)
sleep_us(TM1637_DELAY)
self.clk(0)
sleep_us(TM1637_DELAY)
self.clk(1)
sleep_us(TM1637_DELAY)
self.clk(0)
sleep_us(TM1637_DELAY)
def brightness(self, val=None):
"""Set the display brightness 0-7."""
# brightness 0 = 1/16th pulse width
# brightness 7 = 14/16th pulse width
if val is None:
return self._brightness
if not 0 <= val <= 7:
raise ValueError("Brightness out of range")
self._brightness = val
self._write_data_cmd()
self._write_dsp_ctrl()
def write(self, segments, pos=0):
"""Display up to 6 segments moving right from a given position.
The MSB in the 2nd segment controls the colon between the 2nd
and 3rd segments."""
if not 0 <= pos <= 5:
raise ValueError("Position out of range")
self._write_data_cmd()
self._start()
self._write_byte(TM1637_CMD2 | pos)
for seg in segments:
self._write_byte(seg)
self._stop()
self._write_dsp_ctrl()
def encode_digit(self, digit):
"""Convert a character 0-9, a-f to a segment."""
return _SEGMENTS[digit & 0x0f]
def encode_string(self, string):
"""Convert an up to 4 character length string containing 0-9, a-z,
space, dash, star to an array of segments, matching the length of the
source string."""
segments = bytearray(len(string))
for i in range(len(string)):
segments[i] = self.encode_char(string[i])
return segments
def encode_char(self, char):
"""Convert a character 0-9, a-z, space, dash or star to a segment."""
o = ord(char)
if o == 32:
return _SEGMENTS[36] # space
if o == 42:
return _SEGMENTS[38] # star/degrees
if o == 45:
return _SEGMENTS[37] # dash
if o >= 65 and o <= 90:
return _SEGMENTS[o-55] # uppercase A-Z
if o >= 97 and o <= 122:
return _SEGMENTS[o-87] # lowercase a-z
if o >= 48 and o <= 57:
return _SEGMENTS[o-48] # 0-9
raise ValueError("Character out of range: {:d} '{:s}'".format(o, chr(o)))
def hex(self, val):
"""Display a hex value 0x0000 through 0xffff, right aligned."""
string = '{:04x}'.format(val & 0xffff)
self.write(self.encode_string(string))
def number(self, num):
"""Display a numeric value -999 through 9999, right aligned."""
# limit to range -999 to 9999
num = max(-999, min(num, 9999))
string = '{0: >4d}'.format(num)
self.write(self.encode_string(string))
def numbers(self, num1, num2, colon=True):
"""Display two numeric values -9 through 99, with leading zeros
and separated by a colon."""
num1 = max(-9, min(num1, 99))
num2 = max(-9, min(num2, 99))
segments = self.encode_string('{0:0>2d}{1:0>2d}'.format(num1, num2))
if colon:
segments[1] |= 0x80 # colon on
self.write(segments)
def temperature(self, num):
if num < -9:
self.show('lo') # low
elif num > 99:
self.show('hi') # high
else:
string = '{0: >2d}'.format(num)
self.write(self.encode_string(string))
self.write([_SEGMENTS[38], _SEGMENTS[12]], 2) # degrees C
def show(self, string, colon=False):
segments = self.encode_string(string)
if len(segments) > 1 and colon:
segments[1] |= 128
self.write(segments[:4])
def scroll(self, string, delay=250):
segments = string if isinstance(string, list) else self.encode_string(string)
data = [0] * 8
data[4:0] = list(segments)
for i in range(len(segments) + 5):
self.write(data[0+i:4+i])
sleep_ms(delay)
class TM1637Decimal(TM1637):
"""Library for quad 7-segment LED modules based on the TM1637 LED driver.
This class is meant to be used with decimal display modules (modules
that have a decimal point after each 7-segment LED).
"""
def encode_string(self, string):
"""Convert a string to LED segments.
Convert an up to 4 character length string containing 0-9, a-z,
space, dash, star and '.' to an array of segments, matching the length of
the source string."""
segments = bytearray(len(string.replace('.','')))
j = 0
for i in range(len(string)):
if string[i] == '.' and j > 0:
segments[j-1] |= TM1637_MSB
continue
segments[j] = self.encode_char(string[i])
j += 1
return segments
''' Original code from https://www.iottrends.tech/blog/how-to-use-ultrasonic-sensor-with-raspberry-pi-pico/
'''
from machine import Pin
import utime
trigger = Pin(26, Pin.OUT)
echo = Pin(27, Pin.IN)
# --------------------------------------------------- #
# FUNCTIONS
# --------------------------------------------------- #
def work_sr04():
trigger.low()
utime.sleep_us(2)
trigger.high()
utime.sleep_us(5)
trigger.low()
while echo.value() == 0:
signaloff = utime.ticks_us()
while echo.value() == 1:
signalon = utime.ticks_us()
timepassed = signalon - signaloff
distance = (timepassed * 0.0330) / 2
return distance
#include <SoftwareSerial.h>
#include <DHT.h>
#include <TM1637Display.h>
#include <Adafruit_NeoPixel.h>
#include <string.h>
//-------------Bluetooth--------------//
#define BLUETXPIN 2
#define BLUERXPIN 3
const byte numChars = 15;
char inputdata[numChars]; // an array to store the received data
boolean newData = false;
//--------Temperature, Humidity--------//
#define DHTPIN A2
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
//-------------Ultrasonic-------------//
#define USTRIGPIN A0
#define USECHOPIN A1
long duration;
long distance;
//--------------Magnetic--------------//
#define MAGPIN 13
int mag_value = 0;
SoftwareSerial wirelessSerial(BLUETXPIN, BLUERXPIN);
//--------------7Segment--------------//
#define TM1637CLKPIN 5
#define TM1637DIOPIN 4
TM1637Display display = TM1637Display(TM1637CLKPIN, TM1637DIOPIN);
// All segments on:
const uint8_t data[] = {0xff, 0xff, 0xff, 0xff};
// All segments off:
const uint8_t blank[] = {0x00, 0x00, 0x00, 0x00};
//--------------NeoPixel--------------//
#define NEOPIXELPIN 6
#define NUMLED 8
Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUMLED, NEOPIXELPIN, NEO_GRB + NEO_KHZ800);
//------------Entrypoint--------------//
void setup() {
// Temp, Hum
dht.begin();
// Ultrasonic
pinMode(USTRIGPIN, OUTPUT);
pinMode(USECHOPIN, INPUT);
// Magnetic
pinMode(MAGPIN, INPUT);
// Bluetooth
wirelessSerial.begin(9600);
// 7Segment
display.clear();
display.setBrightness(7);
// NeoPixel
strip.begin();
strip.show();
// Test
Serial.begin(9600);
}
//------------Functions-------------//
void recvWithEndMarker() {
static byte ndx = 0;
char endMarker = '\n';
char rc;
while (wirelessSerial.available() > 0 && newData == false) {
rc = wirelessSerial.read();
if (rc != endMarker) {
inputdata[ndx] = rc;
ndx++;
if (ndx >= numChars) {
ndx = numChars - 1;
}
}
else {
inputdata[ndx] = '\0'; // terminate the string
ndx = 0;
newData = true;
}
}
if (newData == true) {
Serial.print("TESTTSETESTST ...... ");
Serial.println(inputdata);
Serial.println(strlen(inputdata));
int inputdata_len = strlen(inputdata) - 10;
Serial.print("INPUTDATALEN: ");
Serial.println(inputdata_len);
inputdata[inputdata_len] = '\0';
Serial.println(inputdata);
Serial.println(strlen(inputdata));
}
}
void showNewData() {
Serial.print("This just in ... ");
Serial.println(inputdata);
Serial.println(strlen(inputdata));
}
void ultrasonicSensor() {
// Send signal
digitalWrite(USTRIGPIN, LOW);
delayMicroseconds(2);
digitalWrite(USTRIGPIN, HIGH);
delayMicroseconds(10);
digitalWrite(USTRIGPIN, LOW);
// Save duration(Oneway x 2)
duration = pulseIn(USECHOPIN, HIGH);
// Calculate distance
Serial.print("Duration: ");
Serial.println(duration);
distance = (duration * 17) / 1000 ;
// Test
Serial.print("Distance: ");
Serial.print(distance);
Serial.println("cm");
// Send thw BLE
wirelessSerial.write(distance);
}
void temphumSensor() {
// Get humidity and temperature
float h = dht.readHumidity();
float t = dht.readTemperature();
// Test
Serial.print("Humidity: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperature: ");
Serial.print(t);
Serial.println(" *C");
// Send thw BLE
wirelessSerial.write(h);
wirelessSerial.write(t);
}
void magneticSensor() {
// Get mag value
mag_value = digitalRead(MAGPIN);
// Test
Serial.print("Magnetic: ");
Serial.println(mag_value);
// Send thw BLE
wirelessSerial.write(mag_value);
}
void cycleNeoPixel() {
for (int i = 0; i < NUMLED; i++) {
strip.setPixelColor(i % NUMLED, 0, 0, 0);
strip.setPixelColor((i + 1) % NUMLED, 0, 1, 2);
strip.setPixelColor((i + 2) % NUMLED, 0, 4, 3);
strip.setPixelColor((i + 3) % NUMLED, 0, 16, 9);
strip.setPixelColor((i + 4) % NUMLED, 0, 30, 16);
strip.setPixelColor((i + 5) % NUMLED, 0, 60, 31);
strip.setPixelColor((i + 6) % NUMLED, 0, 0, 0);
strip.setPixelColor((i + 7) % NUMLED, 1, 2, 0);
strip.show();
delay(80);
}
}
void offNeoPixel() {
for (int i = 0; i < NUMLED; i++) {
strip.setPixelColor(i, 0, 0, 0);
}
strip.show();
}
void doseDisplay() {
Serial.print("Dose: ");
Serial.println(inputdata);
Serial.println(int(inputdata[0] - '0'));
for (int i = 0; i < 10; i++) {
cycleNeoPixel();
display.showNumberDec(int(inputdata[0] - '0'), false, 1, 3);
}
display.clear();
offNeoPixel();
}
void dateDisplay() {
Serial.print("Last time: ");
Serial.print(inputdata[0]);
Serial.print(inputdata[1]);
Serial.print(inputdata[2]);
Serial.println(inputdata[3]);
display.showNumberDec(int(inputdata[0] - '0'), false, 1, 0);
display.showNumberDec(int(inputdata[1] - '0'), false, 1, 1);
display.showNumberDec(int(inputdata[2] - '0'), false, 1, 2);
display.showNumberDec(int(inputdata[3] - '0'), false, 1, 3);
delay(5000);
display.clear();
}
//---------------Main----------------//
void loop() {
// Data
if (newData == false) {
recvWithEndMarker();
}
// Call Functions
if (newData == true) {
showNewData();
// Menu
if (inputdata[0] == 'A') {
ultrasonicSensor();
}
else if (inputdata[0] == 'B') {
temphumSensor();
}
else if (inputdata[0] == 'C') {
magneticSensor();
}
else if (strlen(inputdata) < 4) {
doseDisplay();
} else {
dateDisplay();
}
newData = false;
}
}
\ No newline at end of file
{
"extends": "eslint:recommended",
"rules": {
"semi": ["warn", "never"],
"quotes": ["warn", "single"],
"no-console": ["off"]
},
"parserOptions": {
"ecmaVersion": 9
},
"env": {
"es6": true,
"node": true,
"browser": true,
"amd": true
},
"globals": {
"$": true,
"require": true,
"process": true
},
"root": true
}
\ No newline at end of file
......@@ -2,6 +2,7 @@
const User = require('../../models/user');
const Joi = require('joi');
exports.register = async(ctx) => {
const { userId, password, passwordCheck } = ctx.request.body;
......@@ -49,7 +50,7 @@ exports.login = async(ctx) => {
}
const user = await User.findByUserId(userId);
if(!user) {
if(!user || !user.userTypeCd) {
ctx.stauts = 401;
return;
}
......
......@@ -2,6 +2,7 @@
const Bottle = require('../../models/bottle');
const Hub = require('../../models/hub');
const Medicine = require('../../models/medicine');
const User = require('../../models/user');
const Mqtt = require('../../lib/MqttModule');
const jwt = require('jsonwebtoken');
......@@ -14,6 +15,12 @@ exports.bottleConnect = async(ctx) => {
}
const { userId } = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(userId);
if(!user || !user.userTypeCd) {
ctx.status = 403;
return;
}
const { bottleId, hubId } = ctx.request.body;
const isExistBottle = await Bottle.findByBottleId(bottleId);
......@@ -62,6 +69,12 @@ exports.bottleDisconnect = async(ctx) => {
}
const { userId } = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(userId);
if(!user || !user.userTypeCd) {
ctx.status = 403;
return;
}
const { bottleId } = ctx.params;
const bottle = await Bottle.findByBottleId(bottleId);
......@@ -97,6 +110,12 @@ exports.lookupInfo = async(ctx) => {
}
const { userId } = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(userId);
if(!user || !user.userTypeCd) {
ctx.status = 403;
return;
}
const { bottleId } = ctx.params;
const isBottleExist = await Bottle.findByBottleId(bottleId);
......@@ -133,6 +152,12 @@ exports.setMedicine = async(ctx) => {
}
const { userId } = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(userId);
if(!user || !user.userTypeCd) {
ctx.status = 403;
return;
}
const { bottleId } = ctx.params;
const { medicineId, dosage } = ctx.request.body;
......@@ -173,6 +198,12 @@ exports.getBottleList = async(ctx) => {
}
const { userId } = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(userId);
if(!user || !user.userTypeCd) {
ctx.status = 403;
return;
}
const { hubId } = ctx.params;
const hub = await Hub.findByHubId(hubId);
......
//허브(Mqtt Broker)등록 및 삭제
const Hub = require('../../models/hub');
const User = require('../../models/user');
const Mqtt = require('../../lib/MqttModule');
const DataProcess = require('../../lib/DataProcess');
const jwt = require('jsonwebtoken');
......@@ -12,6 +13,12 @@ exports.hubConnect = async (ctx) => {
}
const { userId } = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(userId);
if(!user || !user.userTypeCd) {
ctx.status = 403;
return;
}
const { hubId, host, port } = ctx.request.body;
const isExistHub = await Hub.findByHubId(hubId);
......@@ -47,6 +54,12 @@ exports.getHubList = async(ctx) => {
}
const { userId } = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(userId);
if(!user || !user.userTypeCd) {
ctx.status = 403;
return;
}
const hubList = await Hub.find({ userId });
if(!hubList || !hubList.length) {
ctx.status = 404;
......@@ -65,6 +78,12 @@ exports.hubDisconnect = async(ctx) => {
}
const { userId } = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(userId);
if(!user || !user.userTypeCd) {
ctx.status = 403;
return;
}
const { hubId } = ctx.params;
const hub = await Hub.findByHubId(hubId);
......
const Router = require('koa-router');
const userCtrl = require('./user.ctrl');
const user = new Router();
/**
* 현재 유저 정보 조회
* request parameter : token
* url : http://localhost:4000/api/user
* return : Object User
*/
user.get('/', userCtrl.myInfo);
/**
* 현재 유저의 타입에 따라 요청 유저 정보 조회(의사 : 환자, 관리자 : 모든 유저)
* request parameter : token
* url : http://localhost:4000/api/user/:reqUserId
* return : status
*/
user.get('/:reqUserId', userCtrl.getUserDetail);
/**
* 현재 유저의 타입에 따라 요청 유저 정보 수정(의사 : 환자, 관리자 : 모든 유저)
* request parameter : token
* url : http://localhost:4000/api/user/:reqUserId
* return : status
*/
user.patch('/:reqUserId', userCtrl.updateReqUser);
//유저에 관련된 Api
const User = require('../../models/user')
const Bottle = require('../../models/bottle')
const Hub = require('../../models/hub')
const jwt = require('jsonwebtoken')
exports.myInfo = async ctx => {
const token = ctx.req.headers.authorization
if (!token || !token.length) {
ctx.status = 401
return
}
const { userId } = jwt.verify(token, process.env.JWT_SECRET)
const user = await User.findById(userId);
if(!user || !user.userTypeCd) {
ctx.status = 403;
return;
}
let result = {
myInfo : user,
myDoctor : null,
patientList : [],
userList : [],
};
if (user.userTypeCd === 'NORMAL') {
const doctor = await User.findById(user.doctorId);
result.myDoctor = doctor;
} else if (user.userTypeCd === 'DOCTOR') {
const patientList = await User.findAllByDoctorId(user.userId);
result.patientList = patientList;
} else if (user.userTypeCd === 'MANAGER') {
const userList = await User.find();
result.userList = userList;
}
ctx.status = 200;
ctx.body = result;
}
exports.getUserDetail = async ctx => {
const token = ctx.req.headers.authorization;
if (!token || !token.length) {
ctx.status = 401;
return;
}
const { userId } = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(userId);
if(!user) {
ctx.status = 403;
return;
} else if (user.userTypeCd === 'NORMAL') {
ctx.status = 403;
return;
}
let result = {
reqUser : user,
reqUserBottleList : [],
};
if (user.userTypeCd === 'DOCTOR') {
const { reqUserId } = ctx.params;
const reqUser = await User.findById(reqUserId);
if (!reqUser) {
ctx.status = 404;
return;
}
if(reqUser.doctorId !== user.userId) {
ctx.status = 403;
return;
}
const reqUserHubList = await Hub.findAllByUserId(reqUserId);
if(reqUserHubList && reqUserHubList.length) {
const reqUserBottleList = [];
await Promise.all(reqUserHubList.forEach(async hub => {
const bottle = await Bottle.findAllByHubId(hub.hubId);
reqUserBottleList.push(...bottle);
}));
result.reqUserBottleList = reqUserBottleList;
}
}
ctx.status = 200;
ctx.body = result;
};
exports.updateReqUser = async ctx => {
const token = ctx.req.headers.authorization;
if (!token || !token.length) {
ctx.status = 401;
return;
}
const { userId } = jwt.verify(token, process.env.JWT_SECRET);
const user = await User.findById(userId);
if(!user) {
ctx.status = 403;
return;
}
if (user.userTypeCd === 'MANAGER') {
const { useYn } = ctx.request.body;
const { reqUserId } = ctx.params;
const reqUser = await User.findById(reqUserId);
if(!reqUser) {
ctx.status = 404;
return;
}
await reqUser.setUseYn(useYn);
await reqUser.save();
return;
}
ctx.status = 200;
}
\ No newline at end of file
const mqtt = require('mqtt');
const clientList = [];
const mqtt = require('mqtt')
const clientList = []
exports.mqttOn = async (hosting, func) => {
const filterIndex = clientList.findIndex(client => {
return (client.options.clientId === hosting.clientId
&& client.options.host === hosting.host
&& client.options.port === hosting.port)
});
})
if(filterIndex === -1) {
const client = mqtt.connect(hosting);
clientList.push(client);
const client = mqtt.connect(hosting)
clientList.push(client)
client.on('connect', () => {
console.log(`Hub connected: `, client.connected);
});
console.log('Hub connected: ', client.connected)
})
client.on('message', async (topic, message, packet) => {
const result = await func(topic, message.toString());
console.log('\x1b[1;32msubscribe : topic', topic, 'message : ', message.toString(), '\x1b[0m');
this.mqttPublishMessage(client, result);
});
client.on('message', async (topic, message) => {
const result = await func(topic, message.toString())
console.log('\x1b[1;32msubscribe : topic', topic, 'message : ', message.toString(), '\x1b[0m')
this.mqttPublishMessage(client, result)
})
return client;
return client
}
return clientList[filterIndex];
};
return clientList[filterIndex]
}
exports.mqttSubscribe = (client, topic) => {
client.subscribe(topic);
};
client.subscribe(topic)
}
exports.mqttPublishMessage = (client, { topic, message }) => {
client.publish(topic, message, () => {
console.log('\x1b[1;33mpublish : topic', topic, 'message : ', message, '\x1b[0m');
});
};
console.log('\x1b[1;33mpublish : topic', topic, 'message : ', message, '\x1b[0m')
})
}
exports.mqttUnsubscribe = (client, topic) => {
client.unsubscribe(topic, () => {
console.log('unsubscribe', topic);
});
};
console.log('unsubscribe', topic)
})
}
exports.mqttOff = (hosting) => {
const filterIndex = clientList.findIndex(client => {
return (client.options.clientId === hosting.clientId
&& client.options.host === hosting.host
&& client.options.port === hosting.port)
});
})
if(filterIndex !== -1) {
clientList[filterIndex].end();
clientList.splice(filterIndex, 1);
clientList[filterIndex].end()
clientList.splice(filterIndex, 1)
}
}
\ No newline at end of file
......
......@@ -7,16 +7,19 @@ const BottleSchema = new Schema ({
temperature : { type : Number, default : 0 },
humidity : { type : Number, default : 0 },
balance : { type : Number, default : 0 },
recentOpen : { type : Date, default : Date.now },
medicineId : { type : Number, default : null, },
hubId : Number,
dosage : { type : Number, default : 0 }
dosage : { type : Number, default : 0 },
hubId : { type : Number, ref : 'Hub' },
})
BottleSchema.statics.findByBottleId = function(bottleId) {
return this.findOne({ bottleId });
};
BottleSchema.statics.findAllByHubId = function(hubId) {
return this.find({ hubId });
};
BottleSchema.methods.getBottleId = function() {
return this.bottleId;
};
......@@ -49,4 +52,12 @@ BottleSchema.methods.getHubId = function() {
return this.hubId;
};
BottleSchema.methods.setMedicineId = function(medicineId) {
this.medicineId = medicineId;
};
BottleSchema.statics.setDosage = function(dosage) {
this.dosage = dosage;
};
module.exports = mongoose.model('Bottle', BottleSchema);
\ No newline at end of file
......
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const TakeMedicineHistorySchema = new Schema ({
takeDate : {
type : Date,
required : true,
default : Date.now,
},
medicineId : {
type : Number,
ref : 'Medicine',
required : true,
},
bottleId : {
type : Number,
ref : 'Bottle',
required : true,
},
});
TakeMedicineHistorySchema.statics.findByBottleId = async function(bottleId) {
return this.find({ bottleId });
};
TakeMedicineHistorySchema.statics.findByBottleIdAndMedicineId = async function(bottleId, medicineId) {
return this.find({ bottleId, medicineId });
};
module.export = mongoose.model("TakeMedicineHist", TakeMedicineHistorySchema);
\ No newline at end of file
......@@ -5,13 +5,17 @@ const Schema = mongoose.Schema;
const HubSchema = new Schema ({
hubId : { type : Number, required : true, unique : true },
hosting : { type : Object, default : null },
userId : { type : String, default : null },
userId : { type : String, default : null, ref : 'User' },
});
HubSchema.statics.findByHubId = function(hubId) {
return this.findOne({ hubId })
};
HubSchema.statics.findAllByUserId = function(userId) {
return this.find({ userId });
};
HubSchema.methods.setHubHost = function(hosting) {
this.hosting = hosting;
};
......
......@@ -5,9 +5,9 @@ const Schema = mongoose.Schema;
const MedicineSchema = new Schema ({
medicineId : { type : Number, required : true, unique : true },
name : { type : String, required : true },
company : String,
company : { type : String, required : true },
target : { type : String, required : true },
dosage : { type : String, required : true },
dosageInfo : { type : String, required : true },
warn : { type : String, required : true },
antiEffect : { type : String, required : true }
})
......
......@@ -4,9 +4,12 @@ const jwt = require('jsonwebtoken');
const Schema = mongoose.Schema;
const UserSchema = new Schema({
userId : { type: String, require : true, unique : true, lowercase : true },
hashedPassword : { type : String, default : null }
const UserSchema = new Schema ({
userId : { type: String, required : true, unique : true, lowercase : true },
hashedPassword : { type : String, required : true },
userTypeCd : { type : String, required : true, default : 'NORMAL' },
doctorId : { type : String, default : null },
useYn : { type : Boolean, default : true },
});
UserSchema.methods.setPassword = async function(password) {
......@@ -19,10 +22,22 @@ UserSchema.methods.checkPassword = async function(password) {
return result;
};
UserSchema.methods.setUseYn = async function(useYn) {
this.useYn = useYn;
}
UserSchema.statics.findByUserId = async function(userId) {
return this.findOne({ userId });
};
UserSchema.statics.findAllByDoctorId = async function(doctorId) {
return this.find({ doctorId });
};
UserSchema.statics.findAllByUserTypeCd = async function(userTypeCd) {
return this.find({ userTypeCd });
};
UserSchema.methods.generateToken = function() {
const token = jwt.sign (
{
......